diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 2299dadb8b..d9ccca4f42 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -180,7 +180,9 @@ grant row on the namespace, of any status, the claim is capped at that grant ins pending or rejected request caps it at no access, and a scoped token keeps its own role there capped at the live grant. A namespace the subject never held a grant on (a `loom mint-token` claim) keeps the claim; grant rows are never deleted, so a revocation is never -forgotten. +forgotten. A `*` claim names no namespace, so no grant caps it, and a platform +administrator's own authority on a namespace that is not a repository is not capped +either: neither comes from a grant. - The subject's rows, under every spelling the directory ties to it, are read in one statement per (org, subject) into a per-process cache (`server/core/grant_cache.py`) kept @@ -280,14 +282,25 @@ authenticated call, from `gates.authorize` in both transports: exception below. 4. An authenticated platform administrator using its own unscoped authority reads every configured or registered repository, including closed and restricted entries. Deployment - tenancy still applies. This authority does not admit writes or any other namespace kind. + tenancy still applies. This authority admits no repository write. 5. A viewer read of an org-readable code namespace (`LOOM_CODE_ORG_READABLE` or the entry's `org_readable`) passes for any principal of that org. 6. A scoped token's `ns_roles` decide for the namespaces they name, in the token's org only. Grants are not consulted for them, except viewer reads of a code namespace. 7. A token acts in its own org only (or `*`, or as platform admin). -8. A flat token's roles apply to every namespace its claims cover. Otherwise a live grant - in `loom.namespace_grants` decides: unrevoked and `active` (`grant_sql.LIVE_GRANT`); a +8. A flat token's roles apply to every namespace its claims cover. A platform + administrator's own unscoped authority (`authz.is_own_platform_admin`) covers every + namespace of every org that reaches this step but a repository, whatever its claims + name, as a `*` claim covers its own org's; an `ns_write` claim still bounds its writes. + A third-party client's sign-in session (an OAuth session that is not Loom's own, + `first_party` false) has none of this authority. + For a read, a repository is an entry this process's configuration or registry + snapshot holds (`NamespaceDirectory.code_entry`). For a write, it is also a namespace + with an active registry row read at the write (`NamespaceDirectory.is_repository`), so + one another replica added a moment ago is one, and a registry that cannot be read + covers no write. A directory row's `kind` makes no repository. Where neither the + claims nor platform authority cover the namespace, a live grant in + `loom.namespace_grants` decides: unrevoked and `active` (`grant_sql.LIVE_GRANT`); a `pending` join request grants nothing. A service account with no grant reads its creator's. A grant raises a flat token's role, never lowers it. A failed read of the grant map serves a cached entry younger than @@ -298,6 +311,24 @@ authenticated call, from `gates.authorize` in both transports: The `all_mine` fan-out and the org-wide rollups use the same predicate, so they never exceed the gate. +**Why platform authority covers every namespace but a repository.** The role spans every org: the +admin routes, the org-wide rollups (`context.reads_every_namespace`) and the collection +gate (`sharing.check`) admit it whatever its claims name. A person's sign-in claim names +only their own namespaces (`login._identity_from_rows`), and a bot's or a minted token's +claim is `*`, which covers only the token's own org. A gate that read the role only +through the claim would refuse the person the namespace ops the role stands for, and +refuse every platform administrator another org's namespaces. Covering by authority gives +the person, the bot and the minted token the same platform reach; a `*` claim still adds +what it covers as a claim, its own org's repositories at the token's role. At this gate, +scoped, delegated and impersonated tokens keep their claims: their authority is what a +principal handed on, not the principal's own. A restricted namespace (step 3), a +repository's writes, a collection and a mirror or code store keep their own rules, which +run before step 8 or exclude it. Every other namespace is in reach, a tracker namespace +and its sources' administration included, as they are for a `*` claim in its own org. +A third-party client's session gets none of it: Loom gives such a session nothing that +outlives it (it registers no bot and links no sign-in), and an admin reach over every +org would let it grant lasting access anywhere. + `code.repo.add` names no namespace, so no grant is read for it (a grant is per namespace, and step 8 has none to read) and the token's own role decides. It asks for `writer`: the op makes a namespace, its caller's admin grant there and an indexing job @@ -376,14 +407,16 @@ that `NamespaceDirectory.code_entry` recognizes in the current configuration or snapshot. This includes restricted, approval and closed repositories across the orgs the deployment holds. `authz.is_own_platform_admin` excludes scoped tokens, delegated tokens and impersonated subjects, even when their flat roles contain `platform_admin`. Namespace -`admin` and `org_admin` confer no such authority. A name beginning with `code-` confers -nothing without a repository entry. +`admin` and `org_admin` confer no such authority. A name beginning with `code-` is no +repository without a repository entry: it is an ordinary namespace +([the gate](#the-gate), step 8). Repository indexes are deployment reference data, so platform administrators need a read authority independent of repository membership. Requiring a separate claim and direct grant for each repository would make this authority depend on token refreshes and grant -provisioning. The exception is limited to viewer reads: writes, refreshes, registration, -grant management and every non-repository namespace keep their existing checks. Collection +provisioning. The exception is limited to viewer reads: writes, refreshes, registration +and grant management keep the claim and grant checks, and a restricted namespace that is +not a repository keeps the four checks above. Collection and mirror boundaries run before repository admission; a repository read does not expose its document mirrors or internal data. @@ -920,7 +953,9 @@ provisioned. The personal-namespace auto-claim passes over a name in use to its name, a workload trust's exchange refuses an agent name in use, and a first write's auto-registration names no owner on a name in use (rows a read or a run leaves aside, `namespace_autoregister.READ_TRACES`, which a fresh `namespace.register` still counts), so -only an admin of the name completes the registration, a writer that is one included. The +only an admin of the name completes the registration, a writer that is one included. It +names none either for a token of another org (a platform administrator's, +`namespace_autoregister.maybe_autoregister`): a name in a tenant org is that org's to own. The exchange sets aside the rows a request writes about itself under the name it names (`namespace_census.REQUEST_TRACES`: a latency reading, an exposure, a search trace), so a lookup of an agent's name before its first exchange does not take the name from the diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index b0fbc2882e..c81ca4a080 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -125,7 +125,7 @@ reaches the operation's role, and the token's own subject holds a live direct gr An authenticated platform administrator using its own unscoped authority can also read registered repositories, including restricted ones, subject to deployment tenancy and the restricted serving kill switch. This does not extend to scoped or delegated tokens, -impersonation, writes or other namespace kinds +impersonation, writes or restricted namespaces that are not repositories ([repository read authority](../architecture/security.md#restricted-namespaces)). No org-readable rule, public visibility, wildcard, inherited service-account grant or `org_admin` bypasses restriction, and a refusal does not reveal whether the namespace exists. Fan-outs, context packs and rollups skip restricted namespaces the @@ -137,13 +137,13 @@ caller cannot read, and each admitted request is audited. The step-by-step setup Roles are ordered, and a higher role satisfies every check for a lower one. Each operation declares the minimum role it needs (`GET /v1/operations` lists it). -| Role | Grants | How it is held | -| ---------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `viewer` | Read. | Token claim or namespace grant. | -| `writer` | Read, and write memory, knowledge and the other data planes. | Token claim or namespace grant. | -| `admin` | Administer one namespace: grants, configuration, policy, restores, promotion to the shared layer. | Token claim or namespace grant; registering a namespace makes you its admin. | -| `org_admin` | Org-wide views (for example cost without a namespace). | A recognised gate with no in-product assignment path. | -| `platform_admin` | Cross-org operator views. | Conferred at login to the handles and verified emails in `LOOM_PLATFORM_ADMINS`, and to the tokens of a bot registered `--platform-admin`; minted only for a service account, with an expiry. | +| Role | Grants | How it is held | +| ---------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `viewer` | Read. | Token claim or namespace grant. | +| `writer` | Read, and write memory, knowledge and the other data planes. | Token claim or namespace grant. | +| `admin` | Administer one namespace: grants, configuration, policy, restores, promotion to the shared layer. | Token claim or namespace grant; registering a namespace makes you its admin. | +| `org_admin` | Org-wide views (for example cost without a namespace). | A recognised gate with no in-product assignment path. | +| `platform_admin` | Every namespace of every org but restricted ones and repositories (which it reads), and the cross-org operator views. | Conferred at login to the handles and verified emails in `LOOM_PLATFORM_ADMINS`, and to the tokens of a bot registered `--platform-admin`; minted only for a service account, with an expiry. | Grants carry only `viewer`, `writer` or `admin`, and so do the tokens Loom mints, but for a `platform_admin` one: org-wide power is an operator decision in configuration or at bot @@ -154,7 +154,11 @@ registration, not something a token can carry away. Code namespaces have readers A call on `(org, namespace)` is allowed when the namespace is not restricted (or passes the restricted checks) and either the token's own role for that namespace reaches the -operation's role, or a live grant does. +operation's role, or a live grant does. A platform administrator's own unscoped +authority reaches every namespace of every org but a restricted one or a repository, +whatever its token names, though an `ns_write` claim still bounds its writes and a +third-party client's sign-in session has none of it +([the gate](../architecture/security.md#the-gate), step 8). - **The token** (`sub`, `org`, `namespaces`, `roles`, optional `ns_roles` and `ns_write`) says which namespaces the caller reads, in priority order, and with what role. A @@ -175,7 +179,8 @@ operation's role, or a live grant does. a revoked or lowered grant (`grants.revoke`, `grants.create` with `replace=true`, `namespace.leave`, a released claim, a restore) ends every older token's claim there, and a pending or rejected request caps it at no access. A scoped token keeps its own - role there, capped at the live grant. + role there, capped at the live grant. No grant caps a `*` claim or a platform + administrator's own authority. - **What is not touched.** A namespace the subject never held a grant on keeps its claim; revoke the token to take that away. - **When it applies.** The process that changed the grant applies it at once, every other diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md index 04d9efa95c..95dd8379b7 100644 --- a/docs/features/namespaces-and-sharing.md +++ b/docs/features/namespaces-and-sharing.md @@ -18,8 +18,8 @@ re-registering an existing namespace needs admin. A name with no row that alread refused unless the caller is already its admin ([what a new name may claim](../architecture/security.md#what-a-new-name-may-claim)). With `LOOM_NAMESPACE_AUTOREGISTER_ENABLED` on (default), a first write into a namespace with no row registers it, with the token subject as owner (no owner when -the name is already in use) and `retention_days = 0`. That owner may complete the registration while nobody else holds -a live grant on the name. +the name is already in use or the token is of another org, as a platform administrator's is) and `retention_days = 0`. +That owner may complete the registration while nobody else holds a live grant on the name. Re-registering is a partial update: an omitted field keeps its stored value. `tags` is replaced whole. For `conflict_threshold`, `capture_generation_io` and `coverage_sweep`, omitted keeps the stored choice and an explicit diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index 74aa988bfa..0e8cd33858 100644 --- a/docs/guides/tokens-and-grants.md +++ b/docs/guides/tokens-and-grants.md @@ -148,13 +148,13 @@ Verification accepts only `HS256` and `RS256`; `alg=none` is rejected. The Roles are ordered; a higher role satisfies every check for a lower one. Each op declares its `required_role` (`GET /v1/operations`, and the [operations reference](../reference/operations.md)). -| Role | Grants | -| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `viewer` | Read. | -| `writer` | Read and write memory, knowledge and the other data planes. | -| `admin` | Administer the namespace: grants, configuration, policy, restore into it. Not org-wide visibility. | -| `org_admin` | Org-wide views (for example `cost.summary` without a namespace). A recognised gate with no in-product assignment path. | -| `platform_admin` | Cross-org operator views. Conferred at login to the handles in `LOOM_PLATFORM_ADMINS`, and to its emails only when an IdP verified them; to every token of a bot registered `--platform-admin`; minted only for a service account, with an expiry. | +| Role | Grants | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `viewer` | Read. | +| `writer` | Read and write memory, knowledge and the other data planes. | +| `admin` | Administer the namespace: grants, configuration, policy, restore into it. Not org-wide visibility. | +| `org_admin` | Org-wide views (for example `cost.summary` without a namespace). A recognised gate with no in-product assignment path. | +| `platform_admin` | Every namespace of every org but restricted ones and repositories (which it reads), and the cross-org operator views. Conferred at login to the handles in `LOOM_PLATFORM_ADMINS`, and to its emails only when an IdP verified them; to every token of a bot registered `--platform-admin`; minted only for a service account, with an expiry. | Grants carry only `viewer`, `writer` or `admin`, and so do tokens, except a `platform_admin` one: a bot's ([Bots and CI](../operations/sso.md#bots-and-ci)) or @@ -174,7 +174,11 @@ A call on `(org, namespace)` is allowed when: widens it, except that a viewer grant lets it read a code namespace; 3. for a **flat** token: the token covers the namespace (`namespaces` for reads, `ns_write` for writes) and a role in `roles` reaches the op's role, or a live grant on the - namespace does. + namespace does. A platform admin's own authority (a flat token that is not delegated + and acts for no other subject) covers every namespace of every org but a repository + (a namespace with a repository entry), whatever `namespaces` names and whatever grant + its subject holds there, as a `*` claim covers its own org's; `ns_write` still bounds + its writes. A third-party MCP client's OAuth session keeps its claim and grants only. A scoped token called without `org` and `namespace` in the body answers 400 `IDENTITY_INCOMPLETE`: its authority is per namespace. The exceptions are ops that read @@ -247,6 +251,7 @@ curl -s "$LOOM_BASE_URL/v1/grants.create" -H "Authorization: Bearer $ADMIN_TOKEN server or another, and a pending or rejected request caps it at no access. A scoped token keeps its own role there, capped at the grant. A namespace an operator named at mint that was never granted to the subject keeps its claim; revoke the token for that. + No grant caps a `*` claim or a platform admin's own authority. - **A grant under an email reaches the account only once the email is verified.** An SSO account's email is verified (the identity provider vouched for it), and so is an email linked to a password account (`loom sso adopt`, `loom sso link`, a password link, or its @@ -475,8 +480,9 @@ read or write passes only when **all** hold: An authenticated platform administrator using its own unscoped authority can read every registered repository, including restricted entries. This authority remains subject to deployment tenancy, token validity, classification availability and `LOOM_RESTRICTED_SERVE`. -It does not extend to scoped or delegated tokens, impersonated subjects, writes or other -namespace kinds ([repository read authority](../architecture/security.md#restricted-namespaces)). +It does not extend to scoped or delegated tokens, impersonated subjects, writes or +restricted namespaces that are not repositories +([repository read authority](../architecture/security.md#restricted-namespaces)). No org-readable rule, `visibility=public` or `org_admin` bypasses restriction. A refusal is the generic "cannot access" message, so it does not reveal whether the namespace exists. If the classification cannot be read, access is denied. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 5720c18859..99095cafa1 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -139,7 +139,11 @@ For a person with no account: (`-2`, `-3`, then a random suffix). Platform admins are the verified emails listed in `LOOM_PLATFORM_ADMINS`. -The provider can never grant admin. +The provider can never grant admin. A platform admin's session reaches every +namespace of every org but a restricted namespace, a repository, a mirror and a +code store, whatever its token names and with no grant there; those keep their +own rules ([namespace access](../guides/tokens-and-grants.md#namespace-access)). A +third-party MCP client the person signs in to Loom holds no such reach. ## Bots and CI @@ -370,7 +374,8 @@ trusts and grants for its tenants, holds the `platform_admin` role as a bot. **Platform admin spans every org**: a token holding it passes every admin route and acts in any org, so give it to as few identities as you can, and prefer a trust (no secret to leak) to a key. `--platform-admin` registers such a bot; it -takes no `--namespace-role` (its tokens cover every namespace), no +takes no `--namespace-role` (its tokens claim every namespace of its org and hold +a signed-in platform admin's reach), no `--agent-claim` (it is one identity, never an agent's), and only exact `--claim` values (a prefix would hand the role to every token it matches). Give it an audience of its own, so no token meant for another trust can meet it: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 05ff6ec9e7..5db5403a97 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -85,7 +85,7 @@ Authentication, tokens and identity providers. | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | -| `LOOM_PLATFORM_ADMINS` | `str` | `''` | | Comma-separated login handles and emails promoted to platform_admin (org-wide visibility). A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no platform admins. | +| `LOOM_PLATFORM_ADMINS` | `str` | `''` | | Comma-separated login handles and emails promoted to platform_admin: a person listed reads, writes and administers every standard namespace of every org (not restricted namespaces, nor repository writes) with no grant there, and passes every admin route. A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no platform admins. | | `LOOM_AUTH_REQUIRED` | `bool` | `True` | | True: every operation requires a valid bearer JWT. False (laptop demos only): missing tokens are not rejected and the SPA synthesizes a local identity. identity_provider=single-user forces auth off regardless. | | `LOOM_DEFAULT_NAMESPACE` | `str` | `'local'` | | The one namespace auth-off mode serves (SPA identity, dashboard bootstrap, MCP/SDK caller defaults). Ignored when auth is required; `personal-*` and a mirror's or code store's name (`acl-` or `crs-` and 24 hex digits) are reserved and rejected. | | `LOOM_OAUTH_ENABLED` | `bool` | `False` | | MCP one-click connect: dynamic client registration and /oauth/authorize on top of the sign-in routes (device grant, token, revoke) every auth-on deployment serves. Opt-in: anyone can register a client. | @@ -1687,7 +1687,7 @@ Namespace registration, write marks and bench-namespace GC. | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | -| `LOOM_NAMESPACE_AUTOREGISTER_ENABLED` | `bool` | `True` | | A principal's first write into a namespace with no loom.namespaces row inserts one: owner = token subject (none on a name already in use), `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a TTL). No ALTER. | +| `LOOM_NAMESPACE_AUTOREGISTER_ENABLED` | `bool` | `True` | | A principal's first write into a namespace with no loom.namespaces row inserts one: owner = token subject (none on a name already in use or from a token of another org), `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a TTL). No ALTER. | | `LOOM_NAMESPACE_AUTOREGISTER_SKIP_PREFIXES` | `str` | `'namespace.,code.,admin.,ops.,grants.,policy.,blacklist.,…` | | Op-name prefixes the auto-register hook ignores: ops on a namespace rather than into it, the code plane (registers `kind = 'code'` itself), and the operator planes. | | `LOOM_NAMESPACE_BENCH_PREFIXES` | `str` | `'lme-,mb-,td-,locomo-,kcurve-,wpath-,bench-,ma-verbatim-,…` | | Comma-separated name prefixes of throwaway harness namespaces: stamped `kind = 'bench'` by `namespace.register` (when no kind is given) and auto-register, and scanned by `namespaces-gc`. | | `LOOM_NAMESPACE_GC_WORKER_ENABLED` | `bool` | `True` | | namespace_gc: `kind = 'bench'` namespaces with live memory and no write for `namespace_gc_idle_hours` are purged by one list-scoped erasure saga per batch, at most `namespace_gc_sagas_per_pass` a pass, kept to loom tables. | diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index 6c11a76a90..9e3ddeb61b 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -268,7 +268,13 @@ What a client gets with and without a plugin is in `claude-desktop`). The cache is in-process and bounded. - **Identity defaults.** Tool calls usually carry only the action's arguments. The server fills `org` from the token and `namespace` and `agent` from the caller's - default workspace; explicit arguments win. `code.*` calls resolve to the code plane + default workspace; explicit arguments win. The default workspace is a namespace of the + caller's own org, so a call that names another org and no `namespace` (a blank or `-` + one names none) gets none: an op whose `namespace` is required fails validation naming + it, and one whose `namespace` is optional runs org-wide in that org. A namespace refusal + there names the grant to request, never omitting the namespace. A call with no token, + on a single-user server, takes the install's namespace whatever org it names, as over + HTTP. `code.*` calls resolve to the code plane instead, and on the `assistant` toolset a read that names no `namespace` or no `agent` follows that toolset's rules (see [The assistant toolset](#the-assistant-toolset)). An `org` argument the token may not act in is refused (`ORG_MISMATCH`): a token acts in its @@ -276,7 +282,9 @@ What a client gets with and without a plugin is in over HTTP (`authz.may_act_in_org`). A restricted namespace still refuses every other org, platform admins included. `loom_search` takes no `namespace` argument: it searches the caller's home namespace and its other memory-kind namespaces, up to the - fan-out cap. + fan-out cap. Naming another org, it searches the caller's namespaces of that org, the + one named after the caller first, and fails validation naming `namespace` when it + reaches none there. - **Code scope.** A client may send `X-Loom-Code-Scope: /` (the Claude Code plugin sends the repository its checkout resolved to). It applies to every `code.*` call that names no namespace, and authorization then runs on diff --git a/loom.example.yaml b/loom.example.yaml index 701871ecbc..bf19c785a7 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -668,8 +668,10 @@ settings: # ===== Authentication, tokens and identity providers ===== - # Comma-separated login handles and emails promoted to platform_admin (org-wide - # visibility). A handle matches a password account's subject; an email matches only an + # Comma-separated login handles and emails promoted to platform_admin: a person listed + # reads, writes and administers every standard namespace of every org (not restricted + # namespaces, nor repository writes) with no grant there, and passes every admin + # route. A handle matches a password account's subject; an email matches only an # IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no # platform admins. [restart] # platform_admins: "" @@ -4994,8 +4996,9 @@ settings: # --- namespace registration and GC --- # A principal's first write into a namespace with no loom.namespaces row inserts one: - # owner = token subject (none on a name already in use), `kind = 'bench'` under a - # bench prefix, `retention_days = 0` (never a TTL). No ALTER. [restart] + # owner = token subject (none on a name already in use or from a token of another + # org), `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a TTL). No + # ALTER. [restart] # namespace_autoregister_enabled: true # Op-name prefixes the auto-register hook ignores: ops on a namespace rather than into diff --git a/pyproject.toml b/pyproject.toml index 08f4b9dd1f..9bbe60500e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -220,6 +220,7 @@ markers = [ "copy_head_check: a unit test that runs the post-copy head re-check (off by default in unit)", "doctor_tier_read: a unit test that runs loom doctor's read of the failing code-index tiers (off by default in unit)", "claim_cap: a unit test that runs the namespace gate's claim cap (off by default in unit)", + "registry_rows: a unit test that runs the gate's repository registry read (off by default in unit)", "deleted_value_check: a unit test that runs an extraction write's read of the refusal policy (off by default in unit)", "code_lead: a unit test that runs the lead block of code.symbol and code.grep (off by default in unit)", ] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index acce2a2bb2..128f1b73e6 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -5931,7 +5931,7 @@ "namespace_autoregister_enabled": { "default": true, "type": "boolean", - "description": "A principal's first write into a namespace with no loom.namespaces row inserts one: owner = token subject (none on a name already in use), `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a TTL). No ALTER." + "description": "A principal's first write into a namespace with no loom.namespaces row inserts one: owner = token subject (none on a name already in use or from a token of another org), `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a TTL). No ALTER." }, "namespace_autoregister_skip_prefixes": { "default": "namespace.,code.,admin.,ops.,grants.,policy.,blacklist.,erasure.", @@ -6470,7 +6470,7 @@ "platform_admins": { "default": "", "type": "string", - "description": "Comma-separated login handles and emails promoted to platform_admin (org-wide visibility). A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no platform admins." + "description": "Comma-separated login handles and emails promoted to platform_admin: a person listed reads, writes and administers every standard namespace of every org (not restricted namespaces, nor repository writes) with no grant there, and passes every admin route. A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no platform admins." }, "policy_cache_ttl_seconds": { "default": 30, diff --git a/server/auth/authz.py b/server/auth/authz.py index beac34dbc7..01881707fe 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -13,7 +13,9 @@ creator's grant — is switched off there, and a read needs BOTH a token that names the namespace AND a live direct grant. A platform administrator using its own unscoped authority may also read a configured repository, subject to -the restricted serving kill switch and classification availability. +the restricted serving kill switch and classification availability, and covers +every standard namespace of every tenant org but a repository, with no grant +capping it (`_platform_covers`). """ from __future__ import annotations @@ -33,6 +35,7 @@ note_unreadable, unreadable, ) +from server.core.cell import ORG_FREE from server.core.grant_sql import GRANT_RANK_SQL, LIVE_GRANT from server.core.logging_config import log_value from server.core.naming import RESERVED_REFUSED, is_reserved_name @@ -359,16 +362,23 @@ async def _check_authorized_claims( # Reads check the readable set; writes (WRITER+) check the narrower # writable set, so a token can read an inherited parent namespace # without being able to write into it (absent a writer grant below). - is_write = required_role.value >= Role.WRITER.value if org is not None and namespace is not None: - ns_covered_by_jwt = ( - auth.can_write(org, namespace) if is_write else auth.can_access(org, namespace) + covered = ( + auth.can_write(org, namespace) + if required_role.value >= Role.WRITER.value + else auth.can_access(org, namespace) ) if cap is not None: live = rank_role(cap) - ns_covered_by_jwt = ns_covered_by_jwt and live is not None and live >= required_role + covered = covered and live is not None and live >= required_role + # Platform authority covers what the claim does not: no grant caps it, as none + # caps `*`. A known grant that admits the call below leaves it unasked. + covered = covered or ( + not _grant_admits(cap, known_grant, required_role) + and await _platform_covers(auth, required_role, org, namespace) + ) else: - ns_covered_by_jwt = False + covered = False # A token acts in its own org unless it is org-wide. This runs before the # grant lookup: grants are keyed on (org, namespace, subject), and a subject @@ -380,7 +390,7 @@ async def _check_authorized_claims( f"principal {auth.subject!r} (org {auth.org!r}) cannot act in org {org!r}" ) - if auth.has_role(required_role) and (ns_covered_by_jwt or namespace is None): + if auth.has_role(required_role) and (covered or namespace is None): return # Grants are per-namespace; with no (org, namespace) to bind one to, @@ -402,7 +412,7 @@ async def _check_authorized_claims( # Be specific so the failing gate is visible to debug clients. if capped: raise _refused(_capped_message(org, namespace, required_role), org, namespace) - if not ns_covered_by_jwt: + if not covered: raise _refused( f"principal {auth.subject!r} cannot access {org}/{namespace} " f"(JWT namespaces + no grant)", @@ -631,6 +641,42 @@ def _platform_repository_read( ) +def _grant_admits(cap: int | None, known_grant: Role | None | _Unknown, role: Role) -> bool: + """Whether the grant a caller handed in admits `role` at the grant step: one the + claim's cap does not override (`_grant_role`).""" + return cap is None and isinstance(known_grant, Role) and known_grant >= role + + +async def _platform_covers( + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str +) -> bool: + """Whether own platform authority covers (org, namespace), as a `*` claim covers its + own org's: any namespace of a tenant org but a repository, which keeps the read-only + authority of `_platform_repository_read`. The gate asks it after mirrors, code stores, + collections, delegated tokens and restricted namespaces have gone to their own checks. + + For a read, a repository is a configured or snapshot entry (`code_entry`), so the + read check of a member write (`member_writes`) stays the grant's. A write also reads + the registry row at the call, and is not covered when that read fails (the refusal + is unverified) or falls outside the token's `ns_write` claim. A blank, `-` or `*` org + is no tenant. A third-party client's sign-in session gets none of it: like + `_only_a_person`, Loom gives such a session nothing that outlives it, and an admin + reach over every org would let it grant lasting access anywhere.""" + if org in ORG_FREE or not is_own_platform_admin(auth): + return False + if auth.session_id and not auth.first_party: + return False + if required_role.value < Role.WRITER.value: + return not _is_code_namespace(org, namespace) + if auth.write_namespaces and not auth.can_write(org, namespace): + return False + try: + return not await directory().is_repository(org, namespace) + except ClassificationUnavailable: + note_unreadable() + return False + + def _code_namespace_read(required_role: Role, org: str, namespace: str) -> bool: """A read of a configured code namespace, which a scoped token leaves to the grant check. On a repository the join IS the read: a code index is @@ -875,7 +921,9 @@ class CachedGate: it falls back to from the cached grant maps (`server.core.grant_cache`) instead of a fresh read per namespace. Each map is read at most once per gate. (A claim capped at a revoked grant still has the gate read a - service account's creator for itself.) + service account's creator for itself, and a platform admin's write that no + claim or grant covers reads the repository registry at each check, as + `_platform_covers` says.) `provisioned`: a personal namespace `gates.authorize` gives this person, with an admin grant, before the gate runs (`caller_home`); counted as diff --git a/server/auth/context.py b/server/auth/context.py index 993f8d3861..00227a5370 100644 --- a/server/auth/context.py +++ b/server/auth/context.py @@ -112,13 +112,13 @@ async def resolve_my_namespaces(org: str, subject: str | None = None) -> list[st # Scoped token: the ordered namespace claim is authoritative. Preserve # order (= read priority); do not union other grants (= subset restrict). if auth is not None and auth.has_ns_roles(): - return await _gate_readable(auth, org, named_claims(auth)) + return await _gate_readable(auth, org, named_claims(auth, org)) jwt_namespaces: set[str] = set() resolved_subject: str | None = None if auth is not None and auth.subject: resolved_subject = auth.subject - jwt_namespaces = set(named_claims(auth)) + jwt_namespaces = set(named_claims(auth, org)) if not resolved_subject: resolved_subject = subject @@ -148,8 +148,12 @@ async def resolve_my_namespaces(org: str, subject: str | None = None) -> list[st return [*await _gate_readable(auth, org, others), *shared] -def named_claims(auth: AuthInfo) -> list[str]: - """The namespaces the token's claim names, in order, without `*`.""" +def named_claims(auth: AuthInfo, org: str) -> list[str]: + """The namespaces of `org` the token's claim names, in order, without `*`. A claim + names namespaces of the token's own org (of every org for an org-wide token): in + another org it names none, as a namespace there only shares a claimed name.""" + if auth.org not in ("*", org): + return [] return list(dict.fromkeys(ns for ns in auth.namespaces if ns and ns != "*")) @@ -207,7 +211,7 @@ async def readable_named_claims( if auth is None or not may_act_in_org(auth, org): return [] gate = gate or CachedGate(auth, org) - return [ns for ns in named_claims(auth) if await gate.admits(ns, Role.VIEWER)] + return [ns for ns in named_claims(auth, org) if await gate.admits(ns, Role.VIEWER)] async def delegated_reach( @@ -222,7 +226,7 @@ async def delegated_reach( from server.operations.base import Role gate = gate or CachedGate(auth, org) - candidates = named_claims(auth) + candidates = named_claims(auth, org) if "*" in auth.namespaces: ranks = (await gate.grants(auth.creator)).ranks candidates += sorted(ns for ns, rank in ranks.items() if rank and ns not in candidates) @@ -327,7 +331,7 @@ async def every_namespace_scope(org: str, *, column: str = "namespace") -> OrgSc return OrgScopeFilter(accessible=False, where="", params={}) auth = current_auth() if auth is not None: - named = named_claims(auth) + named = named_claims(auth, org) refused = set(named) - set(await readable_named_claims(auth, org)) hidden = sorted(set(hidden) | refused) where, params = await collection_clause(org, column) diff --git a/server/auth/directory.py b/server/auth/directory.py index 015e6e8015..e3e1c21b5f 100644 --- a/server/auth/directory.py +++ b/server/auth/directory.py @@ -63,6 +63,12 @@ def code_entry(self, org: str, namespace: str) -> CodeEntry | None: """The configured code-plane entry for (org, namespace). No I/O.""" ... + async def is_repository(self, org: str, namespace: str) -> bool: + """Whether (org, namespace) is a repository: a configured code-plane entry, or an + active registry row read at the call (one this process's snapshot may not hold + yet). Raises `ClassificationUnavailable` when the registry cannot be read.""" + ... + def restricted_code_namespaces(self, org: str) -> set[str]: """The configured code-plane entries of `org` classified restricted. No I/O.""" ... diff --git a/server/code/app/index/repo_registry.py b/server/code/app/index/repo_registry.py index 81b7d99ad8..235ba6de09 100644 --- a/server/code/app/index/repo_registry.py +++ b/server/code/app/index/repo_registry.py @@ -295,6 +295,19 @@ async def insert_entry( ) +async def registered(org: str, namespace: str) -> bool: + """Whether (org, namespace) holds an active registry row, read at the call: a repository + another replica added is one before this process's snapshot reads it. False with + self-service off, where the snapshot reads no registry either.""" + if not settings.code_self_service_enabled: + return False + from server.code.store.index import CodeRepo + from server.core.ch import sequential_reads + + with sequential_reads(): + return await CodeRepo().is_registered_repository(org, namespace) + + async def live_row(cfg: Any, ch: Any | None = None) -> dict[str, Any] | None: """`cfg`'s registry row read now, when active; None for an operator entry with no active row. NOT_A_REPO for a branch added from the page whose row is gone or diff --git a/server/code/store/index/code_repos.py b/server/code/store/index/code_repos.py index 461f58e7d3..3d9f17d1c9 100644 --- a/server/code/store/index/code_repos.py +++ b/server/code/store/index/code_repos.py @@ -60,6 +60,16 @@ async def code_repo_row(self, org: str, ns: str) -> dict[str, Any] | None: ) return row + async def is_registered_repository(self, org: str, ns: str) -> bool: + """Whether the namespace holds an active registry row, one point read. A + maintainer's access row names no repository: the snapshot leaves it out too.""" + row: dict[str, Any] | None = await self._ch.query_one( + "SELECT active, row_kind FROM loom.code_repos FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} LIMIT 1", + {"org": org, "ns": ns}, + ) + return bool(row and row.get("active") and row.get("row_kind") != "access") + async def insert_code_repo_row(self, row: dict[str, Any]) -> None: await self._ch.insert("loom.code_repos", [row]) diff --git a/server/identity/app/caller_home.py b/server/identity/app/caller_home.py index 45f91c00dc..a84dee4643 100644 --- a/server/identity/app/caller_home.py +++ b/server/identity/app/caller_home.py @@ -138,7 +138,7 @@ async def default_and_readable(auth: Any, org: str) -> tuple[str, list[str]]: if auth is not None: gate = CachedGate(auth, org, provisioned=await _provisioned(auth, org)) admits, extra = await _gate_view(auth, org, home, gate) - named = [] if auth is None else named_claims(auth) + named = [] if auth is None else named_claims(auth, org) default = await _pick_default(auth, org, home, named, admits, extra) return default, [] if default else await readable_named_claims(auth, org, gate) except BackendUnavailableError: diff --git a/server/identity/app/directory.py b/server/identity/app/directory.py index a950789514..5bebfbfdb1 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -5,15 +5,21 @@ from __future__ import annotations +import logging + +from server.auth.directory import ClassificationUnavailable from server.code.domain.index import repos from server.code.domain.index.repos import RepoConfig from server.core.ch import sequential_reads +from server.core.logging_config import log_value from server.core.repo_base import _CHClient from server.erasure.app import ledger_reads from server.identity.app import namespace_classification, namespace_kinds, namespace_visibility from server.identity.store import namespace_census from server.tracker.domain.namespaces import tracker_namespace +log = logging.getLogger(__name__) + def configured_restricted_pairs() -> set[tuple[str, str]]: return { @@ -39,6 +45,22 @@ def config_classification(self, org: str, namespace: str) -> str: def code_entry(self, org: str, namespace: str) -> RepoConfig | None: return repos.config_entry(org, namespace) + async def is_repository(self, org: str, namespace: str) -> bool: + if self.code_entry(org, namespace) is not None: + return True + from server.code.app.index import repo_registry + + try: + return await repo_registry.registered(org, namespace) + except Exception as e: # any read failure must refuse the write, not fail the request + log.warning( + "repository registry read failed for %s/%s: %s", + log_value(org), + log_value(namespace), + log_value(e), + ) + raise ClassificationUnavailable("the repository registry could not be read") from e + def restricted_code_namespaces(self, org: str) -> set[str]: return { namespace for entry_org, namespace in configured_restricted_pairs() if entry_org == org diff --git a/server/identity/app/namespace_autoregister.py b/server/identity/app/namespace_autoregister.py index 4ff9ea657c..024c4ced53 100644 --- a/server/identity/app/namespace_autoregister.py +++ b/server/identity/app/namespace_autoregister.py @@ -6,18 +6,18 @@ The first write a principal makes into an unregistered namespace inserts the registry row `namespace.register` would have written for it, with that op's defaults: owner = the token -subject, or none when the name is already in use (`IdentityDirectory.in_use`), `kind = -'bench'` when the name is under one of `namespace_bench_prefixes` (else `memory`), -`retention_days = 0`. The row is the only write: no TTL clause is touched (a per-namespace -retention is a clause in eight tables' TTL expressions, and setting one re-issues `MODIFY -TTL` on all of them), no ALTER is issued, and no grant is written. An owner row is not -elevation: the register op's admin grant for its caller would have made a writer an admin -of every namespace it touched (`memory.unlock` open to writers; `grants.revoke` refusing -to remove "the only admin"), and `resolve_my_namespaces` unions a wildcard token's grants, -so a subject's searches fanned out across every namespace it had ever written to. The -owner named on an auto-registered row may complete its registration with -`namespace.register` while nobody else holds a live grant on it; nothing else changes for -the writer. +subject, or none when the name is already in use (`IdentityDirectory.in_use`) or the token +is of another org (a platform admin's); `kind = 'bench'` when the name is under one of +`namespace_bench_prefixes` (else `memory`); `retention_days = 0`. The row is the only +write: no TTL clause is touched (a per-namespace retention is a clause in eight tables' TTL +expressions, and setting one re-issues `MODIFY TTL` on all of them), no ALTER is issued, +and no grant is written. An owner row is not elevation: the register op's admin grant for +its caller would have made a writer an admin of every namespace it touched (`memory.unlock` +open to writers; `grants.revoke` refusing to remove "the only admin"), and +`resolve_my_namespaces` unions a wildcard token's grants, so a subject's searches fanned +out across every namespace it had ever written to. The owner named on an auto-registered +row may complete its registration with `namespace.register` while nobody else holds a live +grant on it; nothing else changes for the writer. The row also opts into nothing an absent row did not: every column reader treats "no row" and the register defaults alike. @@ -116,9 +116,11 @@ async def ensure_registered( subject: str, op_name: str, ch: Any | None = None, + ownerless: bool = False, ) -> bool: """Insert the registry row for (org, namespace) if none exists. Returns - True when a row was inserted. Never raises.""" + True when a row was inserted. Never raises. `ownerless`: the writer is not of + `org` (a platform admin of another org), so the row names no owner.""" from server.auth.authz import identity_write if (org, namespace) in _known or reserved_for_sso(namespace): @@ -149,14 +151,16 @@ async def ensure_registered( # A name that already holds state (data written with auth off, a grant) is not its # first writer's to own: the row names no owner, so only an admin completes it. # Identity's own directory: the gate's seam takes no `skip`. - in_use = await IdentityDirectory().in_use(org, namespace, ch=ch, skip=READ_TRACES) + ownerless = ownerless or await IdentityDirectory().in_use( + org, namespace, ch=ch, skip=READ_TRACES + ) kind = classify_kind(namespace) now = datetime.now(UTC).replace(tzinfo=None, microsecond=0) row = registry_row( NamespaceRegisterInput( org=org, namespace=namespace, - owner_email="" if in_use else subject, + owner_email="" if ownerless else subject, description=f"Auto-registered on first write ({op_name}) by {subject}.", kind=None, # classified by name (`classify_kind`), as `kind` above tags=[AUTO_REGISTER_TAG] + (["bench"] if kind == "bench" else []), @@ -167,7 +171,7 @@ async def ensure_registered( ) # Both versions sit below any explicit row's (a register, a restriction), so an # explicit row wins under FINAL, even one another replica wrote a moment ago. - row["updated_at"] = OWNERLESS_ROW_VERSION if in_use else AUTO_ROW_VERSION + row["updated_at"] = OWNERLESS_ROW_VERSION if ownerless else AUTO_ROW_VERSION with identity_write(): await ch.insert("loom.namespaces", [row]) _remember(org, namespace) @@ -206,4 +210,11 @@ async def maybe_autoregister( if not should_autoregister(op, org, namespace): return False assert org is not None and namespace is not None - return await ensure_registered(org, namespace, subject=str(auth.subject), op_name=op.name) + # A name in another org is that org's to own, not an outside writer's. + return await ensure_registered( + org, + namespace, + subject=str(auth.subject), + op_name=op.name, + ownerless=auth.org not in ("*", org), + ) diff --git a/server/identity/app/namespace_membership.py b/server/identity/app/namespace_membership.py index 3b1ff5467f..2f3a650b7e 100644 --- a/server/identity/app/namespace_membership.py +++ b/server/identity/app/namespace_membership.py @@ -566,12 +566,12 @@ async def handle_namespace_list_mine( ] from server.auth.authz import live_claims - from server.auth.context import current_auth + from server.auth.context import current_auth, named_claims auth = current_auth() if auth is not None: jwt_only = await live_claims( - auth, input.org, [ns for ns in auth.namespaces if ns not in seen] + auth, input.org, [ns for ns in named_claims(auth, input.org) if ns not in seen] ) # Claim-only namespaces have no grant row to JOIN through, so look up # kind/visibility directly — otherwise a code namespace named in a diff --git a/server/settings/catalog.py b/server/settings/catalog.py index a4355121fb..7c0e1fa056 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -150,10 +150,12 @@ def signs_for(self, org: str) -> bool: class AuthSettings(BaseModel): """Authentication, tokens and identity providers.""" - # Comma-separated login handles and emails promoted to platform_admin - # (org-wide visibility). A handle matches a password account's subject; an - # email matches only an IdP-verified (OIDC) email, never the unverified - # self-signup address. Empty = no platform admins. + # Comma-separated login handles and emails promoted to platform_admin: a + # person listed reads, writes and administers every standard namespace of + # every org (not restricted namespaces, nor repository writes) with no grant + # there, and passes every admin route. A handle matches a password account's + # subject; an email matches only an IdP-verified (OIDC) email, never the + # unverified self-signup address. Empty = no platform admins. platform_admins: str = "" @property @@ -4385,9 +4387,9 @@ class NamespaceSettings(BaseModel): # ---- namespace registration and GC ---- # A principal's first write into a namespace with no loom.namespaces row - # inserts one: owner = token subject (none on a name already in use), - # `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a - # TTL). No ALTER. + # inserts one: owner = token subject (none on a name already in use or from + # a token of another org), `kind = 'bench'` under a bench prefix, + # `retention_days = 0` (never a TTL). No ALTER. namespace_autoregister_enabled: bool = True # Op-name prefixes the auto-register hook ignores: ops on a namespace # rather than into it, the code plane (registers `kind = 'code'` itself), diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index bb8c79cf9c..9af8ddb325 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -20,6 +20,7 @@ unverified_class, ) from server.core.naming import present +from server.identity.app.caller_home import caller_org from server.observability.consumer import ASSISTANT_CONSUMER from server.operations.base import Role from server.transport.mcp_config import ( @@ -66,9 +67,12 @@ def _not_accessible_result( *, assistant: bool = False, unverified: bool = False, + away: bool = False, ) -> dict[str, Any]: """A namespace the token may not read. `assistant`: the connection is the assistant toolset, which reaches neither loom_search nor loom_op, so neither is suggested. + `away`: the call names another org than the caller's, where no default fills an + omitted namespace, so omitting it is not suggested. `unverified`: the check itself failed (a grant could not be read), so a collection's refusal asks for no grant: the caller may hold one and should retry. A plain namespace's refusal is the same either way.""" @@ -107,13 +111,18 @@ def _not_accessible_result( ns, ) msg = f"{noun} {ns!r} is not in your accessible list and you don't have an active grant on it." + grant = f"a grant from the dashboard {DASHBOARD_REQUEST}" + omit = "Omit the namespace argument to use your default namespace" + # A call naming another org gets no default namespace there: omitting it is no step. if assistant: - msg += ( - f" Ask the collection's admin for a grant on it or a collection above it.{creator}" - if collection - else " Omit the namespace argument to use your default namespace, or request a " - f"grant from the dashboard {DASHBOARD_REQUEST}." - ) + if collection: + msg += ( + f" Ask the collection's admin for a grant on it or a collection above it.{creator}" + ) + elif away: + msg += f" Request {grant}." + else: + msg += f" {omit}, or request {grant}." elif collection: # Never "omit the namespace": a write meant for the collection would land in the # default namespace instead. @@ -122,16 +131,16 @@ def _not_accessible_result( f"collection.list (through loom_op) lists the collections you can read.{creator}" ) else: - reads = ( - "your namespaces and the collections you can read" - if knowledge_search_reads_collections() - else "your namespaces" - ) - msg += ( - f" Next: {NAMESPACE_NEXT}. Omit the namespace argument to use your default " - f"namespace (loom_search reads {reads}), or request a grant from the dashboard " - f"{DASHBOARD_REQUEST}.{creator}" - ) + msg += f" Next: {NAMESPACE_NEXT}." + if away: + msg += f" Request {grant}.{creator}" + else: + reads = ( + "your namespaces and the collections you can read" + if knowledge_search_reads_collections() + else "your namespaces" + ) + msg += f" {omit} (loom_search reads {reads}), or request {grant}.{creator}" return _refusal_body(msg, ns, next=NAMESPACE_NEXT) return _refusal_body(msg, ns) @@ -442,9 +451,13 @@ async def _screen_tool_call( target_org = req_org or auth.org if not req_ns: return None + # No default fills an omitted namespace outside the caller's own org. + away = req_org not in (None, caller_org(auth)) try: - return await _screen_namespace(req, tool_name, args, auth, target_org, req_ns, consumer) + return await _screen_namespace( + req, tool_name, args, auth, target_org, req_ns, consumer, away=away + ) except WrongCellError as e: # Another cell's org, as a tool result: escaping, it would answer a bare HTTP # 409 with no JSON-RPC frame and lose the batch's other answers. @@ -510,10 +523,12 @@ async def _screen_namespace( target_org: str, req_ns: str, consumer: str, + *, + away: bool = False, ) -> dict[str, Any] | None: """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.""" + the refusal, ledgered. `away`: the call names another org than the caller's.""" from server.transport import gates # A code call that omits `org` acts in the code plane's, as on HTTP: the org its @@ -544,6 +559,7 @@ async def _screen_namespace( req_ns, assistant=consumer == ASSISTANT_CONSUMER, unverified=given_unverified, + away=away, ) unverified = given_unverified # The org the token may act in, as HTTP records the same refusal. diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index f4dce186d7..9d3eee3abb 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -24,6 +24,7 @@ from server.code.domain.scope import apply_code_scope, current_code_scope from server.core import llm_free from server.core.errors import ( + BackendUnavailableError, LoomServerError, SessionProtectionRequiredError, UnknownBranchError, @@ -31,10 +32,11 @@ unverified_class, ) from server.core.errors import ValidationError as LoomValidationError +from server.core.logging_config import log_value from server.core.naming import named, present from server.identity.app.caller_home import home_namespace from server.observability import capture_consent, genai, invocation, otel -from server.observability.consumer import ASSISTANT_CONSUMER +from server.observability.consumer import ASSISTANT_CONSUMER, bind_current_consumer from server.observability.ledger import required_call_exit, run_id_of from server.operations.base import Operation from server.operations.toolsets import ( @@ -182,30 +184,60 @@ async def _tag_session_repository(op: Operation, arguments: dict[str, Any], auth SEARCH_OP = "search.query" -async def _address_home(arguments: dict[str, Any], auth: Any) -> None: +async def _address_home(arguments: dict[str, Any], auth: Any, request_id: str = "") -> None: """An unaddressed `all_mine` search addresses the caller's own namespace first, even when the token's first claimed namespace is a teammate's (the page park, the exposures and the ledger row follow it): the namespace the defaults filled in moves to the caller's home among the fan-out set. The set is memory-kind only, so a caller whose saved default is a code - namespace lands on its first memory namespace. An explicit namespace is - never rewritten (the gate refuses it if it must).""" - if arguments.get("namespace_scope") != "all_mine": + namespace lands on its first memory namespace. A search in another org has + no default there, so it addresses the caller's home among that org's fan-out, + else its first, whatever its scope, and none when it reaches none. A fan-out it + cannot read there is ledgered and raised, as there is no default to fall back to: + a server fault, or any error that is not Loom's, answers a 503; the caller's own + (an org another cell holds, a name past the limit) a tool error, as the gate's. + An explicit namespace is never rewritten (the gate refuses it if it must); a + blank or "-" one names none, as the gates read it.""" + addressed = present(arguments.get("namespace")) + if arguments.get("namespace_scope") != "all_mine" and addressed: return from server.auth.fanout import resolve_fanout try: - fanout = await resolve_fanout(str(arguments.get("org") or "")) - except Exception as e: # noqa: BLE001 — no fan-out namespaces narrows the search, never widens - log.warning("loom_search namespace resolution failed (non-fatal): %s", e) - return + fanout = await resolve_fanout(present(arguments.get("org")) or "") + except Exception as e: # a filled default stays when the fan-out cannot be read + if addressed: + log.warning("loom_search namespace resolution failed (non-fatal): %s", log_value(e)) + return + # Nothing to fall back to: the error is answered as raised, any not Loom's a 503. + err = ( + e + if isinstance(e, LoomServerError) + else BackendUnavailableError("namespaces could not be read", operation="fanout") + ) + if err.status_code >= 500: + log.warning("loom_search namespaces could not be read: %s", log_value(e)) + emit_token_refusal(SEARCH_OP, auth, error_code=err.code, request_id=request_id) + if err is e: + raise + raise err from e # The home is chosen from every namespace of the caller, before the cap. accessible = list(fanout.namespaces) if accessible: subject = str(getattr(auth, "subject", "") or "") if auth is not None else "" - arguments["namespace"] = home_namespace( - accessible, subject, str(arguments.get("namespace") or "") - ) + arguments["namespace"] = home_namespace(accessible, subject, addressed or "") + if not addressed: + # No default filled it: the note says when it is not the caller's own. + note_default_namespace(True, arguments["namespace"], auth) + + +def _in_home_org(arguments: dict[str, Any], defaults: dict[str, str] | None, auth: Any) -> bool: + """Whether the call acts in the caller's own org: it names none, or the defaults'. + The default namespace is one of that org's, so a call naming another org gets none. + A call with no token (a single-user server) is always home: no platform authority + reaches another org's namesake, and HTTP fills the install's namespace whatever org + the call names (`gates.with_single_user_identity`).""" + return auth is None or present(arguments.get("org")) in (None, (defaults or {}).get("org")) def _address_first_claim(arguments: dict[str, Any], readable: list[str]) -> bool: @@ -293,7 +325,12 @@ async def _call_tool( if refused is not None: return refused explicit_identity = not IDENTITY_KEYS.isdisjoint(arguments) - request_id, defaults = await _bind_caller_identity(op, arguments, auth, client_name) + try: + request_id, defaults = await _bind_caller_identity(op, arguments, auth, client_name) + except (WrongCellError, LoomValidationError) as e: + # The caller's to fix, as the gate answers it (a search's fan-out in another + # org, `_address_home`, ledgered it). + return _ok(req_id, refusal_result(e)) run_caller, stamped_run = _stamp_session_run(op, arguments, defaults, mcp_session_id) @@ -628,7 +665,6 @@ async def _bind_caller_identity( # The consumer column — the call's own `consumer`, else # the token's subject class — published for the event, audit and budget # writers of this call. - from server.observability.consumer import bind_current_consumer from server.observability.traffic_class import bind_claimed_class bind_current_consumer(arguments, auth) @@ -653,14 +689,21 @@ async def _bind_caller_identity( emit_token_refusal(op.name, auth, error_code=e.code, request_id=request_id) raise explicit_agent = bool(arguments.get("agent")) - # A blank or "-" namespace names none, as the gates read it. - unnamed = not present(arguments.get("namespace")) + # A call takes the default namespace when it names none (a blank or "-" names none, + # as the gates read it) and acts in the caller's own org. + in_home_org = _in_home_org(arguments, defaults, auth) + unaddressed_away = not in_home_org and not present(arguments.get("namespace")) + if unaddressed_away: + # No default fills it there: a required namespace fails validation naming it, an + # optional one runs org-wide. + arguments.pop("namespace", None) + takes_default_ns = not present(arguments.get("namespace")) and in_home_org # An empty default namespace (a delegated token whose claim holds no home) # is not filled in: the call then fails validation naming `namespace`. filled_ns = ( bool(defaults and defaults["namespace"]) and "namespace" in op.input_model.model_fields - and unnamed + and takes_default_ns and not op.name.startswith("code.") ) if defaults and not op.name.startswith("code."): @@ -668,23 +711,31 @@ async def _bind_caller_identity( for k, v in defaults.items(): # A blank or "-" org names none, as the gates read it. if k == "namespace": - missing = unnamed + missing = takes_default_ns elif k == "org": missing = not present(arguments.get(k)) else: missing = not arguments.get(k) if v and k in field_names and missing: arguments[k] = v - if defaults and defaults["namespace"] and "lesson_namespaces" in op.input_model.model_fields: - # a code read's lessons include the caller's own memories, from its memory home - arguments.setdefault("lesson_namespaces", [defaults["namespace"]]) - if op.name == SEARCH_OP and defaults and not defaults["namespace"] and unnamed: + if op.name == SEARCH_OP and defaults and not defaults["namespace"] and takes_default_ns: filled_ns = _address_first_claim(arguments, defaults.get("readable") or []) note_default_namespace(filled_ns, str(arguments.get("namespace") or ""), auth) _scope_arguments(op.name, arguments, defaults, explicit_agent) + if ( + defaults + and defaults["namespace"] + and gates.org_for_op(op.name, arguments.get("org"), auth) in (None, defaults["org"]) + and "lesson_namespaces" in op.input_model.model_fields + ): + # A code read's lessons include the caller's own memories, from its memory home, + # when the read acts in the caller's org (its code scope or plane may be another's). + arguments.setdefault("lesson_namespaces", [defaults["namespace"]]) await _tag_session_repository(op, arguments, auth) - if op.name == SEARCH_OP and filled_ns: - await _address_home(arguments, auth) + # A search naming another org and no namespace has no default there: its fan-out + # in that org addresses it. + if op.name == SEARCH_OP and (filled_ns or unaddressed_away): + await _address_home(arguments, auth, request_id) # Read-shaped ops default to cross-agent within the namespace (memory is # shared across tools). Writes keep the caller's own agent for provenance. diff --git a/tests/analyzer/cases/code.py b/tests/analyzer/cases/code.py index c506524791..7dba0525dd 100644 --- a/tests/analyzer/cases/code.py +++ b/tests/analyzer/cases/code.py @@ -304,6 +304,7 @@ async def _point_readers(ch: RecordingCH, c: dict[str, Any]) -> None: tests_flag = c["variant"] await repo.get_state(ORG, NS, "k") await repo.all_state(ORG, NS) + await repo.is_registered_repository(ORG, NS) await repo.live_chunks_for_path(ORG, NS, "src/a.py", MODEL, with_embedding=tests_flag) await repo.live_chunk_index_for_path(ORG, NS, "src/a.py", MODEL) # A SQL test's live facet rows, the ingest key-diff's read; diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index c4a8edbace..08be4b2173 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -259,6 +259,7 @@ 1ea0c8768c0e SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 1ef2654703f8 SELECT DISTINCT source_uri FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(u -> startsWith(source_uri, concat(u, ?)), {uris:Array(String)}) ORDER BY sour 1f46432bb4a5 SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, degree FROM ( SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, row_number() OVER (PARTITION BY src +1f8ffe1a2ec3 SELECT active, row_kind FROM loom.code_repos FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 1f90ede3098e SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 1fd1361296a7 SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () AS total FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(pa 2048d3599a42 SELECT DISTINCT namespace, memory_key FROM loom.shared FINAL WHERE org = {org:String} AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(promoted_from, {sources:Array( diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 84ff3d6cbd..341722191c 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -1143,6 +1143,59 @@ def test_a_dash_org_is_the_tokens_own_org(control_plane_url, seed, tokens) -> No assert nonce not in r.text, f"another org read a '-'-org write: {r.text[:200]}" +def test_a_platform_admin_of_another_org_reads_and_writes_its_standard_namespaces( + control_plane_url, seed, mint_test_token +) -> None: + """Own platform authority reaches a standard namespace of every org with no claim + or grant there (security.md, the gate, step 8); the same claims with the admin and + writer roles reach nothing in that org.""" + claims = {"org": f"{seed.org}-ops", "namespaces": ["ops-home"], "subject": "leak-platform"} + admin = mint_test_token(roles=["platform_admin"], **claims) + member = mint_test_token(roles=["admin", "writer"], **claims) + read = {"org": seed.org, "namespace": seed.ns_a, "agent": "a", "memory_key": seed.keys[0]} + r = _post(control_plane_url, member, "memory.get", read) + assert r.status_code in _OK_STATUSES and not seed.leaked(r.text), r.text[:200] + r = _post(control_plane_url, admin, "memory.get", read) + assert r.status_code == 200, r.text[:200] + assert r.json()["found"] is True and seed.leaked(r.text), r.text[:200] + nonce = _canary() + write = { + "org": seed.org, + "namespace": f"tenant-p-{uuid.uuid4().hex[:6]}", + "agent": "a", + "memory_key": f"platform_{uuid.uuid4().hex[:6]}", + } + r = _post(control_plane_url, member, "memory.set", {**write, "value": nonce}) + assert r.status_code == 403, r.text[:200] + assert r.json()["detail"]["code"] == "AUTH_INSUFFICIENT", r.text[:200] + r = _post(control_plane_url, admin, "memory.set", {**write, "value": nonce}) + assert r.status_code == 200, r.text[:200] + memory_id = r.json()["memory_id"] + r = _post(control_plane_url, admin, "memory.get", write) + assert r.status_code == 200, r.text + row = r.json() + assert row["found"] is True, r.text[:200] + assert (row["memory_id"], row["agent"], row["value"], row["user_id"], row["session_id"]) == ( + memory_id, + "a", + nonce, + "-", + "-", + ) + assert (row["actor"], row["source_class"], row["memory_type"]) == ( + "process:leak-platform", + "asserted", + "semantic", + ) + # The first write registered the name with no owner: it is the other org's to own. + where = {"org": seed.org, "namespace": write["namespace"]} + r = _post(control_plane_url, admin, "namespace.get", where) + assert r.status_code == 200, r.text[:200] + got = r.json() + assert (got["found"], got["owner_email"], got["active"]) == (True, "", True), r.text[:300] + assert "auto-registered" in got["tags"], r.text[:300] + + def test_error_bodies_do_not_echo_canaries(control_plane_url, seed, tokens) -> None: """A 403 that quotes the forbidden row is still a leak.""" r = _post( diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index c051fac248..22370acecc 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -560,6 +560,25 @@ async def _no_groups(org: str) -> dict[str, list[str]]: grant_cache.clear() +@pytest.fixture(autouse=True) +def _no_registry_rows(request: pytest.FixtureRequest) -> Iterator[None]: + """Platform authority covers a write only where the repository registry holds no + active row for the namespace (`repo_registry.registered`, read at the write). Unit + fakes answer statements by shape, so the registry holds no row beyond the configured + entries unless a test is marked `registry_rows`.""" + from server.code.app.index import repo_registry + + before = repo_registry.registered + if not request.node.get_closest_marker("registry_rows"): + + async def _none(org: str, namespace: str) -> bool: + return False + + repo_registry.registered = _none # type: ignore[assignment] + yield + repo_registry.registered = before # type: ignore[assignment] + + @pytest.fixture def subjects_not_revoked(monkeypatch: pytest.MonkeyPatch) -> None: """Token-minting paths read the subject's revocations from ClickHouse; diff --git a/tests/unit/test_blacklist_authority.py b/tests/unit/test_blacklist_authority.py index a6445d280c..34aec3ffe4 100644 --- a/tests/unit/test_blacklist_authority.py +++ b/tests/unit/test_blacklist_authority.py @@ -382,7 +382,7 @@ def test_sweep_matrix(repo: _Repo, monkeypatch, scope: str, role: str) -> None: assert swept == [] -@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("role", [r for r in ROLES if r != "PLATFORM_ADMIN"]) def test_sweep_hides_a_namespace_pattern_outside_the_callers_namespaces( repo: _Repo, monkeypatch, role: str ) -> None: @@ -402,6 +402,17 @@ def test_sweep_hides_a_namespace_pattern_outside_the_callers_namespaces( assert swept == [] +def test_a_platform_admin_sweeps_a_namespace_pattern_its_claim_does_not_name( + repo: _Repo, monkeypatch +) -> None: + """Platform authority reaches every standard namespace, whatever the claim names.""" + repo.rows["pb"] = _row("pb", "namespace", namespace="ns-b") + swept = _record_sweeps(monkeypatch) + set_current_auth(_auth("PLATFORM_ADMIN", namespaces=("ns-a",))) + asyncio.run(h.handle_blacklist_sweep(_sweep("pb", namespace="ns-a"))) + assert [(c["org"], c["namespace"], c["scope"]) for c in swept] == [(ORG, "ns-b", "namespace")] + + def test_sweep_of_an_own_namespace_pattern_sweeps_that_namespace(repo: _Repo, monkeypatch) -> None: repo.rows["pa"] = _row("pa", "namespace", namespace="ns-b") swept = _record_sweeps(monkeypatch) diff --git a/tests/unit/test_default_namespace_gate_property.py b/tests/unit/test_default_namespace_gate_property.py index 5fc1de2379..bc1b91b7d5 100644 --- a/tests/unit/test_default_namespace_gate_property.py +++ b/tests/unit/test_default_namespace_gate_property.py @@ -277,13 +277,21 @@ def _owner_first(names: list[str], subject: str) -> list[str]: return sorted(names, key=lambda ns: ns.lower() != login) +def _claims(token: AuthInfo) -> list[str]: + """The namespaces of ORG the token's claim names: a claim names its own org's (every + org's for an org-wide token), so a token of another org names none of ORG's.""" + if token.org not in ("*", ORG): + return [] + return list(dict.fromkeys(ns for ns in token.namespaces if ns != "*")) + + def _candidates(token: AuthInfo) -> tuple[list[str], list[str]]: """The names a default may come from, in order, as two passes: (the minted home, the saved pick and the claims, the ranked grants and the fallback).""" from server.identity.app.caller_home import is_memory_home home = token.creator or token.subject - named = [ns for ns in token.namespaces if ns != "*"] + named = _claims(token) subjects = [home] if not token.creator and token.subject == BOT and WORLD.inherits: subjects.append(PERSON) @@ -295,7 +303,8 @@ def _candidates(token: AuthInfo) -> tuple[list[str], list[str]]: fallback = [_provisioned(token) or derive_personal_slug(token.subject)] saved = WORLD.saved if home == PERSON else "" star_home = "*" in token.namespaces and token.namespaces[0] != "*" - minted = named[0] if token.creator and star_home else "" + # The home a delegated `*` token was minted with is read off its claim as sent. + minted = token.namespaces[0] if token.creator and star_home else "" early = [minted, saved, *_owner_first(named, home)] late = _owner_first(ranked, home) + fallback @@ -336,7 +345,7 @@ async def _resolve_violation(token: AuthInfo) -> str: if token.creator or token.ns_roles: return "" subjects = [token.subject, *([PERSON] if token.subject == BOT and WORLD.inherits else [])] - reach = [*token.namespaces, *(str(r["namespace"]) for r in _ranked_rows(subjects))] + reach = [*_claims(token), *(str(r["namespace"]) for r in _ranked_rows(subjects))] missed = [ ns for ns in dict.fromkeys(reach) @@ -360,8 +369,7 @@ async def _violation(token: AuthInfo) -> str: return f"default {default!r}, the gate's first is {expected!r} of {early} + {late}" if default: return "" - named = list(dict.fromkeys(ns for ns in token.namespaces if ns != "*")) - admitted = [ns for ns in named if await _admits(token, Role.VIEWER, ns)] + admitted = [ns for ns in _claims(token) if await _admits(token, Role.VIEWER, ns)] if readable != admitted: return f"readable {readable} != admitted {admitted}" return "" diff --git a/tests/unit/test_delete_by_key.py b/tests/unit/test_delete_by_key.py index ec6851f344..2c688f801a 100644 --- a/tests/unit/test_delete_by_key.py +++ b/tests/unit/test_delete_by_key.py @@ -237,18 +237,6 @@ async def _get_by_key(identity: Any, key: str, **kw: Any) -> Any: assert _delete_at(world["row"].version).tombstoned is True -def test_every_unaddressed_search_takes_the_home_namespace() -> None: - """The rule fires whenever the caller named no namespace, not only - when the saved default fell outside the fan-out list.""" - import inspect - - from server.transport import mcp_call - - bind = inspect.getsource(mcp_call._bind_caller_identity) - assert "if op.name == SEARCH_OP and filled_ns:" in bind - assert "home_namespace(" in inspect.getsource(mcp_call._address_home) - - def test_get_looks_namespace_wide_after_an_exact_miss_for_the_same_user(world) -> None: """memory.get has the delete's fallback — the caller's own identity first, then the namespace-wide `*` form; the wide row is accepted only diff --git a/tests/unit/test_erasure_authz_matrix.py b/tests/unit/test_erasure_authz_matrix.py index 41626245a8..0a6e2deea0 100644 --- a/tests/unit/test_erasure_authz_matrix.py +++ b/tests/unit/test_erasure_authz_matrix.py @@ -227,14 +227,14 @@ async def _list(ch: _ListCH) -> str: "writer": {"ns_own": "403", "ns_other": "403", "user_id": "403", "ns_list": "403"}, } # A namespace export is checked against the namespace; a subject export needs -# the org-wide view. +# the org-wide view. A platform admin, of any org, reaches every standard namespace. EXPORT: dict[str, dict[str, str]] = { "admin": {"ns_own": "ok", "ns_other": "403", "user_id": "403"}, "empty_subject": {"ns_own": "403", "ns_other": "403", "user_id": "403"}, "org_admin": {"ns_own": "ok", "ns_other": "403", "user_id": "ok"}, "org_admin_other_org": {"ns_own": "403", "ns_other": "403", "user_id": "403"}, "org_admin_wildcard_org": {"ns_own": "ok", "ns_other": "403", "user_id": "ok"}, - "platform_admin": {"ns_own": "403", "ns_other": "403", "user_id": "ok"}, + "platform_admin": {"ns_own": "ok", "ns_other": "ok", "user_id": "ok"}, "scoped": {"ns_own": "ok", "ns_other": "403", "user_id": "403"}, "viewer": {"ns_own": "403", "ns_other": "403", "user_id": "403"}, "wildcard_viewer": {"ns_own": "403", "ns_other": "403", "user_id": "403"}, @@ -261,8 +261,8 @@ async def _list(ch: _ListCH) -> str: "ns_list": "ok", }, "platform_admin": { - "ns_own": "hidden", - "ns_other": "hidden", + "ns_own": "ok", + "ns_other": "ok", "user_id": "hidden", "ns_list": "hidden", }, diff --git a/tests/unit/test_error_envelope.py b/tests/unit/test_error_envelope.py index 307721b228..f99e55ad9c 100644 --- a/tests/unit/test_error_envelope.py +++ b/tests/unit/test_error_envelope.py @@ -527,6 +527,22 @@ def test_the_namespace_screen_names_no_step_where_it_would_not_help( assert body["code"] == "NAMESPACE_NOT_ACCESSIBLE" and "next" not in body +@pytest.mark.parametrize("assistant", [False, True]) +def test_a_refusal_in_another_org_never_advises_omitting_the_namespace(assistant: bool) -> None: + """No default fills an omitted namespace in another org: omitting it would fail + validation, so the refusal there names only the grant.""" + from server.transport import mcp_auth + + auth = SimpleNamespace(subject="viewer@dev", org="dev", creator=None) + home = mcp_auth._not_accessible_result("loom_memory_get", auth, "x", assistant=assistant) + away = mcp_auth._not_accessible_result( + "loom_memory_get", auth, "x", assistant=assistant, away=True + ) + assert "Omit the namespace argument" in home["structuredContent"]["error"] + text = away["structuredContent"]["error"] + assert "Omit" not in text and "Request a grant from the dashboard" in text + + def test_an_unverified_plain_namespace_refusal_is_answered_as_any_other() -> None: """A restricted namespace is refused before the grant read that fails, so a different answer for an unverified one would tell it from a namespace that does not exist.""" diff --git a/tests/unit/test_knowledge_move.py b/tests/unit/test_knowledge_move.py index 62ed0a4f4b..33d696bb4e 100644 --- a/tests/unit/test_knowledge_move.py +++ b/tests/unit/test_knowledge_move.py @@ -848,7 +848,7 @@ async def test_me_from_an_end_user_moves_into_their_own_collection( mine = personal_name(ORG, "user:u1") store[mine] = {} - monkeypatch.setattr(move, "current_auth", lambda: SimpleNamespace(subject="user:u1")) + monkeypatch.setattr(move, "current_auth", lambda: SimpleNamespace(subject="user:u1", org=ORG)) out = await _run(to="@me") assert out.to_namespace == mine assert _answers(out) == [(URI, True, "")] @@ -1001,17 +1001,20 @@ async def test_the_namespace_moved_to_is_registered_under_the_transports_rule( from server.identity.app import namespace_autoregister from server.settings import settings - registered: list[tuple[str, str]] = [] + registered: list[tuple[str, str, bool]] = [] - async def ensure(org: str, ns: str, *, subject: str, op_name: str) -> bool: - registered.append((ns, op_name)) + async def ensure( + org: str, ns: str, *, subject: str, op_name: str, ownerless: bool = False + ) -> bool: + registered.append((ns, op_name, ownerless)) return True monkeypatch.setattr(namespace_autoregister, "ensure_registered", ensure) monkeypatch.setattr(settings, "namespace_autoregister_enabled", enabled) - monkeypatch.setattr(move, "current_auth", lambda: SimpleNamespace(subject="svc")) + monkeypatch.setattr(move, "current_auth", lambda: SimpleNamespace(subject="svc", org=ORG)) assert _answers(await _run()) == [(URI, True, "")] - assert registered == ([("dst", "knowledge.move")] if enabled else []) + # A token of the org the move lands in registers the namespace as its owner. + assert registered == ([("dst", "knowledge.move", False)] if enabled else []) async def test_a_wildcard_namespace_is_refused(store: dict[str, Any]) -> None: diff --git a/tests/unit/test_list_mine_inherited.py b/tests/unit/test_list_mine_inherited.py index f44ee9fa48..5e96f64e69 100644 --- a/tests/unit/test_list_mine_inherited.py +++ b/tests/unit/test_list_mine_inherited.py @@ -244,3 +244,28 @@ async def _unreadable(org: str) -> frozenset[str]: rows = {r.namespace: r for r in out.rows} assert set(rows) == {"code-private"} assert rows["code-private"].inherited is False + + +@pytest.mark.asyncio +async def test_a_claim_lists_no_namespace_of_another_org(wired, monkeypatch) -> None: + """A claim names namespaces of the token's own org: in another org a platform admin + lists only its grants there, never a namespace sharing a claimed name.""" + from server.identity.api.models import NamespaceListMineInput + + fake = _FakeCH([], None) + admin = AuthInfo( + subject="jdoe", + org=ORG, + namespaces=("jdoe",), + roles=(Role.PLATFORM_ADMIN,), + is_service_account=False, + ) + _install(monkeypatch, fake, admin) + mine = await membership.handle_namespace_list_mine( + NamespaceListMineInput(org=ORG, subject="jdoe") + ) + assert [(r.namespace, r.role) for r in mine.rows] == [("jdoe", "jwt")] + other = await membership.handle_namespace_list_mine( + NamespaceListMineInput(org="other", subject="jdoe") + ) + assert other.rows == [] diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index 0a07db0379..293d6feac9 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -292,3 +292,356 @@ async def _admits(ns: str, role: Role) -> bool: return ns in names return _admits + + +def _platform_admin() -> AuthInfo: + from tests.unit.principals import principal + + return principal(Role.PLATFORM_ADMIN, org="o", namespaces=("alice",), service_account=False) + + +def _org_wide_writer() -> AuthInfo: + from tests.unit.principals import principal + + return principal(Role.WRITER, org="*", namespaces=("*",), service_account=False) + + +def _bind( + monkeypatch: pytest.MonkeyPatch, + op_name: str, + arguments: dict[str, Any], + auth: AuthInfo, + scope: tuple[str, str] | None = None, +) -> dict[str, Any]: + """`arguments` as the MCP transport fills them for `auth`, whose default is + `o/alice`, on a connection whose code scope is `scope`.""" + import server.transport.mcp_call as mcp_call + from server.operations.registry import OPERATIONS_BY_NAME + + async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: + return {"org": "o", "namespace": "alice", "agent": "a"} + + monkeypatch.setattr(mcp_call, "_caller_defaults", _defaults) + monkeypatch.setattr(mcp_call, "current_code_scope", lambda: scope) + op = OPERATIONS_BY_NAME[op_name] + asyncio.run(mcp_call._bind_caller_identity(op, arguments, auth, None)) + return arguments + + +@pytest.mark.parametrize("namespace", [None, "-"]) +def test_a_call_with_no_token_takes_the_installs_namespace_whatever_org_it_names( + monkeypatch: pytest.MonkeyPatch, namespace: str | None +) -> None: + """A single-user server with no token has no platform authority to reach another + org's namesake, and HTTP fills the install's namespace whatever org the call + names (`gates.with_single_user_identity`): MCP does the same.""" + args: dict[str, Any] = {"org": "acme", "memory_key": "k", "value": "v"} + if namespace is not None: + args["namespace"] = namespace + bound = _bind(monkeypatch, "memory.set", args, None) # type: ignore[arg-type] + assert bound["namespace"] == "alice" + + +@pytest.mark.parametrize("who", ["platform_admin", "org_wide_writer"]) +@pytest.mark.parametrize(("org", "namespace"), [(None, "alice"), ("o", "alice"), ("acme", None)]) +def test_the_default_namespace_is_filled_only_in_the_callers_org( + monkeypatch: pytest.MonkeyPatch, who: str, org: str | None, namespace: str | None +) -> None: + """The default is a namespace of the caller's org: another org's namesake is not it.""" + auth = _platform_admin() if who == "platform_admin" else _org_wide_writer() + args: dict[str, Any] = {"agent": "a", "memory_key": "k"} + if org: + args["org"] = org + _bind(monkeypatch, "memory.get", args, auth) + assert (args["org"], args.get("namespace")) == (org or "o", namespace) + + +@pytest.mark.parametrize( + ("org", "code_org", "scope", "lessons"), + [ + (None, "o", None, ["alice"]), # the code plane is the caller's org + (None, "acme", None, None), # the code plane is another org's + (None, "o", ("acme", "code-x"), None), # the connection's code scope is another org's + ("acme", "o", None, None), # the call names another org + ], +) +def test_a_code_reads_lessons_come_from_the_home_only_in_the_callers_org( + monkeypatch: pytest.MonkeyPatch, + org: str | None, + code_org: str, + scope: tuple[str, str] | None, + lessons: list[str] | None, +) -> None: + from server.operations.registry import OPERATIONS_BY_NAME + from server.settings import settings + + assert "lesson_namespaces" in OPERATIONS_BY_NAME["code.search"].input_model.model_fields + monkeypatch.setattr(settings, "code_org", code_org) + args: dict[str, Any] = {"query": "q"} + if org: + args["org"] = org + _bind(monkeypatch, "code.search", args, _platform_admin(), scope) + assert args.get("lesson_namespaces") == lessons + + +@pytest.mark.parametrize("namespace", [None, "", "-", " "]) +def test_a_call_naming_another_org_and_no_namespace_fails_validation_naming_it( + monkeypatch: pytest.MonkeyPatch, namespace: str | None +) -> None: + """A blank or "-" namespace names none, as the gates read it: the call fails + validation, never runs on that literal namespace of the other org.""" + import dataclasses + + import server.transport.mcp_call as mcp_call + from server.settings import settings + from tests.unit.ch_fake import RecordingCH + + ran: list[Any] = [] + + async def _handler(inp: Any) -> Any: + ran.append(inp) + raise RuntimeError("not reached") + + async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: + return {"org": "o", "namespace": "alice", "agent": "a"} + + tool = "loom_memory_get" + monkeypatch.setitem( + mcp_call.TOOLS_BY_NAME, + tool, + dataclasses.replace(mcp_call.TOOLS_BY_NAME[tool], handler=_handler), + ) + monkeypatch.setattr(mcp_call, "_caller_defaults", _defaults) + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + RecordingCH(strict=False).install(monkeypatch) + args = {"org": "acme", "agent": "a", "memory_key": "k"} + if namespace is not None: + args["namespace"] = namespace + answer = asyncio.run( + mcp_call._call_tool(1, {"name": tool, "arguments": args}, auth=_platform_admin()) + ) + result = answer["result"] + assert result["isError"] and not ran + body = result["structuredContent"] + assert body["code"] == "VALIDATION_FAILED" + assert [list(e["loc"]) for e in body["errors"]] == [["namespace"]] + + +@pytest.mark.parametrize("org", ["acme", " acme "]) +@pytest.mark.parametrize("who", ["platform_admin", "org_wide_writer"]) +@pytest.mark.parametrize( + ("fanout", "namespace"), [(("team-a", "HOME"), "HOME"), (("team-a",), "team-a"), ((), None)] +) +def test_a_search_naming_another_org_addresses_that_orgs_fanout( + monkeypatch: pytest.MonkeyPatch, + org: str, + who: str, + fanout: tuple[str, ...], + namespace: str | None, +) -> None: + """`loom_search` takes no namespace (the screen drops one), so a search naming another + org searches the caller's namespaces there, its home first, and none it does not reach. + A padded org is that org, as the gates read it.""" + from types import SimpleNamespace + + import server.auth.fanout as fanout_mod + from server.transport.mcp_auth import _screen_tool_call + + asked: list[str] = [] + auth = _platform_admin() if who == "platform_admin" else _org_wide_writer() + home = auth.subject.split("@")[0] # the namespace named after the caller + fanout = tuple(home if ns == "HOME" else ns for ns in fanout) + namespace = home if namespace == "HOME" else namespace + + async def _fanout(org: str, *a: Any, **k: Any) -> Any: + asked.append(org) + return SimpleNamespace(namespaces=fanout) + + monkeypatch.setattr(fanout_mod, "resolve_fanout", _fanout) + import server.transport.mcp_call as mcp_call + from server.transport.mcp_identity import default_namespace_note + + notes: list[dict[str, str]] = [] + note = mcp_call.note_default_namespace + + def _note(filled: bool, ns: str, a: Any) -> None: + note(filled, ns, a) + notes.append(default_namespace_note()) + + monkeypatch.setattr(mcp_call, "note_default_namespace", _note) + args: dict[str, Any] = {"org": org, "namespace": "alice", "query": "q"} + req = {"params": {"name": "loom_search", "arguments": args}} + assert asyncio.run(_screen_tool_call(req, auth)) is None + assert "namespace" not in args + for scope in ("all_mine", "this"): + asked.clear() + bound = _bind(monkeypatch, "search.query", {**args, "namespace_scope": scope}, auth) + assert (bound["org"].strip(), bound.get("namespace"), asked) == ( + "acme", + namespace, + ["acme"], + ) + # The result notes a namespace the search landed on that is not the caller's own. + away = namespace not in (None, home) + assert notes[-1] == ({"namespace_defaulted": namespace} if away else {}) + + +@pytest.mark.parametrize( + ("org", "away"), [(None, False), ("o", False), ("acme", True), (" acme ", True)] +) +def test_the_screens_refusal_in_another_org_never_advises_omitting_the_namespace( + monkeypatch: pytest.MonkeyPatch, org: str | None, away: bool +) -> None: + """Omitting the namespace there would only fail validation (no default fills it), so + the screen's refusal names the grant alone; in the caller's org it keeps the advice.""" + from server.transport import mcp_auth + + async def _refused(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + return False, False + + monkeypatch.setattr(mcp_auth, "_may_read", _refused) + monkeypatch.setattr(mcp_auth, "_ledger_refusal", lambda *a, **k: None) + args: dict[str, Any] = {"namespace": "team", "agent": "a", "memory_key": "k"} + if org is not None: + args["org"] = org + req = {"id": 1, "params": {"name": "loom_memory_get", "arguments": args}} + out = asyncio.run(mcp_auth._screen_tool_call(req, _platform_admin())) + assert out is not None + body = out["result"]["structuredContent"] + assert body["code"] == "NAMESPACE_NOT_ACCESSIBLE" + assert ("Omit the namespace argument" in body["error"]) is not away + + +def test_a_search_naming_another_org_raises_when_its_fanout_cannot_be_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """No default stands in there, so a failed fan-out read is the server's 503, not a + validation failure telling the caller to name a namespace it cannot name.""" + import server.auth.fanout as fanout_mod + + async def _down(org: str, *a: Any, **k: Any) -> Any: + raise BackendUnavailableError("grants could not be read", operation="grant_map") + + import server.transport.mcp_call as mcp_call + + rows: list[tuple[str, str, str]] = [] + monkeypatch.setattr( + mcp_call, + "emit_token_refusal", + lambda op, auth, *, error_code, request_id="", **k: rows.append( + (op, error_code, request_id) + ), + ) + monkeypatch.setattr(fanout_mod, "resolve_fanout", _down) + with pytest.raises(BackendUnavailableError): + _bind(monkeypatch, "search.query", {"org": "acme", "query": "q"}, _platform_admin()) + [(op, code, request_id)] = rows + assert (op, code) == ("search.query", BackendUnavailableError.code) and request_id + # In the caller's org the default stands: the search runs on it, and nothing is ledgered. + bound = _bind(monkeypatch, "search.query", {"query": "q"}, _platform_admin()) + assert (bound["org"], bound["namespace"], len(rows)) == ("o", "alice", 1) + + +@pytest.mark.parametrize("error", ["wrong_cell", "too_long"]) +def test_the_callers_own_fanout_error_in_another_org_answers_as_a_tool_error( + monkeypatch: pytest.MonkeyPatch, error: str +) -> None: + """An org another cell holds, or a name past the limit, is the caller's to fix: the + search answers it as a tool error with its code, as the gate would, never an + unframed exception that loses a batch's other answers.""" + import dataclasses + + import server.auth.fanout as fanout_mod + import server.transport.mcp_call as mcp_call + from server.core.errors import ValidationError, WrongCellError + from server.settings import settings + from tests.unit.ch_fake import RecordingCH + + raised = WrongCellError("acme") if error == "wrong_cell" else ValidationError("org too long") + ran: list[Any] = [] + rows: list[str] = [] + + async def _refused(org: str, *a: Any, **k: Any) -> Any: + raise raised + + async def _handler(inp: Any) -> Any: + ran.append(inp) + + async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: + return {"org": "o", "namespace": "alice", "agent": "a"} + + tool = "loom_search" + monkeypatch.setitem( + mcp_call.TOOLS_BY_NAME, + tool, + dataclasses.replace(mcp_call.TOOLS_BY_NAME[tool], handler=_handler), + ) + monkeypatch.setattr(mcp_call, "_caller_defaults", _defaults) + monkeypatch.setattr(fanout_mod, "resolve_fanout", _refused) + monkeypatch.setattr( + mcp_call, + "emit_token_refusal", + lambda op, auth, *, error_code, **k: rows.append(error_code), + ) + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + RecordingCH(strict=False).install(monkeypatch) + args = {"org": "acme", "query": "q"} + answer = asyncio.run( + mcp_call._call_tool(1, {"name": tool, "arguments": args}, auth=_platform_admin()) + ) + result = answer["result"] + assert result["isError"] and not ran + assert result["structuredContent"]["code"] == raised.code + assert rows == [raised.code] + + +@pytest.mark.parametrize("namespace", [None, "-", ""]) +def test_a_failed_fanout_in_another_org_is_a_503_whatever_it_raised( + monkeypatch: pytest.MonkeyPatch, namespace: str | None +) -> None: + """A raw driver error or a bug is not the caller's either: it answers 503, never a + bare 500. A blank or "-" namespace names none, as the gates read it.""" + import server.auth.fanout as fanout_mod + + async def _broken(org: str, *a: Any, **k: Any) -> Any: + raise RuntimeError("Code: 241. Memory limit exceeded") + + monkeypatch.setattr(fanout_mod, "resolve_fanout", _broken) + args: dict[str, Any] = {"org": "acme", "query": "q", "namespace_scope": "this"} + if namespace is not None: + args["namespace"] = namespace + with pytest.raises(BackendUnavailableError) as raised: + _bind(monkeypatch, "search.query", args, _platform_admin()) + assert isinstance(raised.value.__cause__, RuntimeError) + + +def test_a_filled_default_moves_to_the_callers_home_among_its_fanout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from types import SimpleNamespace + + import server.auth.fanout as fanout_mod + + auth = _platform_admin() + home = auth.subject.split("@")[0] + + async def _fanout(org: str, *a: Any, **k: Any) -> Any: + return SimpleNamespace(namespaces=("alice", home)) + + monkeypatch.setattr(fanout_mod, "resolve_fanout", _fanout) + bound = _bind(monkeypatch, "search.query", {"query": "q"}, auth) + assert (bound["org"], bound["namespace"]) == ("o", home) + + +def test_an_optional_namespace_op_naming_another_org_runs_org_wide_there( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.operations.registry import OPERATIONS_BY_NAME + + model = OPERATIONS_BY_NAME["learnings.quality"].input_model + assert not model.model_fields["namespace"].is_required() + bound = _bind(monkeypatch, "learnings.quality", {"org": "acme"}, _platform_admin()) + assert (bound["org"], bound.get("namespace")) == ("acme", None) + model.model_validate(bound) # valid as filled: the handler runs its org-wide rollup diff --git a/tests/unit/test_namespace_autoregister.py b/tests/unit/test_namespace_autoregister.py index b7092e4f4e..29b62d89a8 100644 --- a/tests/unit/test_namespace_autoregister.py +++ b/tests/unit/test_namespace_autoregister.py @@ -48,8 +48,9 @@ async def insert(self, table: str, rows: list[dict[str, Any]], settings: Any = N class _Auth: - def __init__(self, subject: str = "b5-memo-bench") -> None: + def __init__(self, subject: str = "b5-memo-bench", org: str = "o") -> None: self.subject = subject + self.org = org @pytest.fixture(autouse=True) @@ -179,6 +180,16 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None): return {"in_use": 1} if "AS in_use" in sql else None +@pytest.mark.asyncio +async def test_a_first_write_from_another_org_records_no_owner() -> None: + ch = _RecordingCH() + assert await ar.ensure_registered( + "o", "team", subject="ann", op_name="memory.set", ch=ch, ownerless=True + ) + [(_, [row])] = ch.inserts + assert row["owner_email"] == "" and row["updated_at"] == ar.OWNERLESS_ROW_VERSION + + @pytest.mark.asyncio async def test_a_first_write_into_a_name_in_use_records_no_owner() -> None: from server.identity.app.namespace import _is_auto_registered_owner @@ -296,10 +307,10 @@ def test_disabled_by_setting(monkeypatch: pytest.MonkeyPatch) -> None: @pytest.mark.asyncio async def test_hook_requires_an_authenticated_subject(monkeypatch: pytest.MonkeyPatch) -> None: - calls: list[tuple[str, str, str]] = [] + calls: list[tuple[str, str, str, bool]] = [] - async def _fake(org, ns, *, subject, op_name, ch=None): - calls.append((org, ns, subject)) + async def _fake(org, ns, *, subject, op_name, ch=None, ownerless=False): + calls.append((org, ns, subject, ownerless)) return True monkeypatch.setattr(ar, "ensure_registered", _fake) @@ -307,7 +318,10 @@ async def _fake(org, ns, *, subject, op_name, ch=None): assert await ar.maybe_autoregister(op, org="o", namespace="n", auth=None) is False assert await ar.maybe_autoregister(op, org="o", namespace="n", auth=_Auth("")) is False assert await ar.maybe_autoregister(op, org="o", namespace="n", auth=_Auth("bob")) is True - assert calls == [("o", "n", "bob")] + # A writer of another org (a platform admin's) owns nothing there; an org-wide one may. + assert await ar.maybe_autoregister(op, org="o", namespace="n", auth=_Auth("ann", "a")) is True + assert await ar.maybe_autoregister(op, org="o", namespace="n", auth=_Auth("bot", "*")) is True + assert calls == [("o", "n", "bob", False), ("o", "n", "ann", True), ("o", "n", "bot", False)] def test_both_transports_call_the_hook_after_authorization() -> None: diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 0f156cde72..fc2b8f284f 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -1,4 +1,5 @@ -"""Platform authority reads registered repositories without widening other scopes.""" +"""Platform authority reads registered repositories and reaches every standard +namespace of every org, without widening other scopes.""" from dataclasses import replace from types import SimpleNamespace @@ -8,14 +9,18 @@ from server.auth import authz from server.auth.directory import ClassificationUnavailable +from server.code.app.index import repo_registry from server.code.domain.index import repos +from server.core import grant_cache from server.identity.app import namespace_classification as classification -from server.operations.base import Role +from server.identity.app import namespace_kinds +from server.operations.base import Role, grant_rank from tests.unit.code_fixtures import repo_config from tests.unit.principals import acting_as, principal ORG = "example" NS = "code-private" +STANDARD = "team" # a namespace with no repository entry or registry row, not restricted @pytest.fixture @@ -38,11 +43,22 @@ def repository(monkeypatch): def _admin(**fields): + # A dashboard session's claim names only the person's own namespaces. return principal( Role.PLATFORM_ADMIN, org=ORG, namespaces=("personal",), service_account=False, **fields ) +def _not_own(auth, authority, monkeypatch): + """`auth` holding platform_admin as a scoped, impersonated or delegated token.""" + if authority == "scoped": + return replace(auth, ns_roles=(("personal", "viewer"),)) + if authority == "impersonated": + return replace(auth, impersonated_by="sa:gateway") + monkeypatch.setattr(authz, "_check_creator", AsyncMock()) + return replace(auth, creator="owner@example.com", parents=("parent-token",)) + + @pytest.mark.parametrize("level", ["standard", "restricted"]) @pytest.mark.parametrize("cross_org", [False, True]) async def test_platform_admin_reads_repository_without_claim_or_grant(repository, level, cross_org): @@ -53,6 +69,191 @@ async def test_platform_admin_reads_repository_without_claim_or_grant(repository await authz.check_authorized(auth, Role.VIEWER, ORG, NS) +@pytest.mark.parametrize("role", [Role.VIEWER, Role.WRITER, Role.ADMIN]) +@pytest.mark.parametrize("cross_org", [False, True]) +async def test_platform_admin_reaches_a_standard_namespace_without_claim_or_grant( + repository, role, cross_org +): + auth = _admin() + if cross_org: + auth = replace(auth, org="other") + await authz.check_authorized(auth, role, ORG, STANDARD) + + +@pytest.mark.parametrize("role", [Role.VIEWER, Role.WRITER]) +@pytest.mark.parametrize("org", ["*", "-"]) +async def test_platform_authority_covers_nothing_in_an_org_that_names_no_tenant( + repository, role, org +): + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), role, org, STANDARD) + + +@pytest.mark.parametrize("authority", ["scoped", "impersonated", "delegated"]) +async def test_platform_role_reaches_no_standard_namespace_through_token_authority( + repository, monkeypatch, authority +): + # The acted-for subject is checked elsewhere; this refusal is the gate's own. + monkeypatch.setattr(authz, "check_acted_for", AsyncMock()) + with pytest.raises(PermissionError): + await authz.check_authorized( + _not_own(_admin(), authority, monkeypatch), Role.ADMIN, ORG, STANDARD + ) + + +@pytest.mark.parametrize("live", ["viewer", None]) # a viewer grant, a revoked one +async def test_no_grant_caps_platform_authority_as_none_caps_a_wildcard( + repository, monkeypatch, live +): + ranks = {STANDARD: grant_rank(live) if live else 0} + monkeypatch.setattr( + grant_cache, "grant_map", AsyncMock(return_value=grant_cache.GrantMap(ranks)) + ) + member = replace(_admin(), namespaces=("personal", STANDARD)) + await authz.check_authorized(member, Role.ADMIN, ORG, STANDARD) + # The same claim under a namespace admin's own role is capped at the grant. + with pytest.raises(PermissionError, match="no further than the grant"): + await authz.check_authorized( + replace(member, roles=(Role.ADMIN,)), Role.ADMIN, ORG, STANDARD + ) + + +async def test_a_scoped_platform_token_stays_capped_at_its_grant(repository, monkeypatch): + monkeypatch.setattr( + grant_cache, "grant_map", AsyncMock(return_value=grant_cache.GrantMap({STANDARD: 0})) + ) + scoped = replace(_admin(), namespaces=(STANDARD,), ns_roles=((STANDARD, "admin"),)) + with pytest.raises(PermissionError, match="no further than the grant"): + await authz.check_authorized(scoped, Role.VIEWER, ORG, STANDARD) + + +async def test_platform_authority_writes_no_repository_the_snapshot_does_not_hold( + repository, monkeypatch +): + # A self-service repository another replica added: its registry row is active though + # this process's snapshot does not hold it yet. Platform authority reads it either + # way, so a read reads no row. + row = AsyncMock(return_value=True) + monkeypatch.setattr(repo_registry, "registered", row) + await authz.check_authorized(_admin(), Role.VIEWER, ORG, "code-new") + row.assert_not_awaited() + for role in (Role.WRITER, Role.ADMIN): + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), role, ORG, "code-new") + row.assert_awaited_with(ORG, "code-new") + + +@pytest.mark.parametrize("role", [Role.VIEWER, Role.WRITER, Role.ADMIN]) +async def test_a_code_kind_row_alone_makes_no_repository(repository, monkeypatch, role): + # `namespace.register` takes a namespace's kind from its caller. + monkeypatch.setattr(namespace_kinds, "kind_map", AsyncMock(return_value={STANDARD: "code"})) + await authz.check_authorized(_admin(), role, ORG, STANDARD) + + +async def test_an_unreadable_registry_covers_no_write_and_the_refusal_is_unverified( + repository, monkeypatch +): + monkeypatch.setattr(repo_registry, "registered", AsyncMock(side_effect=OSError("down"))) + await authz.check_authorized(_admin(), Role.VIEWER, ORG, STANDARD) + with pytest.raises(PermissionError) as refused: + await authz.check_authorized(_admin(), Role.ADMIN, ORG, STANDARD) + assert getattr(refused.value, "unverified", False) + + +async def test_a_write_the_claim_covers_reads_no_registry(repository, monkeypatch): + row = AsyncMock(return_value=False) + monkeypatch.setattr(repo_registry, "registered", row) + await authz.check_authorized(_admin(), Role.ADMIN, ORG, "personal") + row.assert_not_awaited() + + +async def test_a_write_a_known_grant_admits_reads_no_registry(repository, monkeypatch): + """A listing or default (`CachedGate`) hands the grant in: one that admits the write + leaves platform authority unasked, and one that does not still asks it.""" + row = AsyncMock(return_value=False) + monkeypatch.setattr(repo_registry, "registered", row) + await authz.check_authorized(_admin(), Role.WRITER, ORG, STANDARD, known_grant=Role.WRITER) + row.assert_not_awaited() + await authz.check_authorized(_admin(), Role.WRITER, ORG, STANDARD, known_grant=Role.VIEWER) + row.assert_awaited_once_with(ORG, STANDARD) + + +@pytest.mark.registry_rows +@pytest.mark.parametrize( + ("row", "registered"), + [ + ({"active": True, "row_kind": "page"}, True), + ({"active": True, "row_kind": ""}, True), + ({"active": True, "row_kind": "access"}, False), + ({"active": False, "row_kind": "page"}, False), + (None, False), + ], +) +async def test_the_registry_read_counts_only_an_active_row(monkeypatch, row, registered): + from server.settings import settings + + reads = [] + + class _CH: + async def query_one(self, sql, params=None): + reads.append((sql, params)) + return row + + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH()) + monkeypatch.setattr(settings, "code_self_service_enabled", True) + assert await repo_registry.registered(ORG, STANDARD) is registered + [(sql, params)] = reads + assert "loom.code_repos" in sql and "LIMIT 1" in sql + assert params == {"org": ORG, "ns": STANDARD} + # With self-service off the snapshot reads no registry, and neither does this. + monkeypatch.setattr(settings, "code_self_service_enabled", False) + assert await repo_registry.registered(ORG, STANDARD) is False + assert len(reads) == 1 + + +async def test_an_entry_is_a_repository_with_no_read_and_an_unread_registry_is_unavailable( + repository, monkeypatch +): + from server.identity.app.directory import IdentityDirectory + + row = AsyncMock(side_effect=OSError("down")) + monkeypatch.setattr(repo_registry, "registered", row) + assert await IdentityDirectory().is_repository(ORG, NS) is True + row.assert_not_awaited() + with pytest.raises(ClassificationUnavailable): + await IdentityDirectory().is_repository(ORG, STANDARD) + + +async def test_an_ns_write_claim_still_bounds_platform_writes(repository): + auth = _admin(write_namespaces=("personal",)) + await authz.check_authorized(auth, Role.VIEWER, ORG, STANDARD) + with pytest.raises(PermissionError): + await authz.check_authorized(auth, Role.WRITER, ORG, STANDARD) + + +async def test_no_grant_caps_platform_writes_inside_the_ns_write_claim(repository, monkeypatch): + monkeypatch.setattr( + grant_cache, + "grant_map", + AsyncMock(return_value=grant_cache.GrantMap({STANDARD: grant_rank("viewer")})), + ) + auth = replace(_admin(write_namespaces=(STANDARD,)), namespaces=("personal", STANDARD)) + await authz.check_authorized(auth, Role.WRITER, ORG, STANDARD) + with pytest.raises(PermissionError): + await authz.check_authorized(auth, Role.WRITER, ORG, "elsewhere") + + +@pytest.mark.parametrize("role", [Role.VIEWER, Role.WRITER, Role.ADMIN]) +@pytest.mark.parametrize("cross_org", [False, True]) +async def test_a_third_party_clients_session_gets_no_platform_reach(repository, role, cross_org): + """A third-party MCP client's sign-in session (`first_party` false) keeps its claim + and grants; Loom's own sessions (the dashboard, `loom login`) keep platform reach.""" + session = replace(_admin(), session_id="family-1", org="other" if cross_org else ORG) + with pytest.raises(PermissionError): + await authz.check_authorized(session, role, ORG, STANDARD) + await authz.check_authorized(replace(session, first_party=True), role, ORG, STANDARD) + + @pytest.mark.parametrize("role", [Role.ADMIN, Role.ORG_ADMIN]) @pytest.mark.parametrize("level", ["standard", "restricted"]) async def test_namespace_and_org_admin_still_need_repository_access(repository, role, level): @@ -68,35 +269,32 @@ async def test_platform_role_does_not_escape_token_authority( repository, monkeypatch, level, authority ): repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) - auth = _admin() - if authority == "scoped": - auth = replace(auth, ns_roles=(("personal", "viewer"),)) - elif authority == "impersonated": - auth = replace(auth, impersonated_by="sa:gateway") - else: - auth = replace(auth, creator="owner@example.com", parents=("parent-token",)) - monkeypatch.setattr(authz, "_check_creator", AsyncMock()) with pytest.raises(PermissionError): - await authz.check_authorized(auth, Role.VIEWER, ORG, NS) + await authz.check_authorized( + _not_own(_admin(), authority, monkeypatch), Role.VIEWER, ORG, NS + ) +@pytest.mark.parametrize("role", [Role.VIEWER, Role.ADMIN]) @pytest.mark.parametrize("namespace", ["memory-private", "tracker-private", "code-unknown"]) -async def test_platform_authority_does_not_widen_unregistered_namespaces( - repository, monkeypatch, namespace +async def test_platform_authority_does_not_open_restricted_namespaces( + repository, monkeypatch, namespace, role ): monkeypatch.setattr( classification, "restricted_set", AsyncMock(return_value=frozenset({namespace})) ) with pytest.raises(PermissionError): - await authz.check_authorized(_admin(), Role.VIEWER, ORG, namespace) + await authz.check_authorized(_admin(), role, ORG, namespace) @pytest.mark.parametrize("role", [Role.WRITER, Role.ADMIN]) @pytest.mark.parametrize("level", ["standard", "restricted"]) -async def test_repository_writes_still_require_access(repository, role, level): +@pytest.mark.parametrize("cross_org", [False, True]) +async def test_repository_writes_still_require_access(repository, role, level, cross_org): repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + auth = replace(_admin(), org="other") if cross_org else _admin() with pytest.raises(PermissionError): - await authz.check_authorized(_admin(), role, ORG, NS) + await authz.check_authorized(auth, role, ORG, NS) async def test_registered_repository_does_not_need_a_code_prefix(repository): @@ -105,7 +303,11 @@ async def test_registered_repository_does_not_need_a_code_prefix(repository): await authz.check_authorized(_admin(), Role.VIEWER, ORG, "repository-index") -async def test_new_registry_entry_is_checked_on_each_read(repository): +async def test_new_registry_entry_is_checked_on_each_read(repository, monkeypatch): + # Restricted, so only the entry admits: a standard name is one platform authority reaches. + monkeypatch.setattr( + classification, "restricted_set", AsyncMock(return_value=frozenset({"code-added"})) + ) with pytest.raises(PermissionError): await authz.check_authorized(_admin(), Role.VIEWER, ORG, "code-added") repository[(ORG, "code-added")] = replace(repository[(ORG, NS)], namespace="code-added") @@ -131,12 +333,15 @@ async def test_unavailable_classification_still_refuses_platform_admin(repositor await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) -async def test_held_org_refusal_precedes_repository_authority(repository, monkeypatch): +@pytest.mark.parametrize(("namespace", "role"), [(NS, Role.VIEWER), (STANDARD, Role.ADMIN)]) +async def test_held_org_refusal_precedes_platform_authority( + repository, monkeypatch, namespace, role +): from server.auth import tenancy monkeypatch.setattr(tenancy, "ensure_held", AsyncMock(side_effect=PermissionError("not held"))) with pytest.raises(PermissionError, match="not held"): - await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) + await authz.check_authorized(_admin(), role, ORG, namespace) async def test_invalid_principal_is_refused_before_repository_authority(repository): @@ -209,23 +414,31 @@ async def test_admin_listing_returns_actual_heads_and_counts( assert status_read.await_count >= 1 -async def test_repository_authority_never_opens_mirrors(repository): +@pytest.mark.parametrize("registered", [True, False]) +@pytest.mark.parametrize("role", [Role.VIEWER, Role.ADMIN]) +async def test_platform_authority_never_opens_mirrors(repository, registered, role): mirror = "acl-0123456789abcdef01234567" - repository[(ORG, mirror)] = replace(repository[(ORG, NS)], namespace=mirror) + if registered: + repository[(ORG, mirror)] = replace(repository[(ORG, NS)], namespace=mirror) for auth in (_admin(), None): with pytest.raises(PermissionError): - await authz.check_authorized(auth, Role.VIEWER, ORG, mirror) + await authz.check_authorized(auth, role, ORG, mirror) -async def test_collection_gate_precedes_repository_authority(repository, monkeypatch): +@pytest.mark.parametrize("registered", [True, False]) +@pytest.mark.parametrize("role", [Role.VIEWER, Role.ADMIN]) +async def test_collection_gate_precedes_platform_authority( + repository, monkeypatch, registered, role +): from server.auth import sharing namespace = sharing.COLLECTION_PREFIX + "private" - repository[(ORG, namespace)] = replace(repository[(ORG, NS)], namespace=namespace) + if registered: + repository[(ORG, namespace)] = replace(repository[(ORG, NS)], namespace=namespace) denied = AsyncMock(side_effect=PermissionError("collection refused")) monkeypatch.setattr(sharing, "check", denied) with pytest.raises(PermissionError, match="collection refused"): - await authz.check_authorized(_admin(), Role.VIEWER, ORG, namespace) + await authz.check_authorized(_admin(), role, ORG, namespace) denied.assert_awaited_once() @@ -279,16 +492,66 @@ def verify(token): read = AsyncMock(return_value=([{"path": "src/private.py", "lang": "python"}], 1)) monkeypatch.setattr(files.CodeRepo, "list_files", read) op = OPERATIONS_BY_NAME["code.files"] - monkeypatch.setattr(http, "ALL_OPERATIONS", [op]) + written = [] + + async def _write(inp): + written.append((inp.org, inp.namespace)) + return write.output_model(version=1) + + write = replace(OPERATIONS_BY_NAME["memory.set"], handler=_write) + monkeypatch.setattr(http, "ALL_OPERATIONS", [op, write]) monkeypatch.setattr(http, "_emit_event", lambda *a, **kw: None) monkeypatch.setattr(mcp_call, "_caller_defaults", AsyncMock()) monkeypatch.setitem(mcp_call.TOOLS_BY_NAME, "loom_code_files", op) + monkeypatch.setitem(mcp_call.TOOLS_BY_NAME, "loom_memory_set", write) for mod in (mcp_call, mcp_outcome): monkeypatch.setattr(mod, "_emit_mcp_event", lambda *a, **kw: None) app = FastAPI() app.include_router(http.build_router()) with TestClient(app) as client: - yield SimpleNamespace(http=client, tokens=tokens, read=read, audit=audit, mcp=mcp_call) + yield SimpleNamespace( + http=client, tokens=tokens, read=read, audit=audit, mcp=mcp_call, written=written + ) + + +# A session's claim names only its own namespaces; another org's standard one is reached +# through platform authority, which a scoped token holding the role does not have. +_FOREIGN_WRITE = {"org": "other", "namespace": STANDARD, "agent": "a", "memory_key": "k"} + + +@pytest.mark.parametrize("who", ["admin", "scoped"]) +def test_http_platform_authority_writes_another_orgs_standard_namespace(transports, who): + response = transports.http.post( + "/v1/memory.set", + json={**_FOREIGN_WRITE, "value": "v"}, + headers={"Authorization": "Bearer " + who}, + ) + if who == "admin": + assert response.status_code == 200, response.text + assert transports.written == [("other", STANDARD)] + else: + assert response.status_code == 403, response.text + assert transports.written == [] + + +@pytest.mark.parametrize("who", ["admin", "scoped"]) +async def test_mcp_platform_authority_writes_another_orgs_standard_namespace( + transports, monkeypatch, who +): + defaults = {"org": ORG, "namespace": "personal", "agent": "a"} + monkeypatch.setattr(transports.mcp, "_caller_defaults", AsyncMock(return_value=defaults)) + response = await transports.mcp._call_tool( + 1, + {"name": "loom_memory_set", "arguments": {**_FOREIGN_WRITE, "value": "v"}}, + auth=transports.tokens[who], + ) + result = response["result"] + if who == "admin": + assert not result["isError"], result + assert transports.written == [("other", STANDARD)] + else: + assert result["isError"], result + assert transports.written == [] @pytest.mark.parametrize( @@ -344,7 +607,10 @@ async def test_self_service_registry_snapshot_decides_repository_authority(monke monkeypatch.setattr(repos, "_configured_from_env", lambda _config, _errors: []) for name in ("_registry_repos", "_registry_namespaces", "_page_namespaces", "_registry_loaded"): monkeypatch.setattr(repos, name, getattr(repos, name)) - monkeypatch.setattr(classification, "restricted_set", AsyncMock(return_value=frozenset())) + # Restricted, so only the entry admits: a standard name is one platform authority reaches. + monkeypatch.setattr( + classification, "restricted_set", AsyncMock(return_value=frozenset({"page-index"})) + ) monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=None)) entry = repo_config( org=ORG, @@ -439,3 +705,13 @@ async def test_provisioning_precedes_repository_authority( with pytest.raises(refusal): await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) check.assert_awaited_once() + + +async def test_provisioning_precedes_standard_namespace_reach(repository, monkeypatch): + from server.auth import scim + + check = AsyncMock(return_value=True) + monkeypatch.setattr(scim, "refuses_auth", check) + with pytest.raises(authz.ActedForRefused): + await authz.check_authorized(_admin(), Role.ADMIN, ORG, STANDARD) + check.assert_awaited_once() diff --git a/tests/unit/test_readable_named_claims.py b/tests/unit/test_readable_named_claims.py index d16abdd11a..d80bf6fa1e 100644 --- a/tests/unit/test_readable_named_claims.py +++ b/tests/unit/test_readable_named_claims.py @@ -256,3 +256,28 @@ async def _counted(org: str, subject: str, **_: Any) -> str | None: token = _token("sa:inherits", ("team", "solo", "left"), is_service_account=True) assert asyncio.run(readable_named_claims(token, ORG)) == ["team"] assert set(calls) == {"sa:inherits"} + + +def test_a_platform_admins_claims_name_no_namespace_of_another_org(monkeypatch) -> None: + """Platform authority reaches another org's `team`; the claim's `team` is a namespace + of the admin's own org, so neither the named claims nor an `all_mine` fan-out there + takes it as the caller's.""" + from server.auth import context + + async def _granted(org: str, subjects: list[str]) -> set[str]: + return {"docs"} if org == ORG else set() + + async def _aliases(org: str, subject: str, *, ch: Any = None) -> list[str]: + return [subject] + + monkeypatch.setattr(context, "_granted_namespaces", _granted) + monkeypatch.setattr("server.auth.aliases.subject_aliases", _aliases) + admin = _token("alice", ("team", "home"), org="other", roles=(Role.PLATFORM_ADMIN,)) + assert asyncio.run(_gate_reads(admin, "team")) + assert asyncio.run(readable_named_claims(admin, ORG)) == [] + assert asyncio.run(readable_named_claims(admin, "other")) == ["team", "home"] + context.set_current_auth(admin) + try: + assert asyncio.run(context.resolve_my_namespaces(ORG)) == ["docs"] + finally: + context.set_current_auth(None)