diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 5395a6706c0..ea1f228515b 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -83,6 +83,24 @@ an entry (`code/app/index/retire.py`) deactivates its rows, runs an erasure saga every `code_*` table for the namespace, and removes the mirror when no other entry uses it on the host that served the call; every other host's sweep removes its own copy. +### A repository's branches + +The entries of one org whose `repo` spells the same repository, whatever remote each +fetches it from, are the repository's members, and `repo_members(org, repo)` in +`code/domain/index/repos.py` is the one place that lists them. They come in the +Repositories page's branch order: `master` or `main` first, then release branches newest +first, then the rest by name. The first is the repository's trunk, and its namespace is +the repository's documents namespace, so every branch reads one set of documents under +the repository's own access rules. + +A request names a branch as `@` in `namespace` +(`namespace_resolve.resolve_branch`, run by the HTTP and MCP admission sequences alike). +`@` is not a namespace character (`server/core/naming.py`), so the form never collides +with a namespace name. The gate then authorizes the namespace the name resolves to, +exactly as it authorizes a namespace named directly, and a branch the repository does not +index, or the caller cannot read, answers `UNKNOWN_BRANCH` naming the branches the caller +can read. + ## Git mirrors on every replica Every serving process can answer a history read (blame, bisect, citations, PR diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index d8976e22e0f..59fab0fbaf4 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -19,6 +19,12 @@ name, or an indexed namespace's name with a longer or shorter commit hash, when caller can read exactly one match. The result says so in `namespace_resolved` ([MCP reference](../../reference/mcp.md#sessions-and-identity)). +On every surface, a code call's `namespace` may name a branch as +`@` (`ClickHouse/ClickHouse@26.4`). It runs on the +namespace that indexes that branch of the repository, and authorization runs on that +namespace as on any other. A branch the repository does not index, or the caller cannot +read, answers `UNKNOWN_BRANCH` and lists the branches the caller can read. + Several ops also take `namespaces=[…]` (up to 8) to ask across branch indexes at once. Every answer that returns results carries a `trace_run_id`; report what you did with the hits through `code.outcome` so ranking learns from it. diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 7dac0d8fe0b..4810979e415 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -964,6 +964,10 @@ Raised in `server/identity/app/me_service_accounts.py`. Raised in `server/transport/arg_check.py`. What to do: [common errors](#common-errors-and-what-to-do). +#### `UNKNOWN_BRANCH` + +HTTP 404, raised as `server.core.errors.UnknownBranchError`. 404 — a code call named `@` and the repository indexes no such branch the caller can read. Category `input`, retryable: no. + #### `UNKNOWN_FIELD` Raised in `server/memory/domain/record_values.py`. diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index d1ec828adc5..649db0c57df 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -303,7 +303,9 @@ What a client gets with and without a plugin is in is refused with `UNKNOWN_NAMESPACE` and the nearest namespaces the caller may be told of (`did_you_mean`). A token whose claim covers every namespace is not refused on the name it gives, so its call runs on that name and nothing is - resolved. Over HTTP a namespace is taken as given. + resolved. Over HTTP a namespace is taken as given, but for a branch spelled + `@`, which a code call resolves on both transports + (`UNKNOWN_BRANCH` for a branch the caller cannot read, with the branches it can). - **Implicit run.** One run per (org, token subject, session), begun in the run ledger by the session's first run-scoped tool call and filed in the caller's default namespace; writes carry its `run_id` (except `run.*`, which diff --git a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb index 5946062a85d..513bc2a0a9d 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb @@ -940,6 +940,11 @@ class UnknownArgument < Error CODE = "UNKNOWN_ARGUMENT" end + # `UNKNOWN_BRANCH`: HTTP 404. 404 — a code call named `@` and the repository indexes no such branch the caller can read. + class UnknownBranch < Error + CODE = "UNKNOWN_BRANCH" + end + # `UNKNOWN_FIELD`: Server code class UnknownField < Error CODE = "UNKNOWN_FIELD" @@ -980,7 +985,7 @@ class WrongCell < Error CODE = "WRONG_CELL" end - # The Error subclass for each server code (195 codes); a code not + # The Error subclass for each server code (196 codes); a code not # listed raises Error itself. ERROR_CLASSES = { "ACTIVITY_UNAVAILABLE" => ActivityUnavailable, @@ -1170,6 +1175,7 @@ class WrongCell < Error "TIMELINE_REQUIRES_FILTER" => TimelineRequiresFilter, "TOKEN_NAME_TAKEN" => TokenNameTaken, "UNKNOWN_ARGUMENT" => UnknownArgument, + "UNKNOWN_BRANCH" => UnknownBranch, "UNKNOWN_FIELD" => UnknownField, "VALIDATION" => Validation, "VALIDATION_FAILED" => ValidationFailed, diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 28ee5819d12..81573be1723 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -95,33 +95,23 @@ async def _settle(tasks: Any, wall_ms: int) -> set[asyncio.Future[Any]]: # ---- branches ---------------------------------------------------------------------- -def release_namespaces(org: str, code_ns: str) -> list[tuple[str, str]]: - """[(namespace, version)] of the release-branch namespaces configured - for the repository `code_ns` indexes, newest first; the trunk itself - never. Operator configuration, not a guess from names.""" - from server.code.domain.index.repos import configured_repos, repo_for_namespace - - me = repo_for_namespace(org, code_ns) - if me is None: - return [] - out: list[tuple[str, str]] = [] - for r in configured_repos(): - if r.org != org or r.namespace == code_ns or r.repo != me.repo: - continue - v = bp.version_key(r.git_branch) - if v is None: - continue - out.append((r.namespace, f"{v[0]}.{v[1]}")) - out.sort(key=lambda x: bp.version_key(x[1]) or (0, 0), reverse=True) - return out - - def resolve_branches(org: str, code_ns: str, wanted: list[str]) -> list[tuple[str, str]]: """The caller's `branches` — a namespace (`code-clickhouse-26-4`) or a release (`26.4`) each — against the configuration; an entry the configuration does not know keeps its name and, when it parses as a - release, that version. Empty → every configured release branch.""" - configured = release_namespaces(org, code_ns) + release, that version. Empty → every configured release branch, newest + first: the other namespaces of the repository `code_ns` indexes whose + branch is a release, never the trunk. Operator configuration, not a guess + from names.""" + from server.code.domain.index.repos import repo_for_namespace, repo_members + + me = repo_for_namespace(org, code_ns) + configured: list[tuple[str, str]] = [] + for r in repo_members(org, me.repo) if me else []: + v = bp.version_key(r.git_branch) + if r.namespace != code_ns and v is not None: + configured.append((r.namespace, f"{v[0]}.{v[1]}")) + configured.sort(key=lambda x: bp.version_key(x[1]) or (0, 0), reverse=True) if not wanted: return configured[:MAX_BRANCHES] by_ns = dict(configured) @@ -535,15 +525,13 @@ async def _ledger_fix() -> PrFacts | None: def branch_refs(org: str, code_ns: str) -> tuple[str, dict[str, str]]: """(the repository's bare mirror, branch namespace → its git ref) from the configuration: what the history leg reads the release branches with.""" - from server.code.domain.index.repos import configured_repos, repo_for_namespace + from server.code.domain.index.repos import repo_for_namespace, repo_members me = repo_for_namespace(org, code_ns) if me is None: return "", {} return me.git_dir, { - r.namespace: r.git_branch - for r in configured_repos() - if r.org == org and r.repo == me.repo and r.namespace != code_ns + r.namespace: r.git_branch for r in repo_members(org, me.repo) if r.namespace != code_ns } diff --git a/server/code/app/memory_links.py b/server/code/app/memory_links.py index b60e50fad1f..92bafe2b9ab 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -30,8 +30,8 @@ from server.code.domain.index.repos import ( RepoConfig, configured_repos, - docs_namespaces, repo_for_namespace, + repo_members, ) from server.code.store.index import CodeRepo from server.settings import settings @@ -49,7 +49,8 @@ def trunk_namespace(org: str, namespace: str) -> str: cfg = repo_for_namespace(org, namespace) if cfg is None: return "" - return docs_namespaces().get((org, cfg.repo), namespace) + members = repo_members(org, cfg.repo) + return members[0].namespace if members else namespace def namespace_for_tags(org: str, tags: list[str]) -> str: diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index b4d31cfca42..129cfa3138c 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -2,7 +2,7 @@ A repository keeps what agents read about it beyond its code (its documents and its decision memories) in one place: its trunk branch's code namespace -(`repos.docs_namespaces`). Every branch of the repository reads that one +(the first of `repos.repo_members`). Every branch of the repository reads that one namespace, and it carries the repository's own access, so a restricted repository's documents and decisions are as restricted as its code. """ @@ -15,8 +15,8 @@ from server.code.domain.index.repos import ( RegistryUnread, configured_repos, - docs_namespaces, repo_for_namespace, + repo_members, ) from server.code.domain.scope import current_code_scope from server.operations.base import Role @@ -30,7 +30,8 @@ def trunk_namespace_of(org: str, code_namespace: str) -> str: cfg = repo_for_namespace(org, code_namespace) if cfg is None: return "" - return docs_namespaces().get((org, str(cfg.repo)), "") + members = repo_members(org, cfg.repo) + return members[0].namespace if members else "" async def readable_repo_namespace(org: str, code_namespace: str) -> str: @@ -62,8 +63,8 @@ def repo_trunk(org: str, repo: str) -> tuple[str, str]: entries = [c for c in configured_repos() if slug and c.org == org and repo_slug(c.repo) == slug] if not entries: return "", "" - # The entries the trunk is chosen from (`docs_namespaces` keys on the spelling of - # `repo`); any of them may be the one that names the remote. + # The entries that spell the repository as the first does; any of them may be the one + # that names the remote. same = [c for c in entries if c.repo == entries[0].repo] tag = next((t for c in same if (t := repo_tag(c.git_remote or c.repo))), "") return trunk_namespace_of(org, entries[0].namespace), tag diff --git a/server/code/app/repos.py b/server/code/app/repos.py index e529f2d2835..a707cf46db7 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -121,7 +121,7 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis # Repositories added from the page appear here as soon as # the snapshot refreshes (TTL-bounded; forced by the add itself). from server.code.app.index.repo_registry import refresh_db_repos - from server.code.domain.index.repos import configured_repos, docs_namespaces + from server.code.domain.index.repos import configured_repos, repo_members await refresh_db_repos() auth = current_auth() @@ -171,7 +171,7 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis ), return_exceptions=True, ) - docs_ns = docs_namespaces() # every entry, not only the listed ones + every = list(configured_repos()) # every entry, not only the listed ones bound = await _bound_trackers() for cfg, readable in gated: key = (cfg.org, cfg.namespace) @@ -184,6 +184,8 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis if readable: st = await _repo_status_cached(cfg) stage = st.state.get(STAGE_KEY) or {} + members = repo_members(cfg.org, cfg.repo, every) + trunk_ns = members[0].namespace if members else "" out.append( CodeRepoSummary( org=st.org, @@ -215,8 +217,8 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis embedding_coverage=st.embedding_coverage, searchable=is_searchable(st.embedding_coverage), has_maintainer=has_maintainer, - docs_namespace=docs_ns.get((cfg.org, cfg.repo), ""), - primary_namespace=docs_ns.get((cfg.org, cfg.repo), ""), + docs_namespace=trunk_ns, + primary_namespace=trunk_ns, # The links as they are, said only to the maintainer bound_trackers=( bound(cfg.org, cfg.namespace) if roles.get(key, "") == "admin" else None diff --git a/server/code/domain/index/repos.py b/server/code/domain/index/repos.py index a53588b62d2..061b4e1da37 100644 --- a/server/code/domain/index/repos.py +++ b/server/code/domain/index/repos.py @@ -778,15 +778,20 @@ def _trunk_rank(branch: str) -> tuple[int, Any]: return (2, branch) -def docs_namespaces(entries: list[RepoConfig] | None = None) -> dict[tuple[str, str], str]: - """(org, repo) → the one namespace the repository's documents live in — its trunk - branch's (the first in the page's branch order), so every branch of the repository - reads the same docs and they carry the repository's own access rules.""" - best: dict[tuple[str, str], RepoConfig] = {} - for c in configured_repos() if entries is None else entries: - key = (c.org, c.repo) - rank = (_trunk_rank(str(c.git_branch or "")), c.namespace) - cur = best.get(key) - if cur is None or rank < (_trunk_rank(str(cur.git_branch or "")), cur.namespace): - best[key] = c - return {k: c.namespace for k, c in best.items()} +def repo_members( + org: str, repo: str, entries: Iterable[RepoConfig] | None = None +) -> list[RepoConfig]: + """Every configured entry of `org` whose `repo` is `repo` as written, in the + Repositories page's branch order: the trunk first, then the release branches newest + first, then the rest by name. The first is the repository's trunk, whose namespace + holds its documents, so every branch reads the same docs under the repository's own + access rules. An entry that fetches the repository from another remote (a fork) is + one of them. `entries` is one snapshot to read, default the configured entries.""" + return sorted( + ( + c + for c in (configured_repos() if entries is None else entries) + if c.org == org and c.repo == repo + ), + key=lambda c: (_trunk_rank(str(c.git_branch or "")), c.namespace), + ) diff --git a/server/core/errors.py b/server/core/errors.py index b0b1b0dad55..8e1ad328d54 100644 --- a/server/core/errors.py +++ b/server/core/errors.py @@ -97,6 +97,25 @@ class NotFoundError(LoomServerError): status_code = 404 +class UnknownBranchError(LoomServerError): + """404 — a code call named `@` and the repository indexes no such + branch the caller can read. `branches` lists the ones the caller can read; retry + with one of them.""" + + code = "UNKNOWN_BRANCH" + status_code = 404 + + def __init__( + self, + message: str = "", + *, + repository: str = "", + branch: str = "", + branches: list[str] | None = None, + ) -> None: + super().__init__(message, repository=repository, branch=branch, branches=branches or []) + + class PreconditionFailedError(LoomServerError): """409 — `if_match_sha256` mismatch, an `approved_sha256` that no longer matches the definition's text, or an erasure that landed while a `namespace.restore` ran. A diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 13ad49ea6d4..77a0a3848a7 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -103,7 +103,7 @@ from server.code.domain.index.remote import repo_tag from server.code.domain.index.repos import ( configured_repos, - docs_namespaces, + repo_members, require_registry_read, ) from server.core import leases @@ -1303,7 +1303,10 @@ def _repo_tag(src: KnowledgeSource) -> str: """`repo:` for a source on a repository's trunk code namespace, else "".""" entries = configured_repos() # one snapshot for both lookups cfg = next((c for c in entries if (c.org, c.namespace) == (src.org, src.namespace)), None) - if cfg is None or docs_namespaces(entries).get((cfg.org, cfg.repo)) != src.namespace: + if cfg is None: + return "" + members = repo_members(cfg.org, cfg.repo, entries) + if members[0].namespace != src.namespace: return "" return repo_tag(cfg.git_remote or cfg.repo) diff --git a/server/transport/gates.py b/server/transport/gates.py index 495d8d3421c..beffdb93bb8 100644 --- a/server/transport/gates.py +++ b/server/transport/gates.py @@ -11,6 +11,9 @@ the request's, else the op's plane default (code.* / tracker.*), else the verified token's own org. A namespace is never authorized without an org: that is a refusal (IDENTITY_INCOMPLETE), not a flat-role pass. +- `with_branch_name`: a code op's `namespace` spelled `@` becomes + the namespace of that branch, before validation, so the gate below authorizes the + namespace it names exactly as it does any other. - `with_single_user_identity`: on a single-user server, a call with no token gets the install's org, and on the everyday memory and search ops (SINGLE_USER_FILLED_OPS) its namespace and the op's agent, where it left @@ -152,10 +155,15 @@ def _plane_default(op: Operation, org: str | None) -> str: return "" +def org_for_op(op_name: str, org: Any, auth: AuthInfo | None) -> str | None: + """The org a call to the op named `op_name` acts in: the request's, else the op's + plane default (code.* / tracker.*), else the verified token's own single org.""" + return present(org) or present(plane_org_for(op_name)) or _token_org(auth) + + def resolve_org(op: Operation, org: Any, auth: AuthInfo | None) -> str | None: - """The org a call acts in: the request's, else the op's plane default - (code.* / tracker.*), else the verified token's own single org.""" - return present(org) or present(plane_org_for(op.name)) or _token_org(auth) + """`org_for_op` of `op`.""" + return org_for_op(op.name, org, auth) def with_resolved_org(op: Operation, args: dict[str, Any], auth: AuthInfo | None) -> dict[str, Any]: @@ -180,6 +188,50 @@ def with_resolved_org(op: Operation, args: dict[str, Any], auth: AuthInfo | None return {**args, **update} if update else args +async def may_read(auth: AuthInfo, org: str, namespace: str) -> tuple[bool, bool]: + """(allowed, unverified): whether the gate admits `auth` to read (org, namespace) + — the claim, a grant (or an inheriting service account's creator's), the + org-readable code rule and the restricted two-factor check, decided by + `check_authorized` alone — and, for a refusal, whether it was made + because a read it needed failed (server.auth.fail_closed): still + refused, but the server's failure.""" + from server.auth.authz import check_authorized + from server.operations.base import Role + + try: + await check_authorized(auth, Role.VIEWER, org=org, namespace=namespace) + except PermissionError as e: + return False, bool(getattr(e, "unverified", False)) + except IdentityIncompleteError: + return False, False + return True, False + + +async def with_branch_name( + op: Operation, args: dict[str, Any], auth: AuthInfo | None +) -> dict[str, Any]: + """The arguments with a code op's `namespace` spelled `@` replaced by the namespace that indexes that branch + (`namespace_resolve.resolve_branch`), so HTTP and MCP resolve it alike before + the gate authorizes the namespace it names, as it authorizes any other. A name + that is not that form, or names no repository, is left for the gate to refuse. + Raises UnknownBranchError for a branch the caller cannot read, and the gate's + PermissionError, marked `unverified`, when a read check could not run. A copy.""" + name = args.get("namespace") + if not (isinstance(name, str) and "@" in name and op.name.startswith("code.")): + return args + org = resolve_org(op, args.get("org"), auth) + if org is None: + return args + from server.transport import namespace_resolve as nr + + async def readable(ns: str) -> tuple[bool, bool]: + return (True, False) if auth is None else await may_read(auth, org, ns) + + resolved = await nr.resolve_branch(org, name.strip(), readable) + return {**args, "namespace": resolved} if resolved else args + + # Ops whose namespace a no-token single-user call may leave out, mapped to the agent # filled when it names none ("": none, so the op reads every agent). Each value is # checked against the op: "http" where it is the writer, or a key read or delete diff --git a/server/transport/http.py b/server/transport/http.py index f747c04dc96..b72f232cd8e 100644 --- a/server/transport/http.py +++ b/server/transport/http.py @@ -36,6 +36,7 @@ AuthInsufficientError, IdentityIncompleteError, LoomServerError, + UnknownBranchError, handler_failure_detail, unverified_class, ) @@ -375,6 +376,31 @@ def _validate_payload(op: Operation, request_id: str, raw_body: Any, auth: AuthI return payload +async def _resolve_branch_name( + op: Operation, call: _HttpCall, args: dict[str, Any] +) -> dict[str, Any]: + """The body with a `@` namespace resolved + (`gates.with_branch_name`), as `_resolve_personal` resolves `@me`: the request + identity, the ledger rows and the gates after validation read the namespace the + call runs on. A branch the caller cannot read is a 404 UNKNOWN_BRANCH naming those + it can; a read check that could not run is the gate's 403 for a failed check.""" + try: + return await gates.with_branch_name(op, args, call.auth) + except UnknownBranchError as e: + raise _refuse(op, call, e.status_code, error_code=e.code, e=e, detail=e.extra) from e + except PermissionError as e: + # Refused as `_authorize` refuses a code index whose check could not run: the + # server's failure, worth a retry, never a branch that is not there. + why = ar.reason_fields(str(args.get("namespace") or ""), unverified=True) + raise _refuse(op, call, 403, error_code=gates.ROLE_REFUSAL_CODE, e=e, detail=why) from e + except LoomServerError as e: + # A read the check could not make past its cache (a 503): counted against the + # server, then answered as raised. + body = _refused_body(call.raw_body, call.auth) + _emit_event(op, call.request_id, body, 0, success=False, error_code=e.code, error=e) + raise + + def _refused_body(raw_body: dict[str, Any], auth: AuthInfo | None) -> dict[str, Any]: """The body a refusal before authorization is ledgered with: one naming an org the token may not act in is recorded in the token's org with @@ -799,6 +825,7 @@ async def endpoint(request: Request, response: Response) -> Any: body = await _read_body(op, request, request_id, auth) call.raw_body = raw_body = await gates.with_single_user_identity(op, body, auth) + call.raw_body = raw_body = await _resolve_branch_name(op, call, raw_body) payload = _validate_payload( op, request_id, gates.with_resolved_org(op, raw_body, auth), auth ) diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index 254d24d13d8..62a954f32a8 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -13,8 +13,8 @@ from server.auth.fanout import knowledge_search_reads_collections from server.code.domain.scope import set_code_scope from server.core.errors import ( - IdentityIncompleteError, LoomServerError, + UnknownBranchError, WrongCellError, classified, unverified_class, @@ -37,22 +37,10 @@ async def _may_read(auth: AuthInfo, org: str, ns: str) -> tuple[bool, bool]: - """(allowed, unverified): whether the gate admits `auth` to read (org, ns) - — the claim, a grant (or an inheriting service account's creator's), the - org-readable code rule and the restricted two-factor check, decided by - `check_authorized` alone — and, for a refusal, whether it was made - because a read it needed failed (server.auth.fail_closed): still - refused, but the server's failure.""" - from server.auth.authz import check_authorized - from server.operations.base import Role + """(allowed, unverified): `gates.may_read`, the one check both transports make.""" + from server.transport import gates - try: - await check_authorized(auth, Role.VIEWER, org=org, namespace=ns) - except PermissionError as e: - return False, bool(getattr(e, "unverified", False)) - except IdentityIncompleteError: - return False, False - return True, False + return await gates.may_read(auth, org, ns) # Where a person asks for a memory namespace's grant in the dashboard, in the namespace @@ -468,6 +456,49 @@ async def _screen_tool_call( raise +async def _branch_namespace( + req: dict[str, Any], + tool_name: Any, + args: dict[str, Any], + auth: AuthInfo, + target_org: str, + org: str, + req_ns: str, + consumer: str, +) -> str | dict[str, Any] | None: + """For a code tool's `namespace` spelled `@` (as + `gates.with_branch_name` reads it on every transport): the namespace of that + branch, written into `args`; the UNKNOWN_BRANCH result, ledgered, for a branch the + caller cannot read; the refusal of the name given, ledgered as the server's, when + a read check could not run; None for any other name. `org` is the one the branch + resolves in, `gates.org_for_op`'s, as on HTTP.""" + from server.transport import namespace_resolve as nr + + if "@" not in req_ns or not str(tool_name or "").startswith("loom_code_"): + return None + + async def readable(ns: str) -> tuple[bool, bool]: + return await _may_read(auth, org, ns) + + try: + to = await nr.resolve_branch(org, req_ns.strip(), readable) + except UnknownBranchError as e: + from server.transport.mcp_refusals import refusal_result + + _ledger_refusal(tool_name, auth, error_code=e.code, org=target_org, consumer=consumer) + return _ok(req.get("id"), refusal_result(e)) + except PermissionError: + refusal = _not_accessible_result(tool_name, auth, req_ns, unverified=True) + code = str(refusal["structuredContent"]["code"]) + _ledger_refusal( + tool_name, auth, error_code=code, org=target_org, server_fault=True, consumer=consumer + ) + return _ok(req.get("id"), refusal) + if to: + args["namespace"] = to + return to + + async def _screen_namespace( req: dict[str, Any], tool_name: Any, @@ -480,7 +511,19 @@ async def _screen_namespace( """The screen's namespace check: None when the caller may read `req_ns` (or the code/tracker index it resolves to, written into `args`), else the refusal, ledgered.""" - allowed, given_unverified = await _may_read(auth, target_org, req_ns) + from server.transport import gates + + # A code call that omits `org` acts in the code plane's, as on HTTP: the org its + # branch resolves in and the namespace it names is then read in. + branch_org = gates.org_for_op("code.", args.get("org"), auth) or target_org + branch = await _branch_namespace( + req, tool_name, args, auth, target_org, branch_org, req_ns, consumer + ) + if isinstance(branch, dict): + return branch # UNKNOWN_BRANCH + read_org = branch_org if branch else target_org + req_ns = branch or req_ns + allowed, given_unverified = await _may_read(auth, read_org, req_ns) if not allowed: # A code/tracker tool's `namespace` that is not a namespace resolves # to one or says so — never the claim text meant for a real refusal. diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index ff3bcfa7ccd..be6120147dd 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -26,6 +26,7 @@ from server.core.errors import ( LoomServerError, SessionProtectionRequiredError, + UnknownBranchError, WrongCellError, unverified_class, ) @@ -286,10 +287,11 @@ async def _call_tool( client_idem_key = _pop_idempotency_key(op, arguments) - validated = _validated_input( + validated = await _named_input( req_id, op, - gates.with_resolved_org(op, arguments, auth), + arguments, + auth, request_id, toolset=toolset, include_example=not explicit_identity, @@ -769,6 +771,47 @@ async def _idempotency_gate( return None, replay.scope, replay.body_hash +async def _named_input( + req_id: Any, + op: Operation, + arguments: dict[str, Any], + auth: Any, + request_id: str, + *, + toolset: str | None = None, + include_example: bool = True, +) -> BaseModel | dict[str, Any]: + """Phase 4 of `_call_tool` with a `@` namespace resolved to + its branch's (`gates.with_branch_name`, as HTTP does), on the arguments as the gate + reads them (`gates.with_resolved_org`). The resolved name is written into + `arguments`, as the screen writes it, so the ledger and admission rows name the + namespace the call runs on. Returns the input model, or the refusal response: + UNKNOWN_BRANCH for a branch the caller cannot read, the gate's refusal + (`_authorize_call`) when a read check could not run, else `_validated_input`'s.""" + try: + named = await gates.with_branch_name(op, arguments, auth) + except UnknownBranchError as e: + _emit_refused(op.name, arguments, error_code=e.code, request_id=request_id, error=e) + return _ok(req_id, refusal_result(e)) + except PermissionError as e: + _emit_refused( + op.name, arguments, error_code=gates.ROLE_REFUSAL_CODE, request_id=request_id, error=e + ) + org = gates.resolve_org(op, arguments.get("org"), auth) + ns = str(arguments.get("namespace") or "") + return _ok(req_id, _forbidden_result(op, e, auth, org, ns)) + if named is not arguments: + arguments["namespace"] = named["namespace"] + return _validated_input( + req_id, + op, + gates.with_resolved_org(op, arguments, auth), + request_id, + toolset=toolset, + include_example=include_example, + ) + + def _validated_input( req_id: Any, op: Operation, diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index 029f64eea52..ca7ccba4ad0 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -9,6 +9,9 @@ ("clickhouse") or a code namespace without its prefix resolves to that repository's code namespace. The call runs there, and the result says so (`namespace_resolved`). +- `@` names the namespace that indexes that branch of + the repository (`resolve_branch`), on HTTP as on MCP. A branch the repository does + not index answers UNKNOWN_BRANCH with the branches the caller reads. - A code namespace named with a longer or shorter commit hash than the indexed one resolves the same way, when the caller reads exactly one such namespace (`revision_matches`). @@ -24,9 +27,12 @@ import difflib import re -from collections.abc import Iterable +from collections.abc import Awaitable, Callable, Iterable from contextvars import ContextVar -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # the registry reads are lazy: no import cycle at runtime + from server.code.domain.index.repos import RepoConfig UNKNOWN_NAMESPACE = "UNKNOWN_NAMESPACE" @@ -88,10 +94,86 @@ def match(name: str, known: dict[str, str], *, default_branch: set[str] | None = return sorted(main or code, key=lambda c: (len(c), c))[0] +def _members(org: str, repo: str) -> list[RepoConfig]: + """The entries of `repo` and of every other spelling of it that `match` takes for + the same repository (case, surrounding slashes), `repo`'s own spelling first.""" + from server.code.domain.index.repos import configured_repos, repo_members + + spellings = { + c.repo for c in configured_repos() if c.org == org and _norm(c.repo) == _norm(repo) + } + spellings.add(repo) + return [ + m for s in sorted(spellings, key=lambda s: (s != repo, s)) for m in repo_members(org, s) + ] + + # A code namespace that ends in a commit hash: (the name up to it, the hash). _REVISION = re.compile(r"^(code-.+)-([0-9a-f]{7,40})$") +async def resolve_branch( + org: str, name: str, may_read: Callable[[str], Awaitable[tuple[bool, bool]]] +) -> str | None: + """The namespace `@` names, for a code call on + any transport. None when `name` is not that form, names no configured repository, + or the caller reads none of the repository's branches: the gate then refuses it + as the namespace it literally is. `@` is not a namespace character + (`server.core.naming`), so the form never collides with a name; a configured + namespace that does hold one (an operator entry is not checked against the rule) + is the name it spells, never a branch. + + `may_read(namespace)` is the gate's read check, `(allowed, unverified)`. A branch + the repository does not index, or that the caller may not read, raises + UnknownBranchError naming the branches the caller reads: one answer for both, so + it confirms no branch the caller cannot read. A check that could not run leaves + the branch unknown, so it is never answered as one that is not there: the gate's + PermissionError, marked `unverified`, and the request is the server's failure + (`server.auth.fail_closed`). The gate still authorizes the namespace this + returns.""" + from server.code.domain.index.repos import RegistryUnread, repo_for_namespace + from server.core.errors import UnknownBranchError + + repository, sep, branch = name.partition("@") + repository, branch = repository.strip(), branch.strip() + if not (sep and repository and branch): + return None + try: + known = known_namespaces(org) + if name in known: # an operator entry is not checked against the name rule + return None + via = match(repository, known, default_branch=default_branches(org)) + cfg = repo_for_namespace(org, via) if via else None + if cfg is None: + return None + members = _members(org, cfg.repo) + except RegistryUnread: + return None + checks = [(m, await may_read(m.namespace)) for m in members if m.git_branch] + readable = [m for m, (allowed, _) in checks if allowed] + hit = next((m for m in readable if m.git_branch == branch), None) + if hit is None and any(unverified for _, (_, unverified) in checks): + from server.auth.fail_closed import note_answered_unverified + + note_answered_unverified() + refused = PermissionError(f"the branches {name!r} names could not be checked") + setattr(refused, "unverified", True) # noqa: B010 — PermissionError declares no field + raise refused + if not readable: + return None + if hit is None: + names = [m.git_branch for m in readable] + raise UnknownBranchError( + f"{cfg.repo!r} indexes no branch {branch!r} that you can read. " + f"Readable branches: {', '.join(names)}.", + repository=cfg.repo, + branch=branch, + branches=names, + ) + RESOLVED.set({"from": name, "to": hit.namespace}) + return hit.namespace + + def revision_matches(name: str, known: Iterable[str]) -> list[str]: """The code namespaces `name` differs from only in the length of its commit hash: the same name up to a trailing hash of 7 to 40 hex characters, and diff --git a/tests/integration/test_repo_at_branch_ledger_live_ch.py b/tests/integration/test_repo_at_branch_ledger_live_ch.py new file mode 100644 index 00000000000..ccb74f839b6 --- /dev/null +++ b/tests/integration/test_repo_at_branch_ledger_live_ch.py @@ -0,0 +1,52 @@ +"""A code call that names a branch as `@` is ledgered under the +namespace it ran on, on live ClickHouse: an erasure export of that namespace finds the rows +both transports wrote, and one of the name as written finds none. + +Skips cleanly when LOOM_CH_HOST is unset. +""" + +from __future__ import annotations + +import asyncio +import os +from typing import Any + +import pytest + +from tests.unit.test_repo_at_branch import ORG, _registry, ledgered_rows, probe + +__all__ = ["_registry", "probe"] # the unit file's fixtures, used here + +pytestmark = pytest.mark.skipif( + not os.environ.get("LOOM_CH_HOST"), + reason="LOOM_CH_HOST not set — integration tests require a live CH", +) + + +def test_an_erasure_of_the_resolved_namespace_finds_the_rows_of_a_branch_named_call( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + from server.core.ch import get_client + from server.erasure.store.exports import export_agent_events + + rows = ledgered_rows(probe, monkeypatch, "Acme/kj@26.7") + ids = {e.request_id for e in rows} + assert len(ids) == 2 + + async def run() -> tuple[set[str], set[str]]: + ch = get_client() + await ch.connect() + try: + # As the event writer flushes them. + await ch.insert( + "loom.agent_events", [e.to_row() for e in rows], settings={"async_insert": 0} + ) + found = await export_agent_events(ORG, "namespace", "code-kj-26-7", limit=10**6, ch=ch) + named = await export_agent_events(ORG, "namespace", "Acme/kj@26.7", limit=10**6, ch=ch) + finally: + await ch.disconnect() + return {r["request_id"] for r in found}, {r["request_id"] for r in named} + + found, named = asyncio.run(run()) + assert ids <= found + assert not ids & named diff --git a/tests/unit/test_backport_release_branch_names.py b/tests/unit/test_backport_release_branch_names.py index 9583c70d762..43d39bc55ed 100644 --- a/tests/unit/test_backport_release_branch_names.py +++ b/tests/unit/test_backport_release_branch_names.py @@ -1,7 +1,7 @@ """A release-branch namespace whose git branch is named `release/26.9` (the private repository's convention) carries the version `26.9` for `code.backport_gap`, like the public `26.9` branch does: -such namespaces stay in `release_namespaces` (no empty version, no `unknown` / +such namespaces stay in the release set (no empty version, no `unknown` / `no_branch_version` verdict), and a bare `26.8` in `branches` resolves to its release branch instead of being refused as a namespace named `26.8`.""" @@ -43,7 +43,7 @@ def _repos(): def test_private_release_namespaces_carry_their_version_newest_first() -> None: with patch("server.code.domain.index.repos.configured_repos", return_value=_repos()): - got = h.release_namespaces("clickhouse", "code-example-private") + got = h.resolve_branches("clickhouse", "code-example-private", []) assert got == [ ("code-example-private-26-9", "26.9"), ("code-example-private-26-8", "26.8"), @@ -51,7 +51,7 @@ def test_private_release_namespaces_carry_their_version_newest_first() -> None: ] # the public repository's set is untouched and never mixes repositories with patch("server.code.domain.index.repos.configured_repos", return_value=_repos()): - assert h.release_namespaces("clickhouse", "code-clickhouse") == [ + assert h.resolve_branches("clickhouse", "code-clickhouse", []) == [ ("code-clickhouse-26-8", "26.8") ] @@ -91,11 +91,11 @@ def test_another_orgs_entries_never_join_the_branch_set() -> None: ] ours = [SimpleNamespace(**{**vars(r), "git_dir": "/ours/mirror"}) for r in _repos()] with patch("server.code.domain.index.repos.configured_repos", return_value=other + ours): - assert h.release_namespaces("clickhouse", "code-clickhouse") == [ + assert h.resolve_branches("clickhouse", "code-clickhouse", []) == [ ("code-clickhouse-26-8", "26.8") ] git_dir, refs = h.branch_refs("clickhouse", "code-clickhouse") assert git_dir == "/ours/mirror" and refs == {"code-clickhouse-26-8": "26.8"} # a namespace this org does not configure has no branches, whoever else does - assert h.release_namespaces("nobody", "code-clickhouse") == [] + assert h.resolve_branches("nobody", "code-clickhouse", []) == [] assert h.branch_refs("nobody", "code-clickhouse") == ("", {}) diff --git a/tests/unit/test_code_backport_gap.py b/tests/unit/test_code_backport_gap.py index 54df5435d1d..da7824398e2 100644 --- a/tests/unit/test_code_backport_gap.py +++ b/tests/unit/test_code_backport_gap.py @@ -188,7 +188,7 @@ def configured(monkeypatch: pytest.MonkeyPatch) -> None: def test_release_namespaces_are_the_same_repository_newest_first(configured) -> None: - got = h.release_namespaces(ORG, NS) + got = h.resolve_branches(ORG, NS, []) assert got[0] == ("code-clickhouse-26-8", "26.8") and got[-1] == ( "code-clickhouse-26-1", "26.1", diff --git a/tests/unit/test_mcp_session_runs.py b/tests/unit/test_mcp_session_runs.py index 52d6e03b7a7..fb2b1cf34c5 100644 --- a/tests/unit/test_mcp_session_runs.py +++ b/tests/unit/test_mcp_session_runs.py @@ -296,7 +296,7 @@ def test_call_tool_stamps_writes_only_and_binds_the_ledger_run() -> None: call = inspect.getsource(mcp_call._call_tool) stamp_at = call.index("_stamp_session_run(op, arguments, defaults, mcp_session_id)") - validate_at = call.index("_validated_input(") + validate_at = call.index("_named_input(") admitted_at = call.index("refused = await _admission_refusal(call)") begin_at = call.index("await _bind_session_run(op, defaults, mcp_session_id, run_caller)") handler_at = call.index("result = await op.handler(input_obj)") diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 4cdfc3a3eb3..0f156cde721 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -169,7 +169,6 @@ async def test_admin_listing_returns_actual_heads_and_counts( repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) monkeypatch.setattr(repo_registry, "refresh_db_repos", AsyncMock(return_value=[])) - monkeypatch.setattr(repos, "docs_namespaces", lambda: {}) monkeypatch.setattr(listing.CodeRepo, "all_state_many", AsyncMock(return_value={})) monkeypatch.setattr( listing, diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py new file mode 100644 index 00000000000..19c0c1bcc51 --- /dev/null +++ b/tests/unit/test_repo_at_branch.py @@ -0,0 +1,750 @@ +"""A code call names a branch as `@`. + +HTTP and MCP resolve the form alike, before the gate: the gate then authorizes the +namespace the name resolves to, as it authorizes any other. A branch the repository +does not index, or the caller cannot read, answers UNKNOWN_BRANCH and names the branches +the caller can read. `repo_members` lists a repository's entries for the docs namespace +and the release set, each answering as the derivation it replaced; the history reads keep +the entries on their own clone. +""" + +from __future__ import annotations + +import asyncio +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +import server.auth.bearer as bearer_mod +import server.transport.mcp_call as mcp_call +import server.transport.mcp_outcome as mcp_outcome +from server.auth.jwt import AuthInfo, TokenError +from server.code.domain.index import repos +from server.operations.base import Operation, Role +from server.operations.registry import OPERATIONS_BY_NAME +from server.settings import settings +from server.settings.catalog import OP_BUDGETS_P99_MS +from server.transport import gates +from server.transport import namespace_resolve as nr +from tests.unit.code_fixtures import repo_config + +ORG = "acme" + + +def _entry(ns: str, repo: str, branch: str, **kw: Any) -> repos.RepoConfig: + return repo_config(org=kw.pop("org", ORG), namespace=ns, repo=repo, git_branch=branch, **kw) + + +ENTRIES = [ + _entry("code-kj-26-7", "Acme/kj", "26.7", git_dir="/m/kj"), + _entry("code-kj-26-10", "Acme/kj", "26.10", git_dir="/m/kj"), + _entry("code-kj", "Acme/kj", "master", git_dir="/m/kj"), + _entry("code-other", "Acme/other", "main", git_dir="/m/other"), + _entry("code-kj", "Acme/kj", "master", org="elsewhere", git_dir="/e/kj"), +] + + +@pytest.fixture(autouse=True) +def _registry(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(repos, "configured_repos", lambda: list(ENTRIES)) + monkeypatch.setattr("server.tracker.domain.namespaces.configured_namespaces", lambda: {}) + + +def _readable(unreadable: set[str] = frozenset(), unchecked: set[str] = frozenset()): # type: ignore[assignment] + """The read check: refused on `unreadable`, and on `unchecked` refused because a read + it needed failed.""" + + async def may_read(ns: str) -> tuple[bool, bool]: + if ns in unchecked: + return False, True + return ns not in unreadable, False + + return may_read + + +def _resolve(name: str, unreadable: set[str] = frozenset()) -> str | None: # type: ignore[assignment] + return _resolved(name, unreadable)[0] + + +def _resolved(name: str, unreadable: set[str] = frozenset()) -> tuple[str | None, Any]: # type: ignore[assignment] + """(the namespace, the note the resolution left): both read in the task that set it.""" + + async def run() -> tuple[str | None, Any]: + nr.RESOLVED.set(None) + got = await nr.resolve_branch(ORG, name, _readable(unreadable)) + return got, nr.RESOLVED.get() + + return asyncio.run(run()) + + +def _unknown_branch(name: str, unreadable: set[str] = frozenset()) -> Any: # type: ignore[assignment] + from server.core.errors import UnknownBranchError + + with pytest.raises(UnknownBranchError) as e: + _resolve(name, unreadable) + return e.value + + +# ------------------------------------------------------------------ the resolver + + +@pytest.mark.parametrize( + ("name", "want"), + [ + ("Acme/kj@26.7", "code-kj-26-7"), # the repository + ("acme/kj@26.10", "code-kj-26-10"), + ("kj@master", "code-kj"), # its name + ("code-kj@26.7", "code-kj-26-7"), # a namespace of it, any branch's + ("code-kj-26-10@master", "code-kj"), + (" kj @ 26.7 ", "code-kj-26-7"), + ], +) +def test_a_repository_or_namespace_with_a_branch_names_that_branchs_namespace( + name: str, want: str +) -> None: + assert _resolved(name) == (want, {"from": name, "to": want}) + + +@pytest.mark.parametrize( + "name", ["kj", "code-kj", "@me", "@26.7", "kj@", "kj@ ", "nosuch@master", "memory-ns@x"] +) +def test_a_name_that_is_no_branch_of_a_repository_is_left_for_the_gate(name: str) -> None: + assert _resolve(name) is None + + +def test_a_configured_namespace_that_holds_an_at_sign_is_the_name_it_spells( + monkeypatch: pytest.MonkeyPatch, +) -> None: + odd = _entry("code-kj@26.7", "Acme/odd", "main", git_dir="/m/odd") + monkeypatch.setattr(repos, "configured_repos", lambda: [*ENTRIES, odd]) + assert _resolve("code-kj@26.7") is None + assert _resolve("kj@26.7") == "code-kj-26-7" + + +def test_the_branches_of_another_org_never_resolve() -> None: + from server.core.errors import UnknownBranchError + + assert asyncio.run(nr.resolve_branch("elsewhere", "kj@master", _readable())) == "code-kj" + with pytest.raises(UnknownBranchError) as e: # that org indexes the repository's trunk only + asyncio.run(nr.resolve_branch("elsewhere", "kj@26.7", _readable())) + assert e.value.extra["branches"] == ["master"] + + +def test_an_unindexed_branch_names_the_branches_the_caller_can_read() -> None: + err = _unknown_branch("Acme/kj@26.9") + assert err.code == "UNKNOWN_BRANCH" and err.status_code == 404 + assert err.extra["repository"] == "Acme/kj" and err.extra["branch"] == "26.9" + assert err.extra["branches"] == ["master", "26.10", "26.7"] # the page's branch order + assert "26.9" in err.message and "master, 26.10, 26.7" in err.message + + +def test_a_branch_the_caller_cannot_read_is_refused_as_an_unindexed_one() -> None: + """One answer for both: a branch the caller cannot read is not confirmed to exist, and + is not listed.""" + hidden = {"code-kj-26-7"} + unreadable = _unknown_branch("kj@26.7", hidden) + unindexed = _unknown_branch("kj@26.9", hidden) + assert unreadable.extra["branches"] == unindexed.extra["branches"] == ["master", "26.10"] + assert unreadable.message.replace("26.7", "X") == unindexed.message.replace("26.9", "X") + + +def test_a_repository_the_caller_reads_no_branch_of_is_left_for_the_gate_to_refuse() -> None: + everything = {"code-kj", "code-kj-26-7", "code-kj-26-10"} + assert _resolve("kj@26.7", everything) is None + + +def test_a_check_that_could_not_run_is_the_servers_failure_never_an_unknown_branch() -> None: + """A branch whose read check failed may be readable: the refusal is the gate's, marked + unverified, and no list of branches is given from a partial check.""" + for asked in ("kj@26.7", "kj@26.9"): + with pytest.raises(PermissionError) as e: + asyncio.run(nr.resolve_branch(ORG, asked, _readable(unchecked={"code-kj-26-7"}))) + assert getattr(e.value, "unverified", False) is True, asked + with pytest.raises(PermissionError): # no branch could be checked + everything = {"code-kj", "code-kj-26-7", "code-kj-26-10"} + asyncio.run(nr.resolve_branch(ORG, "kj@26.7", _readable(unchecked=everything))) + # The branch asked for was checked and is readable: it resolves. + got = asyncio.run(nr.resolve_branch(ORG, "kj@26.10", _readable(unchecked={"code-kj-26-7"}))) + assert got == "code-kj-26-10" + + +def test_a_registry_not_yet_read_resolves_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + def unread() -> list[Any]: + raise repos.RegistryUnread("not read") + + monkeypatch.setattr(repos, "configured_repos", unread) + assert _resolve("kj@26.7") is None + + +# ------------------------------------------------------------------ repo_members + + +def test_repo_members_lists_one_repository_of_one_org_in_the_pages_branch_order() -> None: + got = repos.repo_members(ORG, "Acme/kj") + assert [c.namespace for c in got] == ["code-kj", "code-kj-26-10", "code-kj-26-7"] + assert [c.namespace for c in repos.repo_members("elsewhere", "Acme/kj")] == ["code-kj"] + assert repos.repo_members(ORG, "Acme/nope") == [] + # the repository as its entries spell it, as the documents namespace always grouped + assert repos.repo_members(ORG, "acme/kj") == [] + # a snapshot handed in is the one read + assert repos.repo_members(ORG, "Acme/kj", ENTRIES[:1]) == ENTRIES[:1] + + +def test_an_entry_of_the_repository_on_a_fork_remote_stays_one_of_its_branches( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An entry that spells the repository as the others do and fetches it from a fork is + one of its branches: it reads the trunk's documents, is in its release set, and its + branch resolves, as before `repo_members`.""" + from server.code.app import backport, memory_links, repo_scope + + fork = "https://github.com/SomeFork/kj.git" + entries = [ + *ENTRIES, + _entry("code-kj-fork", "Acme/kj", "26.9", git_dir="/m/kf", git_remote=fork), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert repo_scope.trunk_namespace_of(ORG, "code-kj-fork") == "code-kj" + assert memory_links.trunk_namespace(ORG, "code-kj-fork") == "code-kj" + assert backport.resolve_branches(ORG, "code-kj", []) == [ + ("code-kj-26-10", "26.10"), + ("code-kj-fork", "26.9"), + ("code-kj-26-7", "26.7"), + ] + assert "code-kj-fork" in backport.branch_refs(ORG, "code-kj")[1] + assert _resolve("kj@26.9") == "code-kj-fork" + + +def test_a_repository_configured_under_two_spellings_resolves_a_branch_of_either( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`match` finds a repository by its normalized spelling, so the branches listed + for it must be found the same way: an entry that spells it `acme/kj` is a branch + of `Acme/kj`, whichever spelling the name lands on.""" + entries = [ + *ENTRIES, + _entry("code-kj-27-1", "acme/kj", "27.1", git_dir="/m/kj"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert _resolve("kj@27.1") == "code-kj-27-1" + assert _resolve("kj@26.7") == "code-kj-26-7" + assert _resolve("code-kj-27-1@master") == "code-kj" + err = _unknown_branch("kj@nope") + assert "27.1" in str(err) and "26.7" in str(err) + + +# ------------------------------------------------------------------ both transports + + +class _In(BaseModel): + org: str = "" + namespace: str = "" + + +class _Out(BaseModel): + ok: bool = True + + +TOOL = "loom_code_test_branch_probe" + + +@pytest.fixture +def probe(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """One code op on both transports; the gate records the (org, namespace) it + authorizes and refuses subject "intruder"; the read check refuses `unreadable`.""" + import server.code.app.member_writes as member_writes + from server.transport import http as http_mod + + seen: dict[str, Any] = { + "authz": [], + "ran": [], + "ledger": [], + "unreadable": set(), + "unchecked": set(), + } + + async def _handler(inp: Any) -> _Out: + seen["ran"].append(inp.namespace) + return _Out() + + op = Operation( + name="code.test_branch_probe", + input_model=_In, + output_model=_Out, + handler=_handler, + idempotent=False, + required_role=Role.VIEWER, + ) + + async def _authorize_op(auth: Any, op_: Any, *, org: Any, namespace: Any, **_k: Any) -> None: + seen["authz"].append((org, namespace)) + if auth.subject == "intruder": + raise PermissionError("not a member") + + async def _may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + if ns in seen["unchecked"]: + return False, True + return ns not in seen["unreadable"], False + + async def _noop(*_a: Any, **_k: Any) -> None: + return None + + tokens = { + "alice": AuthInfo( + subject="alice", + org=ORG, + namespaces=("*",), + roles=(Role.WRITER,), + is_service_account=True, + ), + "intruder": AuthInfo( + subject="intruder", + org=ORG, + namespaces=("*",), + roles=(Role.WRITER,), + is_service_account=True, + ), + } + + def _verify(token: str) -> AuthInfo: + if token not in tokens: + raise TokenError("bad token") + return tokens[token] + + monkeypatch.setattr(member_writes, "authorize_op", _authorize_op) + monkeypatch.setattr(gates, "may_read", _may_read, raising=False) + monkeypatch.setattr("server.transport.gates._admitted", _noop) + monkeypatch.setattr("server.auth.personal_namespace.ensure_personal_namespace_cached", _noop) + monkeypatch.setattr(settings, "code_org", ORG) + monkeypatch.setattr(settings, "code_namespace", "code-kj") + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(http_mod, "ALL_OPERATIONS", [op]) + monkeypatch.setitem(OP_BUDGETS_P99_MS, op.name, 10_000) + monkeypatch.setattr(bearer_mod, "authenticate_token", AsyncMock(side_effect=_verify)) + seen["http_emit"] = http_mod._emit_event # the ledger writer, for a test that reads its rows + monkeypatch.setattr( + http_mod, "_emit_event", lambda *a, **k: seen["ledger"].append(("http", k["error_code"])) + ) + app = FastAPI() + app.include_router(http_mod.build_router()) + seen["http"] = TestClient(app) + seen["tokens"] = tokens + monkeypatch.setitem(mcp_call.TOOLS_BY_NAME, TOOL, op) + + async def _no_defaults(auth: Any, client_name: str | None = None) -> None: + return None + + monkeypatch.setattr(mcp_call, "_caller_defaults", _no_defaults) + for mod in (mcp_call, mcp_outcome): + monkeypatch.setattr( + mod, + "_emit_mcp_event", + lambda *a, **k: seen["ledger"].append(("mcp", k.get("error_code", ""))), + ) + return seen + + +def _http(seen: dict[str, Any], who: str, namespace: str) -> Any: + return seen["http"].post( + "/v1/code.test_branch_probe", + json={"org": ORG, "namespace": namespace}, + headers={"Authorization": f"Bearer {who}"}, + ) + + +def _mcp(seen: dict[str, Any], who: str, namespace: str) -> dict[str, Any]: + params = {"name": TOOL, "arguments": {"org": ORG, "namespace": namespace}} + return asyncio.run(mcp_call._call_tool(1, params, auth=seen["tokens"][who]))["result"] # type: ignore[no-any-return] + + +def test_both_transports_authorize_and_run_on_the_namespace_a_branch_name_resolves_to( + probe: dict[str, Any], +) -> None: + r = _http(probe, "alice", "Acme/kj@26.7") + assert r.status_code == 200, r.text + out = _mcp(probe, "alice", "Acme/kj@26.7") + assert out["isError"] is False + want = (ORG, "code-kj-26-7") + assert probe["authz"] == [want, want] + assert probe["ran"] == ["code-kj-26-7", "code-kj-26-7"] + + +def _ledger_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """The list the probe op's ledger rows land in from here on, as the transports hand + them to the event writer.""" + from server.observability import ledger + from server.transport import http as http_mod + from server.transport import mcp_tools + + rows: list[Any] = [] + monkeypatch.setattr(http_mod, "_emit_event", probe["http_emit"]) + for mod in (mcp_call, mcp_outcome): + monkeypatch.setattr(mod, "_emit_mcp_event", mcp_tools._emit_mcp_event) + monkeypatch.setattr(ledger, "_dispatch_event", lambda e: rows.append(e) or True) + return rows + + +def ledgered_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: + """The ledger rows of one served call on each transport that names `name`.""" + rows = _ledger_rows(probe, monkeypatch) + assert _http(probe, "alice", name).status_code == 200 + assert _mcp(probe, "alice", name)["isError"] is False + return [e for e in rows if e.operation == "code.test_branch_probe"] + + +def test_a_served_call_is_ledgered_under_the_namespace_it_ran_on( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The identity tuple of the row is the namespace the call ran on, so the namespace's + activity, usage and erasure reach it; the branch name the caller wrote is nowhere in + it.""" + rows = ledgered_rows(probe, monkeypatch, "Acme/kj@26.7") + assert [(e.transport, e.org, e.namespace, e.success) for e in rows] == [ + ("http", ORG, "code-kj-26-7", True), + ("mcp", ORG, "code-kj-26-7", True), + ] + assert all("Acme/kj@26.7" not in e.args.values() for e in rows) + + +def test_the_gate_still_refuses_the_resolved_namespace_to_a_caller_it_does_not_admit( + probe: dict[str, Any], +) -> None: + r = _http(probe, "intruder", "kj@26.7") + assert r.status_code == 403 and r.json()["detail"]["code"] == "AUTH_INSUFFICIENT" + out = _mcp(probe, "intruder", "kj@26.7") + assert out["isError"] and out["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert probe["authz"] == [(ORG, "code-kj-26-7")] * 2 # the namespace it names, not the form + assert probe["ran"] == [] + + +def test_an_unreadable_or_unindexed_branch_is_refused_before_the_gate_on_both( + probe: dict[str, Any], +) -> None: + probe["unreadable"] = {"code-kj-26-7"} + for name in ("kj@26.7", "kj@26.9"): + r = _http(probe, "alice", name) + detail = r.json()["detail"] + assert r.status_code == 404 and detail["code"] == "UNKNOWN_BRANCH", r.text + assert detail["branches"] == ["master", "26.10"] + out = _mcp(probe, "alice", name) + assert out["isError"] and out["structuredContent"]["code"] == "UNKNOWN_BRANCH" + assert out["structuredContent"]["branches"] == ["master", "26.10"] + assert probe["authz"] == [] and probe["ran"] == [] + assert probe["ledger"] == [("http", "UNKNOWN_BRANCH"), ("mcp", "UNKNOWN_BRANCH")] * 2 + + +def test_a_check_that_could_not_run_is_refused_as_the_servers_failure_on_both( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """Not UNKNOWN_BRANCH, the caller's error: the gate's refusal, marked as the check's + failure, as the gate answers its own failed check on each transport.""" + probe["unchecked"] = {"code-kj-26-7"} + rows = _ledger_rows(probe, monkeypatch) + r = _http(probe, "alice", "kj@26.7") + detail = r.json()["detail"] + assert r.status_code == 403 and detail["code"] == "AUTH_INSUFFICIENT", r.text + assert detail["retry"] is True and detail["category"] == "dependency" + out = _mcp(probe, "alice", "kj@26.7") + assert out["isError"] and out["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert probe["authz"] == [] and probe["ran"] == [] + assert [(e.transport, e.error_code, e.status_class) for e in rows] == [ + ("http", "AUTH_INSUFFICIENT", "server"), + ("mcp", "AUTH_INSUFFICIENT", "server"), + ] + + +def test_a_name_that_is_no_branch_form_reaches_the_gate_as_given(probe: dict[str, Any]) -> None: + for name in ("code-kj", "nosuch@master"): + _http(probe, "alice", name) + _mcp(probe, "alice", name) + assert probe["authz"] == [ + (ORG, "code-kj"), + (ORG, "code-kj"), + (ORG, "nosuch@master"), + (ORG, "nosuch@master"), + ] + + +def test_only_a_code_op_reads_the_form() -> None: + args = {"org": ORG, "namespace": "kj@26.7"} + for name, want in ( + ("code.search", "code-kj-26-7"), + ("memory.search", "kj@26.7"), + ("tracker.item", "kj@26.7"), + ): + got = asyncio.run(gates.with_branch_name(OPERATIONS_BY_NAME[name], args, None)) + assert got["namespace"] == want, name + assert args["namespace"] == "kj@26.7" # a copy + + +# ------------------------------------------------------------------ the MCP screen + + +class _Auth: + org = ORG + subject = "sa:agent-x" + + def can_access(self, org: str, ns: str) -> bool: + return True + + +def _screen( # type: ignore[no-untyped-def] + monkeypatch: pytest.MonkeyPatch, + tool: str, + namespace: str, + unreadable: set[str], + unchecked: set[str] = frozenset(), # type: ignore[assignment] +): + from server.transport import mcp_auth + + async def may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + if ns in unchecked: + return False, True + return ns not in unreadable, False + + monkeypatch.setattr(gates, "may_read", may_read, raising=False) + args = {"namespace": namespace, "query": "q"} + req = { + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": tool, "arguments": args}, + } + + async def run() -> tuple[Any, Any]: + refused = await mcp_auth._screen_tool_call(req, _Auth()) # type: ignore[arg-type] + return refused, nr.RESOLVED.get() + + refused, note = asyncio.run(run()) + return refused, args, note + + +def test_the_mcp_screen_rewrites_a_branch_name_and_notes_the_resolution( + monkeypatch: pytest.MonkeyPatch, +) -> None: + refused, args, note = _screen(monkeypatch, "loom_code_search", "Acme/kj@26.10", set()) + assert refused is None and args["namespace"] == "code-kj-26-10" + assert note == {"from": "Acme/kj@26.10", "to": "code-kj-26-10"} + + +def test_the_mcp_screen_answers_unknown_branch_for_an_unreadable_or_unindexed_one( + monkeypatch: pytest.MonkeyPatch, +) -> None: + for name in ("kj@26.7", "kj@26.9"): + refused, args, _ = _screen(monkeypatch, "loom_code_search", name, {"code-kj-26-7"}) + assert refused is not None and refused["id"] == 7 + body = refused["result"]["structuredContent"] + assert body["code"] == "UNKNOWN_BRANCH" and body["branches"] == ["master", "26.10"] + assert args["namespace"] == name # nothing was rewritten + + +def test_the_mcp_screen_refuses_a_check_that_could_not_run_as_the_servers_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.transport import mcp_auth + + faults: list[bool] = [] + monkeypatch.setattr( + mcp_auth, "_ledger_refusal", lambda *a, **k: faults.append(k.get("server_fault", False)) + ) + refused, args, _ = _screen(monkeypatch, "loom_code_search", "kj@26.7", set(), {"code-kj-26-7"}) + assert refused is not None + assert refused["result"]["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert args["namespace"] == "kj@26.7" and faults == [True] + + +def test_the_mcp_screen_leaves_a_tracker_tool_alone(monkeypatch: pytest.MonkeyPatch) -> None: + refused, args, note = _screen(monkeypatch, "loom_tracker_search", "kj@26.7", set()) + assert args["namespace"] == "kj@26.7" and note is None + assert refused is None # the form is a code call's: the tracker gate reads the name as given + + +# ------------------------------------------------------------------ the callers keep their answers +# +# The two derivations `repo_members` replaced, as they were: each caller's answer on one +# configuration must equal theirs. + + +def _was_docs_namespaces(entries: list[Any]) -> dict[tuple[str, str], str]: + best: dict[tuple[str, str], Any] = {} + for c in entries: + key = (c.org, c.repo) + rank = (repos._trunk_rank(str(c.git_branch or "")), c.namespace) + cur = best.get(key) + if cur is None or rank < (repos._trunk_rank(str(cur.git_branch or "")), cur.namespace): + best[key] = c + return {k: c.namespace for k, c in best.items()} + + +def _was_release_namespaces(entries: list[Any], org: str, ns: str) -> list[tuple[str, str]]: + from server.tracker.domain import backport as bp + + me = next((c for c in entries if (c.org, c.namespace) == (org, ns)), None) + if me is None: + return [] + out = [] + for r in entries: + if r.org != org or r.namespace == ns or r.repo != me.repo: + continue + v = bp.version_key(r.git_branch) + if v is not None: + out.append((r.namespace, f"{v[0]}.{v[1]}")) + out.sort(key=lambda x: bp.version_key(x[1]) or (0, 0), reverse=True) + return out + + +def test_the_docs_namespace_and_the_release_set_answer_as_they_did( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.code.app import backport, memory_links, repo_scope + + entries = [ + *ENTRIES, + _entry("code-w-dev", "Acme/w", "dev", git_dir="/m/w"), + _entry("code-w-26-1", "Acme/w", "26.1", git_dir="/m/w"), + _entry("code-w-26-3", "Acme/w", "release/26.3", git_dir="/m/w"), + _entry("code-w-26-4", "Acme/w", "26.4", git_dir="/m/wf", git_remote="https://f.example/w"), + _entry("code-w-26-2", "acme/w", "26.2", git_dir="/m/w"), # another spelling + _entry("code-z-b", "Acme/z", "beta", git_dir="/m/z"), + _entry("code-z-a", "Acme/z", "alpha", git_dir="/m/z"), + _entry("code-w-elsewhere", "Acme/w", "26.9", org="elsewhere", git_dir="/e/w"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + docs = _was_docs_namespaces(entries) + for c in entries: + assert repo_scope.trunk_namespace_of(c.org, c.namespace) == docs[(c.org, c.repo)] + assert memory_links.trunk_namespace(c.org, c.namespace) == docs[(c.org, c.repo)] + assert ( + backport.resolve_branches(c.org, c.namespace, []) + == _was_release_namespaces(entries, c.org, c.namespace)[: backport.MAX_BRANCHES] + ) + assert repo_scope.trunk_namespace_of(ORG, "code-nosuch") == "" + assert backport.resolve_branches(ORG, "code-nosuch", []) == [] + + +class _Stop(Exception): + """Raised where a history read is handed its siblings: nothing after it runs.""" + + +def _history_siblings(monkeypatch: pytest.MonkeyPatch, op: str, ns: str) -> list[str]: + """The siblings `code.blame_range` or `code.first_build` hands its history reads, for + a call on `ns`.""" + from types import SimpleNamespace + + from server.code.app import blame, first_build + + mod = blame if op == "blame_range" else first_build + seen: list[str] = [] + + def stop(*args: Any) -> Any: + seen.extend(c.namespace for c in next(a for a in args if isinstance(a, list))) + raise _Stop + + async def git_dir(cfg: Any, op: str, **_k: Any) -> tuple[str, str]: + return cfg.git_dir, "" + + async def no_head(*_a: Any) -> str: + return "" + + monkeypatch.setattr(mod, "require_code_intel", lambda: None) + monkeypatch.setattr(mod, "resolve_code_identity", lambda o, n: (ORG, ns)) + monkeypatch.setattr(mod, "CodeRepo", lambda: object()) + # The seam each handler reads: blame reaches the resolver on the mirrors + # module it imports, first_build imported the name itself. + if op == "blame_range": + monkeypatch.setattr(blame.mirrors, "history_dir", git_dir) + else: + monkeypatch.setattr(first_build, "history_dir", git_dir) + monkeypatch.setattr(blame, "history_enabled", lambda: True) + monkeypatch.setattr(blame, "_namespace_head", no_head) + monkeypatch.setattr(blame, "_resolve_window", stop) + monkeypatch.setattr(first_build, "IndexedView", stop) + inp = SimpleNamespace( + org=ORG, + namespace=ns, + sha="a" * 40, + pr_number=0, + path="a.py", + start_line=1, + end_line=2, + stage="", + to_sha="a" * 40, + to_version="", + from_sha="", + from_version="", + ) + handler = ( + blame.handle_code_blame_range + if op == "blame_range" + else first_build.handle_code_first_build + ) + with pytest.raises(_Stop): + asyncio.run(handler(inp)) + return seen + + +@pytest.mark.parametrize("op", ["blame_range", "first_build"]) +def test_the_history_reads_keep_the_entries_on_their_own_clone( + monkeypatch: pytest.MonkeyPatch, op: str +) -> None: + """A branch the operator gave its own clone is no sibling of the others: a history + read resolves its refs in one clone. The entries on that clone are, however the + repository is spelled, in the configuration's order.""" + entries = [ + _entry("code-x-26-1", "Acme/x", "26.1", git_dir="/m/x-own"), + _entry("code-x", "Acme/x", "master", git_dir="/m/x"), + _entry("code-x-26-2", "acme/x", "26.2", git_dir="/m/x"), + _entry("code-x-26-3", "Acme/x", "26.3", git_dir="/m/x"), + _entry("code-x", "Acme/x", "master", org="elsewhere", git_dir="/m/x"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert _history_siblings(monkeypatch, op, "code-x") == ["code-x", "code-x-26-2", "code-x-26-3"] + assert _history_siblings(monkeypatch, op, "code-x-26-1") == ["code-x-26-1"] + + +def test_an_omitted_org_resolves_and_reads_in_the_code_plane_org_on_both_transports( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A code call that names no org acts in the code plane's, not the token's: the + branch resolves there and the namespace it names is read there, on HTTP (the + resolver the transport calls) and on the MCP screen.""" + from server.transport import mcp_auth + + plane = "plane" + entries = [ + *ENTRIES, + _entry("code-pl-26-7", "Acme/pl", "26.7", org=plane, git_dir="/p/pl"), + _entry("code-pl", "Acme/pl", "master", org=plane, git_dir="/p/pl"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + monkeypatch.setattr(settings, "code_org", plane) + reads: list[tuple[str, str]] = [] + + async def may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + reads.append((org, ns)) + return True, False + + monkeypatch.setattr(gates, "may_read", may_read, raising=False) + + op = OPERATIONS_BY_NAME["code.search"] + http = asyncio.run(gates.with_branch_name(op, {"namespace": "pl@26.7"}, _Auth())) # type: ignore[arg-type] + http_reads = list(reads) + reads.clear() + + args = {"namespace": "pl@26.7", "query": "q"} + req = { + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": "loom_code_search", "arguments": args}, + } + assert asyncio.run(mcp_auth._screen_tool_call(req, _Auth())) is None # type: ignore[arg-type] + assert http["namespace"] == args["namespace"] == "code-pl-26-7" + # the screen then reads the namespace it resolved to: in that org too, never the token's + assert reads[: len(http_reads)] == http_reads and reads[-1] == (plane, "code-pl-26-7") + assert {org for org, _ in reads} == {plane} diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index d693476b0ca..dad1630ee3b 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -29,6 +29,11 @@ def _cfg(ns: str, repo: str, branch: str) -> Any: return SimpleNamespace(org=ORG, namespace=ns, repo=repo, git_branch=branch) +def _docs_namespace(repo: str) -> str: + """The first of the repository's members: the namespace its documents live in.""" + return repos.repo_members(ORG, repo)[0].namespace + + ENTRIES = [ _cfg("code-kj-26-7", "Acme/kj", "26.7"), _cfg("code-kj-26-10", "Acme/kj", "26.10"), @@ -81,18 +86,16 @@ def _repos(monkeypatch): def test_the_docs_namespace_is_the_trunk_branchs_the_page_order() -> None: - assert repos.docs_namespaces() == { - (ORG, "Acme/kj"): "code-kj", # master first - (ORG, "Acme/w"): "code-w-26-1", # then release branches, newest first - (ORG, "Acme/z"): "code-z-a", # then by name - } + assert _docs_namespace("Acme/kj") == "code-kj" # master first + assert _docs_namespace("Acme/w") == "code-w-26-1" # then release branches, newest first + assert _docs_namespace("Acme/z") == "code-z-a" # then by name # every branch of a repository reads one namespace, its trunk's trunk = repo_scope.trunk_namespace_of(ORG, "code-kj-26-7") assert trunk == "code-kj" assert repo_scope.trunk_namespace_of(ORG, "memory-ns") == "" ENTRIES.append(_cfg("code-kj-27-1", "Acme/kj", "27.1")) try: - assert repos.docs_namespaces()[(ORG, "Acme/kj")] == "code-kj" + assert _docs_namespace("Acme/kj") == "code-kj" assert repos._trunk_rank("26.10") < repos._trunk_rank("26.7") # numeric, not lexical finally: ENTRIES.pop() diff --git a/tests/unit/test_sdk_errors_from_response.py b/tests/unit/test_sdk_errors_from_response.py index 615825e10ff..f94d3fd20b3 100644 --- a/tests/unit/test_sdk_errors_from_response.py +++ b/tests/unit/test_sdk_errors_from_response.py @@ -124,6 +124,7 @@ def test_a_5xx_is_backend_unavailable_and_a_429_rate_limited_whatever_the_code() "AUTH_INSUFFICIENT": AuthInsufficient, "IDENTITY_INCOMPLETE": ValidationError, "RESOURCE_NOT_FOUND": NotFound, + "UNKNOWN_BRANCH": NotFound, # a 404 with no SDK class: mapped by status "PRECONDITION_FAILED": PreconditionFailed, "GRANT_WOULD_DOWNGRADE": PreconditionFailed, "READS_LLM_FREE": PreconditionFailed,