File size: 12,102 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fa7eea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""Persistent browser context management."""
import json
import logging
import os
import shutil
import tempfile
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any

from ..browser.errors import classify_os_error, write_diagnostic_log
from ..browser.manager import _app_runtime_dir, _resolve_writable_dir
from ..config import settings

logger = logging.getLogger(__name__)

# Context ids are generated as ctx_ + hex; anything containing path
# separators or parent references can never be a valid id and is rejected
# before it reaches a filesystem path.
_SAFE_CONTEXT_ID = frozenset(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
)


def _is_safe_context_id(context_id: str) -> bool:
    return bool(context_id) and all(ch in _SAFE_CONTEXT_ID for ch in context_id)


def _paths_overlap(first: str, second: str) -> bool:
    """Case-normalized equality/containment check for two realpath'd paths."""
    a, b = os.path.normcase(first), os.path.normcase(second)
    try:
        return os.path.commonpath([a, b]) in (a, b)
    except ValueError:
        return a == b


class ContextManager:
    """Manages persistent browser contexts.



    The storage root is resolved through a WRITE PROBE, not by assuming the

    configured directory works. A root can exist and still be unable to hold a

    new directory - the reported ``PermissionError: [WinError 5] Access is

    denied`` on the ``.browser-automation-agent`` path is exactly that case

    (a sandboxed process, an ACL owned by another identity, or an elevated

    owner). When the configured root cannot hold a context directory the

    manager falls back to the app's own runtime root, which lives beside the

    backend source and is writable by default.

    """

    def __init__(self, storage_dir: Path | None = None) -> None:
        configured = (
            Path(storage_dir).expanduser()
            if storage_dir is not None
            else Path(settings.context_storage_dir).expanduser()
        )
        fallback = _app_runtime_dir() / "contexts"
        self.storage_dir = _resolve_writable_dir(configured, fallback)
        if self.storage_dir != configured:
            logger.warning(
                "Configured context storage directory is not writable; using %s",
                self.storage_dir,
            )
        self._contexts: dict[str, dict[str, Any]] = {}
        self._load_contexts()

    def _load_contexts(self) -> None:
        """Load context metadata from disk.



        The path is a fixed filename under the trusted storage root (no user

        input reaches it), normalized with realpath and confined to that root

        before any filesystem access.

        """
        base = os.path.realpath(self.storage_dir)
        metadata_file = Path(os.path.realpath(os.path.join(base, "contexts.json")))
        if os.path.commonpath([base, str(metadata_file)]) != base:
            raise ValueError("metadata path escapes the storage root")
        if metadata_file.exists():
            try:
                self._contexts = json.loads(metadata_file.read_text(encoding="utf-8"))
            except Exception:  # noqa: BLE001 - corrupt metadata falls back to empty
                self._contexts = {}

    def _save_contexts(self) -> None:
        """Save context metadata to disk through classified error handling.



        Same confinement check as _load_contexts: the normalized path must

        stay inside the storage root, and the write goes through

        Path.write_text so no raw handle escapes that check.  Metadata I/O

        failures use the same OS classification and diagnostic-log path as

        profile-directory failures instead of escaping as raw OSError.

        """
        base = os.path.realpath(self.storage_dir)
        metadata_file = Path(os.path.realpath(os.path.join(base, "contexts.json")))
        if os.path.commonpath([base, str(metadata_file)]) != base:
            raise ValueError("metadata path escapes the storage root")
        try:
            # Write a sibling temporary file and atomically replace the
            # metadata document.  A failed persistence attempt therefore
            # cannot truncate the previous durable metadata.
            fd, temp_name = tempfile.mkstemp(
                prefix=f".{metadata_file.name}.",
                suffix=".tmp",
                dir=metadata_file.parent,
            )
            try:
                with os.fdopen(fd, "w", encoding="utf-8") as handle:
                    handle.write(json.dumps(self._contexts, indent=2))
                    handle.flush()
                    os.fsync(handle.fileno())
                os.replace(temp_name, metadata_file)
            finally:
                try:
                    os.unlink(temp_name)
                except FileNotFoundError:
                    pass
        except OSError as exc:
            err = classify_os_error(
                exc,
                path=metadata_file,
                operation="save browser context metadata",
            )
            write_diagnostic_log(err, exc)
            raise err from exc

    def _context_dir(self, context_id: str) -> Path:
        """Storage path for a context id; rejects ids that could escape

        the storage root (separators, parent references)."""
        if not _is_safe_context_id(context_id):
            raise ValueError(f"invalid context id: {context_id!r}")
        # Defense in depth: even though the whitelist already excludes path
        # separators, normalize and confirm the joined path stays inside the
        # storage root before it is used for any filesystem operation.
        base = os.path.realpath(self.storage_dir)
        context_path = Path(os.path.realpath(os.path.join(base, context_id)))
        if os.path.commonpath([base, str(context_path)]) != base:
            raise ValueError(f"context path escapes storage root: {context_id!r}")
        return context_path

    def create_context(

        self,

        name: str,

        description: str = "",

        tags: list[str] | None = None,

    ) -> str:
        """Create a new persistent context."""
        context_id = f"ctx_{uuid.uuid4().hex[:8]}"
        context_dir = self._context_dir(context_id)
        try:
            context_dir.mkdir(parents=True, exist_ok=True)
        except OSError as exc:
            # A raw OSError here became a generic HTTP 500 and, in the field,
            # the reported "PermissionError: [WinError 5] Access is denied".
            # Classify it so the user gets one actionable message and a
            # diagnostic id instead of a stack trace.
            err = classify_os_error(
                exc,
                path=context_dir,
                operation="create browser context directory",
            )
            write_diagnostic_log(err, exc)
            raise err from exc

        context_data = {
            "context_id": context_id,
            "name": name,
            "description": description,
            "tags": tags or [],
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat(),
            "session_count": 0,
            "last_used": None,
            "storage_path": str(context_dir),
        }

        self._contexts[context_id] = context_data
        try:
            self._save_contexts()
        except Exception:
            # Persistence is part of creation.  A metadata write failure must
            # not leave a half-created context behind in memory or on disk.
            self._contexts.pop(context_id, None)
            try:
                shutil.rmtree(context_dir)
            except OSError:
                logger.warning(
                    "Could not roll back context directory %s after metadata save failure",
                    context_dir,
                    exc_info=True,
                )
            raise

        return context_id

    def get_context(self, context_id: str) -> dict[str, Any] | None:
        """Get context metadata."""
        return self._contexts.get(context_id)

    def list_contexts(self) -> list[dict[str, Any]]:
        """List all contexts."""
        return list(self._contexts.values())

    def update_context(

        self,

        context_id: str,

        **kwargs: Any,

    ) -> bool:
        """Update context metadata."""
        if context_id not in self._contexts:
            return False

        previous = dict(self._contexts[context_id])
        for key, value in kwargs.items():
            if key in self._contexts[context_id]:
                self._contexts[context_id][key] = value

        self._contexts[context_id]["updated_at"] = datetime.now().isoformat()
        try:
            self._save_contexts()
        except Exception:
            # Keep the in-memory record consistent with the last durable
            # metadata when persistence fails.
            self._contexts[context_id] = previous
            raise
        return True

    def delete_context(self, context_id: str) -> bool:
        """Delete a context and its data.



        Deletion discipline (plan §6 item 4): the rmtree targets ONLY this

        context's metadata directory under the storage root, and NEVER a

        browser-data (user-data) directory — a storage root misconfigured to

        overlap the profile root is refused, not deleted. Callers close the

        browser object BEFORE invoking this (main.delete_context_handler).

        """
        if context_id not in self._contexts:
            return False

        try:
            context_dir = self._context_dir(context_id)
        except ValueError:
            return False
        if context_dir.exists():
            self._ensure_not_browser_data(context_dir)
            shutil.rmtree(context_dir)

        del self._contexts[context_id]
        self._save_contexts()
        return True

    def _ensure_not_browser_data(self, context_dir: Path) -> None:
        """Refuse deletion of anything overlapping the user-data root.



        The target may not BE the user-data root, live inside it, or contain

        it (deleting the parent would destroy the profile root).

        """
        user_data_root = os.path.realpath(str(settings.browser_user_data_dir))
        target = os.path.realpath(str(context_dir))
        if _paths_overlap(target, user_data_root):
            raise ValueError(
                "refusing to delete: context directory overlaps the browser "
                f"user-data root: {target}"
            )

    def record_session_use(self, context_id: str) -> None:
        """Record that a session used this context."""
        if context_id in self._contexts:
            self._contexts[context_id]["session_count"] += 1
            self._contexts[context_id]["last_used"] = datetime.now().isoformat()
            self._save_contexts()

    def get_context_path(self, context_id: str) -> Path | None:
        """Get the filesystem path for a context."""
        context = self._contexts.get(context_id)
        if context:
            return Path(context["storage_path"])
        return None

    def cleanup_old_contexts(self, max_age_days: int = 30) -> int:
        """Clean up contexts older than max_age_days."""
        from datetime import timedelta

        cutoff = datetime.now() - timedelta(days=max_age_days)
        removed = 0

        for context_id, context in list(self._contexts.items()):
            last_used = context.get("last_used")
            if last_used:
                last_used_dt = datetime.fromisoformat(last_used)
                if last_used_dt < cutoff:
                    self.delete_context(context_id)
                    removed += 1

        return removed


# Global context manager instance
context_manager = ContextManager()