From 364e2a22f761a8eaa6ab7bfd8eb62aefd45e8414 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:38:06 +0530 Subject: [PATCH 01/16] A platform admin's own authority reaches every standard namespace of every org A sign-in token names only the person's own namespaces, and the gate read platform_admin only through the claim, so it refused the person the namespace ops the role stands for; a bot's or a minted token's `*` claim reached every namespace of its own org and none of another's. Own platform authority (not scoped, delegated or impersonated) covers every namespace that is not a repository, in every org, and no grant row caps it, as none caps a `*` claim. Restricted namespaces, collections, mirrors and code stores, repository writes, tenancy and the acted-for check keep their own rules; an `ns_write` claim still bounds writes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 30 +++- docs/guides/tokens-and-grants.md | 25 ++-- docs/operations/sso.md | 9 +- server/auth/authz.py | 18 ++- tests/unit/test_blacklist_authority.py | 13 +- tests/unit/test_erasure_authz_matrix.py | 8 +- .../test_platform_admin_repository_read.py | 132 ++++++++++++++---- 7 files changed, 186 insertions(+), 49 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 2299dadb8b5..1bfb76438d2 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,17 @@ 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 is not a repository, whatever its claims name, as a `*` + claim covers its own org's; an `ns_write` claim still bounds its writes. Otherwise 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 +303,18 @@ 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 standard namespace.** 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 reach. 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. + `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 @@ -382,8 +399,9 @@ nothing without a repository entry. 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. diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index 74aa988bfa1..c5af7459115 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 standard namespace of every org, 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,10 @@ 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, + 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 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 +250,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 +479,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 of other kinds +([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 5720c18859e..4e27d361ec0 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 that is not restricted and not a repository, with no +grant there, though its token names only the person's own namespaces; a +restricted namespace and a repository keep their own rules +([namespace access](../guides/tokens-and-grants.md#namespace-access)). ## 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 reach what 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/server/auth/authz.py b/server/auth/authz.py index beac34dbc78..882dbbb6fc7 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -339,7 +339,12 @@ async def _check_authorized_claims( # A claim on a namespace where the subject holds a grant row is capped at # that grant, so a revoked or lowered grant ends every older token's claim. - cap = None if org is None or namespace is None else await claim_cap(auth, org, namespace) + # Platform authority comes from no grant, so none caps it, as none caps `*`. + cap = ( + None + if org is None or namespace is None or _platform_covers(auth, org, namespace) + else await claim_cap(auth, org, namespace) + ) capped = cap is not None # Scoped token (carries an `ns_roles` map): the per-namespace role is @@ -359,11 +364,12 @@ 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). + # An `ns_write` claim still bounds platform authority's writes. 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) - ) + ) or (_platform_covers(auth, org, namespace) and not (is_write and auth.write_namespaces)) 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 @@ -631,6 +637,14 @@ def _platform_repository_read( ) +def _platform_covers(auth: AuthorizationClaims, org: str, namespace: str) -> bool: + """Own platform authority covers a standard namespace of every org, as a `*` + claim covers its own org's. The gate asks after it has sent restricted + namespaces, collections and delegated tokens to their own checks; a + repository keeps the read-only authority of `_platform_repository_read`.""" + return is_own_platform_admin(auth) and not _is_code_namespace(org, namespace) + + 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 diff --git a/tests/unit/test_blacklist_authority.py b/tests/unit/test_blacklist_authority.py index a6445d280c4..34aec3ffe42 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_erasure_authz_matrix.py b/tests/unit/test_erasure_authz_matrix.py index 41626245a88..0a6e2deea08 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_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 0f156cde721..5f2daf1ce1e 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 @@ -9,13 +10,15 @@ from server.auth import authz from server.auth.directory import ClassificationUnavailable 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.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, classified standard @pytest.fixture @@ -38,11 +41,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 +67,53 @@ 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("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_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) + + @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,27 +129,22 @@ 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]) @@ -105,7 +161,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 +191,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 +272,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() @@ -344,7 +415,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 +513,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() From ee06f8fd3edece9b7f8fd348fa690d649591c8df Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:18:18 +0530 Subject: [PATCH 02/16] Platform authority reads a repository's kind row before it covers a name The registry snapshot each process holds is refreshed on a timer, so a repository another replica registered a moment ago may not be in it. Platform coverage also asks the kind directory (kind `code`), read fail closed: kinds that cannot be read cover nothing and the refusal is unverified. The docs name the cases platform authority leaves to their own rules and how a `*` claim adds its own org's repositories. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 25 ++++++++----- docs/guides/tokens-and-grants.md | 17 +++++---- docs/operations/sso.md | 11 +++--- server/auth/authz.py | 37 +++++++++++++------ server/auth/directory.py | 6 +++ server/identity/app/directory.py | 11 ++++++ tests/unit/test_blacklist_authority.py | 5 +++ .../test_default_namespace_gate_property.py | 2 +- .../test_platform_admin_repository_read.py | 35 +++++++++++++++++- 9 files changed, 112 insertions(+), 37 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 1bfb76438d2..c7d01687e28 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -290,8 +290,12 @@ authenticated call, from `gates.authorize` in both transports: 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. A platform administrator's own unscoped authority (`authz.is_own_platform_admin`) covers every - namespace of every org that is not a repository, whatever its claims name, as a `*` - claim covers its own org's; an `ns_write` claim still bounds its writes. Otherwise a + 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 repository is a configured or registry entry, or a directory row of kind `code` + (`NamespaceDirectory.is_repository`), so one this process's registry snapshot has not + read yet is still one. The kinds are cached per org for 30 s, as the classifications + are, and kinds that cannot be read cover nothing. Otherwise 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 @@ -303,17 +307,19 @@ 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 standard namespace.** The role spans every org: the +**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 reach. 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. +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. `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 @@ -393,8 +399,9 @@ 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 or a directory row of kind `code`: 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 diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index c5af7459115..f29a7d06a50 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` | Every standard namespace of every org, 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. | +| 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 @@ -175,7 +175,8 @@ A call on `(org, namespace)` is allowed when: 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. 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, + and acts for no other subject) covers every namespace of every org but a repository (a + code namespace, `kind=code`), whatever `namespaces` names and whatever grant its subject holds there, as a `*` claim covers its own org's; `ns_write` still bounds its writes. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 4e27d361ec0..3269d28bc35 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -140,10 +140,9 @@ For a person with no account: Platform admins are the verified emails listed in `LOOM_PLATFORM_ADMINS`. The provider can never grant admin. A platform admin's session reaches every -namespace of every org that is not restricted and not a repository, with no -grant there, though its token names only the person's own namespaces; a -restricted namespace and a repository keep their own rules -([namespace access](../guides/tokens-and-grants.md#namespace-access)). +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)). ## Bots and CI @@ -374,8 +373,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 reach what a signed-in platform admin's -reach), 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/server/auth/authz.py b/server/auth/authz.py index 882dbbb6fc7..dd15cf45ecb 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -340,9 +340,10 @@ async def _check_authorized_claims( # A claim on a namespace where the subject holds a grant row is capped at # that grant, so a revoked or lowered grant ends every older token's claim. # Platform authority comes from no grant, so none caps it, as none caps `*`. + platform = await _platform_covers(auth, required_role, org, namespace) cap = ( None - if org is None or namespace is None or _platform_covers(auth, org, namespace) + if org is None or namespace is None or platform else await claim_cap(auth, org, namespace) ) capped = cap is not None @@ -364,12 +365,12 @@ 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). - # An `ns_write` claim still bounds platform authority's writes. - 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) - ) or (_platform_covers(auth, org, namespace) and not (is_write and auth.write_namespaces)) + ns_covered_by_jwt = platform or ( + 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 @@ -637,12 +638,24 @@ def _platform_repository_read( ) -def _platform_covers(auth: AuthorizationClaims, org: str, namespace: str) -> bool: - """Own platform authority covers a standard namespace of every org, as a `*` - claim covers its own org's. The gate asks after it has sent restricted - namespaces, collections and delegated tokens to their own checks; a - repository keeps the read-only authority of `_platform_repository_read`.""" - return is_own_platform_admin(auth) and not _is_code_namespace(org, namespace) +async def _platform_covers( + auth: AuthorizationClaims, required_role: Role, org: str | None, namespace: str | None +) -> bool: + """Whether own platform authority covers (org, namespace), as a `*` claim covers its + own org's: any namespace of any org but a repository, which keeps the read-only + authority of `_platform_repository_read`. An `ns_write` claim still bounds a write. + The gate asks after it has sent mirrors and code stores, collections, delegated + tokens and restricted namespaces to their own checks. Kinds that cannot be read + cover nothing: the claim and grant checks decide, and a refusal is unverified.""" + if org is None or namespace is None or not is_own_platform_admin(auth): + return False + if required_role.value >= Role.WRITER.value and auth.write_namespaces: + 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: diff --git a/server/auth/directory.py b/server/auth/directory.py index 015e6e80159..d359dd89cfb 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 a + directory row of kind `code` (one this process's registry snapshot may not hold + yet). Raises `ClassificationUnavailable` when the kinds 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/identity/app/directory.py b/server/identity/app/directory.py index a9507895144..9fbf54522cc 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -5,9 +5,11 @@ from __future__ import annotations +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.errors import BackendUnavailableError 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 @@ -39,6 +41,15 @@ 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 + try: + kinds = await namespace_kinds.kind_map(org, fail_closed=True) + except BackendUnavailableError as e: + raise ClassificationUnavailable(str(e)) from e + return kinds.get(namespace) == "code" + 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/tests/unit/test_blacklist_authority.py b/tests/unit/test_blacklist_authority.py index 34aec3ffe42..7ba5ddefe7e 100644 --- a/tests/unit/test_blacklist_authority.py +++ b/tests/unit/test_blacklist_authority.py @@ -406,6 +406,11 @@ 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.""" + + async def _no_kinds(org: str, *, fail_closed: bool = False) -> dict[str, str]: + return {} + + monkeypatch.setattr("server.identity.app.namespace_kinds.kind_map", _no_kinds) repo.rows["pb"] = _row("pb", "namespace", namespace="ns-b") swept = _record_sweeps(monkeypatch) set_current_auth(_auth("PLATFORM_ADMIN", namespaces=("ns-a",))) diff --git a/tests/unit/test_default_namespace_gate_property.py b/tests/unit/test_default_namespace_gate_property.py index 5fc1de2379f..1ffcffe7f9a 100644 --- a/tests/unit/test_default_namespace_gate_property.py +++ b/tests/unit/test_default_namespace_gate_property.py @@ -139,7 +139,7 @@ async def _restricted_set(org: str) -> frozenset[str]: raise ClassificationUnavailable("down") return WORLD.restricted - async def _kinds(org: str) -> dict[str, str]: + async def _kinds(org: str, *, fail_closed: bool = False) -> dict[str, str]: return dict(WORLD.kinds) async def _aliases(org: str, subject: str, *, ch: Any = None) -> list[str]: diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 5f2daf1ce1e..70dab25f8b2 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -11,14 +11,16 @@ from server.auth.directory import ClassificationUnavailable from server.code.domain.index import repos from server.core import grant_cache +from server.core.errors import BackendUnavailableError from server.identity.app import namespace_classification as classification +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, classified standard +STANDARD = "team" # a namespace with no repository entry or `code` kind row, not restricted @pytest.fixture @@ -37,6 +39,7 @@ def repository(monkeypatch): monkeypatch.setattr(classification, "restricted_set", AsyncMock(return_value=frozenset())) monkeypatch.setattr(authz, "grant_role_for", AsyncMock(return_value=None)) monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=None)) + monkeypatch.setattr(namespace_kinds, "kind_map", AsyncMock(return_value={})) return entries @@ -107,6 +110,36 @@ async def test_no_grant_caps_platform_authority_as_none_caps_a_wildcard( ) +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) + + +@pytest.mark.parametrize("role", [Role.WRITER, Role.ADMIN]) +async def test_platform_authority_writes_no_repository_the_snapshot_does_not_hold( + repository, monkeypatch, role +): + # A self-service repository another replica added, or one this process has not read + # yet: its directory row says `code` though the registry snapshot lacks it. + monkeypatch.setattr(namespace_kinds, "kind_map", AsyncMock(return_value={"code-new": "code"})) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), role, ORG, "code-new") + + +async def test_unreadable_kinds_cover_nothing_and_the_refusal_is_unverified( + repository, monkeypatch +): + down = AsyncMock(side_effect=BackendUnavailableError("namespace kinds could not be read")) + monkeypatch.setattr(namespace_kinds, "kind_map", down) + with pytest.raises(PermissionError) as refused: + await authz.check_authorized(_admin(), Role.ADMIN, ORG, STANDARD) + assert getattr(refused.value, "unverified", False) + + 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) From e398d2e1c03d61d1bff878676879ece3c134950b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:29:52 +0530 Subject: [PATCH 03/16] The kind directory read raises with the caller text of its error `IdentityDirectory.is_repository` passed the caught error's text into `ClassificationUnavailable`; `caller_text` gives the code and message a Loom error writes for callers, and `kind_map` has already logged the failure (`test_exception_text_ratchet`). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/identity/app/directory.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/identity/app/directory.py b/server/identity/app/directory.py index 9fbf54522cc..7cc303cbd84 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -9,7 +9,7 @@ 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.errors import BackendUnavailableError +from server.core.errors import BackendUnavailableError, caller_text 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 @@ -47,7 +47,7 @@ async def is_repository(self, org: str, namespace: str) -> bool: try: kinds = await namespace_kinds.kind_map(org, fail_closed=True) except BackendUnavailableError as e: - raise ClassificationUnavailable(str(e)) from e + raise ClassificationUnavailable(caller_text(e)) from e return kinds.get(namespace) == "code" def restricted_code_namespaces(self, org: str) -> set[str]: From ade7e9ff646d851ba5aed00a94660dffe1fa84a5 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:49:33 +0530 Subject: [PATCH 04/16] A platform admin's write reads the repository registry row, not the kind column `namespace.register` takes a namespace's kind from its caller, so a directory row of kind `code` took a standard namespace out of platform authority, though it is no repository and platform authority does not read it. The kinds were also cached per org for 30 s, so a repository another replica added could still be written for that long. A read leaves out the entries this process's configuration and registry snapshot hold, which keeps the member write check the grant's; platform authority reads any other repository anyway. A write also reads the namespace's registry row at the write, under sequential reads, and a registry that cannot be read covers no write. The kind column decides nothing, and the property test's fake `kind_map` keeps its signature. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 16 ++++---- docs/guides/tokens-and-grants.md | 10 ++--- server/auth/authz.py | 15 +++++--- server/auth/directory.py | 6 +-- server/code/app/index/repo_registry.py | 11 ++++++ server/identity/app/directory.py | 21 +++++++--- tests/unit/test_blacklist_authority.py | 6 +-- .../test_default_namespace_gate_property.py | 7 +++- tests/unit/test_erasure_authz_matrix.py | 1 + .../test_platform_admin_repository_read.py | 38 ++++++++++++------- 10 files changed, 89 insertions(+), 42 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index c7d01687e28..152ad341c0b 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -292,11 +292,13 @@ authenticated call, from `gates.authorize` in both transports: 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 repository is a configured or registry entry, or a directory row of kind `code` - (`NamespaceDirectory.is_repository`), so one this process's registry snapshot has not - read yet is still one. The kinds are cached per org for 30 s, as the classifications - are, and kinds that cannot be read cover nothing. Otherwise a - live grant in `loom.namespace_grants` decides: unrevoked and `active` (`grant_sql.LIVE_GRANT`); a + 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 @@ -400,8 +402,8 @@ snapshot. This includes restricted, approval and closed repositories across 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-` is no -repository without a repository entry or a directory row of kind `code`: it is an ordinary -namespace ([the gate](#the-gate), step 8). +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 diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index f29a7d06a50..5176de9fdc0 100644 --- a/docs/guides/tokens-and-grants.md +++ b/docs/guides/tokens-and-grants.md @@ -175,10 +175,10 @@ A call on `(org, namespace)` is allowed when: 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. 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 - code namespace, `kind=code`), - whatever `namespaces` names and whatever grant its subject holds there, as a `*` claim - covers its own org's; `ns_write` still bounds its writes. + 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 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 @@ -481,7 +481,7 @@ An authenticated platform administrator using its own unscoped authority can rea 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 -restricted namespaces of other kinds +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. diff --git a/server/auth/authz.py b/server/auth/authz.py index dd15cf45ecb..640fd7e3dd7 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -643,13 +643,18 @@ async def _platform_covers( ) -> bool: """Whether own platform authority covers (org, namespace), as a `*` claim covers its own org's: any namespace of any org but a repository, which keeps the read-only - authority of `_platform_repository_read`. An `ns_write` claim still bounds a write. - The gate asks after it has sent mirrors and code stores, collections, delegated - tokens and restricted namespaces to their own checks. Kinds that cannot be read - cover nothing: the claim and grant checks decide, and a refusal is unverified.""" + authority of `_platform_repository_read`. The gate asks after it has sent mirrors + and code stores, collections, delegated tokens and restricted namespaces to their + own checks. A read leaves out the configured entries alone, so the read check of a + member write (`member_writes`) stays the grant's; a repository outside them is one + platform authority reads anyway. A write also leaves out an active registry row read + now, and an `ns_write` claim still bounds it. A registry that cannot be read covers + no write: the claim and grant checks decide, and a refusal is unverified.""" if org is None or namespace is None or not is_own_platform_admin(auth): return False - if required_role.value >= Role.WRITER.value and auth.write_namespaces: + if required_role.value < Role.WRITER.value: + return not _is_code_namespace(org, namespace) + if auth.write_namespaces: return False try: return not await directory().is_repository(org, namespace) diff --git a/server/auth/directory.py b/server/auth/directory.py index d359dd89cfb..a0e042e6b95 100644 --- a/server/auth/directory.py +++ b/server/auth/directory.py @@ -64,9 +64,9 @@ def code_entry(self, org: str, namespace: str) -> CodeEntry | None: ... async def is_repository(self, org: str, namespace: str) -> bool: - """Whether (org, namespace) is a repository: a configured code-plane entry, or a - directory row of kind `code` (one this process's registry snapshot may not hold - yet). Raises `ClassificationUnavailable` when the kinds cannot be read.""" + """Whether (org, namespace) is a repository: a configured code-plane entry, or an + active registry row read now (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]: diff --git a/server/code/app/index/repo_registry.py b/server/code/app/index/repo_registry.py index 81b7d99ad8f..30c8d0a577a 100644 --- a/server/code/app/index/repo_registry.py +++ b/server/code/app/index/repo_registry.py @@ -295,6 +295,17 @@ async def insert_entry( ) +async def registered(org: str, namespace: str) -> bool: + """Whether (org, namespace) holds an active registry row, read now: a repository + another replica added is one before this process's snapshot reads it.""" + from server.code.store.index import CodeRepo + from server.core.ch import sequential_reads + + with sequential_reads(): + row = await CodeRepo().code_repo_row(org, namespace) + return bool(row and row.get("active")) + + 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/identity/app/directory.py b/server/identity/app/directory.py index 7cc303cbd84..92668a7d77d 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -5,17 +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.errors import BackendUnavailableError, caller_text +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 { @@ -44,11 +48,18 @@ def code_entry(self, org: str, namespace: str) -> RepoConfig | None: 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: - kinds = await namespace_kinds.kind_map(org, fail_closed=True) - except BackendUnavailableError as e: - raise ClassificationUnavailable(caller_text(e)) from e - return kinds.get(namespace) == "code" + return await repo_registry.registered(org, namespace) + except Exception as e: # any failure refuses: an unreadable registry decides nothing + 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 { diff --git a/tests/unit/test_blacklist_authority.py b/tests/unit/test_blacklist_authority.py index 7ba5ddefe7e..a3c8a548540 100644 --- a/tests/unit/test_blacklist_authority.py +++ b/tests/unit/test_blacklist_authority.py @@ -407,10 +407,10 @@ def test_a_platform_admin_sweeps_a_namespace_pattern_its_claim_does_not_name( ) -> None: """Platform authority reaches every standard namespace, whatever the claim names.""" - async def _no_kinds(org: str, *, fail_closed: bool = False) -> dict[str, str]: - return {} + async def _no_row(org: str, namespace: str) -> bool: + return False - monkeypatch.setattr("server.identity.app.namespace_kinds.kind_map", _no_kinds) + monkeypatch.setattr("server.code.app.index.repo_registry.registered", _no_row) repo.rows["pb"] = _row("pb", "namespace", namespace="ns-b") swept = _record_sweeps(monkeypatch) set_current_auth(_auth("PLATFORM_ADMIN", namespaces=("ns-a",))) diff --git a/tests/unit/test_default_namespace_gate_property.py b/tests/unit/test_default_namespace_gate_property.py index 1ffcffe7f9a..df18e03fb37 100644 --- a/tests/unit/test_default_namespace_gate_property.py +++ b/tests/unit/test_default_namespace_gate_property.py @@ -113,6 +113,7 @@ def _fakes(monkeypatch: pytest.MonkeyPatch) -> None: import server.auth.delegation as delegation import server.auth.personal_namespace as personal_namespace import server.auth.service_accounts as service_accounts + import server.code.app.index.repo_registry as repo_registry import server.code.domain.index.repos as repos import server.core.ch as chmod import server.core.grant_cache as grant_cache @@ -139,9 +140,12 @@ async def _restricted_set(org: str) -> frozenset[str]: raise ClassificationUnavailable("down") return WORLD.restricted - async def _kinds(org: str, *, fail_closed: bool = False) -> dict[str, str]: + async def _kinds(org: str) -> dict[str, str]: return dict(WORLD.kinds) + async def _registered(org: str, namespace: str) -> bool: + return False # the configured entries are the world's only repositories + async def _aliases(org: str, subject: str, *, ch: Any = None) -> list[str]: return [subject] @@ -172,6 +176,7 @@ def _code_entry(org: str, namespace: str) -> _CodeEntry | None: monkeypatch.setattr(delegation, "creator_account_active", _active) monkeypatch.setattr(nc, "restricted_set", _restricted_set) monkeypatch.setattr(nk, "kind_map", _kinds) + monkeypatch.setattr(repo_registry, "registered", _registered) monkeypatch.setattr(aliases, "subject_aliases", _aliases) monkeypatch.setattr(caller_defaults, "saved_default", _saved) monkeypatch.setattr(caller_defaults, "ranked_grants", _ranked) diff --git a/tests/unit/test_erasure_authz_matrix.py b/tests/unit/test_erasure_authz_matrix.py index 0a6e2deea08..5f064ea3c76 100644 --- a/tests/unit/test_erasure_authz_matrix.py +++ b/tests/unit/test_erasure_authz_matrix.py @@ -122,6 +122,7 @@ async def _mine(org: str, subject: str | None = None) -> list[str]: monkeypatch.setattr(authz, "_lookup_grant", _no_grant) monkeypatch.setattr(authz, "may_be_restricted", _false) monkeypatch.setattr(authz, "is_org_readable_code_namespace", _false) + monkeypatch.setattr("server.code.app.index.repo_registry.registered", _false) monkeypatch.setattr(handlers, "begin_erasure", _begin) for name in ( "export_memory", diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 70dab25f8b2..37b29b5896d 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -9,9 +9,9 @@ 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.core.errors import BackendUnavailableError from server.identity.app import namespace_classification as classification from server.identity.app import namespace_kinds from server.operations.base import Role, grant_rank @@ -20,7 +20,7 @@ ORG = "example" NS = "code-private" -STANDARD = "team" # a namespace with no repository entry or `code` kind row, not restricted +STANDARD = "team" # a namespace with no repository entry or registry row, not restricted @pytest.fixture @@ -39,7 +39,7 @@ def repository(monkeypatch): monkeypatch.setattr(classification, "restricted_set", AsyncMock(return_value=frozenset())) monkeypatch.setattr(authz, "grant_role_for", AsyncMock(return_value=None)) monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=None)) - monkeypatch.setattr(namespace_kinds, "kind_map", AsyncMock(return_value={})) + monkeypatch.setattr(repo_registry, "registered", AsyncMock(return_value=False)) return entries @@ -119,22 +119,34 @@ async def test_a_scoped_platform_token_stays_capped_at_its_grant(repository, mon await authz.check_authorized(scoped, Role.VIEWER, ORG, STANDARD) -@pytest.mark.parametrize("role", [Role.WRITER, Role.ADMIN]) async def test_platform_authority_writes_no_repository_the_snapshot_does_not_hold( - repository, monkeypatch, role + repository, monkeypatch ): - # A self-service repository another replica added, or one this process has not read - # yet: its directory row says `code` though the registry snapshot lacks it. - monkeypatch.setattr(namespace_kinds, "kind_map", AsyncMock(return_value={"code-new": "code"})) - with pytest.raises(PermissionError): - await authz.check_authorized(_admin(), role, ORG, "code-new") + # 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_unreadable_kinds_cover_nothing_and_the_refusal_is_unverified( +async def test_an_unreadable_registry_covers_no_write_and_the_refusal_is_unverified( repository, monkeypatch ): - down = AsyncMock(side_effect=BackendUnavailableError("namespace kinds could not be read")) - monkeypatch.setattr(namespace_kinds, "kind_map", down) + 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) From a3ace4f2a7c9c7709369b508359c689887ef02eb Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:28:17 +0530 Subject: [PATCH 05/16] An MCP call naming another org takes no default namespace The default namespace an MCP call is filled with is one of the caller's own org, but the fill kept a call's explicit org, so a call naming another org and no namespace ran on that org's namesake of the default. Platform authority admits that pair, so the call names its namespace or fails validation naming `namespace`. The gate asks platform authority only where the claim, after its cap, does not cover the namespace, so a write the claim covers reads no registry row. A unit fixture answers the registry read with no row unless a test is marked `registry_rows`, in place of four copies of that stub; tests cover the read itself and the directory's answer. The concept page names platform authority with the role, the gate and the grant cap. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/concepts/identities-and-namespaces.md | 23 ++++--- pyproject.toml | 1 + server/auth/authz.py | 27 ++++---- server/identity/app/directory.py | 2 +- server/transport/mcp_call.py | 16 ++++- tests/unit/conftest.py | 19 ++++++ tests/unit/test_blacklist_authority.py | 5 -- .../test_default_namespace_gate_property.py | 5 -- tests/unit/test_erasure_authz_matrix.py | 1 - .../test_platform_admin_repository_read.py | 67 ++++++++++++++++++- 10 files changed, 125 insertions(+), 41 deletions(-) diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 3c441a44e14..509eca6fce4 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,9 @@ 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 ([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 +177,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/pyproject.toml b/pyproject.toml index 08f4b9dd1fe..9bbe60500ed 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/server/auth/authz.py b/server/auth/authz.py index 640fd7e3dd7..d7f32f118ef 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -339,13 +339,7 @@ async def _check_authorized_claims( # A claim on a namespace where the subject holds a grant row is capped at # that grant, so a revoked or lowered grant ends every older token's claim. - # Platform authority comes from no grant, so none caps it, as none caps `*`. - platform = await _platform_covers(auth, required_role, org, namespace) - cap = ( - None - if org is None or namespace is None or platform - else await claim_cap(auth, org, namespace) - ) + cap = None if org is None or namespace is None else await claim_cap(auth, org, namespace) capped = cap is not None # Scoped token (carries an `ns_roles` map): the per-namespace role is @@ -366,16 +360,19 @@ async def _check_authorized_claims( # writable set, so a token can read an inherited parent namespace # without being able to write into it (absent a writer grant below). if org is not None and namespace is not None: - ns_covered_by_jwt = platform or ( + 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 `*`. + covered = covered or 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 @@ -387,7 +384,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, @@ -409,7 +406,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)", @@ -639,7 +636,7 @@ def _platform_repository_read( async def _platform_covers( - auth: AuthorizationClaims, required_role: Role, org: str | None, namespace: str | None + 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 any org but a repository, which keeps the read-only @@ -649,8 +646,8 @@ async def _platform_covers( member write (`member_writes`) stays the grant's; a repository outside them is one platform authority reads anyway. A write also leaves out an active registry row read now, and an `ns_write` claim still bounds it. A registry that cannot be read covers - no write: the claim and grant checks decide, and a refusal is unverified.""" - if org is None or namespace is None or not is_own_platform_admin(auth): + no write: the grant check decides, and a refusal is unverified.""" + if not is_own_platform_admin(auth): return False if required_role.value < Role.WRITER.value: return not _is_code_namespace(org, namespace) diff --git a/server/identity/app/directory.py b/server/identity/app/directory.py index 92668a7d77d..a78090e2420 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -52,7 +52,7 @@ async def is_repository(self, org: str, namespace: str) -> bool: try: return await repo_registry.registered(org, namespace) - except Exception as e: # any failure refuses: an unreadable registry decides nothing + except Exception as e: # unreadable: platform authority then covers no write log.warning( "repository registry read failed for %s/%s: %s", log_value(org), diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 359cf245498..98963cf77aa 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -646,8 +646,13 @@ 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 blank or "-" namespace names none, as the gates read it. The default namespace + # is one of the caller's own org: a call naming another org gets none, and fails + # validation naming `namespace` unless it names one. + unnamed = not present(arguments.get("namespace")) and present(arguments.get("org")) in ( + None, + (defaults or {}).get("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 = ( @@ -668,7 +673,12 @@ async def _bind_caller_identity( 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: + if ( + defaults + and defaults["namespace"] + and present(arguments.get("org")) 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 arguments.setdefault("lesson_namespaces", [defaults["namespace"]]) if op.name == SEARCH_OP and defaults and not defaults["namespace"] and unnamed: diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index c051fac248c..22370acecc9 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 a3c8a548540..34aec3ffe42 100644 --- a/tests/unit/test_blacklist_authority.py +++ b/tests/unit/test_blacklist_authority.py @@ -406,11 +406,6 @@ 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.""" - - async def _no_row(org: str, namespace: str) -> bool: - return False - - monkeypatch.setattr("server.code.app.index.repo_registry.registered", _no_row) repo.rows["pb"] = _row("pb", "namespace", namespace="ns-b") swept = _record_sweeps(monkeypatch) set_current_auth(_auth("PLATFORM_ADMIN", namespaces=("ns-a",))) diff --git a/tests/unit/test_default_namespace_gate_property.py b/tests/unit/test_default_namespace_gate_property.py index df18e03fb37..5fc1de2379f 100644 --- a/tests/unit/test_default_namespace_gate_property.py +++ b/tests/unit/test_default_namespace_gate_property.py @@ -113,7 +113,6 @@ def _fakes(monkeypatch: pytest.MonkeyPatch) -> None: import server.auth.delegation as delegation import server.auth.personal_namespace as personal_namespace import server.auth.service_accounts as service_accounts - import server.code.app.index.repo_registry as repo_registry import server.code.domain.index.repos as repos import server.core.ch as chmod import server.core.grant_cache as grant_cache @@ -143,9 +142,6 @@ async def _restricted_set(org: str) -> frozenset[str]: async def _kinds(org: str) -> dict[str, str]: return dict(WORLD.kinds) - async def _registered(org: str, namespace: str) -> bool: - return False # the configured entries are the world's only repositories - async def _aliases(org: str, subject: str, *, ch: Any = None) -> list[str]: return [subject] @@ -176,7 +172,6 @@ def _code_entry(org: str, namespace: str) -> _CodeEntry | None: monkeypatch.setattr(delegation, "creator_account_active", _active) monkeypatch.setattr(nc, "restricted_set", _restricted_set) monkeypatch.setattr(nk, "kind_map", _kinds) - monkeypatch.setattr(repo_registry, "registered", _registered) monkeypatch.setattr(aliases, "subject_aliases", _aliases) monkeypatch.setattr(caller_defaults, "saved_default", _saved) monkeypatch.setattr(caller_defaults, "ranked_grants", _ranked) diff --git a/tests/unit/test_erasure_authz_matrix.py b/tests/unit/test_erasure_authz_matrix.py index 5f064ea3c76..0a6e2deea08 100644 --- a/tests/unit/test_erasure_authz_matrix.py +++ b/tests/unit/test_erasure_authz_matrix.py @@ -122,7 +122,6 @@ async def _mine(org: str, subject: str | None = None) -> list[str]: monkeypatch.setattr(authz, "_lookup_grant", _no_grant) monkeypatch.setattr(authz, "may_be_restricted", _false) monkeypatch.setattr(authz, "is_org_readable_code_namespace", _false) - monkeypatch.setattr("server.code.app.index.repo_registry.registered", _false) monkeypatch.setattr(handlers, "begin_erasure", _begin) for name in ( "export_memory", diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 37b29b5896d..ff836187558 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -39,7 +39,6 @@ def repository(monkeypatch): monkeypatch.setattr(classification, "restricted_set", AsyncMock(return_value=frozenset())) monkeypatch.setattr(authz, "grant_role_for", AsyncMock(return_value=None)) monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=None)) - monkeypatch.setattr(repo_registry, "registered", AsyncMock(return_value=False)) return entries @@ -152,6 +151,72 @@ async def test_an_unreadable_registry_covers_no_write_and_the_refusal_is_unverif 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() + + +@pytest.mark.registry_rows +@pytest.mark.parametrize( + ("row", "registered"), [({"active": True}, True), ({"active": False}, False), (None, False)] +) +async def test_the_registry_read_counts_only_an_active_row(monkeypatch, row, registered): + from server.code.store.index import CodeRepo + + read = AsyncMock(return_value=row) + monkeypatch.setattr(CodeRepo, "code_repo_row", read) + assert await repo_registry.registered(ORG, STANDARD) is registered + read.assert_awaited_once_with(ORG, STANDARD) + + +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) + + +@pytest.mark.parametrize(("org", "ran"), [(ORG, [(ORG, "personal")]), ("other", [])]) +async def test_an_mcp_call_naming_another_org_takes_no_default_namespace( + repository, monkeypatch, org, ran +): + import server.transport.mcp_call as mcp_call + from server.settings import settings + from tests.unit.ch_fake import RecordingCH + + calls = [] + + async def _handler(inp): + calls.append((inp.org, inp.namespace)) + raise RuntimeError("recorded; the handler's answer is not under test") + + async def _defaults(auth, client_name=None): + return {"org": ORG, "namespace": "personal", "agent": "a"} + + tool = "loom_memory_get" + monkeypatch.setitem( + mcp_call.TOOLS_BY_NAME, tool, 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": org, "agent": "a", "memory_key": "k"} + answer = await mcp_call._call_tool(1, {"name": tool, "arguments": args}, auth=_admin()) + # Another org's call names its namespace: the caller's own default is not one of it. + assert calls == ran + if not ran: + assert "namespace" in str(answer) + + 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) From 4c88e5a7292d8487319aa676f2505b2c095506ef Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:03:56 +0530 Subject: [PATCH 06/16] A token's named claims are namespaces of its own org `named_claims` returned the claim's names for whatever org a caller asked about, and the namespace resolvers (`resolve_my_namespaces`, `readable_named_claims`, `every_namespace_scope`, `namespace.list_mine`) relied on the gate refusing them in another org. Platform authority reaches another org's namespace of the same name, so an `all_mine` fan-out there read it as the caller's own. `named_claims(auth, org)` returns none outside the token's org (every org for an org-wide token). A code read's lessons default is set after its code scope is applied, and only when the read acts in the caller's org: its plane or scope may be another org's, where the home's name is another namespace. The registry read is one `SELECT active ... LIMIT 1` point read (`CodeRepo.code_repo_active`, with its analyzer shape), and reads nothing with self-service off, where the snapshot reads no registry. The MCP reference names the default-namespace rule. Tests cover the read, the directory's answer, the defaults in another org, and a platform admin's write to another org over HTTP and MCP. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/mcp.md | 4 +- server/auth/context.py | 18 +-- server/code/app/index/repo_registry.py | 8 +- server/code/store/index/code_repos.py | 9 ++ server/identity/app/caller_home.py | 2 +- server/identity/app/directory.py | 2 +- server/identity/app/namespace_membership.py | 4 +- server/transport/mcp_call.py | 13 +- tests/analyzer/cases/code.py | 1 + tests/analyzer/shapes.txt | 1 + .../test_default_namespace_gate_property.py | 18 ++- tests/unit/test_mcp_default_namespace.py | 115 ++++++++++++++++++ .../test_platform_admin_repository_read.py | 108 ++++++++++------ tests/unit/test_readable_named_claims.py | 25 ++++ 14 files changed, 263 insertions(+), 65 deletions(-) diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index d6a0a73c243..0e25674b3b9 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -268,7 +268,9 @@ 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` gets none and + fails validation naming `namespace`. `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 diff --git a/server/auth/context.py b/server/auth/context.py index 993f8d38619..00227a5370b 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/code/app/index/repo_registry.py b/server/code/app/index/repo_registry.py index 30c8d0a577a..55e168fbdc7 100644 --- a/server/code/app/index/repo_registry.py +++ b/server/code/app/index/repo_registry.py @@ -297,13 +297,15 @@ async def insert_entry( async def registered(org: str, namespace: str) -> bool: """Whether (org, namespace) holds an active registry row, read now: a repository - another replica added is one before this process's snapshot reads it.""" + 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(): - row = await CodeRepo().code_repo_row(org, namespace) - return bool(row and row.get("active")) + return await CodeRepo().code_repo_active(org, namespace) async def live_row(cfg: Any, ch: Any | None = None) -> dict[str, Any] | None: diff --git a/server/code/store/index/code_repos.py b/server/code/store/index/code_repos.py index 461f58e7d3c..4f1bd84c4ce 100644 --- a/server/code/store/index/code_repos.py +++ b/server/code/store/index/code_repos.py @@ -60,6 +60,15 @@ async def code_repo_row(self, org: str, ns: str) -> dict[str, Any] | None: ) return row + async def code_repo_active(self, org: str, ns: str) -> bool: + """Whether the namespace holds an active registry row: one point read.""" + row: dict[str, Any] | None = await self._ch.query_one( + "SELECT active 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")) + 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 45f91c00dc1..a84dee4643d 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 a78090e2420..8806e92e637 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -52,7 +52,7 @@ async def is_repository(self, org: str, namespace: str) -> bool: try: return await repo_registry.registered(org, namespace) - except Exception as e: # unreadable: platform authority then covers no write + except Exception as e: # a failed registry read is raised as ClassificationUnavailable log.warning( "repository registry read failed for %s/%s: %s", log_value(org), diff --git a/server/identity/app/namespace_membership.py b/server/identity/app/namespace_membership.py index 3b1ff5467f2..2f3a650b7ee 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/transport/mcp_call.py b/server/transport/mcp_call.py index 98963cf77aa..a4aa2c7f125 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -673,18 +673,19 @@ async def _bind_caller_identity( missing = not arguments.get(k) if v and k in field_names and missing: arguments[k] = v + if op.name == SEARCH_OP and defaults and not defaults["namespace"] and unnamed: + 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 present(arguments.get("org")) in (None, defaults["org"]) + and gates.org_for_op(op.name, arguments.get("org"), auth) == 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 + # 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"]]) - if op.name == SEARCH_OP and defaults and not defaults["namespace"] and unnamed: - 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) await _tag_session_repository(op, arguments, auth) if op.name == SEARCH_OP and filled_ns: await _address_home(arguments, auth) diff --git a/tests/analyzer/cases/code.py b/tests/analyzer/cases/code.py index c5065247911..cd5944253da 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.code_repo_active(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 e5fe6675a42..bd4ffa21de0 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -248,6 +248,7 @@ 1ca42e357807 ALTER TABLE loom.entity_triple_rows DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1ca47c4c11f3 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 1cb430ccdf4d SELECT ? FROM (SELECT * FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND msg_id IN {ids:Array(Str +1cb969c07e0f SELECT active FROM loom.code_repos FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 1cfc6f95dc0f SELECT uniqExact(pr_number) AS fixes, count() AS branch_rows, max(computed_at) AS last_computed, min(computed_at) AS first_computed FROM loom.code_backport_gaps FINAL WHERE org = {org:String} AND code 1d111f0f3599 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND user_id = {uid:String} 1d56611f4e39 ALTER TABLE loom.blob_uploads DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? diff --git a/tests/unit/test_default_namespace_gate_property.py b/tests/unit/test_default_namespace_gate_property.py index 5fc1de2379f..bc1b91b7d56 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_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index 0a07db0379f..190ff45f0c3 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -292,3 +292,118 @@ 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("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 + + +def test_a_call_naming_another_org_and_no_namespace_fails_validation_naming_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + 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"} + 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"]] diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index ff836187558..c32f1c46933 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -163,12 +163,25 @@ async def test_a_write_the_claim_covers_reads_no_registry(repository, monkeypatc ("row", "registered"), [({"active": True}, True), ({"active": False}, False), (None, False)] ) async def test_the_registry_read_counts_only_an_active_row(monkeypatch, row, registered): - from server.code.store.index import CodeRepo + from server.settings import settings + + reads = [] + + class _CH: + async def query_one(self, sql, params=None): + reads.append((sql, params)) + return row - read = AsyncMock(return_value=row) - monkeypatch.setattr(CodeRepo, "code_repo_row", read) + 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 - read.assert_awaited_once_with(ORG, STANDARD) + [(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( @@ -184,39 +197,6 @@ async def test_an_entry_is_a_repository_with_no_read_and_an_unread_registry_is_u await IdentityDirectory().is_repository(ORG, STANDARD) -@pytest.mark.parametrize(("org", "ran"), [(ORG, [(ORG, "personal")]), ("other", [])]) -async def test_an_mcp_call_naming_another_org_takes_no_default_namespace( - repository, monkeypatch, org, ran -): - import server.transport.mcp_call as mcp_call - from server.settings import settings - from tests.unit.ch_fake import RecordingCH - - calls = [] - - async def _handler(inp): - calls.append((inp.org, inp.namespace)) - raise RuntimeError("recorded; the handler's answer is not under test") - - async def _defaults(auth, client_name=None): - return {"org": ORG, "namespace": "personal", "agent": "a"} - - tool = "loom_memory_get" - monkeypatch.setitem( - mcp_call.TOOLS_BY_NAME, tool, 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": org, "agent": "a", "memory_key": "k"} - answer = await mcp_call._call_tool(1, {"name": tool, "arguments": args}, auth=_admin()) - # Another org's call names its namespace: the caller's own default is not one of it. - assert calls == ran - if not ran: - assert "namespace" in str(answer) - - 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) @@ -460,16 +440,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 in (401, 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( diff --git a/tests/unit/test_readable_named_claims.py b/tests/unit/test_readable_named_claims.py index d16abdd11ae..d80bf6fa1ef 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) From a1511872f74a9d98f62ea5d831e90d8b4ccb8eef Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:32:30 +0530 Subject: [PATCH 07/16] Platform authority names a tenant org and reads no access row as a repository - `_platform_covers` returns False for a blank, `-` or `*` org (`cell.ORG_FREE`). `tenancy.ensure_held` passes those, and a platform admin of another org was admitted there. - `code_repo_active` reads `row_kind` and counts no maintainer's `access` row, as the snapshot, the mirrors and `active_code_repo_count` leave it out. Reads and writes then agree on what a repository is. The analyzer shape is regenerated. - A code read's lessons default applies when `org_for_op` is the caller's org or None: a read that names no org anywhere acts in no other org. - `mcp_call` splits `in_home_org` out of `unnamed`. - Tests: platform authority refused in a `*` or `-` org, an access row that is no repository, and a platform admin's `list_mine` in another org listing no claim row. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/authz.py | 6 +++-- server/code/store/index/code_repos.py | 7 +++--- server/transport/mcp_call.py | 8 +++--- tests/analyzer/shapes.txt | 2 +- tests/unit/test_list_mine_inherited.py | 25 +++++++++++++++++++ .../test_platform_admin_repository_read.py | 18 ++++++++++++- 6 files changed, 54 insertions(+), 12 deletions(-) diff --git a/server/auth/authz.py b/server/auth/authz.py index d7f32f118ef..898999cec13 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -33,6 +33,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 @@ -646,8 +647,9 @@ async def _platform_covers( member write (`member_writes`) stays the grant's; a repository outside them is one platform authority reads anyway. A write also leaves out an active registry row read now, and an `ns_write` claim still bounds it. A registry that cannot be read covers - no write: the grant check decides, and a refusal is unverified.""" - if not is_own_platform_admin(auth): + no write: the grant check decides, and a refusal is unverified. A blank, `-` or `*` + org names no tenant, so platform authority covers nothing there.""" + if org in ORG_FREE or not is_own_platform_admin(auth): return False if required_role.value < Role.WRITER.value: return not _is_code_namespace(org, namespace) diff --git a/server/code/store/index/code_repos.py b/server/code/store/index/code_repos.py index 4f1bd84c4ce..93c50babdc5 100644 --- a/server/code/store/index/code_repos.py +++ b/server/code/store/index/code_repos.py @@ -61,13 +61,14 @@ async def code_repo_row(self, org: str, ns: str) -> dict[str, Any] | None: return row async def code_repo_active(self, org: str, ns: str) -> bool: - """Whether the namespace holds an active registry row: one point read.""" + """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 FROM loom.code_repos FINAL " + "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")) + 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/transport/mcp_call.py b/server/transport/mcp_call.py index a4aa2c7f125..60060783b86 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -649,10 +649,8 @@ async def _bind_caller_identity( # A blank or "-" namespace names none, as the gates read it. The default namespace # is one of the caller's own org: a call naming another org gets none, and fails # validation naming `namespace` unless it names one. - unnamed = not present(arguments.get("namespace")) and present(arguments.get("org")) in ( - None, - (defaults or {}).get("org"), - ) + in_home_org = present(arguments.get("org")) in (None, (defaults or {}).get("org")) + unnamed = 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 = ( @@ -680,7 +678,7 @@ async def _bind_caller_identity( if ( defaults and defaults["namespace"] - and gates.org_for_op(op.name, arguments.get("org"), auth) == defaults["org"] + 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, diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index bd4ffa21de0..bae0e0ea277 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -248,7 +248,6 @@ 1ca42e357807 ALTER TABLE loom.entity_triple_rows DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1ca47c4c11f3 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 1cb430ccdf4d SELECT ? FROM (SELECT * FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND msg_id IN {ids:Array(Str -1cb969c07e0f SELECT active FROM loom.code_repos FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 1cfc6f95dc0f SELECT uniqExact(pr_number) AS fixes, count() AS branch_rows, max(computed_at) AS last_computed, min(computed_at) AS first_computed FROM loom.code_backport_gaps FINAL WHERE org = {org:String} AND code 1d111f0f3599 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND user_id = {uid:String} 1d56611f4e39 ALTER TABLE loom.blob_uploads DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -270,6 +269,7 @@ 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 1f7f08f173b3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +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 202a8461a799 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g diff --git a/tests/unit/test_list_mine_inherited.py b/tests/unit/test_list_mine_inherited.py index f44ee9fa487..5e96f64e696 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_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index c32f1c46933..9dd04d0660b 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -80,6 +80,15 @@ async def test_platform_admin_reaches_a_standard_namespace_without_claim_or_gran 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 @@ -160,7 +169,14 @@ async def test_a_write_the_claim_covers_reads_no_registry(repository, monkeypatc @pytest.mark.registry_rows @pytest.mark.parametrize( - ("row", "registered"), [({"active": True}, True), ({"active": False}, False), (None, False)] + ("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 From 5d645cb422b7bda581d7278f7c557719514e09ee Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:00:52 +0530 Subject: [PATCH 08/16] A platform admin's first write in another org leaves no owner - `namespace_autoregister.ensure_registered` takes `ownerless`, and the transport hook sets it for a token of another org (not `*`): the row names no owner, at the ownerless version, as for a name in use. A name in a tenant org is not an outside writer's to own. The setting's description, its generated reference, schema and example, and the namespaces page say so. - The gate asks platform authority only where a known grant does not admit the call: a listing or default (`CachedGate`) that hands in a grant reaching the role, with no claim cap over it, reads no registry row. - The `_platform_covers` and module docstrings say plainly what platform authority covers; the concepts page says an `ns_write` claim still bounds its writes. - Tests: the known-grant case, a repository write refused from another org, the HTTP scoped refusal is a 403, the ownerless first write, and an integration case in the leakage suite where a platform admin of another org reads and writes a standard namespace that the same claims under an org admin's roles do not reach. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/concepts/identities-and-namespaces.md | 3 +- docs/features/namespaces-and-sharing.md | 4 +- docs/reference/configuration.md | 2 +- loom.example.yaml | 5 +- schemas/loom-settings.schema.json | 2 +- server/auth/authz.py | 29 +++++++----- server/identity/app/namespace_autoregister.py | 24 +++++++--- server/settings/catalog.py | 3 +- .../test_cross_principal_leakage.py | 46 +++++++++++++++++++ tests/unit/test_namespace_autoregister.py | 22 +++++++-- .../test_platform_admin_repository_read.py | 19 ++++++-- 11 files changed, 126 insertions(+), 33 deletions(-) diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 509eca6fce4..e5ade8b6797 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -156,7 +156,8 @@ A call on `(org, namespace)` is allowed when the namespace is not restricted (or the restricted checks) and either the token's own role for that namespace reaches the 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 ([the gate](../architecture/security.md#the-gate), step 8). +whatever its token names, though an `ns_write` claim still bounds its writes +([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 diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md index 04d9efa95c0..95dd8379b76 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/reference/configuration.md b/docs/reference/configuration.md index 266815d77d9..e509b749d66 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1685,7 +1685,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/loom.example.yaml b/loom.example.yaml index ffb7b922b6d..a492219c70e 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -4982,8 +4982,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/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 483984c3f5b..c303b2bf5a9 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -5926,7 +5926,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.", diff --git a/server/auth/authz.py b/server/auth/authz.py index 898999cec13..5892fb283de 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 @@ -370,8 +372,11 @@ async def _check_authorized_claims( live = rank_role(cap) 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 `*`. - covered = covered or await _platform_covers(auth, required_role, org, namespace) + # caps `*`. A known grant that admits the call below leaves it unasked. + covered = covered or ( + not (cap is None and isinstance(known_grant, Role) and known_grant >= required_role) + and await _platform_covers(auth, required_role, org, namespace) + ) else: covered = False @@ -640,15 +645,15 @@ 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 any org but a repository, which keeps the read-only - authority of `_platform_repository_read`. The gate asks after it has sent mirrors - and code stores, collections, delegated tokens and restricted namespaces to their - own checks. A read leaves out the configured entries alone, so the read check of a - member write (`member_writes`) stays the grant's; a repository outside them is one - platform authority reads anyway. A write also leaves out an active registry row read - now, and an `ns_write` claim still bounds it. A registry that cannot be read covers - no write: the grant check decides, and a refusal is unverified. A blank, `-` or `*` - org names no tenant, so platform authority covers nothing there.""" + 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 now, and is not covered when that read fails (the + refusal is unverified) or the token carries `ns_write`. A blank, `-` or `*` org is + no tenant.""" if org in ORG_FREE or not is_own_platform_admin(auth): return False if required_role.value < Role.WRITER.value: diff --git a/server/identity/app/namespace_autoregister.py b/server/identity/app/namespace_autoregister.py index 4ff9ea657c6..cca33b5ebdb 100644 --- a/server/identity/app/namespace_autoregister.py +++ b/server/identity/app/namespace_autoregister.py @@ -6,7 +6,8 @@ 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 = +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 @@ -116,9 +117,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 +152,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 +172,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 +211,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/settings/catalog.py b/server/settings/catalog.py index f5314b83450..37b99ca44e5 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -4376,7 +4376,8 @@ 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), + # 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 diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 84ff3d6cbd1..1173a3d72d4 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -1143,6 +1143,52 @@ 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 under an org + admin's 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", + ) + + 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/test_namespace_autoregister.py b/tests/unit/test_namespace_autoregister.py index b7092e4f4e3..2d6718e62e1 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 @@ -298,8 +309,8 @@ def test_disabled_by_setting(monkeypatch: pytest.MonkeyPatch) -> None: async def test_hook_requires_an_authenticated_subject(monkeypatch: pytest.MonkeyPatch) -> None: calls: list[tuple[str, str, str]] = [] - 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 9dd04d0660b..5e7d7cc6ca6 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -167,6 +167,17 @@ async def test_a_write_the_claim_covers_reads_no_registry(repository, monkeypatc 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"), @@ -255,10 +266,12 @@ async def test_platform_authority_does_not_open_restricted_namespaces( @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): @@ -494,7 +507,7 @@ def test_http_platform_authority_writes_another_orgs_standard_namespace(transpor assert response.status_code == 200, response.text assert transports.written == [("other", STANDARD)] else: - assert response.status_code in (401, 403), response.text + assert response.status_code == 403, response.text assert transports.written == [] From a3bf99481f91766a5a16b0df65dd072b3c60100a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:35:09 +0530 Subject: [PATCH 09/16] A third-party client's session gets no platform reach - `_platform_covers` returns False for a sign-in session that is not Loom's own (`session_id` set, `first_party` false). Loom already gives such a session nothing that outlives it (`_only_a_person`, `delegation`), and an admin reach over every org would let it grant lasting access anywhere. The dashboard, `loom login`, bots and minted tokens keep the reach. - An `ns_write` claim bounds platform writes instead of dropping them: a write inside the claim is covered, with no grant capping it. - `_grant_admits` names the known-grant check; `code_repo_active` is `is_registered_repository`; the MCP variable is `takes_default_ns`. - The `LOOM_PLATFORM_ADMINS` description names what the role reaches; the security page says a third-party session has none of it and that tracker namespaces are in reach. Generated settings files are regenerated. - Tests: the third-party session at every role in both orgs, a capped claim inside `ns_write`, and the integration case reads back the ownerless registry row with `namespace.get`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 8 ++++++- docs/concepts/identities-and-namespaces.md | 3 ++- docs/guides/tokens-and-grants.md | 2 +- docs/operations/sso.md | 3 ++- docs/reference/configuration.md | 2 +- loom.example.yaml | 10 ++++---- schemas/loom-settings.schema.json | 2 +- server/auth/authz.py | 22 +++++++++++++----- server/auth/directory.py | 2 +- server/code/app/index/repo_registry.py | 4 ++-- server/code/store/index/code_repos.py | 2 +- server/identity/app/directory.py | 2 +- server/identity/app/namespace_autoregister.py | 23 +++++++++---------- server/settings/catalog.py | 11 +++++---- server/transport/mcp_call.py | 15 ++++++------ tests/analyzer/cases/code.py | 2 +- .../test_cross_principal_leakage.py | 7 ++++++ .../test_platform_admin_repository_read.py | 23 +++++++++++++++++++ 18 files changed, 97 insertions(+), 46 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 152ad341c0b..6ba49b5fd5b 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -292,6 +292,8 @@ authenticated call, from `gates.authorize` in both transports: 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 @@ -321,7 +323,11 @@ what it covers as a claim, its own org's repositories at the token's role. At th 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. +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 diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 6f8ae784774..c81ca4a080d 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -156,7 +156,8 @@ A call on `(org, namespace)` is allowed when the namespace is not restricted (or the restricted checks) and either the token's own role for that namespace reaches the 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 +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`) diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index 5176de9fdc0..0e8cd338580 100644 --- a/docs/guides/tokens-and-grants.md +++ b/docs/guides/tokens-and-grants.md @@ -178,7 +178,7 @@ A call on `(org, namespace)` is allowed when: 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. + 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 diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 3269d28bc35..99095cafa11 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -142,7 +142,8 @@ Platform admins are the verified emails listed in `LOOM_PLATFORM_ADMINS`. 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)). +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 diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 19b4a43d62f..9e100dca8cb 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 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. | diff --git a/loom.example.yaml b/loom.example.yaml index 0ac81aec481..6c96ea62b6a 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -668,10 +668,12 @@ 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 - # IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no - # platform admins. [restart] + # 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 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: "" # True: every operation requires a valid bearer JWT. False (laptop demos only): diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 99742eeb5ea..f6dd624f785 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6465,7 +6465,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 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 5892fb283de..61746cf121e 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -374,7 +374,7 @@ async def _check_authorized_claims( # 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 (cap is None and isinstance(known_grant, Role) and known_grant >= required_role) + not _grant_admits(cap, known_grant, required_role) and await _platform_covers(auth, required_role, org, namespace) ) else: @@ -641,6 +641,12 @@ 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: @@ -650,15 +656,19 @@ async def _platform_covers( 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 now, and is not covered when that read fails (the - refusal is unverified) or the token carries `ns_write`. A blank, `-` or `*` org is - no tenant.""" + 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: + if auth.write_namespaces and not auth.can_write(org, namespace): return False try: return not await directory().is_repository(org, namespace) diff --git a/server/auth/directory.py b/server/auth/directory.py index a0e042e6b95..58fa5c0923d 100644 --- a/server/auth/directory.py +++ b/server/auth/directory.py @@ -65,7 +65,7 @@ def code_entry(self, org: str, namespace: str) -> CodeEntry | None: 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 now (one this process's snapshot may not hold yet). Raises + active registry row read at the call (one this process's snapshot may not hold yet). Raises `ClassificationUnavailable` when the registry cannot be read.""" ... diff --git a/server/code/app/index/repo_registry.py b/server/code/app/index/repo_registry.py index 55e168fbdc7..235ba6de09b 100644 --- a/server/code/app/index/repo_registry.py +++ b/server/code/app/index/repo_registry.py @@ -296,7 +296,7 @@ async def insert_entry( async def registered(org: str, namespace: str) -> bool: - """Whether (org, namespace) holds an active registry row, read now: a repository + """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: @@ -305,7 +305,7 @@ async def registered(org: str, namespace: str) -> bool: from server.core.ch import sequential_reads with sequential_reads(): - return await CodeRepo().code_repo_active(org, namespace) + return await CodeRepo().is_registered_repository(org, namespace) async def live_row(cfg: Any, ch: Any | None = None) -> dict[str, Any] | None: diff --git a/server/code/store/index/code_repos.py b/server/code/store/index/code_repos.py index 93c50babdc5..3d9f17d1c93 100644 --- a/server/code/store/index/code_repos.py +++ b/server/code/store/index/code_repos.py @@ -60,7 +60,7 @@ async def code_repo_row(self, org: str, ns: str) -> dict[str, Any] | None: ) return row - async def code_repo_active(self, org: str, ns: str) -> bool: + 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( diff --git a/server/identity/app/directory.py b/server/identity/app/directory.py index 8806e92e637..5bebfbfdb1e 100644 --- a/server/identity/app/directory.py +++ b/server/identity/app/directory.py @@ -52,7 +52,7 @@ async def is_repository(self, org: str, namespace: str) -> bool: try: return await repo_registry.registered(org, namespace) - except Exception as e: # a failed registry read is raised as ClassificationUnavailable + 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), diff --git a/server/identity/app/namespace_autoregister.py b/server/identity/app/namespace_autoregister.py index cca33b5ebdb..024c4ced531 100644 --- a/server/identity/app/namespace_autoregister.py +++ b/server/identity/app/namespace_autoregister.py @@ -7,18 +7,17 @@ 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`) 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. +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. diff --git a/server/settings/catalog.py b/server/settings/catalog.py index c705579e36f..4420981ace3 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -150,8 +150,10 @@ 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 + # 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 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 = "" @@ -4381,9 +4383,8 @@ 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 or from - # a token of another org), - # `kind = 'bench'` under a bench prefix, `retention_days = 0` (never a - # TTL). No ALTER. + # 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_call.py b/server/transport/mcp_call.py index 373d83d7303..31ecc125e00 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -646,17 +646,18 @@ 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. The default namespace - # is one of the caller's own org: a call naming another org gets none, and fails - # validation naming `namespace` unless it names one. + # 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: the default is one of that + # org's, so a call naming another org gets none and fails validation naming + # `namespace` unless it names one. in_home_org = present(arguments.get("org")) in (None, (defaults or {}).get("org")) - unnamed = not present(arguments.get("namespace")) and in_home_org + 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."): @@ -664,14 +665,14 @@ 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 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) diff --git a/tests/analyzer/cases/code.py b/tests/analyzer/cases/code.py index cd5944253da..7dba0525dd5 100644 --- a/tests/analyzer/cases/code.py +++ b/tests/analyzer/cases/code.py @@ -304,7 +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.code_repo_active(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/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 1173a3d72d4..67ee83c7f07 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -1187,6 +1187,13 @@ def test_a_platform_admin_of_another_org_reads_and_writes_its_standard_namespace "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: diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 5e7d7cc6ca6..fc2b8f284fc 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -231,6 +231,29 @@ async def test_an_ns_write_claim_still_bounds_platform_writes(repository): 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): From 89fe7765c81bbef165ed3881de39182a7d147003 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:02:27 +0530 Subject: [PATCH 10/16] A loom_search naming another org searches the caller's namespaces there - The MCP screen drops a `loom_search` namespace, and a call naming another org takes no default, so such a search failed validation with no way to name one. `_bind_caller_identity` now addresses it through `_address_home` from that org's fan-out, at either scope, the namespace named after the caller first; it fails validation only when the caller reaches none there. - `docs/reference/mcp.md` says what a call naming another org and no namespace does per op: a required namespace fails validation, an optional one runs org-wide, `loom_search` searches that org's fan-out. - `security.md` names the ownerless first write from another org; the `LOOM_PLATFORM_ADMINS` description is reworded and regenerated. - Tests: `loom_search` naming another org through the MCP screen and the binding; `test_delete_by_key.py`'s source check names the new condition. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 4 ++- docs/reference/configuration.md | 2 +- docs/reference/mcp.md | 9 ++++-- loom.example.yaml | 8 +++--- schemas/loom-settings.schema.json | 2 +- server/settings/catalog.py | 6 ++-- server/transport/mcp_call.py | 10 +++++-- tests/unit/test_delete_by_key.py | 5 ++-- tests/unit/test_mcp_default_namespace.py | 35 ++++++++++++++++++++++++ 9 files changed, 63 insertions(+), 18 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 6ba49b5fd5b..d9ccca4f428 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -953,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/reference/configuration.md b/docs/reference/configuration.md index 9e100dca8cb..2d275af3578 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: a person listed reads, writes and administers every standard namespace of every org (not restricted namespaces, nor repository writes) with no grant there, and 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_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. | diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index 0e25674b3b9..be6a44c29ef 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -269,8 +269,9 @@ What a client gets with and without a plugin is in - **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. The default workspace is a namespace of the - caller's own org, so a call that names another org and no `namespace` gets none and - fails validation naming `namespace`. `code.*` calls resolve to the code plane + caller's own org, so a call that names another org and no `namespace` gets none: an + op whose `namespace` is required fails validation naming it, and one whose `namespace` + is optional runs org-wide in that org. `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 @@ -278,7 +279,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 6c96ea62b6a..110b92a07a9 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -670,10 +670,10 @@ settings: # 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 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] + # 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: "" # True: every operation requires a valid bearer JWT. False (laptop demos only): diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index f6dd624f785..b165fb82475 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6465,7 +6465,7 @@ "platform_admins": { "default": "", "type": "string", - "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 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." + "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/settings/catalog.py b/server/settings/catalog.py index 4420981ace3..245c6f8ad22 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -153,9 +153,9 @@ class AuthSettings(BaseModel): # 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 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. + # 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 diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 31ecc125e00..6d61174e3e2 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -188,9 +188,11 @@ async def _address_home(arguments: dict[str, Any], auth: Any) -> None: 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 + namespace lands on its first memory namespace. A search in another org has + no default there, so it addresses its first namespace of that org's fan-out + whatever its scope, and none when it reaches none. An explicit namespace is never rewritten (the gate refuses it if it must).""" - if arguments.get("namespace_scope") != "all_mine": + if arguments.get("namespace_scope") != "all_mine" and arguments.get("namespace"): return from server.auth.fanout import resolve_fanout @@ -686,7 +688,9 @@ async def _bind_caller_identity( # 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: + if op.name == SEARCH_OP and ( + filled_ns or not (in_home_org or present(arguments.get("namespace"))) + ): await _address_home(arguments, auth) # Read-shaped ops default to cross-agent within the namespace (memory is diff --git a/tests/unit/test_delete_by_key.py b/tests/unit/test_delete_by_key.py index ec6851f3444..7e4ceda6bdc 100644 --- a/tests/unit/test_delete_by_key.py +++ b/tests/unit/test_delete_by_key.py @@ -239,13 +239,14 @@ async def _get_by_key(identity: Any, key: str, **kw: Any) -> Any: 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.""" + when the saved default fell outside the fan-out list, and for a search + naming another org, which no default fills.""" 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 "filled_ns or not (in_home_org or present(arguments.get(\"namespace\")))" in bind assert "home_namespace(" in inspect.getsource(mcp_call._address_home) diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index 190ff45f0c3..dedd6bce1c3 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -407,3 +407,38 @@ async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: body = result["structuredContent"] assert body["code"] == "VALIDATION_FAILED" assert [list(e["loc"]) for e in body["errors"]] == [["namespace"]] + + +@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, 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.""" + 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) + args: dict[str, Any] = {"org": "acme", "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"], bound.get("namespace"), asked) == ("acme", namespace, ["acme"]) From 72dd287afecba9b5f14f8038c7ec124b9aca8eb6 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:25:43 +0530 Subject: [PATCH 11/16] A cross-org loom_search fails as the server's when its fan-out is unread - `_address_home` re-raises a fan-out failure when no default filled the namespace: with nothing to fall back to, the failure is the server's (a 503), not a validation error asking for a namespace the caller cannot name. A filled default still stands, as before. - A search it addresses with no default carries the `namespace_defaulted` note when the namespace is not the caller's own. - The call-site condition reads without a double negative, and the comment and docstring say what an op with an optional namespace does and that the caller's home is picked first. - Tests: the note, the fan-out failure in another org and in the caller's, and an optional-namespace op naming another org. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/transport/mcp_call.py | 23 +++++++++---- tests/unit/test_delete_by_key.py | 2 +- tests/unit/test_mcp_default_namespace.py | 44 ++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 6d61174e3e2..adbb1530e8a 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -189,25 +189,32 @@ async def _address_home(arguments: dict[str, Any], auth: Any) -> None: 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. A search in another org has - no default there, so it addresses its first namespace of that org's fan-out - whatever its scope, and none when it reaches none. An explicit namespace is - never rewritten (the gate refuses it if it must).""" + 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 + that cannot be read then raises, as there is no default to fall back to. An + explicit namespace is never rewritten (the gate refuses it if it must).""" if arguments.get("namespace_scope") != "all_mine" and arguments.get("namespace"): 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 + except Exception as e: # a filled default stays when the fan-out cannot be read + if not arguments.get("namespace"): + raise # nothing to fall back to: the failure is the server's, not the caller's log.warning("loom_search namespace resolution failed (non-fatal): %s", e) return # 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 "" + unaddressed = not arguments.get("namespace") arguments["namespace"] = home_namespace( accessible, subject, str(arguments.get("namespace") or "") ) + if unaddressed: + # No default filled it: the note says when it is not the caller's own. + note_default_namespace(True, arguments["namespace"], auth) def _address_first_claim(arguments: dict[str, Any], readable: list[str]) -> bool: @@ -650,8 +657,8 @@ async def _bind_caller_identity( explicit_agent = bool(arguments.get("agent")) # 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: the default is one of that - # org's, so a call naming another org gets none and fails validation naming - # `namespace` unless it names one. + # org's, so a call naming another org gets none. An op that requires a namespace then + # fails validation naming it; one with an optional namespace runs org-wide there. in_home_org = present(arguments.get("org")) in (None, (defaults or {}).get("org")) takes_default_ns = not present(arguments.get("namespace")) and in_home_org # An empty default namespace (a delegated token whose claim holds no home) @@ -688,8 +695,10 @@ async def _bind_caller_identity( # 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) + # 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 not (in_home_org or present(arguments.get("namespace"))) + filled_ns or (not in_home_org and not present(arguments.get("namespace"))) ): await _address_home(arguments, auth) diff --git a/tests/unit/test_delete_by_key.py b/tests/unit/test_delete_by_key.py index 7e4ceda6bdc..5822ed4a425 100644 --- a/tests/unit/test_delete_by_key.py +++ b/tests/unit/test_delete_by_key.py @@ -246,7 +246,7 @@ def test_every_unaddressed_search_takes_the_home_namespace() -> None: from server.transport import mcp_call bind = inspect.getsource(mcp_call._bind_caller_identity) - assert "filled_ns or not (in_home_org or present(arguments.get(\"namespace\")))" in bind + assert 'filled_ns or (not in_home_org and not present(arguments.get("namespace")))' in bind assert "home_namespace(" in inspect.getsource(mcp_call._address_home) diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index dedd6bce1c3..606195e0982 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -434,6 +434,17 @@ async def _fanout(org: str, *a: Any, **k: Any) -> Any: 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": "acme", "namespace": "alice", "query": "q"} req = {"params": {"name": "loom_search", "arguments": args}} assert asyncio.run(_screen_tool_call(req, auth)) is None @@ -442,3 +453,36 @@ async def _fanout(org: str, *a: Any, **k: Any) -> Any: asked.clear() bound = _bind(monkeypatch, "search.query", {**args, "namespace_scope": scope}, auth) assert (bound["org"], 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 {}) + + +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") + + monkeypatch.setattr(fanout_mod, "resolve_fanout", _down) + with pytest.raises(BackendUnavailableError): + _bind(monkeypatch, "search.query", {"org": "acme", "query": "q"}, _platform_admin()) + # In the caller's org the default stands: the search runs on it. + bound = _bind(monkeypatch, "search.query", {"query": "q"}, _platform_admin()) + assert (bound["org"], bound["namespace"]) == ("o", "alice") + + +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 From ba527122626355cd60f35ba497af1e01e0f63d38 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:51:49 +0530 Subject: [PATCH 12/16] A cross-org loom_search answers 503 for any unread fan-out, ledgered - `_address_home` reads the namespace as the gates do (a blank or "-" names none), once. With none named, a fan-out failure is the server's: a `LoomServerError` raises as is, anything else as `BackendUnavailableError` from it, so no bare 500 escapes the call or drops a batch's other answers. The refusal is ledgered against the token, as a failed defaults read is. - `test_delete_by_key.py` stops pinning the call site's source text; a behaviour test covers a filled default moving to the caller's home. - Tests: a raw error with no, "-" or blank namespace answers `BackendUnavailableError`, the refusal row, and the filled default. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/directory.py | 4 +- server/transport/mcp_call.py | 37 ++++++++++------ tests/unit/test_delete_by_key.py | 8 ++-- tests/unit/test_mcp_default_namespace.py | 54 +++++++++++++++++++++++- 4 files changed, 80 insertions(+), 23 deletions(-) diff --git a/server/auth/directory.py b/server/auth/directory.py index 58fa5c0923d..e3e1c21b5f6 100644 --- a/server/auth/directory.py +++ b/server/auth/directory.py @@ -65,8 +65,8 @@ def code_entry(self, org: str, namespace: str) -> CodeEntry | None: 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.""" + 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]: diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index adbb1530e8a..2cf9135508f 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, @@ -182,7 +183,9 @@ 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, op_name: str = SEARCH_OP, 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 @@ -191,28 +194,34 @@ async def _address_home(arguments: dict[str, Any], auth: Any) -> None: 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 - that cannot be read then raises, as there is no default to fall back to. An - explicit namespace is never rewritten (the gate refuses it if it must).""" - if arguments.get("namespace_scope") != "all_mine" and arguments.get("namespace"): + that cannot be read then answers a 503, ledgered as the server's, as there is + no default to fall back to. 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: # a filled default stays when the fan-out cannot be read - if not arguments.get("namespace"): - raise # nothing to fall back to: the failure is the server's, not the caller's - log.warning("loom_search namespace resolution failed (non-fatal): %s", e) - return + if addressed: + log.warning("loom_search namespace resolution failed (non-fatal): %s", e) + return + # Nothing to fall back to: the failure is the server's, not the caller's. + err = ( + e + if isinstance(e, LoomServerError) + else BackendUnavailableError("namespaces could not be read", operation="fanout") + ) + emit_token_refusal(op_name, auth, error_code=err.code, request_id=request_id) + 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 "" - unaddressed = not arguments.get("namespace") - arguments["namespace"] = home_namespace( - accessible, subject, str(arguments.get("namespace") or "") - ) - if unaddressed: + 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) @@ -700,7 +709,7 @@ async def _bind_caller_identity( if op.name == SEARCH_OP and ( filled_ns or (not in_home_org and not present(arguments.get("namespace"))) ): - await _address_home(arguments, auth) + await _address_home(arguments, auth, op.name, 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/unit/test_delete_by_key.py b/tests/unit/test_delete_by_key.py index 5822ed4a425..b0e76bd4850 100644 --- a/tests/unit/test_delete_by_key.py +++ b/tests/unit/test_delete_by_key.py @@ -238,15 +238,13 @@ async def _get_by_key(identity: Any, key: str, **kw: Any) -> Any: 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, and for a search - naming another org, which no default fills.""" + """An unaddressed search is addressed through `home_namespace`. When it fires (a + filled default, a search naming another org) is checked by behaviour in + `test_mcp_default_namespace.py`.""" import inspect from server.transport import mcp_call - bind = inspect.getsource(mcp_call._bind_caller_identity) - assert 'filled_ns or (not in_home_org and not present(arguments.get("namespace")))' in bind assert "home_namespace(" in inspect.getsource(mcp_call._address_home) diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index 606195e0982..a2b15bd8ba3 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -468,12 +468,62 @@ def test_a_search_naming_another_org_raises_when_its_fanout_cannot_be_read( 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()) - # In the caller's org the default stands: the search runs on it. + [(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"]) == ("o", "alice") + assert (bound["org"], bound["namespace"], len(rows)) == ("o", "alice", 1) + + +@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( From 8f7f559e36ae28a475fa407edf1c3d7c5ad75bcd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:20:48 +0530 Subject: [PATCH 13/16] A blank or "-" namespace in another org's MCP call names none A call naming another org takes no default namespace, but a blank, whitespace or "-" value it sent stayed in its arguments, so the op ran on that literal namespace of the other org. The binding drops it there (`_in_home_org`): an op that requires a namespace fails validation naming it, as over HTTP. A namespace refusal in another org does not advise omitting the namespace, which would only fail validation there. A fan-out that cannot be read for such a search is logged, and a server error is re-raised as is. The source-text test of the search call site is gone, behaviour tests cover it, and the CachedGate docstring names the registry read. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/mcp.md | 7 +++-- server/auth/authz.py | 4 ++- server/transport/mcp_auth.py | 17 +++++----- server/transport/mcp_call.py | 31 +++++++++++++------ .../test_cross_principal_leakage.py | 4 +-- tests/unit/test_delete_by_key.py | 11 ------- tests/unit/test_error_envelope.py | 16 ++++++++++ tests/unit/test_mcp_default_namespace.py | 7 ++++- 8 files changed, 62 insertions(+), 35 deletions(-) diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index be6a44c29ef..ec698fdb65f 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -269,9 +269,10 @@ What a client gets with and without a plugin is in - **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. The default workspace is a namespace of the - caller's own org, so a call that names another org and no `namespace` gets none: an - op whose `namespace` is required fails validation naming it, and one whose `namespace` - is optional runs org-wide in that org. `code.*` calls resolve to the code plane + 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. `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 diff --git a/server/auth/authz.py b/server/auth/authz.py index 61746cf121e..01881707feb 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -921,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/transport/mcp_auth.py b/server/transport/mcp_auth.py index bb8c79cf9c3..f48d2fe82d7 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,12 +111,13 @@ 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 = "" if away else "Omit the namespace argument to use your default namespace" 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}." + else (f" {omit}, or request {grant}." if omit else f" Request {grant}.") ) elif collection: # Never "omit the namespace": a write meant for the collection would land in the @@ -127,11 +132,8 @@ def _not_accessible_result( 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}" - ) + step = f"{omit} (loom_search reads {reads}), or request" if omit else "Request" + msg += f" Next: {NAMESPACE_NEXT}. {step} {grant}.{creator}" return _refusal_body(msg, ns, next=NAMESPACE_NEXT) return _refusal_body(msg, ns) @@ -544,6 +546,7 @@ async def _screen_namespace( req_ns, assistant=consumer == ASSISTANT_CONSUMER, unverified=given_unverified, + away=present(args.get("org")) not in (None, caller_org(auth)), ) 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 2cf9135508f..4375f70d036 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -32,6 +32,7 @@ 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 @@ -183,9 +184,7 @@ 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, op_name: str = SEARCH_OP, request_id: str = "" -) -> 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 @@ -206,15 +205,18 @@ async def _address_home( fanout = await resolve_fanout(str(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", e) + log.warning("loom_search namespace resolution failed (non-fatal): %s", log_value(e)) return # Nothing to fall back to: the failure is the server's, not the caller's. + log.warning("loom_search namespaces could not be read: %s", log_value(e)) err = ( e if isinstance(e, LoomServerError) else BackendUnavailableError("namespaces could not be read", operation="fanout") ) - emit_token_refusal(op_name, auth, error_code=err.code, request_id=request_id) + 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) @@ -226,6 +228,17 @@ async def _address_home( note_default_namespace(True, arguments["namespace"], auth) +def _in_home_org(arguments: dict[str, Any], defaults: dict[str, str] | None) -> 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, + and a blank or "-" one it sent is dropped: an op that requires a namespace then fails + validation naming it, one with an optional namespace runs org-wide there.""" + home = present(arguments.get("org")) in (None, (defaults or {}).get("org")) + if not home and not present(arguments.get("namespace")): + arguments.pop("namespace", None) + return home + + def _address_first_claim(arguments: dict[str, Any], readable: list[str]) -> bool: """A `loom_search` naming no namespace from a token with no default one searches the token's first readable claim (`readable`, from its @@ -665,10 +678,8 @@ async def _bind_caller_identity( raise explicit_agent = bool(arguments.get("agent")) # 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: the default is one of that - # org's, so a call naming another org gets none. An op that requires a namespace then - # fails validation naming it; one with an optional namespace runs org-wide there. - in_home_org = present(arguments.get("org")) in (None, (defaults or {}).get("org")) + # as the gates read it) and acts in the caller's own org. + in_home_org = _in_home_org(arguments, defaults) 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`. @@ -709,7 +720,7 @@ async def _bind_caller_identity( if op.name == SEARCH_OP and ( filled_ns or (not in_home_org and not present(arguments.get("namespace"))) ): - await _address_home(arguments, auth, op.name, request_id) + 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/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 67ee83c7f07..341722191c5 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -1147,8 +1147,8 @@ def test_a_platform_admin_of_another_org_reads_and_writes_its_standard_namespace 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 under an org - admin's roles reach nothing in that org.""" + 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) diff --git a/tests/unit/test_delete_by_key.py b/tests/unit/test_delete_by_key.py index b0e76bd4850..2c688f801ae 100644 --- a/tests/unit/test_delete_by_key.py +++ b/tests/unit/test_delete_by_key.py @@ -237,17 +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: - """An unaddressed search is addressed through `home_namespace`. When it fires (a - filled default, a search naming another org) is checked by behaviour in - `test_mcp_default_namespace.py`.""" - import inspect - - from server.transport import mcp_call - - 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_error_envelope.py b/tests/unit/test_error_envelope.py index 307721b228d..f99e55ad9c5 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_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index a2b15bd8ba3..897a8c9387e 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -370,9 +370,12 @@ def test_a_code_reads_lessons_come_from_the_home_only_in_the_callers_org( 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, + 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 @@ -399,6 +402,8 @@ async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: 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()) ) From d8faa36ba879259a9d250c3d95e3d59cb8532a05 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:34:10 +0530 Subject: [PATCH 14/16] The knowledge.move test stand-ins carry an org `maybe_autoregister` reads the token's org to decide whether a first write records an owner, and two tests stood in a caller with a subject alone. Each stand-in names the org the move lands in, and the `ensure_registered` stub takes `ownerless`, asserted false for a token of that org. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- tests/unit/test_knowledge_move.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_knowledge_move.py b/tests/unit/test_knowledge_move.py index 62ed0a4f4bd..33d696bb4e7 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: From 195ecb197ac6448bd6d13940b576371002a8fe7b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:51:09 +0530 Subject: [PATCH 15/16] The caller's own fan-out error in another org answers as a tool error A loom_search naming an org another cell holds, or a new org name past the limit, raised WrongCellError or ValidationError out of the binding, before any phase that frames them, so the call escaped `_call_tool` unframed. `_call_tool` answers them as tool errors with their code, as the gate would; only a server fault logs. A call with no token on a single-user server takes the install's namespace whatever org it names, as HTTP fills it. `_in_home_org` is a predicate again, and the binding drops a blank namespace on its own line. The namespace refusal text is plain branches. The corpus is regenerated after merging main: main's knowledge_sources read was not listed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/mcp.md | 4 +- server/transport/mcp_auth.py | 33 +++++++----- server/transport/mcp_call.py | 42 +++++++++------ tests/analyzer/shapes.txt | 2 +- tests/unit/test_mcp_default_namespace.py | 68 ++++++++++++++++++++++++ 5 files changed, 118 insertions(+), 31 deletions(-) diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index a4c239be413..9e3ddeb61bb 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -272,7 +272,9 @@ What a client gets with and without a plugin is in 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. `code.*` calls resolve to the code plane + 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 diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index f48d2fe82d7..812e1eca2b2 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -112,13 +112,17 @@ def _not_accessible_result( ) 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 = "" if away else "Omit the namespace argument to use your default namespace" + 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 (f" {omit}, or request {grant}." if omit else f" Request {grant}.") - ) + 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. @@ -127,13 +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" - ) - step = f"{omit} (loom_search reads {reads}), or request" if omit else "Request" - msg += f" Next: {NAMESPACE_NEXT}. {step} {grant}.{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) diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 2c1b214e1fc..2b2867f2990 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -192,10 +192,12 @@ async def _address_home(arguments: dict[str, Any], auth: Any, request_id: str = set is memory-kind only, so a caller whose saved default is a code 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 - that cannot be read then answers a 503, ledgered as the server's, as there is - no default to fall back to. An explicit namespace is never rewritten (the gate - refuses it if it must); a blank or "-" one names none, as the gates read it.""" + 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 @@ -207,13 +209,14 @@ async def _address_home(arguments: dict[str, Any], auth: Any, request_id: str = if addressed: log.warning("loom_search namespace resolution failed (non-fatal): %s", log_value(e)) return - # Nothing to fall back to: the failure is the server's, not the caller's. - log.warning("loom_search namespaces could not be read: %s", log_value(e)) + # 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 @@ -228,15 +231,13 @@ async def _address_home(arguments: dict[str, Any], auth: Any, request_id: str = note_default_namespace(True, arguments["namespace"], auth) -def _in_home_org(arguments: dict[str, Any], defaults: dict[str, str] | None) -> bool: +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, - and a blank or "-" one it sent is dropped: an op that requires a namespace then fails - validation naming it, one with an optional namespace runs org-wide there.""" - home = present(arguments.get("org")) in (None, (defaults or {}).get("org")) - if not home and not present(arguments.get("namespace")): - arguments.pop("namespace", None) - return home + 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: @@ -324,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) @@ -686,7 +692,11 @@ async def _bind_caller_identity( explicit_agent = bool(arguments.get("agent")) # 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) + in_home_org = _in_home_org(arguments, defaults, auth) + if not in_home_org and not present(arguments.get("namespace")): + # 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`. diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index c2f519829fa..08be4b2173e 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -575,6 +575,7 @@ 40dfbf0248ef SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, content, context, tags, chunk_metadata, ingested_at, agent, session_id, toString(source_class) AS 40e24f5cf835 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 4113c01ac87f SELECT memory_key, count() AS matches FROM (SELECT tm.memory_key FROM loom.entity_triple_memories AS tm INNER JOIN loom.entity_triples AS t ON t.org = tm.org AND t.namespace = tm.namespace AND t.subje +413546300ccb SELECT namespace, name, credential_mode, toString(source_id) AS source_id, owner_subject FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND namespace IN {names:Array(String)} AND active AN 413b4ddac97c SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS 415f2e580ed9 SELECT * FROM loom.service_accounts FINAL WHERE org = {org:String} AND (created_by = {by:String} OR has(lineage, {by:String})) AND NOT hasAll(lineage, {above:Array(String)}) AND (expires_at IS NULL OR 4162e2756b17 ALTER TABLE loom.memory_term_freq DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -826,7 +827,6 @@ 5b39f4c73106 SELECT memory_key, record_json, created_at, (memory_key, identity_agent, user_id, session_id) IN ( SELECT memory_key, agent, user_id, session_id FROM loom.memory FINAL WHERE org = {org:String} AND nam 5b4266159703 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 5b82b22d8ce2 SELECT namespace, source_uri FROM loom.documents FINAL WHERE org = {org:String} AND (namespace, source_uri) IN {pairs:Array(Tuple(String, String))} LIMIT {limit:UInt32} -5b96b3ab8467 SELECT namespace, name, credential_mode, toString(source_id) AS source_id FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND namespace IN {names:Array(String)} AND active AND access = ? AN 5b9b9bcb4313 SELECT symbol_id, qualified_name, path, fan_in_calls, fan_in_nontest, fan_in_name, caller_files, defined_files, is_test FROM loom.code_symbol_stats FINAL WHERE org = {org:String} AND namespace = {ns:S 5bcdfad6f454 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 5c174b8803f6 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index 897a8c9387e..ddc3863433c 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -328,6 +328,20 @@ async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: 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( @@ -493,6 +507,60 @@ async def _down(org: str, *a: Any, **k: Any) -> Any: 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 From e4de9b703f29532eed3eec015f1b6ea3a7668777 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:17:53 +0530 Subject: [PATCH 16/16] A cross-org loom_search reads the fan-out of the org as the gates read it The binding read a padded org (" acme ") through `present` and took the call as one in another org, but `_address_home` read the fan-out of the padded name, which holds nothing, so the search failed validation where "acme" searched. It reads the org through `present` too. The MCP screen passes whether the call names another org into its namespace check, from the org it already read, and a test through the screen covers the refusal text there. The binding names the "another org, no namespace" check once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/transport/mcp_auth.py | 12 +++++-- server/transport/mcp_call.py | 12 +++---- tests/unit/test_mcp_default_namespace.py | 44 ++++++++++++++++++++--- tests/unit/test_namespace_autoregister.py | 2 +- 4 files changed, 55 insertions(+), 15 deletions(-) diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index 812e1eca2b2..9af8ddb325a 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -451,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. @@ -519,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 @@ -553,7 +559,7 @@ async def _screen_namespace( req_ns, assistant=consumer == ASSISTANT_CONSUMER, unverified=given_unverified, - away=present(args.get("org")) not in (None, caller_org(auth)), + 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 2b2867f2990..9d3eee3abba 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -36,7 +36,7 @@ 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 ( @@ -204,7 +204,7 @@ async def _address_home(arguments: dict[str, Any], auth: Any, request_id: str = from server.auth.fanout import resolve_fanout try: - fanout = await resolve_fanout(str(arguments.get("org") or "")) + 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)) @@ -665,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) @@ -693,7 +692,8 @@ async def _bind_caller_identity( # 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) - if not in_home_org and not present(arguments.get("namespace")): + 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) @@ -734,9 +734,7 @@ async def _bind_caller_identity( await _tag_session_repository(op, 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 (not in_home_org and not present(arguments.get("namespace"))) - ): + 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 diff --git a/tests/unit/test_mcp_default_namespace.py b/tests/unit/test_mcp_default_namespace.py index ddc3863433c..293d6feac9c 100644 --- a/tests/unit/test_mcp_default_namespace.py +++ b/tests/unit/test_mcp_default_namespace.py @@ -428,15 +428,21 @@ async def _defaults(auth: Any, client_name: Any = None) -> dict[str, Any]: 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, who: str, fanout: tuple[str, ...], namespace: str | None + 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.""" + 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 @@ -464,19 +470,49 @@ def _note(filled: bool, ns: str, a: Any) -> None: notes.append(default_namespace_note()) monkeypatch.setattr(mcp_call, "note_default_namespace", _note) - args: dict[str, Any] = {"org": "acme", "namespace": "alice", "query": "q"} + 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"], bound.get("namespace"), asked) == ("acme", namespace, ["acme"]) + 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: diff --git a/tests/unit/test_namespace_autoregister.py b/tests/unit/test_namespace_autoregister.py index 2d6718e62e1..29b62d89a8f 100644 --- a/tests/unit/test_namespace_autoregister.py +++ b/tests/unit/test_namespace_autoregister.py @@ -307,7 +307,7 @@ 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, ownerless=False): calls.append((org, ns, subject, ownerless))