From 97834de91a7f4e15d062ffb99461eb66cabc4ce1 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 19 Nov 2026 17:58:53 +0000 Subject: [PATCH 1/3] Platform administrators can read every registered repository Admit repository viewer reads from a platform administrator using its own unscoped authority. Preserve restricted serving, classification, tenancy, delegated-token and write boundaries. Signed-off-by: zlareb1 --- docs/architecture/security.md | 44 +- docs/concepts/identities-and-namespaces.md | 12 +- docs/guides/tokens-and-grants.md | 17 +- server/auth/authz.py | 81 +++- server/code/app/repo_admin.py | 4 +- tests/unit/test_authz_restricted_namespace.py | 8 +- .../test_platform_admin_repository_read.py | 398 ++++++++++++++++++ 7 files changed, 521 insertions(+), 43 deletions(-) create mode 100644 tests/unit/test_platform_admin_repository_read.py diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 14d2b5cd24..779ccc3ada 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -276,13 +276,17 @@ authenticated call, from `gates.authorize` in both transports: creator holds that role somewhere in the org, and on a namespace needs its own claim to reach the role and the creator's live grant to reach it too (`_check_delegated`; restricted namespaces also take the restricted gate). Nothing below applies to it. -3. A restricted namespace goes to the restricted gate only. -4. A viewer read of an org-readable code namespace (`LOOM_CODE_ORG_READABLE` or the +3. A restricted namespace goes to the restricted gate, including its repository read + 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. +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. -5. A scoped token's `ns_roles` decide for the namespaces they name, in the token's 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. -6. A token acts in its own org only (or `*`, or as platform admin). -7. A flat token's roles apply to every namespace its claims cover. Otherwise a live grant +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 `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 @@ -333,8 +337,8 @@ foreign row and a missing row look the same. ### Restricted namespaces A namespace classified `restricted` (in `loom.namespaces` or its repository entry; either -restricts) turns off every widening rule (`_check_restricted` in `server/auth/authz.py`). -A call passes only when all of these hold: +restricts) uses `_check_restricted` in `server/auth/authz.py`. Except for the repository +read authority below, a call passes only when all of these hold: - the token's org is the namespace's (`*` does not count); - the token names the namespace literally; @@ -342,7 +346,31 @@ A call passes only when all of these hold: - a live direct grant for the token's own subject reaches it (a service account does not inherit its creator's grant). -No org-readable rule, `visibility=public`, `org_admin` or `platform_admin` bypasses it. A +An authenticated `platform_admin` using its own unscoped authority reads every repository +that `NamespaceDirectory.code_entry` recognizes in the current configuration or registry +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. + +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 +and mirror boundaries run before repository admission; a repository read does not expose +its document mirrors or internal data. + +Classification must remain available, `restricted_serve=false` refuses restricted reads +even for platform administrators, and tenancy and token verification still run first. +Revoked or unverifiable credentials gain no authority. HTTP, MCP, row-scoped checks and +repository listings share this decision through `check_authorized`. The listing returns +actual heads and counts only after that gate admits the read. Restricted-access audit +behavior also applies to platform administrators. No schema or stored-grant migration is +needed. Auth-off behavior is unchanged. + +No org-readable rule, `visibility=public` or `org_admin` bypasses the restricted gate. A refusal is the generic "cannot access". If the classification cannot be read, access is denied. diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 05f85261bc..5abee022a6 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -117,10 +117,14 @@ refuses joins. A **restricted** namespace (`classification=restricted` on its directory row, or on its entry in `LOOM_CODE_REPOS_JSON`) admits a call only when the token belongs to the namespace's org, names the namespace literally (not through `*`), holds a role there that -reaches the operation's role, and the token's own subject holds a live direct grant. No -org-readable rule, public visibility, wildcard, inherited service-account grant, -`org_admin` or `platform_admin` bypasses it, and a refusal does not reveal whether the -namespace exists. Fan-outs, context packs and rollups skip restricted namespaces the +reaches the operation's role, and the token's own subject holds a live direct grant. +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 +([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 caller cannot read, and each admitted request is audited. The step-by-step setup is in [Tokens and grants](../guides/tokens-and-grants.md#restricted-namespaces-classificationrestricted). diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index ee3cc8bb73..5d7184ff82 100644 --- a/docs/guides/tokens-and-grants.md +++ b/docs/guides/tokens-and-grants.md @@ -21,7 +21,7 @@ of the token. This guide holds the procedures; ```bash loom mint-token --subject my-bot --org acme --namespaces support --roles writer --ttl-days 30 --save -# /home/you/.loom/token +# ~/.loom/token ``` `loom` ships with the server package and the Docker image, not with the SDK; in a container @@ -472,12 +472,19 @@ read or write passes only when **all** hold: 4. a live **direct** grant for the token's own subject reaches it (a service account does not inherit its creator's grant). -No org-readable rule, `visibility=public`, `org_admin` or `platform_admin` bypasses this. 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. +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)). +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. - Search fan-out, context packs and org-wide rollups skip the restricted namespaces the - caller cannot read, and `code.repos` hides them. + caller cannot read. `code.repos` returns readable metadata only when its authorization + gate admits the repository; a same-org caller may see a request-only entry when its + join policy permits requests. - Each request admitted to the restricted namespace it names writes a `namespace.restricted_access` audit row before the answer (`LOOM_RESTRICTED_AUDIT_INLINE=false` writes it beside the request instead, diff --git a/server/auth/authz.py b/server/auth/authz.py index d998e4a40b..016680168d 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -10,8 +10,10 @@ A namespace classified `restricted` is the one exception to "additive": every default that widens a read — the org-readable code rule, `visibility=public`, a wildcard claim, a service account inheriting its -creator's grant, a platform role — is switched off there, and a read needs -BOTH a token that names the namespace AND a live direct grant. +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. """ from __future__ import annotations @@ -66,11 +68,23 @@ class _Unknown(Enum): _UNKNOWN_GRANT = _Unknown.GRANT +def is_own_platform_admin(auth: AuthInfo) -> bool: + """Platform authority belongs to the unscoped principal itself, never a + delegated token or the subject a trusted caller acts for.""" + return ( + not auth.has_ns_roles() + and not auth.impersonated_by + and not auth.creator + and not auth.parents + and auth.has_role(Role.PLATFORM_ADMIN) + ) + + def may_act_in_org(auth: AuthInfo, org: str) -> bool: """Whether `auth` may act in `org` at all: a token of that org, an org-wide (`*`) token, or a platform admin. The one cross-org rule — the - transports and every handler's same-org check ask this; a restricted - namespace still refuses every other org (`_check_restricted`).""" + transports and every handler's same-org check ask this. Restricted + non-repository data still requires the namespace's own org.""" return auth.org in ("*", org) or auth.has_role(Role.PLATFORM_ADMIN) @@ -269,28 +283,15 @@ async def check_authorized( await _check_delegated(auth, required_role, org, namespace, known_grant, grants) return - # A restricted namespace is decided here and nowhere - # below — none of the widening rules that follow may apply to it. + # Restricted reads retain their safety guards before repository admission. if org is not None and namespace is not None and await may_be_restricted(org, namespace): await _check_restricted(auth, required_role, org, namespace, grants) return - # Code namespaces are org-shared reference data, not anyone's memory. When - # the deployment says so (LOOM_CODE_ORG_READABLE / per-entry org_readable) - # every authenticated principal of that org reads it with the token it - # already holds — scoped or flat, no grant, no re-mint. Writes (refresh, - # watermark repair) stay grant-driven. Otherwise code namespaces follow - # the ordinary rules: a grant (joined) or a token naming the namespace. - # The directory row's visibility never widens reads — `join_policy = open` - # means joinable in one click, not readable unjoined. if ( - required_role.value <= Role.VIEWER.value - and org is not None + org is not None and namespace is not None - and (auth.org == org or auth.has_role(Role.PLATFORM_ADMIN)) - # A service's end user is no member of the org's code. - and not principal_id(auth.subject, USER) - and await is_org_readable_code_namespace(org, namespace) + and await _standard_code_read(auth, required_role, org, namespace) ): return @@ -543,6 +544,38 @@ def _scoped_role( return role +async def _standard_code_read( + auth: AuthInfo, required_role: Role, org: str, namespace: str +) -> bool: + """Read exceptions for code after restricted safety guards have run. + + Platform authority reads every repository. Org-readable entries also admit + the org's authenticated principals with their existing tokens. A service's + end user is no member of its org's code. Directory visibility affects joining, + never reading. Writes keep the ordinary claim and grant checks. + """ + if _platform_repository_read(auth, required_role, org, namespace): + return True + return ( + required_role.value <= Role.VIEWER.value + and (auth.org == org or auth.has_role(Role.PLATFORM_ADMIN)) + and not principal_id(auth.subject, USER) + and await is_org_readable_code_namespace(org, namespace) + ) + + +def _platform_repository_read( + auth: AuthInfo, required_role: Role, org: str, namespace: str +) -> bool: + """Repository read authority, independent of claims and membership. The + caller checks tenancy and restricted safety guards before admitting it.""" + return ( + is_own_platform_admin(auth) + and not is_mirror_name(namespace) + and _code_namespace_read(required_role, 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 @@ -609,6 +642,8 @@ async def _check_restricted( 4. a live DIRECT grant for the token's subject reaches `required_role` (no service-account → creator inheritance). + A platform administrator's own unscoped authority also admits repository + viewer reads after the kill switch and classification check, within held orgs. The refusal text is the generic "cannot access" line so a caller learns nothing about whether the namespace exists or why it was refused. `LOOM_RESTRICTED_SERVE=false` refuses everyone (kill switch: the plane @@ -625,6 +660,12 @@ async def _check_restricted( except ClassificationUnavailable as e: note_unreadable() raise refusal from e + if _platform_repository_read(auth, required_role, org, namespace): + from server.auth import tenancy + + # restricted_allows also calls this gate directly, outside check_authorized. + await tenancy.ensure_held(org, auth) + return if auth.org != org: raise refusal if not names_namespace(auth, org, namespace): diff --git a/server/code/app/repo_admin.py b/server/code/app/repo_admin.py index ee87998d24..bcc604d408 100644 --- a/server/code/app/repo_admin.py +++ b/server/code/app/repo_admin.py @@ -68,13 +68,11 @@ def _is_platform_admin() -> bool: call is no platform admin's (an MCP endpoint in `open` mode takes one that sends no bearer).""" from server.auth.context import current_auth - from server.operations.base import Role auth = current_auth() if auth is None: return not settings.auth_actually_required() - flat = not auth.has_ns_roles() and not auth.impersonated_by - return flat and auth.has_role(Role.PLATFORM_ADMIN) + return authz.is_own_platform_admin(auth) def _require_platform_admin() -> None: diff --git a/tests/unit/test_authz_restricted_namespace.py b/tests/unit/test_authz_restricted_namespace.py index b653e683f9..2a1118f3b5 100644 --- a/tests/unit/test_authz_restricted_namespace.py +++ b/tests/unit/test_authz_restricted_namespace.py @@ -1,7 +1,8 @@ """Restricted namespaces: a read needs a token that names the namespace AND a live direct grant. Every widening rule — org-readable code, -visibility=public, wildcard claims, service-account inheritance, platform -roles — is off there, and the directory lookup fails closed.""" +visibility=public, wildcard claims and service-account inheritance — is off +there. Platform authority admits only registered repository reads; the +directory lookup fails closed.""" from __future__ import annotations @@ -155,7 +156,8 @@ async def test_other_org_is_refused(restricted) -> None: @pytest.mark.asyncio -async def test_platform_admin_has_no_content_bypass(restricted) -> None: +async def test_platform_admin_needs_two_factors_outside_registered_repositories(restricted) -> None: + # A directory-only namespace is not a registered repository, despite its code prefix. await _denied(_flat(namespaces=("*",), roles=(Role.PLATFORM_ADMIN,))) restricted["grants"][(ORG, NS, "alice@x")] = Role.VIEWER await authz.check_authorized( diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py new file mode 100644 index 0000000000..4c03fe1b1b --- /dev/null +++ b/tests/unit/test_platform_admin_repository_read.py @@ -0,0 +1,398 @@ +"""Platform authority reads registered repositories without widening other scopes.""" + +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.auth import authz +from server.auth.directory import ClassificationUnavailable +from server.code.domain.index import repos +from server.identity.app import namespace_classification as classification +from server.operations.base import Role +from tests.unit.code_fixtures import repo_config +from tests.unit.principals import acting_as, principal + +ORG = "example" +NS = "code-private" + + +@pytest.fixture +def repository(monkeypatch): + entries = { + (ORG, NS): repo_config( + org=ORG, + namespace=NS, + repo="example/private", + classification="restricted", + org_readable=False, + ) + } + monkeypatch.setattr(repos, "config_entry", lambda org, ns: entries.get((org, ns))) + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries.values())) + 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)) + return entries + + +def _admin(**fields): + return principal( + Role.PLATFORM_ADMIN, org=ORG, namespaces=("personal",), service_account=False, **fields + ) + + +@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): + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + auth = _admin() + if cross_org: + auth = replace(auth, org="other") + await authz.check_authorized(auth, Role.VIEWER, ORG, NS) + + +@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): + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + auth = replace(_admin(), roles=(role,)) + with pytest.raises(PermissionError): + await authz.check_authorized(auth, Role.VIEWER, ORG, NS) + + +@pytest.mark.parametrize("level", ["standard", "restricted"]) +@pytest.mark.parametrize("authority", ["scoped", "impersonated", "delegated"]) +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) + + +@pytest.mark.parametrize("namespace", ["memory-private", "tracker-private", "code-unknown"]) +async def test_platform_authority_does_not_widen_unregistered_namespaces( + repository, monkeypatch, namespace +): + monkeypatch.setattr( + classification, "restricted_set", AsyncMock(return_value=frozenset({namespace})) + ) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, namespace) + + +@pytest.mark.parametrize("role", [Role.WRITER, Role.ADMIN]) +@pytest.mark.parametrize("level", ["standard", "restricted"]) +async def test_repository_writes_still_require_access(repository, role, level): + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), role, ORG, NS) + + +async def test_registered_repository_does_not_need_a_code_prefix(repository): + cfg = repository.pop((ORG, NS)) + repository[(ORG, "repository-index")] = replace(cfg, namespace="repository-index") + await authz.check_authorized(_admin(), Role.VIEWER, ORG, "repository-index") + + +async def test_new_registry_entry_is_checked_on_each_read(repository): + 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") + await authz.check_authorized(_admin(), Role.VIEWER, ORG, "code-added") + del repository[(ORG, "code-added")] + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, "code-added") + + +async def test_restricted_kill_switch_still_refuses_platform_admin(repository, monkeypatch): + from server.settings import settings + + monkeypatch.setattr(settings, "restricted_serve", False) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) + + +async def test_unavailable_classification_still_refuses_platform_admin(repository, monkeypatch): + monkeypatch.setattr( + authz.directory(), "is_restricted", AsyncMock(side_effect=ClassificationUnavailable()) + ) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) + + +async def test_held_org_refusal_precedes_repository_authority(repository, monkeypatch): + 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) + + +async def test_invalid_principal_is_refused_before_repository_authority(repository): + with pytest.raises(PermissionError, match="invalid auth principal"): + await authz.check_authorized( + SimpleNamespace(roles=(Role.PLATFORM_ADMIN,)), Role.VIEWER, ORG, NS + ) + + +async def test_row_scope_agrees_without_revealing_foreign_memory(repository, monkeypatch): + monkeypatch.setattr( + classification, "restricted_set", AsyncMock(return_value=frozenset({"memory-private"})) + ) + with acting_as(_admin()): + assert await authz.row_in_scope(ORG, NS) + assert not await authz.row_in_scope(ORG, "memory-private") + assert not await authz.row_in_scope(ORG, NS, Role.WRITER) + with acting_as(replace(_admin(), ns_roles=(("personal", "viewer"),))): + assert not await authz.row_in_scope(ORG, NS) + + +@pytest.mark.parametrize("join_policy", ["open", "approval", "closed"]) +@pytest.mark.parametrize("level", ["standard", "restricted"]) +async def test_admin_listing_returns_actual_heads_and_counts( + repository, monkeypatch, join_policy, level +): + from server.code.api.models_repos import CodeReposInput + from server.code.app import repos as listing + from server.code.app.index import repo_registry + + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + monkeypatch.setattr(repo_registry, "refresh_db_repos", AsyncMock(return_value=[])) + monkeypatch.setattr(repos, "docs_namespaces", lambda: {}) + monkeypatch.setattr(listing.CodeRepo, "all_state_many", AsyncMock(return_value={})) + monkeypatch.setattr( + listing, + "_repo_directory_state", + AsyncMock(return_value=({(ORG, NS): join_policy}, {}, {}, set())), + ) + monkeypatch.setattr(listing, "_bound_trackers", AsyncMock(return_value=lambda *a: [])) + status = SimpleNamespace( + org=ORG, + namespace=NS, + repo="example/private", + branch="main", + git_head="actual-index-head", + clone_head="actual-clone-head", + clone_fetched_at="2026-01-01T00:00:00Z", + fast_tier_lag=2, + scip_lag=3, + scip_py_lag=4, + tier_health=[], + state={}, + last_refresh_at="2026-01-01T00:00:00Z", + counts={"files": 17, "symbols": 23}, + chunks_total=10, + chunks_embedded=10, + embedding_coverage=1.0, + ) + status_read = AsyncMock(return_value=status) + monkeypatch.setattr(listing, "_repo_status_cached", status_read) + with acting_as(replace(_admin(), org="other")): + rows = await listing._code_repo_rows(CodeReposInput(org="other"), None) + assert len(rows) == 1 + row = rows[0] + assert row.readable and row.join_policy == join_policy + assert row.git_head == status.git_head and row.clone_head == status.clone_head + assert row.counts == status.counts and row.last_refresh_at == status.last_refresh_at + assert row.chunks_total == 10 and row.scip_lag == 3 + assert row.my_role == "" # read authority does not invent a maintainer grant + assert status_read.await_count >= 1 + + +async def test_repository_authority_never_opens_mirrors(repository): + mirror = "acl-0123456789abcdef01234567" + 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) + + +async def test_collection_gate_precedes_repository_authority(repository, monkeypatch): + from server.auth import sharing + + namespace = sharing.COLLECTION_PREFIX + "private" + 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) + denied.assert_awaited_once() + + +async def test_direct_restricted_predicate_checks_tenancy(repository, monkeypatch): + from server.auth import tenancy + + assert await authz.restricted_allows(_admin(), Role.VIEWER, ORG, NS) + monkeypatch.setattr(tenancy, "ensure_held", AsyncMock(side_effect=PermissionError("not held"))) + assert not await authz.restricted_allows(_admin(), Role.VIEWER, ORG, NS) + + +@pytest.fixture +def transports(repository, monkeypatch): + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from server.auth import bearer + from server.auth.jwt import TokenError + from server.code.app import files + from server.operations.registry import OPERATIONS_BY_NAME + from server.settings import settings + from server.transport import http, mcp_call, mcp_outcome + + tokens = { + "admin": _admin(), + "other-org-admin": replace(_admin(), org="other"), + "namespace-admin": replace(_admin(), roles=(Role.ADMIN,)), + "scoped": replace(_admin(), ns_roles=(("personal", "viewer"),)), + } + + def verify(token): + if token not in tokens: + raise TokenError("revoked or unverifiable token") + return tokens[token] + + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(bearer, "verify_token", verify) + monkeypatch.setattr( + "server.auth.personal_namespace.ensure_personal_namespace_cached", AsyncMock() + ) + monkeypatch.setattr( + "server.identity.app.namespace_autoregister.maybe_autoregister", AsyncMock() + ) + audit = AsyncMock() + monkeypatch.setattr("server.identity.app.restricted_access.note_restricted_access", audit) + monkeypatch.setattr(files, "require_code_intel", lambda: None) + monkeypatch.setattr(files, "_not_covered_output", lambda *a: None) + monkeypatch.setattr(files, "schedule_code_trace", lambda **kw: None) + monkeypatch.setattr(files, "index_as_of", AsyncMock(return_value={"commit": "indexed-head"})) + 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]) + 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) + 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) + + +@pytest.mark.parametrize( + "who", ["admin", "other-org-admin", "namespace-admin", "scoped", "revoked"] +) +def test_http_repository_read_uses_actual_authorization(transports, who): + response = transports.http.post( + "/v1/code.files", + json={"org": ORG, "namespace": NS, "path_prefix": "src/"}, + headers={"Authorization": "Bearer " + who}, + ) + if who in ("admin", "other-org-admin"): + assert response.status_code == 200, response.text + assert response.json()["files"] == [{"path": "src/private.py", "lang": "python"}] + transports.read.assert_awaited_once() + transports.audit.assert_awaited_once() + else: + assert response.status_code in (401, 403), response.text + assert "src/private.py" not in response.text + transports.read.assert_not_awaited() + transports.audit.assert_not_awaited() + + +@pytest.mark.parametrize("who", ["admin", "other-org-admin", "namespace-admin", "scoped"]) +async def test_mcp_repository_read_uses_actual_authorization(transports, who): + response = await transports.mcp._call_tool( + 1, + { + "name": "loom_code_files", + "arguments": {"org": ORG, "namespace": NS, "path_prefix": "src/"}, + }, + auth=transports.tokens[who], + ) + result = response["result"] + if who in ("admin", "other-org-admin"): + assert not result["isError"], result + assert result["structuredContent"]["files"] == [ + {"path": "src/private.py", "lang": "python"} + ] + transports.read.assert_awaited_once() + transports.audit.assert_awaited_once() + else: + assert result["isError"], result + assert "src/private.py" not in str(result) + transports.read.assert_not_awaited() + transports.audit.assert_not_awaited() + + +async def test_self_service_registry_snapshot_decides_repository_authority(monkeypatch): + from server.settings import settings + + monkeypatch.setattr(settings, "code_self_service_enabled", True) + monkeypatch.setattr(repos, "_configured_from_env", lambda: []) + 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())) + monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=None)) + entry = repo_config( + org=ORG, + namespace="page-index", + repo="example/page", + classification="restricted", + source="registry", + row_kind="page", + org_readable=False, + ) + repos.set_registry_repos([], frozenset()) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, entry.namespace) + repos.set_registry_repos([entry], frozenset({(ORG, entry.namespace)})) + await authz.check_authorized(_admin(), Role.VIEWER, ORG, entry.namespace) + repos.set_registry_repos([], frozenset({(ORG, entry.namespace)})) + with pytest.raises(PermissionError): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, entry.namespace) + + +@pytest.mark.parametrize("level", ["standard", "restricted"]) +async def test_read_authority_does_not_admit_repository_refresh(repository, level): + from server.code.app.member_writes import authorize_op + from server.operations.registry import OPERATIONS_BY_NAME + + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + with pytest.raises(PermissionError): + await authorize_op(_admin(), OPERATIONS_BY_NAME["code.refresh"], org=ORG, namespace=NS) + + +@pytest.mark.parametrize("transport", ["http", "mcp"]) +async def test_transport_restricted_kill_switch_precedes_repository_read( + transports, monkeypatch, transport +): + from server.settings import settings + + monkeypatch.setattr(settings, "restricted_serve", False) + body = {"org": ORG, "namespace": NS, "path_prefix": "src/"} + if transport == "http": + response = transports.http.post( + "/v1/code.files", json=body, headers={"Authorization": "Bearer admin"} + ) + assert response.status_code == 403, response.text + else: + response = await transports.mcp._call_tool( + 1, {"name": "loom_code_files", "arguments": body}, auth=transports.tokens["admin"] + ) + assert response["result"]["isError"], response + transports.read.assert_not_awaited() + transports.audit.assert_not_awaited() From 6a95a618fa89c94d289c72833a783e0775040675 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 19 Nov 2026 19:12:06 +0000 Subject: [PATCH 2/3] Repository read authority preserves member write scope Keep the ordinary namespace and organization limits when member writes check read access. Signed-off-by: zlareb1 --- docs/architecture/security.md | 3 +++ server/auth/authz.py | 27 +++++++++++++++---- server/code/app/member_writes.py | 5 +++- .../test_platform_admin_repository_read.py | 25 +++++++++++++++++ 4 files changed, 54 insertions(+), 6 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 779ccc3ada..8abcf58d2e 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -362,6 +362,9 @@ grant management and every non-repository namespace keep their existing checks. and mirror boundaries run before repository admission; a repository read does not expose its document mirrors or internal data. +The member-write fallback checks the ordinary read rules without the platform read +exception. A live viewer grant alone cannot widen a token's restricted write scope. + Classification must remain available, `restricted_serve=false` refuses restricted reads even for platform administrators, and tenancy and token verification still run first. Revoked or unverifiable credentials gain no authority. HTTP, MCP, row-scoped checks and diff --git a/server/auth/authz.py b/server/auth/authz.py index 016680168d..5b817bccb9 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -233,6 +233,7 @@ async def check_authorized( row_scoped: bool = False, known_grant: Role | None | _Unknown = _UNKNOWN_GRANT, grants: GrantMap | None = None, + allow_repository_read: bool = True, ) -> None: """Raise PermissionError if `auth` lacks `required_role` or access to `(org, namespace)`. Consults `loom.namespace_grants` as a fallback when the JWT role alone @@ -285,13 +286,22 @@ async def check_authorized( # Restricted reads retain their safety guards before repository admission. if org is not None and namespace is not None and await may_be_restricted(org, namespace): - await _check_restricted(auth, required_role, org, namespace, grants) + await _check_restricted( + auth, + required_role, + org, + namespace, + grants, + allow_repository_read=allow_repository_read, + ) return if ( org is not None and namespace is not None - and await _standard_code_read(auth, required_role, org, namespace) + and await _standard_code_read( + auth, required_role, org, namespace, allow_repository_read=allow_repository_read + ) ): return @@ -545,7 +555,12 @@ def _scoped_role( async def _standard_code_read( - auth: AuthInfo, required_role: Role, org: str, namespace: str + auth: AuthInfo, + required_role: Role, + org: str, + namespace: str, + *, + allow_repository_read: bool, ) -> bool: """Read exceptions for code after restricted safety guards have run. @@ -554,7 +569,7 @@ async def _standard_code_read( end user is no member of its org's code. Directory visibility affects joining, never reading. Writes keep the ordinary claim and grant checks. """ - if _platform_repository_read(auth, required_role, org, namespace): + if allow_repository_read and _platform_repository_read(auth, required_role, org, namespace): return True return ( required_role.value <= Role.VIEWER.value @@ -631,6 +646,8 @@ async def _check_restricted( org: str, namespace: str, grants: GrantMap | None = None, + *, + allow_repository_read: bool = True, ) -> None: """The two-factor gate for restricted namespaces. Raises PermissionError unless: @@ -660,7 +677,7 @@ async def _check_restricted( except ClassificationUnavailable as e: note_unreadable() raise refusal from e - if _platform_repository_read(auth, required_role, org, namespace): + if allow_repository_read and _platform_repository_read(auth, required_role, org, namespace): from server.auth import tenancy # restricted_allows also calls this gate directly, outside check_authorized. diff --git a/server/code/app/member_writes.py b/server/code/app/member_writes.py index 98bc25137f..3f40e8160c 100644 --- a/server/code/app/member_writes.py +++ b/server/code/app/member_writes.py @@ -65,7 +65,10 @@ async def code_member_may_write( if not subject or await _lookup_grant(org, namespace, subject) is None: return False try: - await check_authorized(auth, Role.VIEWER, org=org, namespace=namespace) + # Membership writes retain token ceilings even when platform authority reads more. + await check_authorized( + auth, Role.VIEWER, org=org, namespace=namespace, allow_repository_read=False + ) except (PermissionError, IdentityIncompleteError): return False return True diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 4c03fe1b1b..852e62eebd 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -396,3 +396,28 @@ async def test_transport_restricted_kill_switch_precedes_repository_read( assert response["result"]["isError"], response transports.read.assert_not_awaited() transports.audit.assert_not_awaited() + + +@pytest.mark.parametrize("op_name", ["memory.set", "memory.update", "memory.delete"]) +@pytest.mark.parametrize("claim", ["missing", "other-org", "named"]) +async def test_repository_read_authority_does_not_widen_member_writes( + repository, monkeypatch, op_name, claim +): + from server.code.app.member_writes import admitted_as_code_member, authorize_op + from server.operations.registry import OPERATIONS_BY_NAME + + monkeypatch.setattr(authz, "grant_role_for", AsyncMock(return_value=Role.VIEWER)) + monkeypatch.setattr(authz, "_lookup_grant", AsyncMock(return_value=Role.VIEWER)) + auth = _admin() + if claim == "other-org": + auth = replace(auth, org="other", namespaces=(NS,)) + elif claim == "named": + auth = replace(auth, namespaces=(NS,)) + await authz.check_authorized(auth, Role.VIEWER, ORG, NS) + if claim == "named": + await authorize_op(auth, OPERATIONS_BY_NAME[op_name], org=ORG, namespace=NS) + assert admitted_as_code_member() + else: + with pytest.raises(PermissionError): + await authorize_op(auth, OPERATIONS_BY_NAME[op_name], org=ORG, namespace=NS) + assert not admitted_as_code_member() From 2e26b042f03d899bb77c757b07a8df916fbc587d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 20 Nov 2026 00:23:36 +0000 Subject: [PATCH 3/3] Repository read authority retains provisioning checks Cover refused and unavailable provisioning before the platform repository read exception for both standard and restricted indexes. Signed-off-by: zlareb1 --- .../test_platform_admin_repository_read.py | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 852e62eebd..d9fa55383b 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -264,7 +264,7 @@ def verify(token): monkeypatch.setattr(settings, "auth_required", True) monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) - monkeypatch.setattr(bearer, "verify_token", verify) + monkeypatch.setattr(bearer, "authenticate_token", AsyncMock(side_effect=verify)) monkeypatch.setattr( "server.auth.personal_namespace.ensure_personal_namespace_cached", AsyncMock() ) @@ -421,3 +421,22 @@ async def test_repository_read_authority_does_not_widen_member_writes( with pytest.raises(PermissionError): await authorize_op(auth, OPERATIONS_BY_NAME[op_name], org=ORG, namespace=NS) assert not admitted_as_code_member() + + +@pytest.mark.parametrize("level", ["standard", "restricted"]) +@pytest.mark.parametrize("unavailable", [False, True]) +async def test_provisioning_precedes_repository_authority( + repository, monkeypatch, level, unavailable +): + from server.auth import login, scim + from server.core.errors import BackendUnavailableError + + repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) + check = AsyncMock(return_value=True) + if unavailable: + check.side_effect = login.SignInUnavailable("provisioning is unavailable") + monkeypatch.setattr(scim, "refuses_auth", check) + refusal = BackendUnavailableError if unavailable else authz.ActedForRefused + with pytest.raises(refusal): + await authz.check_authorized(_admin(), Role.VIEWER, ORG, NS) + check.assert_awaited_once()