diff --git a/libs/code/THREAT_MODEL.md b/libs/code/THREAT_MODEL.md index 178fc7360f4..58653dc7171 100644 --- a/libs/code/THREAT_MODEL.md +++ b/libs/code/THREAT_MODEL.md @@ -231,7 +231,7 @@ #### TB4: MCP Config → Process / Network -- **Inside**: `mcp_tools._validate_server_config` validates JSON structure and field types. Project-level servers (stdio and remote) require approval: an interactive prompt (`main._check_mcp_project_trust`) that offers allow-for-this-session ("y"), remember a chosen subset of servers ("r"), or deny ("N") — unless `--trust-project-mcp` is set, which trusts the whole config for the run. Whole-config trust is never persisted; it exists only as in-memory run state, set by `--trust-project-mcp` or by an interactive allow-once/remember decision. The remembered subset governs only what is persisted for future runs — both allow-once and remember load every prompted server for the current session. Persistent "remember" (a.k.a. "always allow") decisions are stored in `[mcp].enabled_project_server_approvals` with project root, server name, and server definition fingerprint, so a different project or changed command/URL under the same name requires re-approval. Users can reject individual project server names via `[mcp].disabled_project_servers` (or `DEEPAGENTS_CODE_DISABLED_PROJECT_MCP_SERVERS`). There is also an explicit process-wide escape hatch, `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS`, that approves matching names globally and intentionally bypasses the project/fingerprint binding. Reject wins over approval and over full trust, with one documented exception: if the user's `config.toml` is unreadable (see below), any deny defined *only* there is lost, so a name that is both TOML-`disabled` and exported in `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` survives — an accepted footgun (`load_mcp_server_trust_lists` documents it inline) that requires a self-contradicting config plus the explicit dangerous opt-in, and the read error is surfaced to the user. These policies are read by `model_config.load_mcp_server_trust_lists` only from user-controlled sources — the user-level `~/.deepagents/config.toml`, the global `~/.deepagents/.env`, and shell-exported env — never from `.mcp.json` or any repo-committed file, so a committed config cannot self-approve its own servers. In particular, the env forms (`DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` / `..._DISABLED_...`) are added to `config._PROJECT_DOTENV_DENIED_ENV_KEYS`, so a committed *project* `.env` cannot inject them into `os.environ` even though it is loaded at bootstrap. The dangerous enable env var and scoped TOML approvals are independent grants: setting the env var, including to an empty value, does not suppress remembered approvals. Disabled *unions* TOML and env so a deny can never be silently emptied by the other source. If the user's `config.toml` exists but cannot be read or parsed, the loader fails closed (project configs are treated as untrusted and the error is surfaced) rather than proceeding with an empty deny list. Only scoped-approved, dangerously env-enabled, or fully trusted names survive into the merged config, so a non-approved remote entry is never preflighted and its interpolated headers are never resolved. +- **Inside**: `mcp_tools._validate_server_config` validates JSON structure and field types. Project-level servers (stdio and remote) require approval: an interactive prompt (`main._check_mcp_project_trust`) that offers allow-for-this-session ("y"), remember a chosen subset of servers ("r"), or deny ("N") — unless `--trust-project-mcp` is set, which trusts the whole config for the run. Whole-config trust is never persisted; it exists only as in-memory run state, set by `--trust-project-mcp` or by an interactive allow-once/remember decision. The remembered subset governs only what is persisted for future runs — both allow-once and remember load every prompted server for the current session. Persistent "remember" (a.k.a. "always allow") decisions are stored in `[mcp].enabled_project_server_approvals` with a local-project identity, server name, and server definition fingerprint. Remote server approvals with fixed URLs are shared by main checkouts and linked worktrees only through validated reciprocal Git common-directory metadata; independent clones remain separate, and non-Git or malformed/forged metadata falls back to the exact resolved root. Remote definitions with interpolated URLs remain exact-worktree scoped because project `.env` files can resolve the same template to different endpoints. Local stdio server approvals always use the exact resolved worktree root because the same command can execute different files in another checkout. A changed command, URL, or transport under the same name requires re-approval. Users can reject individual project server names via `[mcp].disabled_project_servers` (or `DEEPAGENTS_CODE_DISABLED_PROJECT_MCP_SERVERS`). There is also an explicit process-wide escape hatch, `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS`, that approves matching names globally and intentionally bypasses the project/fingerprint binding. Reject wins over approval and over full trust, with one documented exception: if the user's `config.toml` is unreadable (see below), any deny defined *only* there is lost, so a name that is both TOML-`disabled` and exported in `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` survives — an accepted footgun (`load_mcp_server_trust_lists` documents it inline) that requires a self-contradicting config plus the explicit dangerous opt-in, and the read error is surfaced to the user. These policies are read by `model_config.load_mcp_server_trust_lists` only from user-controlled sources — the user-level `~/.deepagents/config.toml`, the global `~/.deepagents/.env`, and shell-exported env — never from `.mcp.json` or any repo-committed file, so a committed config cannot self-approve its own servers. In particular, the env forms (`DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` / `..._DISABLED_...`) are added to `config._PROJECT_DOTENV_DENIED_ENV_KEYS`, so a committed *project* `.env` cannot inject them into `os.environ` even though it is loaded at bootstrap. The dangerous enable env var and scoped TOML approvals are independent grants: setting the env var, including to an empty value, does not suppress remembered approvals. Disabled *unions* TOML and env so a deny can never be silently emptied by the other source. If the user's `config.toml` exists but cannot be read or parsed, the loader fails closed (project configs are treated as untrusted and the error is surfaced) rather than proceeding with an empty deny list. Only scoped-approved, dangerously env-enabled, or fully trusted names survive into the merged config, so a non-approved remote entry is never preflighted and its interpolated headers are never resolved. - **Outside**: Stdio server `command`, `args`, and `env` fields are user-controlled strings passed directly to `StdioConnection`. The `env` dict from MCP config is forwarded without filtering — users can set arbitrary environment variables (including `PATH`, `LD_PRELOAD`, `PYTHONPATH`) for the MCP subprocess. - **Crossing mechanism**: `subprocess.Popen` (via `langchain_mcp_adapters`) for stdio; HTTP/SSE for remote servers. diff --git a/libs/code/deepagents_code/_git.py b/libs/code/deepagents_code/_git.py index 2a94b9863ba..973e9ba4f46 100644 --- a/libs/code/deepagents_code/_git.py +++ b/libs/code/deepagents_code/_git.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import os import re from pathlib import Path from typing import NamedTuple @@ -159,6 +160,182 @@ def find_git_root(path: str | Path) -> Path | None: return None +def _read_single_git_metadata_line(path: Path) -> str | None: + """Read one non-empty line from a regular Git metadata file. + + Args: + path: Metadata file to read. + + Returns: + The stripped line, or `None` when the file is unsafe or malformed. + """ + if path.is_symlink() or not path.is_file(): + return None + try: + raw = path.read_text(encoding="utf-8") + except (OSError, UnicodeError): + logger.debug("Failed to read Git metadata from %s", path, exc_info=True) + return None + + lines = raw.splitlines() + if len(lines) != 1: + return None + value = lines[0].strip() + if not value or "\x00" in value: + return None + return value + + +def _resolve_git_metadata_path(path: Path, *, relative_to: Path) -> Path | None: + """Resolve a path stored in a single-line Git metadata file. + + Args: + path: Metadata file containing the path. + relative_to: Base directory for a relative stored path. + + Returns: + The strictly resolved path, or `None` when it cannot be trusted. + """ + value = _read_single_git_metadata_line(path) + if value is None: + return None + candidate = Path(value) + if not candidate.is_absolute(): + candidate = relative_to / candidate + try: + return candidate.resolve(strict=True) + except (OSError, RuntimeError, ValueError): + logger.debug("Failed to resolve Git metadata path from %s", path, exc_info=True) + return None + + +def _normalize_git_metadata_path(path: Path, *, relative_to: Path) -> Path | None: + """Normalize a stored path without following its target. + + Args: + path: Metadata file containing the path. + relative_to: Base directory for a relative stored path. + + Returns: + The absolute lexical path, or `None` when the metadata is malformed. + """ + value = _read_single_git_metadata_line(path) + if value is None: + return None + candidate = Path(value) + if not candidate.is_absolute(): + candidate = relative_to / candidate + try: + return Path(os.path.abspath(candidate)) # noqa: PTH100 # do not follow links + except (OSError, RuntimeError, ValueError): + logger.debug( + "Failed to normalize Git metadata path from %s", path, exc_info=True + ) + return None + + +def _parse_trusted_git_dir_pointer(git_entry: Path) -> Path | None: + """Resolve a strict worktree `.git` pointer for a trust decision. + + Args: + git_entry: Regular `.git` file to parse. + + Returns: + The canonical administration directory, or `None` for an invalid pointer. + """ + value = _read_single_git_metadata_line(git_entry) + if value is None or not value.startswith(_GIT_DIR_POINTER_PREFIX): + return None + pointer = value.removeprefix(_GIT_DIR_POINTER_PREFIX).strip() + if not pointer: + return None + candidate = Path(pointer) + if not candidate.is_absolute(): + candidate = git_entry.parent / candidate + try: + git_dir = candidate.resolve(strict=True) + except (OSError, RuntimeError, ValueError): + logger.debug( + "Failed to resolve trusted gitdir pointer %s", git_entry, exc_info=True + ) + return None + return git_dir if git_dir.is_dir() else None + + +def _is_valid_git_common_dir(path: Path) -> bool: + """Return whether `path` has the required shared-repository metadata.""" + return ( + path.is_dir() + and (path / "HEAD").is_file() + and (path / "config").is_file() + and (path / "objects").is_dir() + and (path / "refs").is_dir() + ) + + +def find_git_common_dir(path: str | Path) -> Path | None: + """Resolve a validated identity shared by one repository's Git worktrees. + + A normal checkout uses its in-tree `.git` directory. A linked worktree is + accepted only when its administration directory lives directly under the + common repository's `worktrees` directory and its `gitdir` file points back + to the current worktree's `.git` file, and both the shared common directory + and the worktree's own administration directory carry valid repository + metadata (`_is_valid_git_common_dir` plus the worktree's own `HEAD`). These + checks prevent a forged pointer or directory link from borrowing another + repository's identity. + + Args: + path: Exact working-tree root or persisted common-directory path. + + Returns: + The canonical Git common directory, or `None` when the metadata cannot + be validated confidently. + """ + try: + root = _normalize_lookup_path(path) + if not root.is_dir(): + return None + if _is_valid_git_common_dir(root): + return root + root = root.resolve(strict=True) + git_entry = root / ".git" + if git_entry.is_symlink(): + return None + + if git_entry.is_dir(): + common_dir = git_entry.resolve(strict=True) + if common_dir != git_entry or not _is_valid_git_common_dir(common_dir): + return None + return common_dir + if not git_entry.is_file(): + return None + + git_dir = _parse_trusted_git_dir_pointer(git_entry) + if git_dir is None: + return None + + common_dir = _resolve_git_metadata_path( + git_dir / "commondir", relative_to=git_dir + ) + if common_dir is None or git_dir.parent != common_dir / "worktrees": + return None + if not _is_valid_git_common_dir(common_dir): + return None + if not (git_dir / "HEAD").is_file(): + return None + + backlink = _normalize_git_metadata_path(git_dir / "gitdir", relative_to=git_dir) + if backlink is None or backlink != git_entry: + return None + except (OSError, RuntimeError, ValueError): + logger.debug( + "Failed to validate Git common directory for %s", path, exc_info=True + ) + return None + return common_dir + + def read_git_branch_from_filesystem(path: str | Path) -> str | None: """Read the current git branch from repository metadata. diff --git a/libs/code/deepagents_code/config_manifest.py b/libs/code/deepagents_code/config_manifest.py index 9cbbd11545b..8abad77dc3e 100644 --- a/libs/code/deepagents_code/config_manifest.py +++ b/libs/code/deepagents_code/config_manifest.py @@ -1249,9 +1249,12 @@ def _credential_options() -> tuple[ConfigOption, ...]: key="mcp.enabled_project_server_approvals", group="MCP", summary=( - "Project MCP server approvals saved by project root, server name, and " - "server fingerprint; edited commands/URLs require re-approval. " - "Process-wide name allowlist (bypasses project/fingerprint binding): " + "Remote project MCP approvals with fixed URLs are shared across one " + "local Git repository's worktrees; local commands and interpolated " + "remote URLs use the exact worktree. All include the server name and " + "fingerprint, so edited commands/URLs or transport changes require " + "re-approval. Process-wide " + "name allowlist (bypasses project/fingerprint binding): " "DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS." ), kind=OptionKind.STRUCTURED, diff --git a/libs/code/deepagents_code/model_config.py b/libs/code/deepagents_code/model_config.py index 2f531520dae..bcb8ed5d6ca 100644 --- a/libs/code/deepagents_code/model_config.py +++ b/libs/code/deepagents_code/model_config.py @@ -25,6 +25,7 @@ import tomli_w from deepagents_code import _env_vars, auth_store +from deepagents_code._git import find_git_common_dir if TYPE_CHECKING: from collections.abc import Iterable, Mapping @@ -3390,18 +3391,32 @@ def unsuppress_warning(key: str, config_path: Path | None = None) -> bool: return True +class _McpProjectScope(NamedTuple): + """A resolved MCP trust identity and whether it is Git-common scoped. + + A `NamedTuple` (mirroring `_git.RepositoryMetadata`) so the boolean slot is + self-documenting at every call site instead of a load-bearing positional. + """ + + identity: str + """Normalized trust identity: a Git common directory or an exact root.""" + + git_common_dir: bool + """Whether `identity` is a validated Git common-directory path.""" + + @dataclass(frozen=True, order=True) class McpProjectServerApproval: """A project-scoped, definition-bound MCP server approval. Membership in a `McpServerTrustLists.approvals` set *is* the trust decision (`is_enabled` reconstructs an approval and tests `approval in approvals`), so - value equality on the three raw strings must line up between the write side - (`add_enabled_project_mcp_servers`) and the read side (`is_enabled`). Build - runtime approvals through `create` and persisted ones through `from_toml`, - never the raw constructor, so every path normalizes the root and computes the - fingerprint identically. `order=True` exists only so `sorted()` yields - deterministic TOML output. + value equality must line up between the write side + (`add_enabled_project_mcp_servers`) and the read side (`is_enabled`). Build new + approvals through `create` and persisted ones through `from_toml`, never the raw + constructor. Legacy unmarked entries intentionally retain their exact-worktree + scope, while new entries reconstruct the same transport-aware scope on both + sides. `order=True` exists only so `sorted()` yields deterministic TOML output. The raw constructor only enforces non-emptiness (`__post_init__`), not that `project_root` is normalized or that `fingerprint` is a real digest. A @@ -3412,7 +3427,7 @@ class McpProjectServerApproval: """ project_root: str - """Resolved project root that originated the approval.""" + """Shared fixed-URL identity or exact worktree-scoped identity.""" name: str """MCP server name within the project config.""" @@ -3420,6 +3435,9 @@ class McpProjectServerApproval: fingerprint: str """Fingerprint of the approved MCP server definition.""" + git_common_dir: bool = field(default=False, kw_only=True) + """Whether `project_root` is a persisted Git common-directory identity.""" + def __post_init__(self) -> None: """Reject degenerate approvals so a bad one can't silently never match. @@ -3438,14 +3456,41 @@ def __post_init__(self) -> None: ) raise ValueError(msg) + @classmethod + def _create_for_scope( + cls, + *, + scope: _McpProjectScope, + name: str, + server: JsonValue, + ) -> McpProjectServerApproval: + """Build an approval from one already-resolved trust scope. + + Args: + scope: Normalized identity and Git-common marker. + name: MCP server name. + server: Parsed MCP server definition to fingerprint. + + Returns: + The normalized, definition-bound approval. + """ + return cls( + project_root=scope.identity, + name=name.strip(), + fingerprint=fingerprint_mcp_server_config(server), + git_common_dir=scope.git_common_dir, + ) + @classmethod def create( cls, *, project_root: str | Path | None, name: str, server: JsonValue ) -> McpProjectServerApproval | None: """Build an approval, normalizing the root and fingerprinting `server`. - The single construction path for runtime approvals, so the write and read - sides cannot drift on how the root is normalized or the server hashed. + Remote servers with fixed URLs use the validated Git common directory so + their approvals can be shared across linked worktrees. Local commands and + remote definitions with interpolated URLs use the exact resolved worktree + because their behavior can differ between checkouts. Args: project_root: Project root to normalize. @@ -3455,39 +3500,35 @@ def create( Returns: The approval, or `None` when `project_root` cannot be normalized. """ - normalized_root = normalize_mcp_project_root(project_root) - if normalized_root is None: - return None - return cls( - project_root=normalized_root, - # Strip so the read side matches the write side and `from_toml`, - # both of which persist/compare a stripped name — otherwise a - # whitespace-padded server key would never match its own approval. - name=name.strip(), - fingerprint=fingerprint_mcp_server_config(server), + scope = _normalize_mcp_project_scope( + project_root, + share_across_worktrees=_mcp_server_uses_remote_transport(server), ) + if scope is None: + return None + return cls._create_for_scope(scope=scope, name=name, server=server) @classmethod def from_toml(cls, item: Mapping[str, object]) -> McpProjectServerApproval | None: """Deserialize a persisted approval table, normalizing the root. - The read-side counterpart to `as_toml`. Applies the *same* root - normalization as `create` so a persisted approval and a freshly built - runtime one compare equal for the same project and definition — the - write/read symmetry the trust decision depends on lives here, not in the - caller. + Legacy entries without `git_common_dir` remain scoped to their exact + stored worktree. Marked entries retain their exact Git identity, so stale + metadata cannot redirect them to an enclosing repository. Args: item: A parsed TOML table with `project_root`, `name`, and - `fingerprint` string fields. + `fingerprint` string fields plus an optional `git_common_dir` + boolean. Returns: - The approval, or `None` for a malformed table (missing, blank, or - non-string field) — fail-closed for an allowlist. + The approval, or `None` for a malformed table — fail-closed for an + allowlist. """ project_root = item.get("project_root") name = item.get("name") fingerprint = item.get("fingerprint") + git_common_dir = item.get("git_common_dir", False) if not ( isinstance(project_root, str) and project_root.strip() @@ -3495,39 +3536,67 @@ def from_toml(cls, item: Mapping[str, object]) -> McpProjectServerApproval | Non and name.strip() and isinstance(fingerprint, str) and fingerprint.strip() + and isinstance(git_common_dir, bool) ): return None - normalized_root = normalize_mcp_project_root(project_root) + + if git_common_dir: + normalized_root = _normalize_persisted_git_common_dir(project_root) + normalized_is_common = True + else: + scope = _normalize_mcp_project_scope( + project_root, share_across_worktrees=False + ) + if scope is None: + return None + normalized_root, normalized_is_common = scope.identity, scope.git_common_dir if normalized_root is None: return None return cls( project_root=normalized_root, name=name.strip(), fingerprint=fingerprint.strip(), + git_common_dir=normalized_is_common, ) - def as_toml(self) -> dict[str, str]: + def as_toml(self) -> dict[str, str | bool]: """Return a TOML-serializable representation.""" - return { + item: dict[str, str | bool] = { "project_root": self.project_root, "name": self.name, "fingerprint": self.fingerprint, } + if self.git_common_dir: + item["git_common_dir"] = True + return item -def normalize_mcp_project_root(project_root: str | Path | None) -> str | None: - """Normalize a project root for persisted MCP trust comparisons. +def _normalize_mcp_project_scope( + project_root: str | Path | None, + *, + share_across_worktrees: bool, +) -> _McpProjectScope | None: + """Resolve an MCP trust identity and whether it is Git-common scoped. Args: project_root: Project root path to normalize. + share_across_worktrees: Whether a validated Git common directory may be + used instead of the exact worktree root. Returns: - Resolved absolute project root string, or `None` when `project_root` - is `None`, cannot be expanded, or resolution detects a path loop. - On an `OSError` from `resolve()`, returns the expanded but - *unresolved* path as a fallback; a transient failure on only one of - the write/read sides then yields different strings and a spurious - re-prompt (fail-closed), never a false match. + One of three outcomes: + + - `(, True)` when `share_across_worktrees` is set and the + resolved root validates as a Git worktree. + - `(, False)` otherwise. + - `(, False)` when `resolve()` raises `OSError`; + the returned string is the expanded-but-unresolved path. A transient + resolve failure on only one of the write/read sides then yields + different identity strings and a spurious re-prompt (fail-closed), + never a false match. + + Returns `None` only when `project_root` is `None`, cannot be expanded, or + resolution detects a path loop (`RuntimeError`). """ if project_root is None: return None @@ -3542,14 +3611,14 @@ def normalize_mcp_project_root(project_root: str | Path | None) -> str | None: return None try: - return str(expanded_root.resolve()) + resolved_root = expanded_root.resolve() except OSError: logger.warning( "Could not resolve MCP project root %s", project_root, exc_info=True, ) - return str(expanded_root) + return _McpProjectScope(str(expanded_root), False) except RuntimeError: logger.warning( "Could not resolve MCP project root %s", @@ -3558,6 +3627,92 @@ def normalize_mcp_project_root(project_root: str | Path | None) -> str | None: ) return None + if share_across_worktrees: + common_dir = find_git_common_dir(resolved_root) + if common_dir is not None: + return _McpProjectScope(str(common_dir), True) + return _McpProjectScope(str(resolved_root), False) + + +def _normalize_persisted_git_common_dir(project_root: str) -> str | None: + """Normalize a marked Git identity without following or rediscovering it. + + Args: + project_root: Persisted Git common-directory path. + + Returns: + The absolute lexical path, or `None` for an invalid stored identity. + """ + try: + expanded_root = Path(project_root).expanduser() + except (OSError, RuntimeError): + logger.warning( + "Could not expand persisted MCP Git identity %s", + project_root, + exc_info=True, + ) + return None + if not expanded_root.is_absolute(): + logger.warning( + "Persisted MCP Git identity %s is not absolute; dropping approval", + project_root, + ) + return None + try: + return os.path.abspath(expanded_root) # noqa: PTH100 # do not follow links + except (OSError, RuntimeError, ValueError): + logger.warning( + "Could not normalize persisted MCP Git identity %s", + project_root, + exc_info=True, + ) + return None + + +_REMOTE_MCP_TRANSPORTS = frozenset( + {"http", "sse", "streamable_http", "streamable-http"} +) + + +def _mcp_server_uses_remote_transport(server: JsonValue) -> bool: + """Return whether `server` is confidently a remote-only definition. + + Malformed, ambiguous, or environment-dependent definitions stay + worktree-scoped. A definition containing `command` is never shared even if it + also contains a remote transport field, and an interpolated URL can resolve to + different endpoints from different worktree `.env` files. + + Args: + server: Parsed MCP server definition. + + Returns: + Whether approvals for the definition may be shared across worktrees. + """ + if not isinstance(server, dict) or "command" in server: + return False + url = server.get("url") + if not isinstance(url, str) or "${" in url: + return False + transport = server.get("type") or server.get("transport") + return transport is None or ( + isinstance(transport, str) and transport in _REMOTE_MCP_TRANSPORTS + ) + + +def normalize_mcp_project_root(project_root: str | Path | None) -> str | None: + """Normalize an exact project root for persisted MCP trust comparisons. + + Args: + project_root: Project root path to normalize. + + Returns: + The resolved absolute project root (or the expanded, unresolved path when + `resolve()` raises `OSError`), or `None` when `project_root` is + unavailable. + """ + scope = _normalize_mcp_project_scope(project_root, share_across_worktrees=False) + return scope.identity if scope is not None else None + def fingerprint_mcp_server_config(server: JsonValue) -> str: """Return a stable fingerprint for an MCP server definition. @@ -3589,9 +3744,11 @@ class McpServerTrustLists: Sourced only from the user's own configuration — the home `config.toml`, the global `~/.deepagents/.env`, and shell-exported env — never from a repo, so a - committed `.mcp.json` cannot self-approve. Persisted approvals are scoped to - a resolved project root and the approved server definition's fingerprint. - Env-sourced approvals remain explicit process-wide name approvals. + committed `.mcp.json` cannot self-approve. Persisted approvals for fixed + remote URLs bind to one validated local Git repository. Local commands and + interpolated remote URLs bind to the exact resolved worktree. All include the + server definition's fingerprint. Env-sourced approvals remain explicit + process-wide name approvals. The "reject wins" invariant — a name in both approval and rejection data is only rejected — is enforced in `__post_init__`, so every instance is disjoint @@ -3640,8 +3797,9 @@ class McpServerTrustLists: malformed_approvals: int = field(default=0, compare=False, kw_only=True) """Count of `[mcp].enabled_project_server_approvals` rows that were dropped as - malformed (wrong-typed key, non-table entry, or a table missing/blank - `project_root`/`name`/`fingerprint`). Non-zero means a persisted approval + malformed (wrong-typed key, non-table entry, a table missing/blank + `project_root`/`name`/`fingerprint`, or an invalid Git identity marker). + Non-zero means a persisted approval could not be read, so its server silently re-prompts; callers should surface it (a bare `logger.warning` is invisible outside debug mode) for parity with `legacy_ignored`. Diagnostic, not resolved policy — excluded from equality.""" @@ -3717,7 +3875,23 @@ def is_enabled( ) if approval is None: return False - return approval in self.approvals + if approval in self.approvals: + return True + if not approval.git_common_dir: + return False + + # Approvals written before remote servers gained a shared Git identity + # have no marker and remain bound to their original worktree. Honor that + # exact-root entry there without broadening it to sibling worktrees. + legacy_scope = _normalize_mcp_project_scope( + project_root, share_across_worktrees=False + ) + if legacy_scope is None: + return False + legacy_approval = McpProjectServerApproval._create_for_scope( + scope=legacy_scope, name=name, server=server + ) + return legacy_approval in self.approvals def _parse_csv_env(name: str) -> list[str] | None: @@ -3838,8 +4012,8 @@ def _toml_project_server_approvals( ) if approval is None: logger.warning( - "[mcp].enabled_project_server_approvals in %s ignored an " - "entry missing project_root, name, or fingerprint", + "[mcp].enabled_project_server_approvals in %s ignored a " + "malformed entry", config_path, ) dropped += 1 @@ -3867,10 +4041,13 @@ def load_mcp_server_trust_lists( - `enabled` (permissive): the env var is an explicit process-wide name allowlist. - - `approvals` (permissive): TOML approvals are scoped to project root and a - server-definition fingerprint. They remain active alongside env-enabled - names, so setting the process-wide escape hatch does not discard choices - remembered by the interactive prompt. Legacy flat TOML + - `approvals` (permissive): TOML approvals bind fixed remote URLs to one + validated local Git repository (shared across its worktrees). Local commands + and interpolated remote URLs bind to an exact worktree. All include a + server-definition fingerprint and remain active alongside env-enabled names, + so setting the process-wide escape hatch does not discard choices remembered + by the interactive prompt. + Legacy flat TOML `enabled_project_servers` entries are ignored because they cannot be safely scoped. - `disabled` (restrictive): the env var *unions* with the TOML list — denies @@ -4012,9 +4189,11 @@ def add_enabled_project_mcp_servers( """Persist project-scoped MCP server approvals. Backs the interactive approval prompt's "always allow" choice: the given - names are added to the user-level `config.toml` allowlist with the current - project root and each server definition's fingerprint, so a different repo - or a changed command/URL under the same name asks for approval again. + names are added to the user-level `config.toml` allowlist with each server + definition's fingerprint. Fixed remote URLs use the local Git repository + identity and are shared by its linked worktrees. Local commands and + interpolated remote URLs use the exact worktree root. A different clone or + changed definition asks again. Defaults to the user-level config (`DEFAULT_CONFIG_PATH`), the sole source `load_mcp_server_trust_lists` reads the allowlist from — so writing to the @@ -4048,8 +4227,7 @@ def add_enabled_project_mcp_servers( if not clean_names: return True - normalized_root = normalize_mcp_project_root(project_root) - if normalized_root is None or server_configs is None: + if project_root is None or server_configs is None: logger.error( "Cannot save enabled project MCP servers without project root and " "server definitions" @@ -4062,12 +4240,12 @@ def add_enabled_project_mcp_servers( logger.error("Cannot save unknown project MCP server %r", name) return False approval = McpProjectServerApproval.create( - project_root=normalized_root, name=name, server=server_configs[name] + project_root=project_root, + name=name, + server=server_configs[name], ) if approval is None: - # normalized_root is already non-None here, so create cannot fail; - # guard anyway so a future change can't smuggle in a bad approval. - logger.error("Could not build approval for project MCP server %r", name) + logger.error("Could not normalize project root for MCP server %r", name) return False approvals_to_add.append(approval) diff --git a/libs/code/tests/unit_tests/test_git.py b/libs/code/tests/unit_tests/test_git.py index 22271afd095..53d655d8e9b 100644 --- a/libs/code/tests/unit_tests/test_git.py +++ b/libs/code/tests/unit_tests/test_git.py @@ -13,6 +13,7 @@ _git_dir_cache, _normalize_lookup_path, _parse_git_dir_pointer, + find_git_common_dir, find_git_dir, find_git_root, parse_repository_metadata, @@ -31,6 +32,34 @@ """A valid 40-char SHA-1 used across the commit-resolution tests.""" +def _run_git(root: Path, *args: str) -> None: + """Run Git in a throwaway repository.""" + subprocess.run( + ["git", *args], + cwd=root, + check=True, + capture_output=True, + text=True, + ) + + +def _init_git_repo(root: Path) -> None: + """Create a committed repository suitable for real worktree tests.""" + root.mkdir() + _run_git(root, "init") + _run_git(root, "config", "user.email", "test@example.com") + _run_git(root, "config", "user.name", "Test") + _run_git(root, "config", "commit.gpgsign", "false") + (root / "tracked.txt").write_text("initial\n") + _run_git(root, "add", "tracked.txt") + _run_git(root, "commit", "-m", "initial") + + +def _add_git_worktree(root: Path, worktree: Path, branch: str) -> None: + """Add a linked worktree backed by `root`'s common metadata.""" + _run_git(root, "worktree", "add", "-b", branch, str(worktree), "HEAD") + + @pytest.fixture(autouse=True) def clear_git_dir_cache() -> Iterator[None]: _git_dir_cache.clear() @@ -167,6 +196,188 @@ def test_find_no_repo(self, tmp_path: Path) -> None: assert find_git_root(tmp_path) is None +class TestFindGitCommonDir: + def test_main_and_genuine_sibling_worktrees_share_identity( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + _init_git_repo(main) + _add_git_worktree(main, first, "first") + _add_git_worktree(main, second, "second") + + expected = (main / ".git").resolve() + assert find_git_common_dir(main) == expected + assert find_git_common_dir(first) == expected + assert find_git_common_dir(second) == expected + + def test_direct_pointer_to_another_common_dir_is_rejected( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + forged = tmp_path / "forged" + _init_git_repo(main) + forged.mkdir() + (forged / ".git").write_text(f"gitdir: {main / '.git'}\n") + + assert find_git_common_dir(forged) is None + + def test_independent_repositories_have_distinct_identities( + self, tmp_path: Path + ) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + _init_git_repo(first) + _init_git_repo(second) + + assert find_git_common_dir(first) == (first / ".git").resolve() + assert find_git_common_dir(second) == (second / ".git").resolve() + assert find_git_common_dir(first) != find_git_common_dir(second) + + def test_non_git_directory_has_no_common_identity(self, tmp_path: Path) -> None: + assert find_git_common_dir(tmp_path) is None + + def test_nested_non_repo_directory_does_not_inherit_parent_identity( + self, tmp_path: Path + ) -> None: + outer = tmp_path / "outer" + _init_git_repo(outer) + child = outer / "child" + child.mkdir() + + assert find_git_common_dir(child) is None + + def test_missing_worktree_common_dir_is_rejected(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + _init_git_repo(main) + _add_git_worktree(main, worktree, "worktree") + git_dir = _parse_git_dir_pointer(worktree / ".git") + assert git_dir is not None + (git_dir / "commondir").unlink() + + assert find_git_common_dir(worktree) is None + + def test_malformed_worktree_common_dir_is_rejected(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + _init_git_repo(main) + _add_git_worktree(main, worktree, "worktree") + git_dir = _parse_git_dir_pointer(worktree / ".git") + assert git_dir is not None + (git_dir / "commondir").write_text("../..\nunexpected\n") + + assert find_git_common_dir(worktree) is None + + def test_worktree_missing_head_is_rejected(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + _init_git_repo(main) + _add_git_worktree(main, worktree, "worktree") + git_dir = _parse_git_dir_pointer(worktree / ".git") + assert git_dir is not None + (git_dir / "HEAD").unlink() + + assert find_git_common_dir(worktree) is None + + def test_worktree_missing_backlink_is_rejected(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + _init_git_repo(main) + _add_git_worktree(main, worktree, "worktree") + git_dir = _parse_git_dir_pointer(worktree / ".git") + assert git_dir is not None + (git_dir / "gitdir").unlink() + + assert find_git_common_dir(worktree) is None + + def test_forged_pointer_to_another_worktree_is_rejected( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + genuine = tmp_path / "genuine" + forged = tmp_path / "forged" + _init_git_repo(main) + _add_git_worktree(main, genuine, "genuine") + git_dir = _parse_git_dir_pointer(genuine / ".git") + assert git_dir is not None + forged.mkdir() + (forged / ".git").write_text(f"gitdir: {git_dir}\n") + + assert find_git_common_dir(genuine) == (main / ".git").resolve() + assert find_git_common_dir(forged) is None + + def test_symlinked_stale_backlink_does_not_validate_forged_worktree( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + genuine = tmp_path / "genuine" + forged = tmp_path / "forged" + _init_git_repo(main) + _add_git_worktree(main, genuine, "genuine") + git_dir = _parse_git_dir_pointer(genuine / ".git") + assert git_dir is not None + forged.mkdir() + (forged / ".git").write_text(f"gitdir: {git_dir}\n") + (genuine / ".git").unlink() + (genuine / ".git").symlink_to(forged / ".git") + + assert find_git_common_dir(forged) is None + + def test_self_consistent_forgery_outside_worktrees_dir_is_rejected( + self, tmp_path: Path + ) -> None: + # A fully self-consistent forgery: the attacker's admin dir has a valid + # `commondir` pointing at the victim repo, a present `HEAD`, and a correct + # self-referential `gitdir` backlink. Every acceptance check passes EXCEPT + # the admin dir's location, so the `worktrees/`-parent guard is the only + # defense that rejects it. Removing that guard makes this test fail. + main = tmp_path / "main" + forged = tmp_path / "forged" + _init_git_repo(main) + forged.mkdir() + common = (main / ".git").resolve() + admin = tmp_path / "attacker" / "wt" + admin.mkdir(parents=True) + (admin / "commondir").write_text(f"{common}\n") + (admin / "HEAD").write_text("ref: refs/heads/forged\n") + (admin / "gitdir").write_text(f"{forged.resolve() / '.git'}\n") + (forged / ".git").write_text(f"gitdir: {admin}\n") + + assert admin.parent != common / "worktrees" + assert find_git_common_dir(forged) is None + + def test_symlinked_git_entry_is_rejected(self, tmp_path: Path) -> None: + main = tmp_path / "main" + forged = tmp_path / "forged" + _init_git_repo(main) + forged.mkdir() + (forged / ".git").symlink_to(main / ".git", target_is_directory=True) + + assert find_git_common_dir(forged) is None + + def test_directory_link_is_rejected_even_when_not_reported_as_symlink( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + main = tmp_path / "main" + forged = tmp_path / "forged" + _init_git_repo(main) + forged.mkdir() + git_entry = forged / ".git" + git_entry.symlink_to(main / ".git", target_is_directory=True) + original_is_symlink = Path.is_symlink + + def _hide_git_entry_link(path: Path) -> bool: + if path == git_entry: + return False + return original_is_symlink(path) + + monkeypatch.setattr(Path, "is_symlink", _hide_git_entry_link) + + assert find_git_common_dir(forged) is None + + class TestReadGitBranchFromFilesystem: def test_read_named_branch(self, tmp_path: Path) -> None: git_dir = tmp_path / ".git" diff --git a/libs/code/tests/unit_tests/test_main.py b/libs/code/tests/unit_tests/test_main.py index ddd40956548..3b314789c8d 100644 --- a/libs/code/tests/unit_tests/test_main.py +++ b/libs/code/tests/unit_tests/test_main.py @@ -2461,6 +2461,28 @@ def test_cwd_with_value_stores_value(self) -> None: class TestCheckMcpProjectTrustPrompt: """The project MCP approval prompt should surface a docs link.""" + @staticmethod + def _create_git_repository(root: Path) -> Path: + root.mkdir() + common_dir = root / ".git" + (common_dir / "objects").mkdir(parents=True) + (common_dir / "refs").mkdir() + (common_dir / "worktrees").mkdir() + (common_dir / "HEAD").write_text("ref: refs/heads/main\n") + (common_dir / "config").write_text("[core]\n\tbare = false\n") + return common_dir + + @staticmethod + def _create_git_worktree(common_dir: Path, root: Path, name: str) -> None: + root.mkdir() + git_entry = root / ".git" + git_dir = common_dir / "worktrees" / name + git_dir.mkdir() + git_entry.write_text(f"gitdir: {git_dir}\n") + (git_dir / "commondir").write_text("../..\n") + (git_dir / "gitdir").write_text(f"{git_entry}\n") + (git_dir / "HEAD").write_text(f"ref: refs/heads/{name}\n") + def test_debug_env_helper_uses_truthy_parsing( self, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -3180,6 +3202,124 @@ def test_always_allow_all_excludes_disabled_server( ) assert lists.disabled == frozenset({"reference"}) + def test_existing_remote_sibling_worktree_approval_skips_prompt( + self, + capsys: pytest.CaptureFixture[str], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + from deepagents_code import model_config + from deepagents_code.main import _check_mcp_project_trust + + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = self._create_git_repository(main) + self._create_git_worktree(common_dir, first, "first") + self._create_git_worktree(common_dir, second, "second") + project_cfg = second / ".mcp.json" + project_cfg.write_text("{}") + server_configs = {"docs": {"type": "http", "url": "https://example.test/mcp"}} + user_config = tmp_path / "config.toml" + assert model_config.add_enabled_project_mcp_servers( + ["docs"], + user_config, + project_root=first, + server_configs=server_configs, + ) + monkeypatch.setattr(model_config, "DEFAULT_CONFIG_PATH", user_config) + project_context = SimpleNamespace(project_root=second, user_cwd=second) + + def _no_input(_prompt: str = "") -> str: + msg = "prompt must be skipped for an approved sibling worktree" + raise AssertionError(msg) + + with ( + patch( + "deepagents_code.project_utils.ProjectContext.from_user_cwd", + return_value=project_context, + ), + patch( + "deepagents_code.mcp_tools.discover_mcp_configs", + return_value=[project_cfg], + ), + patch( + "deepagents_code.mcp_tools.classify_discovered_configs", + return_value=([], [project_cfg]), + ), + patch( + "deepagents_code.mcp_tools.load_merged_mcp_configs_lenient", + return_value={"mcpServers": server_configs}, + ), + patch( + "deepagents_code.mcp_tools.extract_project_server_summaries", + return_value=[("docs", "http", "https://example.test/mcp")], + ), + patch("builtins.input", _no_input), + ): + decision = _check_mcp_project_trust(trust_flag=False) + + assert decision is None + assert capsys.readouterr().err == "" + + def test_existing_local_sibling_worktree_approval_prompts( + self, + capsys: pytest.CaptureFixture[str], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + from deepagents_code import model_config + from deepagents_code.main import _check_mcp_project_trust + + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = self._create_git_repository(main) + self._create_git_worktree(common_dir, first, "first") + self._create_git_worktree(common_dir, second, "second") + project_cfg = second / ".mcp.json" + project_cfg.write_text("{}") + server_configs = {"docs": {"command": "python", "args": ["server.py"]}} + user_config = tmp_path / "config.toml" + assert model_config.add_enabled_project_mcp_servers( + ["docs"], + user_config, + project_root=first, + server_configs=server_configs, + ) + monkeypatch.setattr(model_config, "DEFAULT_CONFIG_PATH", user_config) + project_context = SimpleNamespace(project_root=second, user_cwd=second) + + with ( + patch( + "deepagents_code.project_utils.ProjectContext.from_user_cwd", + return_value=project_context, + ), + patch( + "deepagents_code.mcp_tools.discover_mcp_configs", + return_value=[project_cfg], + ), + patch( + "deepagents_code.mcp_tools.classify_discovered_configs", + return_value=([], [project_cfg]), + ), + patch( + "deepagents_code.mcp_tools.load_merged_mcp_configs_lenient", + return_value={"mcpServers": server_configs}, + ), + patch( + "deepagents_code.mcp_tools.extract_project_server_summaries", + return_value=[("docs", "stdio", "python server.py")], + ), + patch("builtins.input", return_value="n"), + ): + decision = _check_mcp_project_trust(trust_flag=False) + + assert decision is False + output = capsys.readouterr().err + assert "Approve project MCP servers" in output + assert '"docs"' in output + def test_all_servers_list_resolved_skip_prompt_without_noise( self, capsys: pytest.CaptureFixture[str], diff --git a/libs/code/tests/unit_tests/test_mcp_tools.py b/libs/code/tests/unit_tests/test_mcp_tools.py index 36de4243797..46cf202ec89 100644 --- a/libs/code/tests/unit_tests/test_mcp_tools.py +++ b/libs/code/tests/unit_tests/test_mcp_tools.py @@ -4477,6 +4477,28 @@ def _stdio(command: str = "echo") -> dict[str, Any]: def _remote(url: str = "https://example.test/mcp") -> dict[str, Any]: return {"type": "sse", "url": url} + @staticmethod + def _create_git_repository(root: Path) -> Path: + root.mkdir() + common_dir = root / ".git" + (common_dir / "objects").mkdir(parents=True) + (common_dir / "refs").mkdir() + (common_dir / "worktrees").mkdir() + (common_dir / "HEAD").write_text("ref: refs/heads/main\n") + (common_dir / "config").write_text("[core]\n\tbare = false\n") + return common_dir + + @staticmethod + def _create_git_worktree(common_dir: Path, root: Path, name: str) -> None: + root.mkdir() + git_entry = root / ".git" + git_dir = common_dir / "worktrees" / name + git_dir.mkdir() + git_entry.write_text(f"gitdir: {git_dir}\n") + (git_dir / "commondir").write_text("../..\n") + (git_dir / "gitdir").write_text(f"{git_entry}\n") + (git_dir / "HEAD").write_text(f"ref: refs/heads/{name}\n") + @staticmethod def _write_user_approvals( user_config: Path, @@ -4619,6 +4641,85 @@ async def test_writer_persisted_approval_loads_through_runtime( assert merged is not None assert set(merged["mcpServers"]) == {"docs"} + async def test_local_approval_does_not_load_in_sibling_worktree( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from deepagents_code import model_config + + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = self._create_git_repository(main) + self._create_git_worktree(common_dir, first, "first") + self._create_git_worktree(common_dir, second, "second") + approved_servers = {"docs": self._stdio("echo")} + self._write_project_config(second, approved_servers) + user_config = tmp_path / "config.toml" + assert model_config.add_enabled_project_mcp_servers( + ["docs"], + user_config, + project_root=first, + server_configs=approved_servers, + ) + + merged = await self._resolve_merged( + second, + monkeypatch, + user_config=user_config, + trust_project_mcp=False, + ) + + assert merged is None + + async def test_remote_approval_loads_in_sibling_but_not_clone_or_new_transport( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from deepagents_code import model_config + + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + clone = tmp_path / "clone" + common_dir = self._create_git_repository(main) + self._create_git_worktree(common_dir, first, "first") + self._create_git_worktree(common_dir, second, "second") + self._create_git_repository(clone) + approved_servers = {"docs": self._remote()} + self._write_project_config(second, approved_servers) + self._write_project_config(clone, approved_servers) + user_config = tmp_path / "config.toml" + assert model_config.add_enabled_project_mcp_servers( + ["docs"], + user_config, + project_root=first, + server_configs=approved_servers, + ) + + sibling_merged = await self._resolve_merged( + second, + monkeypatch, + user_config=user_config, + trust_project_mcp=False, + ) + clone_merged = await self._resolve_merged( + clone, + monkeypatch, + user_config=user_config, + trust_project_mcp=False, + ) + self._write_project_config(second, {"docs": self._stdio("python")}) + changed_merged = await self._resolve_merged( + second, + monkeypatch, + user_config=user_config, + trust_project_mcp=False, + ) + + assert sibling_merged is not None + assert set(sibling_merged["mcpServers"]) == {"docs"} + assert clone_merged is None + assert changed_merged is None + async def test_same_name_in_different_project_is_not_approved( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/libs/code/tests/unit_tests/test_model_config.py b/libs/code/tests/unit_tests/test_model_config.py index 7966c4ca9e1..01075b24354 100644 --- a/libs/code/tests/unit_tests/test_model_config.py +++ b/libs/code/tests/unit_tests/test_model_config.py @@ -68,6 +68,35 @@ ) +def _create_git_common_dir(common_dir: Path) -> Path: + """Create the minimal shared metadata required by Git trust resolution.""" + (common_dir / "objects").mkdir(parents=True) + (common_dir / "refs").mkdir() + (common_dir / "worktrees").mkdir() + (common_dir / "HEAD").write_text("ref: refs/heads/main\n") + (common_dir / "config").write_text("[core]\n\tbare = false\n") + return common_dir + + +def _create_git_repository(root: Path) -> Path: + """Create a worktree with an in-tree Git common directory.""" + root.mkdir() + return _create_git_common_dir(root / ".git") + + +def _create_git_worktree(common_dir: Path, root: Path, name: str) -> Path: + """Create reciprocal linked-worktree metadata under `common_dir`.""" + root.mkdir() + git_entry = root / ".git" + git_dir = common_dir / "worktrees" / name + git_dir.mkdir() + git_entry.write_text(f"gitdir: {git_dir}\n") + (git_dir / "commondir").write_text("../..\n") + (git_dir / "gitdir").write_text(f"{git_entry}\n") + (git_dir / "HEAD").write_text(f"ref: refs/heads/{name}\n") + return git_dir + + @pytest.fixture(autouse=True) def _clear_model_caches() -> Iterator[None]: """Clear module-level caches before and after each test.""" @@ -5957,6 +5986,82 @@ def test_symlink_resolves_to_target(self, tmp_path: Path) -> None: assert normalize_mcp_project_root(link) == normalize_mcp_project_root(target) + def test_main_and_linked_worktree_keep_exact_roots(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + + assert normalize_mcp_project_root(main) == str(main.resolve()) + assert normalize_mcp_project_root(worktree) == str(worktree.resolve()) + assert normalize_mcp_project_root(main) != normalize_mcp_project_root(worktree) + + def test_sibling_worktrees_keep_distinct_roots(self, tmp_path: Path) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + + assert normalize_mcp_project_root(first) == str(first.resolve()) + assert normalize_mcp_project_root(second) == str(second.resolve()) + assert normalize_mcp_project_root(first) != normalize_mcp_project_root(second) + + def test_independent_clones_use_distinct_local_identities( + self, tmp_path: Path + ) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + _create_git_repository(first) + _create_git_repository(second) + + assert normalize_mcp_project_root(first) != normalize_mcp_project_root(second) + + def test_non_git_roots_keep_exact_resolved_paths(self, tmp_path: Path) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + first.mkdir() + second.mkdir() + + assert normalize_mcp_project_root(first) == str(first.resolve()) + assert normalize_mcp_project_root(second) == str(second.resolve()) + assert normalize_mcp_project_root(first) != normalize_mcp_project_root(second) + + def test_missing_worktree_metadata_falls_back_to_exact_root( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + git_dir = _create_git_worktree(common_dir, worktree, "worktree") + (git_dir / "commondir").unlink() + + assert normalize_mcp_project_root(worktree) == str(worktree.resolve()) + + def test_malformed_worktree_metadata_falls_back_to_exact_root( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + git_dir = _create_git_worktree(common_dir, worktree, "worktree") + (git_dir / "commondir").write_text("../..\nunexpected\n") + + assert normalize_mcp_project_root(worktree) == str(worktree.resolve()) + + def test_git_metadata_does_not_change_exact_root(self, tmp_path: Path) -> None: + main = tmp_path / "main" + genuine = tmp_path / "genuine" + forged = tmp_path / "forged" + common_dir = _create_git_repository(main) + git_dir = _create_git_worktree(common_dir, genuine, "genuine") + forged.mkdir() + (forged / ".git").write_text(f"gitdir: {git_dir}\n") + + assert normalize_mcp_project_root(genuine) == str(genuine.resolve()) + assert normalize_mcp_project_root(forged) == str(forged.resolve()) + def test_oserror_falls_back_to_expanded_unresolved_path( self, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -6037,6 +6142,71 @@ def test_create_normalizes_and_fingerprints(self, tmp_path: Path) -> None: fingerprint=fingerprint_mcp_server_config(server), ) + def test_local_server_uses_exact_worktree_root(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + + approval = McpProjectServerApproval.create( + project_root=worktree, + name="docs", + server={"command": "python", "args": ["server.py"]}, + ) + + assert approval is not None + assert approval.project_root == str(worktree.resolve()) + assert approval.git_common_dir is False + + def test_remote_server_uses_shared_git_identity(self, tmp_path: Path) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + + approval = McpProjectServerApproval.create( + project_root=worktree, + name="docs", + server={"url": "https://example.test/mcp"}, + ) + + assert approval is not None + assert approval.project_root == str(common_dir.resolve()) + assert approval.git_common_dir is True + + def test_interpolated_remote_url_uses_exact_worktree_root( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + + approval = McpProjectServerApproval.create( + project_root=worktree, + name="docs", + server={"url": "https://${MCP_HOST}/mcp"}, + ) + + assert approval is not None + assert approval.project_root == str(worktree.resolve()) + assert approval.git_common_dir is False + + def test_scope_marker_participates_in_equality(self) -> None: + exact = McpProjectServerApproval( + project_root="/repo/.git", + name="docs", + fingerprint="sha256:value", + ) + shared = McpProjectServerApproval( + project_root="/repo/.git", + name="docs", + fingerprint="sha256:value", + git_common_dir=True, + ) + + assert exact != shared + def test_create_returns_none_for_unavailable_root(self) -> None: """`create` returns `None` (not a bad approval) when the root is `None`.""" assert ( @@ -6062,6 +6232,60 @@ def test_from_toml_matches_create(self, tmp_path: Path) -> None: assert restored == runtime + def test_marked_git_identity_does_not_rebind_when_metadata_is_stale( + self, tmp_path: Path + ) -> None: + outer = tmp_path / "outer" + _create_git_repository(outer) + nested_common_dir = _create_git_common_dir(outer / "nested.git") + worktree = tmp_path / "worktree" + _create_git_worktree(nested_common_dir, worktree, "worktree") + server = {"type": "http", "url": "https://example.test/mcp"} + runtime = McpProjectServerApproval.create( + project_root=worktree, name="docs", server=server + ) + assert runtime is not None + persisted = runtime.as_toml() + assert persisted["git_common_dir"] is True + (nested_common_dir / "HEAD").unlink() + + restored = McpProjectServerApproval.from_toml(persisted) + outer_approval = McpProjectServerApproval.create( + project_root=outer, name="docs", server=server + ) + + assert restored is not None + assert restored.project_root == str(nested_common_dir.resolve()) + assert restored.git_common_dir is True + assert restored != outer_approval + + def test_from_toml_rejects_non_boolean_git_marker(self) -> None: + assert ( + McpProjectServerApproval.from_toml( + { + "project_root": "/project/.git", + "name": "docs", + "fingerprint": "sha256:value", + "git_common_dir": "true", + } + ) + is None + ) + + def test_from_toml_rejects_relative_marked_root(self) -> None: + """A marked Git identity with a relative root fails closed.""" + assert ( + McpProjectServerApproval.from_toml( + { + "project_root": "relative/project/.git", + "name": "docs", + "fingerprint": "sha256:value", + "git_common_dir": True, + } + ) + is None + ) + def test_from_toml_normalizes_unresolved_root(self, tmp_path: Path) -> None: """A persisted, not-yet-resolved root is normalized on read. @@ -6083,6 +6307,24 @@ def test_from_toml_normalizes_unresolved_root(self, tmp_path: Path) -> None: assert restored == runtime + def test_legacy_exact_root_is_not_broadened_to_git_identity( + self, tmp_path: Path + ) -> None: + project = tmp_path / "project" + _create_git_repository(project) + + restored = McpProjectServerApproval.from_toml( + { + "project_root": str(project), + "name": "docs", + "fingerprint": "sha256:value", + } + ) + + assert restored is not None + assert restored.project_root == str(project.resolve()) + assert restored.git_common_dir is False + def test_from_toml_returns_none_for_malformed(self) -> None: """A table missing or blanking any field yields `None` (fail-closed).""" assert McpProjectServerApproval.from_toml({"name": "docs"}) is None @@ -6106,9 +6348,18 @@ class TestMcpServerTrustListsIsEnabled: def _server() -> dict[str, object]: return {"command": "echo", "args": ["run"]} - def _approval_for(self, root: Path, name: str) -> McpProjectServerApproval: + @staticmethod + def _remote_server() -> dict[str, object]: + return {"type": "http", "url": "https://example.test/mcp"} + + def _approval_for( + self, + root: Path, + name: str, + server: dict[str, object] | None = None, + ) -> McpProjectServerApproval: approval = McpProjectServerApproval.create( - project_root=root, name=name, server=self._server() + project_root=root, name=name, server=server or self._server() ) assert approval is not None return approval @@ -6123,6 +6374,141 @@ def test_exact_scoped_match_is_enabled(self, tmp_path: Path) -> None: assert lists.is_enabled("docs", project_root=tmp_path, server=self._server()) + def test_local_approval_does_not_enable_linked_worktree( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(main, "docs")}), + ) + + assert not lists.is_enabled( + "docs", project_root=worktree, server=self._server() + ) + + def test_remote_approval_is_shared_by_sibling_worktrees( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + server = self._remote_server() + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(first, "docs", server)}), + ) + + assert lists.is_enabled("docs", project_root=second, server=server) + + def test_interpolated_remote_url_is_not_shared_by_sibling_worktrees( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + server: dict[str, object] = {"url": "https://${MCP_HOST}/mcp"} + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(first, "docs", server)}), + ) + + assert not lists.is_enabled("docs", project_root=second, server=server) + + def test_marked_git_approval_does_not_enable_local_server( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + worktree = tmp_path / "worktree" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, worktree, "worktree") + server = self._server() + stale = McpProjectServerApproval( + project_root=str(common_dir.resolve()), + name="docs", + fingerprint=fingerprint_mcp_server_config(server), + git_common_dir=True, + ) + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({stale}), + ) + + assert not lists.is_enabled("docs", project_root=main, server=server) + assert not lists.is_enabled("docs", project_root=worktree, server=server) + + def test_legacy_remote_approval_stays_in_original_worktree( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + server = self._remote_server() + legacy = McpProjectServerApproval( + project_root=str(first.resolve()), + name="docs", + fingerprint=fingerprint_mcp_server_config(server), + ) + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({legacy}), + ) + + assert lists.is_enabled("docs", project_root=first, server=server) + assert not lists.is_enabled("docs", project_root=second, server=server) + + def test_independent_clone_does_not_share_remote_approval( + self, tmp_path: Path + ) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + _create_git_repository(first) + _create_git_repository(second) + server = self._remote_server() + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(first, "docs", server)}), + ) + + assert not lists.is_enabled("docs", project_root=second, server=server) + + def test_forged_worktree_pointer_cannot_borrow_approval( + self, tmp_path: Path + ) -> None: + main = tmp_path / "main" + genuine = tmp_path / "genuine" + forged = tmp_path / "forged" + common_dir = _create_git_repository(main) + git_dir = _create_git_worktree(common_dir, genuine, "genuine") + forged.mkdir() + (forged / ".git").write_text(f"gitdir: {git_dir}\n") + server = self._remote_server() + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(genuine, "docs", server)}), + ) + + assert not lists.is_enabled("docs", project_root=forged, server=server) + def test_blank_name_is_not_enabled(self, tmp_path: Path) -> None: """A blank server name (only from a malformed config) fails closed. @@ -6165,6 +6551,33 @@ def test_changed_definition_not_enabled(self, tmp_path: Path) -> None: server={"command": "echo", "args": ["--exfiltrate"]}, ) + @pytest.mark.parametrize( + ("approved", "current"), + [ + ( + {"command": "echo", "args": ["run"]}, + {"type": "http", "url": "https://example.test/mcp"}, + ), + ( + {"type": "http", "url": "https://example.test/mcp"}, + {"command": "echo", "args": ["run"]}, + ), + ], + ) + def test_transport_change_is_not_enabled( + self, + tmp_path: Path, + approved: dict[str, object], + current: dict[str, object], + ) -> None: + lists = McpServerTrustLists( + enabled=frozenset(), + disabled=frozenset(), + approvals=frozenset({self._approval_for(tmp_path, "docs", approved)}), + ) + + assert not lists.is_enabled("docs", project_root=tmp_path, server=current) + def test_env_enabled_is_project_agnostic(self, tmp_path: Path) -> None: """An env-enabled name matches any project, even with no root at all.""" lists = McpServerTrustLists(enabled=frozenset({"docs"}), disabled=frozenset()) @@ -6173,6 +6586,7 @@ def test_env_enabled_is_project_agnostic(self, tmp_path: Path) -> None: assert lists.is_enabled( "docs", project_root=tmp_path / "anywhere", server=self._server() ) + assert lists.is_enabled("docs", project_root=None, server=self._remote_server()) def test_disabled_name_never_enabled(self, tmp_path: Path) -> None: """A disabled name is rejected regardless of approvals/env.""" @@ -6311,6 +6725,54 @@ def test_reads_approvals_and_disabled_list_from_toml(self, tmp_path: Path) -> No ), ) + def test_legacy_worktree_approvals_remain_exact(self, tmp_path: Path) -> None: + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + fingerprint = fingerprint_mcp_server_config({"command": "echo"}) + roots = [main, first, second] + entries = ",\n".join( + f' {{ project_root = "{root}", name = "docs", ' + f'fingerprint = "{fingerprint}" }}' + for root in roots + ) + config_path = tmp_path / "config.toml" + config_path.write_text( + f"[mcp]\nenabled_project_server_approvals = [\n{entries}\n]\n" + ) + + result = load_mcp_server_trust_lists(config_path) + + assert {approval.project_root for approval in result.approvals} == { + str(root.resolve()) for root in roots + } + assert not any(approval.git_common_dir for approval in result.approvals) + assert result.malformed_approvals == 0 + + def test_marked_git_identity_is_read_from_toml(self, tmp_path: Path) -> None: + """A persisted `git_common_dir = true` row loads as a marked approval.""" + common_dir = _create_git_repository(tmp_path / "main") + fingerprint = fingerprint_mcp_server_config({"url": "https://example.test"}) + config_path = tmp_path / "config.toml" + config_path.write_text( + "[mcp]\n" + "enabled_project_server_approvals = [\n" + f' {{ project_root = "{common_dir}", name = "docs", ' + f'fingerprint = "{fingerprint}", git_common_dir = true }}\n' + "]\n" + ) + + result = load_mcp_server_trust_lists(config_path) + + assert result.malformed_approvals == 0 + assert len(result.approvals) == 1 + (approval,) = result.approvals + assert approval.git_common_dir is True + assert approval.project_root == str(common_dir) + def test_unresolvable_approval_root_is_dropped( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -7112,7 +7574,7 @@ def _server_configs() -> JsonObject: "github": {"command": "gh", "args": ["api"]}, } - def _approvals(self, config_path: Path) -> list[dict[str, str]]: + def _approvals(self, config_path: Path) -> list[dict[str, str | bool]]: import tomllib with config_path.open("rb") as f: @@ -7174,6 +7636,80 @@ def test_appends_and_dedupes(self, tmp_path: Path) -> None: approvals = self._approvals(config_path) assert [approval["name"] for approval in approvals] == ["docs", "reference"] + def test_scopes_mixed_transports_per_server_across_worktrees( + self, tmp_path: Path + ) -> None: + from deepagents_code.model_config import add_enabled_project_mcp_servers + + main = tmp_path / "main" + first = tmp_path / "first" + second = tmp_path / "second" + common_dir = _create_git_repository(main) + _create_git_worktree(common_dir, first, "first") + _create_git_worktree(common_dir, second, "second") + server_configs = self._server_configs() + config_path = tmp_path / "config.toml" + + for project_root in (first, second): + assert add_enabled_project_mcp_servers( + ["docs", "reference"], + config_path, + project_root=project_root, + server_configs=server_configs, + ) + + approvals = self._approvals(config_path) + local = [approval for approval in approvals if approval["name"] == "docs"] + remote = [approval for approval in approvals if approval["name"] == "reference"] + assert {approval["project_root"] for approval in local} == { + str(first.resolve()), + str(second.resolve()), + } + assert all("git_common_dir" not in approval for approval in local) + assert remote == [ + { + "project_root": str(common_dir.resolve()), + "name": "reference", + "fingerprint": fingerprint_mcp_server_config( + server_configs["reference"] + ), + "git_common_dir": True, + } + ] + + def test_nested_external_common_identity_stays_idempotent( + self, tmp_path: Path + ) -> None: + from deepagents_code.model_config import add_enabled_project_mcp_servers + + outer = tmp_path / "outer" + _create_git_repository(outer) + nested_common_dir = _create_git_common_dir(outer / "nested.git") + worktree = tmp_path / "nested-worktree" + _create_git_worktree(nested_common_dir, worktree, "nested") + server_configs = self._server_configs() + config_path = tmp_path / "config.toml" + + assert add_enabled_project_mcp_servers( + ["reference"], + config_path, + project_root=worktree, + server_configs=server_configs, + ) + + approvals = self._approvals(config_path) + assert approvals[0]["project_root"] == str(nested_common_dir.resolve()) + assert approvals[0]["git_common_dir"] is True + lists = load_mcp_server_trust_lists(config_path) + assert lists.is_enabled( + "reference", + project_root=worktree, + server=server_configs["reference"], + ) + assert not lists.is_enabled( + "reference", project_root=outer, server=server_configs["reference"] + ) + def test_removes_migrated_names_from_legacy_approvals(self, tmp_path: Path) -> None: """Scoped approvals consume matching names from the legacy allowlist.""" from deepagents_code.model_config import add_enabled_project_mcp_servers