From dd3044f351c68b18fb15abc9e01f3ab303d43418 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:20:54 +0530 Subject: [PATCH 01/23] auth: an identity-provider group can confer platform_admin LOOM_OIDC_PLATFORM_ADMIN_GROUP names one group. An OIDC sign-in whose verified ID token lists it in its `groups` claim mints platform_admin, whatever LOOM_PLATFORM_ADMINS says. Each refresh verifies the ID token the provider issues with the refreshed token and keeps the role only while it names the same verified email and still lists the group; a missing or unverifiable ID token ends the role. A refresh never promotes. The decision is set from the verified ID token in the callback and stored with the sign-in, so an account link that finishes later keeps it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 9 ++- docs/guides/tokens-and-grants.md | 14 ++--- docs/operations/deployment.md | 4 +- docs/operations/monitoring.md | 2 +- docs/operations/sso.md | 28 +++++++-- docs/reference/configuration.md | 3 +- docs/reference/mcp.md | 3 +- loom.example.yaml | 10 +++- schemas/loom-settings.schema.json | 7 ++- server/auth/oauth.py | 37 +++++++++++- server/auth/oidc.py | 38 +++++++++--- server/settings/catalog.py | 8 ++- tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_device_login.py | 4 +- tests/unit/test_oauth.py | 64 +++++++++++++++++++++ tests/unit/test_oidc.py | 57 ++++++++++++++++++ tests/unit/test_oidc_backchannel.py | 2 +- tests/unit/test_scim_sessions.py | 4 +- 18 files changed, 259 insertions(+), 36 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 2299dadb8b5..0774ec2e9d5 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -242,7 +242,11 @@ Each op declares `required_role`. reservation covers the rows that exist when the sign-up reads them; one written to a name while its sign-up runs lands on the new account. - `platform_admin` is written into the token at login for entries of - `LOOM_PLATFORM_ADMINS` (`platform_roles` in `server/auth/login.py`). A handle matches a + `LOOM_PLATFORM_ADMINS` (`platform_roles` in `server/auth/login.py`), and at an OIDC + sign-in whose verified ID token lists `LOOM_OIDC_PLATFORM_ADMIN_GROUP` in its `groups` + claim (`oidc.in_platform_admin_group`). A refresh keeps a group-conferred role only while + the ID token the provider issues with it verifies, names the same email and still lists + the group (`_still_in_admin_group` in `server/auth/oauth.py`). A handle matches a password account; an email matches only an OIDC-verified sign-in. Self-signup emails are unverified and never confer a role, and self-signup refuses a listed handle as a name, so a handle promotes only an account that existed before it was listed. An OAuth refresh @@ -303,7 +307,8 @@ namespace, and step 8 has none to read) and the token's own role decides. It ask `writer`: the op makes a namespace, its caller's admin grant there and an indexing job that clones, stores and embeds a repository and can run its build code. A sign-in (password, OIDC, the device grant) and a sign-up (self-signup, agent sign-up) mint -`writer`, or `platform_admin` for a name in `LOOM_PLATFORM_ADMINS`, so any member adds +`writer`, or `platform_admin` for a name in `LOOM_PLATFORM_ADMINS` or a member of +`LOOM_OIDC_PLATFORM_ADMIN_GROUP`, so any member adds a repository. A token whose own role is `viewer` does not, and neither does a token scoped to namespaces (step 1). The ops on an existing index (`code.repo.add_branch`, `code.repo.set_access`, `code.repo.set_source`, `code.repo.remove`) ask for `admin` of diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index 74aa988bfa1..3c9f34e25e3 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` | Cross-org operator views. Conferred at login to the handles in `LOOM_PLATFORM_ADMINS`, to its emails only when an IdP verified them, and to members of the IdP group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names; 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 diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 1aaabb0e942..2e25c311e50 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -309,7 +309,7 @@ back. | `LOOM_SELF_SIGNUP_ORG` | `dev` | You want signed-up accounts in your own org. | | `LOOM_DEFAULT_NAMESPACE` | `local` | Renaming the one namespace `single-user` mode serves. Ignored when auth is required. | | `LOOM_JWT_SECRET` | the checked-in development secret | Always, when auth is on. | -| `LOOM_PLATFORM_ADMINS` | empty | Naming the operators. It is the only path to `platform_admin`. | +| `LOOM_PLATFORM_ADMINS` | empty | Naming the operators. With SSO, `LOOM_OIDC_PLATFORM_ADMIN_GROUP` is the other path to `platform_admin`. | | `LOOM_TRUSTED_CALLERS` | empty | In `gateway` mode, a subject may send `X-Loom-On-Behalf-Of` to act for an end user. | - **`LOOM_JWT_SECRET`** is the root secret: it signs tokens as kid `default` (HS256) @@ -344,6 +344,8 @@ back. does). `loom set-host ` writes the variable into `.env` (`--append` extends the list); the person signs in again to pick up the role. Self-signup refuses a listed handle as a new name, so create the account first, then list its handle. + With SSO, an identity-provider group can confer the role instead + ([platform admins](sso.md#platform-admins)). ### Public URL and clients diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 1dca93dd08e..f5a21576003 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -27,7 +27,7 @@ environment and `.env`. `loom --help` documents every flag, and the [CLI reference](../reference/cli.md) lists them all. Org-wide views (cost across namespaces, `ops.health`) need `ORG_ADMIN` or -`PLATFORM_ADMIN`, which only `LOOM_PLATFORM_ADMINS` grants +`PLATFORM_ADMIN`, which only `LOOM_PLATFORM_ADMINS` and `LOOM_OIDC_PLATFORM_ADMIN_GROUP` grant ([deployment](./deployment.md#required-environment)). The deployment-wide `/v1/admin/*` routes need `PLATFORM_ADMIN`; `token.mint`, `namespace.adopt` and `claim_release` need `ORG_ADMIN` in the org they act on. A namespace `admin` reaches none of them. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 5720c18859e..5fc1fcf8918 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -24,7 +24,11 @@ with their Loom password and approves. Nothing here needs configuring. See (for example `https://loom.example.com/oauth/callback`). No sign-out redirect is needed. 4. **Assignments:** the people or groups allowed into Loom. -5. Copy the client ID and secret, then set: +5. Optionally, a platform-admin group: assign it to the app too, and under + **Sign On → OpenID Connect ID Token** set the groups claim to type + **Filter**, name `groups`, matching only that group. Its members sign in as + platform admins ([below](#platform-admins)). +6. Copy the client ID and secret, then set: ```bash LOOM_OAUTH_LOGIN_PROVIDER=oidc @@ -50,7 +54,9 @@ provider's discovery document lists it (Okta's does). It needs: A provider that issues no refresh token gets no Loom refresh token either: its sessions end when the hour-long access token does. -Group claims are not mapped. Namespace access comes from Loom's own grants. +One group claim can be read: the `groups` entry `LOOM_OIDC_PLATFORM_ADMIN_GROUP` +names ([platform admins](#platform-admins)). Namespace access comes from +Loom's own grants. Loom checks an ID token's signature with the algorithms the discovery document lists in `id_token_signing_alg_values_supported`, among RS256, RS384, RS512, @@ -138,8 +144,22 @@ For a person with no account: was turned on stays theirs, and the person gets the next free one (`-2`, `-3`, then a random suffix). -Platform admins are the verified emails listed in `LOOM_PLATFORM_ADMINS`. -The provider can never grant admin. +### Platform admins + +A person signs in as a platform admin when `LOOM_PLATFORM_ADMINS` lists their +verified email, or when their verified ID token's `groups` claim holds the +group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, exactly: + +```bash +LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin +``` + +Each refresh, at most an hour apart, reads the ID token the provider issues +with it. A person taken out of the group, or whose refresh brings no ID token +Loom can verify for the same email, refreshes as a member without the role. A +refresh never adds the role: a person added to the group signs in again to +get it. The provider grants nothing else: namespace roles come from Loom's +own grants. ## Bots and CI diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 266815d77d9..fc6044d9f95 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 (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 names nobody here; `oidc_platform_admin_group` is the other way to the role. | | `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. | @@ -101,6 +101,7 @@ Authentication, tokens and identity providers. | `LOOM_OIDC_JIT_PROVISION` | `bool` | `False` | | JIT provisioning: a first OIDC sign-in with no account creates a personal namespace in oidc_jit_org instead of being rejected. Off = fail closed. oidc_jit_email_domains (comma-separated) restricts it; empty admits any verified email the IdP authenticates. | | `LOOM_OIDC_JIT_ORG` | `str` | `''` | | Org that JIT-provisioned accounts are created in; required when `oidc_jit_provision` is on. | | `LOOM_OIDC_JIT_EMAIL_DOMAINS` | `str` | `''` | | Comma-separated email domains JIT provisioning admits; empty admits any verified email. | +| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An identity-provider group whose members sign in as platform_admin: an exact entry of the verified ID token's `groups` claim. Each refresh reads the ID token the provider issues with it, so a person taken out of the group loses the role at their session's next refresh. Empty = no group confers a role. | | `LOOM_IDENTITY_PROVIDER_TIMEOUT_S` | `float` | `10.0` | live | Seconds one call to an identity provider may take: OIDC discovery, the token and revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user issuer's JWKS fetch. | | `LOOM_SCIM_TOKEN` | `str` | *(unset)* | | Bearer tokens (comma-separated, any one accepted) an identity provider presents to deactivate and reactivate people over SCIM 2.0 (/scim/v2). Empty = off; needs auth on, oidc. With LOOM_CELL set, at most two entries, named for that cell; only the observed first cell also accepts unnamed tokens. Generate one with `loom cell scim-token new --cell NAME`. Enforced cells also require active provisioning for every nonexempt person. | | `LOOM_JWT_SECRET` | `str` | *(set)* | | The root secret, and the one secret a deployment carries: it signs tokens as kid `default` and seals every stored credential and every signing key in loom.signing_keys (`loom signing-key rotate` adds those). Required when auth is on. The default is the checked-in DEV secret anyone can mint with: a deployment with auth on refuses to start with it, except the `make dev` stack (`loom doctor` warns everywhere else). A non-loopback bind refuses an HMAC secret under 32 bytes or an RSA key under 2048 bits. | diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index d6a0a73c243..a14cf867c80 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -210,7 +210,8 @@ connect by browser sign-in instead of a pasted token (`server/auth/oauth.py`): the host the authorization goes to. - Each refresh re-checks that the account is still active and re-derives its roles, so a released account, or a subject removed from - `LOOM_PLATFORM_ADMINS`, does not keep its access by refreshing. + `LOOM_PLATFORM_ADMINS` or from the group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` + names, does not keep its access by refreshing. [Security](../architecture/security.md) covers the token model behind this. diff --git a/loom.example.yaml b/loom.example.yaml index ffb7b922b6d..8e6094f6578 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -670,8 +670,8 @@ settings: # 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] + # IdP-verified (OIDC) email, never the unverified self-signup address. Empty names + # nobody here; `oidc_platform_admin_group` is the other way to the role. [restart] # platform_admins: "" # True: every operation requires a valid bearer JWT. False (laptop demos only): @@ -740,6 +740,12 @@ settings: # email. [restart] # oidc_jit_email_domains: "" + # An identity-provider group whose members sign in as platform_admin: an exact entry + # of the verified ID token's `groups` claim. Each refresh reads the ID token the + # provider issues with it, so a person taken out of the group loses the role at their + # session's next refresh. Empty = no group confers a role. [restart] + # oidc_platform_admin_group: "" + # Seconds one call to an identity provider may take: OIDC discovery, the token and # revocation endpoints, its signing keys, a machine issuer's discovery, and an # end-user issuer's JWKS fetch. [live] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 483984c3f5b..9e61b5b73be 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6111,6 +6111,11 @@ "type": "boolean", "description": "JIT provisioning: a first OIDC sign-in with no account creates a personal namespace in oidc_jit_org instead of being rejected. Off = fail closed. oidc_jit_email_domains (comma-separated) restricts it; empty admits any verified email the IdP authenticates." }, + "oidc_platform_admin_group": { + "default": "", + "type": "string", + "description": "An identity-provider group whose members sign in as platform_admin: an exact entry of the verified ID token's `groups` claim. Each refresh reads the ID token the provider issues with it, so a person taken out of the group loses the role at their session's next refresh. Empty = no group confers a role." + }, "openai_base_url": { "default": "https://api.openai.com/v1", "type": "string", @@ -6465,7 +6470,7 @@ "platform_admins": { "default": "", "type": "string", - "description": "Comma-separated login handles and emails promoted to platform_admin (org-wide visibility). A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty = no platform admins." + "description": "Comma-separated login handles and emails promoted to platform_admin (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 names nobody here; `oidc_platform_admin_group` is the other way to the role." }, "policy_cache_ttl_seconds": { "default": 30, diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 1a8c8103ee9..7e6fdb25827 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -50,6 +50,7 @@ from server.settings import settings if TYPE_CHECKING: + from server.auth import oidc from server.auth.login import Identity log = logging.getLogger(__name__) @@ -753,6 +754,9 @@ async def _finish_oidc_login(request: Request) -> Response: return _sign_in_unavailable(_restart_url(pending)) finally: _exchanging.discard(state) + # Set here, from the verified ID token, whatever the sealed round trip carried: an account + # link finishes from the stored sign-in, without the token. + pending["platform_admin_group"] = oidc.in_platform_admin_group(id_claims) upstream = str(tokens.get("refresh_token") or "") # The IdP vouched for this person: only now is the round trip marked used, # so a callback nobody signed in for writes nothing. @@ -842,6 +846,8 @@ async def _signed_in_as( identity[0], pending, upstream, org=identity[1], verified_email=email ): return refused + if pending.get("platform_admin_group"): + identity = (identity[0], identity[1], identity[2], ["platform_admin"]) if verified_claims is not None: try: await sso_links.attest_domain(email, identity[1], identity[0], verified_claims) @@ -1420,10 +1426,10 @@ def presented_right(g: Grant) -> bool: raise _unavailable() from e -async def _ask_identity_provider(grant: Grant, refresh_token: str) -> str: +async def _ask_identity_provider(grant: Grant, refresh_token: str) -> oidc.Refreshed: """Spend the session's IdP refresh token; the IdP refusing means the user is gone there (deactivated, signed out everywhere), so the session ends. - Returns the IdP refresh token to keep.""" + Returns the IdP refresh token to keep and the ID token issued with it.""" from server.auth import oidc if not grant["upstream_refresh"]: @@ -1522,8 +1528,11 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: grant["subject"], org=grant["org"], verified_email=grant.get("verified_email", "") ): raise _invalid_grant("this person cannot sign in under the cell's provisioning policy") + in_admin_group = False if settings.oauth_login_provider == "oidc": - grant["upstream_refresh"] = await _ask_identity_provider(grant, refresh_token) + refreshed = await _ask_identity_provider(grant, refresh_token) + grant["upstream_refresh"] = refreshed.refresh_token + in_admin_group = await _still_in_admin_group(grant, refreshed.id_token) elif grant["upstream_refresh"]: # Signed in through SSO, now off: nothing vouches for the user any more. raise _invalid_grant("single sign-on is off here; sign in again") @@ -1534,6 +1543,8 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: if roles is None: await end_session(grant, "account no longer active") raise _invalid_grant() + if in_admin_group: # asked only of a platform admin's session: it never promotes + roles = ["platform_admin"] return await issue_tokens( {**grant, "roles": roles}, grant["client_id"], @@ -1542,6 +1553,26 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: ) +async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: + """Whether the ID token the IdP issued with this refresh still puts the session's person + in `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. Only a platform admin's refresh asks. A missing or + unverifiable token, or one for another verified email, answers no: the role ends.""" + from server.auth import oidc + + if "platform_admin" not in grant["roles"] or not settings.oidc_platform_admin_group: + return False + email = scim.normalized(str(grant.get("verified_email") or "")) + if not id_token or not email: + return False + try: + claims = await oidc.verify_refreshed_id_token(id_token) + except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role + log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) + return False + same = scim.normalized(oidc.verified_email(claims)) == email + return same and oidc.in_platform_admin_group(claims) + + def _refused(e: machines.Refused) -> OAuthError: status = {"invalid_client": 401, "temporarily_unavailable": 503}.get(e.error, 400) return OAuthError(e.error, status, description=e.description) diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 925e48f7be3..bafb9d053fc 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -24,7 +24,7 @@ import logging import secrets import time -from typing import Any +from typing import Any, NamedTuple from urllib.parse import urlencode, urlsplit, urlunsplit import httpx @@ -166,9 +166,15 @@ async def exchange_code(*, code: str, redirect_uri: str, code_verifier: str) -> ) -async def refresh(refresh_token: str) -> str: - """Spend the IdP refresh token; returns the one to keep next (the IdP may - rotate it). Raises UpstreamRefused for `invalid_grant` and +class Refreshed(NamedTuple): + """What spending an IdP refresh token returns.""" + + refresh_token: str # the one to keep next (the IdP may rotate it) + id_token: str # the ID token the IdP issued with it, unverified; '' when it sent none + + +async def refresh(refresh_token: str) -> Refreshed: + """Spend the IdP refresh token. Raises UpstreamRefused for `invalid_grant` and UpstreamUnavailable for anything else that goes wrong.""" try: async with asyncio.timeout(_REFRESH_DEADLINE_S): @@ -181,7 +187,9 @@ async def refresh(refresh_token: str) -> str: raise UpstreamUnavailable(f"HTTP {e.response.status_code}") from e except (httpx.HTTPError, ValueError, KeyError, TimeoutError) as e: raise UpstreamUnavailable(type(e).__name__) from e - return str(tokens.get("refresh_token") or refresh_token) + return Refreshed( + str(tokens.get("refresh_token") or refresh_token), str(tokens.get("id_token") or "") + ) def error_code(response: httpx.Response) -> str: @@ -254,6 +262,16 @@ async def verify_id_token(id_token: str, *, nonce: str) -> dict[str, Any]: """Verify the IdP id_token (signature against JWKS with an algorithm the IdP lists, iss, aud, exp) and the nonce, returning the claims. Raises on any failure.""" + claims = await verify_refreshed_id_token(id_token) + if not nonce or not secrets.compare_digest(str(claims.get("nonce") or ""), nonce): + raise ValueError("id_token nonce mismatch") + return claims + + +async def verify_refreshed_id_token(id_token: str) -> dict[str, Any]: + """`verify_id_token` without the nonce, for the ID token a refresh returns: that one + carries the sign-in's nonce or none (OpenID Connect Core 12.2), and this process no + longer holds the sign-in's.""" doc = await _discover() algorithms = id_token_algorithms(doc) key = await asyncio.to_thread(signing_key, doc["jwks_uri"], id_token, sign_in=True) @@ -265,11 +283,17 @@ async def verify_id_token(id_token: str, *, nonce: str) -> dict[str, Any]: issuer=doc["issuer"], options={"require": ["exp", "iat", "aud", "iss"]}, ) - if not nonce or not secrets.compare_digest(str(claims.get("nonce") or ""), nonce): - raise ValueError("id_token nonce mismatch") return claims +def in_platform_admin_group(claims: dict[str, Any]) -> bool: + """Whether verified ID token `claims` list `LOOM_OIDC_PLATFORM_ADMIN_GROUP` in their + `groups` claim, exactly. A `groups` that is not a list of names lists nothing.""" + group = settings.oidc_platform_admin_group + groups = claims.get("groups") + return bool(group) and isinstance(groups, list) and group in groups + + def verified_email(claims: dict[str, Any]) -> str: """The id_token's email when the IdP asserts it verified it, else ''. `email_verified` must be the boolean true (or the string "true" some IdPs diff --git a/server/settings/catalog.py b/server/settings/catalog.py index f5314b83450..7de65701723 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -153,7 +153,8 @@ class AuthSettings(BaseModel): # 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. + # self-signup address. Empty names nobody here; `oidc_platform_admin_group` is the other + # way to the role. platform_admins: str = "" @property @@ -268,6 +269,11 @@ def _check_default_namespace(self) -> AuthSettings: oidc_jit_org: str = "" # Comma-separated email domains JIT provisioning admits; empty admits any verified email. oidc_jit_email_domains: str = "" + # An identity-provider group whose members sign in as platform_admin: an exact entry of + # the verified ID token's `groups` claim. Each refresh reads the ID token the provider + # issues with it, so a person taken out of the group loses the role at their session's + # next refresh. Empty = no group confers a role. + oidc_platform_admin_group: str = "" # Seconds one call to an identity provider may take: OIDC discovery, the token and # revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user # issuer's JWKS fetch. diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 6a9bed59121..c3c7c984a81 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -1069,6 +1069,7 @@ "oidc_jit_email_domains": "", "oidc_jit_org": "", "oidc_jit_provision": false, + "oidc_platform_admin_group": "", "openai_base_url": "https://api.openai.com/v1", "ops_incidents_error_share": 0.1, "ops_incidents_min_requests": 20, diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index 7c5eeb0b718..acaf56def46 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -549,12 +549,12 @@ async def verify(token: str, *, nonce: str) -> dict[str, Any]: async def issuer_ok(iss: str) -> bool: return iss in ("", "https://idp.example") - async def refresh(token: str) -> str: + async def refresh(token: str) -> oidc.Refreshed: if idp["upstream"] == "refused": raise oidc.UpstreamRefused if idp["upstream"] == "down": raise oidc.UpstreamUnavailable("ConnectError") - return token + "+" + return oidc.Refreshed(token + "+", "") async def by_email(email: str) -> Any: return _USER if email == "alice@example.com" else None diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 52f148c9d23..0b0856d9ddd 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -445,6 +445,70 @@ async def demoted(subject: str, org: str, roles: list[str]) -> list[str]: assert [r.name for r in verify_token(tok["access_token"]).roles] == ["WRITER"] +@pytest.mark.parametrize(("in_group", "want"), [(True, ["PLATFORM_ADMIN"]), (False, ["WRITER"])]) +def test_a_platform_admin_keeps_the_role_while_the_refreshed_id_token_lists_the_group( + monkeypatch: pytest.MonkeyPatch, in_group: bool, want: list[str] +) -> None: + from server.auth import oidc + from server.auth.jwt import verify_token + from server.settings import settings + + async def demoted(subject: str, org: str, roles: list[str]) -> list[str]: + return ["writer"] # LOOM_PLATFORM_ADMINS does not name the person + + async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: + return oidc.Refreshed("idp-next", "idp-id-token") + + async def still(grant: dict[str, Any], id_token: str) -> bool: + assert id_token == "idp-id-token" + return in_group + + c = _client() + rt = _refresh_token(c, roles=["platform_admin"]) + monkeypatch.setattr(settings, "oauth_login_provider", "oidc") + monkeypatch.setattr(login, "refreshed_roles", demoted) + monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) + monkeypatch.setattr(oauth, "_still_in_admin_group", still) + tok = _refresh(c, rt).json() + assert [r.name for r in verify_token(tok["access_token"]).roles] == want + + +def _admin_grant(roles: list[str], email: str = "ada@example.com") -> dict[str, Any]: + return {"roles": roles, "verified_email": email} + + +@pytest.mark.parametrize( + ("grant", "id_token", "claims", "want"), + [ + (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"]}, True), + (_admin_grant(["platform_admin"]), "t", {"groups": ["eng"]}, False), + (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"], "email": "eve@x.io"}, False), + (_admin_grant(["writer"]), "t", {"groups": ["admins"]}, False), # never promotes + (_admin_grant(["platform_admin"]), "", {"groups": ["admins"]}, False), # none sent + (_admin_grant(["platform_admin"], ""), "t", {"groups": ["admins"], "email": ""}, False), + (_admin_grant(["platform_admin"]), "t", None, False), # it fails verification + ], +) +async def test_still_in_admin_group_fails_closed( + monkeypatch: pytest.MonkeyPatch, + grant: dict[str, Any], + id_token: str, + claims: dict[str, Any] | None, + want: bool, +) -> None: + from server.auth import oidc + from server.settings import settings + + async def verify(token: str) -> dict[str, Any]: + if claims is None: + raise ValueError("signature") + return {"email": "ada@example.com", "email_verified": True, **claims} + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") + monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + assert await oauth._still_in_admin_group(grant, id_token) is want # type: ignore[arg-type] + + class _RowCH: def __init__(self, row: dict[str, object] | None) -> None: self.row = row diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 942302ce95e..219e2785531 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -684,3 +684,60 @@ class _Req: "someone", # the identity resolver's owner, not the JIT account name {"email": "bob@acme.com", "email_verified": True}, ) + + +@pytest.mark.parametrize( + ("groups", "carried", "want"), + [ + (["eng", "loom-admins"], False, ["platform_admin"]), + (["eng"], False, ["writer"]), + ("loom-admins", False, ["writer"]), # a groups claim that is no list lists nothing + (["loom-admins-old"], False, ["writer"]), # an exact entry, never a prefix + (["eng"], True, ["writer"]), # the verified ID token decides, not the sealed cookie + ], +) +async def test_the_platform_admin_group_signs_its_members_in_as_platform_admin( + monkeypatch, groups: Any, carried: bool, want: list[str] +) -> None: + from unittest.mock import AsyncMock + + from fastapi import Response + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") + pending = {"kind": "dashboard", "nonce": "n", "code_verifier": "v", "state": "s"} + if carried: + pending["platform_admin_group"] = True # type: ignore[assignment] + signed_in: dict[str, Any] = {} + + async def exchange(**_k: Any) -> dict[str, str]: + return {"id_token": "t"} + + async def claims(*_a: Any, **_k: Any) -> dict[str, Any]: + return {"email": "bob@acme.com", "email_verified": True, "groups": groups} + + async def account(*_a: Any) -> login.Identity: + return ("bob", "acme", ["bob"], ["writer"]) + + async def dashboard(identity: login.Identity, *_a: Any, **_k: Any) -> Response: + signed_in["roles"] = identity[3] + return Response(status_code=302) + + class _Req: + client = None + query_params = {"code": "c", "state": "s"} + cookies = {oauth._state_cookie("s"): oauth.seal_pending(pending | {"exp": 2**31 - 1})} + + monkeypatch.setattr(oauth, "store", MemoryOAuthStore()) + monkeypatch.setattr(oidc, "exchange_code", exchange) + monkeypatch.setattr(oidc, "verify_id_token", claims) + monkeypatch.setattr(oauth, "_account_for", account) + monkeypatch.setattr(oauth, "_dashboard_signed_in", dashboard) + monkeypatch.setattr(oauth.scim, "refuses_subject", AsyncMock(return_value=False)) + monkeypatch.setattr(oauth.sso_links, "attest_domain", AsyncMock()) + assert (await oauth.oidc_callback(_Req())).status_code == 302 # type: ignore[arg-type] + assert signed_in["roles"] == want + + +def test_no_group_is_the_platform_admin_group_when_none_is_set(monkeypatch) -> None: + monkeypatch.setattr(settings, "oidc_platform_admin_group", "") + assert not oidc.in_platform_admin_group({"groups": [""]}) diff --git a/tests/unit/test_oidc_backchannel.py b/tests/unit/test_oidc_backchannel.py index 0e42696def1..97bf7bbc00c 100644 --- a/tests/unit/test_oidc_backchannel.py +++ b/tests/unit/test_oidc_backchannel.py @@ -134,7 +134,7 @@ def respond(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"access_token": "a", "token_type": "Bearer"}) seen = _serve(monkeypatch, respond) - assert await oidc.refresh("idp-refresh") == "idp-refresh" + assert (await oidc.refresh("idp-refresh")).refresh_token == "idp-refresh" await oidc.revoke("idp-refresh") calls = [(str(r.url), r.headers["host"]) for r in seen[1:]] assert calls == [ diff --git a/tests/unit/test_scim_sessions.py b/tests/unit/test_scim_sessions.py index 3b1d741ae7e..e64e29273fa 100644 --- a/tests/unit/test_scim_sessions.py +++ b/tests/unit/test_scim_sessions.py @@ -33,7 +33,7 @@ def mint(*args, **kwargs): async def rotate(grant, refresh): rotated.append(grant["upstream_refresh"]) - return "unit-upstream-next" + return oidc.Refreshed("unit-upstream-next", "") async def revoke(value): revoked.append(value) @@ -177,7 +177,7 @@ async def rotated_then_unavailable(current, refresh): session["rotated"].append(current["upstream_refresh"]) authz.forget_ended("identity", "alice") people.unavailable = True - return "unit-upstream-next" + return oidc.Refreshed("unit-upstream-next", "") monkeypatch.setattr(oauth, "_ask_identity_provider", rotated_then_unavailable) await session["store"].save_refresh("unit-refresh", grant()) From bd3afc6153931a8d5df826757efb8938c6714bdd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:43:58 +0530 Subject: [PATCH 02/23] auth: ask for the groups scope and keep the role through a key outage Sign-in asks for `groups` where discovery lists it, since an org authorization server puts the claim in the ID token only then. A refresh whose ID token cannot be checked because the provider's keys or discovery are unreachable answers 503 with its token put back, instead of dropping the role. Tests cover the scope, the nonce-free refresh verification, the outage, and an account link that finishes the sign-in later. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 26 ++++++----- docs/concepts/identities-and-namespaces.md | 19 ++++---- docs/operations/sso.md | 23 ++++++---- docs/reference/configuration.md | 2 +- frontend/src/views/admin/Users.tsx | 4 +- loom.example.yaml | 7 ++- schemas/loom-settings.schema.json | 2 +- server/auth/oauth.py | 12 +++-- server/auth/oidc.py | 24 +++++++--- server/settings/catalog.py | 6 +-- tests/unit/test_device_login.py | 29 ++++++++++++ tests/unit/test_oauth.py | 21 +++++++++ tests/unit/test_oidc.py | 52 +++++++++++++++++++++- 13 files changed, 175 insertions(+), 52 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 0774ec2e9d5..66a5c88d192 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -242,18 +242,20 @@ Each op declares `required_role`. reservation covers the rows that exist when the sign-up reads them; one written to a name while its sign-up runs lands on the new account. - `platform_admin` is written into the token at login for entries of - `LOOM_PLATFORM_ADMINS` (`platform_roles` in `server/auth/login.py`), and at an OIDC - sign-in whose verified ID token lists `LOOM_OIDC_PLATFORM_ADMIN_GROUP` in its `groups` - claim (`oidc.in_platform_admin_group`). A refresh keeps a group-conferred role only while - the ID token the provider issues with it verifies, names the same email and still lists - the group (`_still_in_admin_group` in `server/auth/oauth.py`). A handle matches a + `LOOM_PLATFORM_ADMINS` (`platform_roles` in `server/auth/login.py`). A handle matches a password account; an email matches only an OIDC-verified sign-in. Self-signup emails are unverified and never confer a role, and self-signup refuses a listed handle as a name, so a handle promotes only an account that existed before it was listed. An OAuth refresh - re-derives the role and never promotes. A bot registered `--platform-admin` gets it in - every machine token, as a flat token over every namespace (`_machine_tokens` in - `server/auth/oauth.py`); such a bot names no namespace, tells no agents apart and, as a - trust, matches every claim exactly. + re-derives the role and never promotes. + An OIDC sign-in whose verified ID token lists `LOOM_OIDC_PLATFORM_ADMIN_GROUP` in its + `groups` claim gets the role too (`oidc.in_platform_admin_group`): whoever manages that + group at the provider decides who administers the platform. A refresh keeps a role so + conferred only while the ID token the provider issues with it verifies, names the same + email and still lists the group (`_still_in_admin_group` in `server/auth/oauth.py`); that + ID token carries no nonce check, since it answers Loom's own back-channel token request. + A bot registered `--platform-admin` gets it in every machine token, as a flat token over + every namespace (`_machine_tokens` in `server/auth/oauth.py`); such a bot names no + namespace, tells no agents apart and, as a trust, matches every claim exactly. Only a person signed in as a platform admin, or an operator on the host, registers one: `/v1/admin/bots.create` refuses the flag to every service account's token and to a third-party client's session, so a token holding the role cannot mint itself a lasting @@ -588,7 +590,8 @@ act for email subjects, which a sign-up name cannot spell, or grant each handle `LOOM_SELF_SIGNUP_ORG` first ([tokens and grants](../guides/tokens-and-grants.md)). **OIDC and OAuth.** OIDC login trusts only the configured issuer's discovery, verified -emails and nonce-bound id_tokens, sends PKCE to the provider, and refuses a callback whose +emails and nonce-bound id_tokens (a refresh's ID token, from Loom's own token request, +is checked without one), sends PKCE to the provider, and refuses a callback whose `iss` names another issuer (RFC 9207). With `LOOM_OAUTH_LOGIN_PROVIDER=oidc` the provider is the only way in: password sign-in and self-signup are refused, since a local password would bypass the provider's MFA and outlive a deactivation there. @@ -658,7 +661,8 @@ common bearer helper. Health remains public but omits denied or unavailable admi so provisioning refusal or outage cannot prevent logout or grant read/write authority. Loom stays the authorization server for every client (the dashboard, `loom login`, MCP -clients); the provider only authenticates the person. The OAuth server: +clients); the provider authenticates the person, and confers nothing but `platform_admin` +through `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. The OAuth server: - accepts only https, loopback-http or app-scheme redirect URIs; - binds codes to client, redirect and PKCE S256; diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 3c441a44e14..47dc3ae2ceb 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -137,17 +137,18 @@ 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` | Cross-org operator views. | Conferred at login to the handles and verified emails in `LOOM_PLATFORM_ADMINS` and to members of the IdP group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, 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 -registration, not something a token can carry away. Code namespaces have readers +`platform_admin` one: org-wide power is an operator decision in configuration, in the +identity provider's platform-admin group or at bot registration, not something a token can +carry away. Code namespaces have readers (`viewer`) and maintainers (`admin`) and no `writer`. ## Who may call what diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 5fc1fcf8918..0e8a7a14d67 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -4,8 +4,9 @@ Loom can hand the human sign-in to an OpenID Connect identity provider. With it on, the dashboard shows one **Sign in with SSO** button, `loom login` and `loom.login()` approve through the provider, MCP clients that connect with OAuth sign in there too, and Loom refuses password sign-in and self-signup. -Loom still issues its own tokens; the provider only vouches for who the user -is. Off by default: a fresh install signs in with passwords. +Loom still issues its own tokens; the provider vouches for who the user is, +and one of its groups can name the platform admins. Off by default: a fresh +install signs in with passwords. ## How sign-in works without SSO @@ -39,7 +40,8 @@ LOOM_OIDC_CLIENT_SECRET=… ``` Loom refuses to start when one of these is missing. The org authorization -server is enough: Loom reads only the ID token's standard claims. +server is enough: Loom reads the ID token's standard claims, and `groups` when +a platform-admin group is set. ### Scopes and claims @@ -154,12 +156,15 @@ group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, exactly: LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin ``` -Each refresh, at most an hour apart, reads the ID token the provider issues -with it. A person taken out of the group, or whose refresh brings no ID token -Loom can verify for the same email, refreshes as a member without the role. A -refresh never adds the role: a person added to the group signs in again to -get it. The provider grants nothing else: namespace roles come from Loom's -own grants. +With the group set, sign-in asks for the `groups` scope where the provider's +discovery document lists it (Okta's org authorization server needs it). With a +custom authorization server, define the groups claim on that server and +include it in the ID token. Each refresh, at most an hour apart, reads the ID +token the provider issues with it: the role lasts while those ID tokens list +the group. A refresh that brings no ID token Loom can verify for the same +email refreshes without the role. A refresh never adds the role: a person +added to the group signs in again to get it. The provider grants nothing else: +namespace roles come from Loom's own grants. ## Bots and CI diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index fc6044d9f95..966b64bddcb 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -101,7 +101,7 @@ Authentication, tokens and identity providers. | `LOOM_OIDC_JIT_PROVISION` | `bool` | `False` | | JIT provisioning: a first OIDC sign-in with no account creates a personal namespace in oidc_jit_org instead of being rejected. Off = fail closed. oidc_jit_email_domains (comma-separated) restricts it; empty admits any verified email the IdP authenticates. | | `LOOM_OIDC_JIT_ORG` | `str` | `''` | | Org that JIT-provisioned accounts are created in; required when `oidc_jit_provision` is on. | | `LOOM_OIDC_JIT_EMAIL_DOMAINS` | `str` | `''` | | Comma-separated email domains JIT provisioning admits; empty admits any verified email. | -| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An identity-provider group whose members sign in as platform_admin: an exact entry of the verified ID token's `groups` claim. Each refresh reads the ID token the provider issues with it, so a person taken out of the group loses the role at their session's next refresh. Empty = no group confers a role. | +| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it. | | `LOOM_IDENTITY_PROVIDER_TIMEOUT_S` | `float` | `10.0` | live | Seconds one call to an identity provider may take: OIDC discovery, the token and revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user issuer's JWKS fetch. | | `LOOM_SCIM_TOKEN` | `str` | *(unset)* | | Bearer tokens (comma-separated, any one accepted) an identity provider presents to deactivate and reactivate people over SCIM 2.0 (/scim/v2). Empty = off; needs auth on, oidc. With LOOM_CELL set, at most two entries, named for that cell; only the observed first cell also accepts unnamed tokens. Generate one with `loom cell scim-token new --cell NAME`. Enforced cells also require active provisioning for every nonexempt person. | | `LOOM_JWT_SECRET` | `str` | *(set)* | | The root secret, and the one secret a deployment carries: it signs tokens as kid `default` and seals every stored credential and every signing key in loom.signing_keys (`loom signing-key rotate` adds those). Required when auth is on. The default is the checked-in DEV secret anyone can mint with: a deployment with auth on refuses to start with it, except the `make dev` stack (`loom doctor` warns everywhere else). A non-loopback bind refuses an HMAC secret under 32 bytes or an RSA key under 2048 bits. | diff --git a/frontend/src/views/admin/Users.tsx b/frontend/src/views/admin/Users.tsx index 34ca28cdc6b..5c866be726b 100644 --- a/frontend/src/views/admin/Users.tsx +++ b/frontend/src/views/admin/Users.tsx @@ -257,7 +257,9 @@ export function Users() {
To make someone a platform admin, an operator adds their login handle, or the email they sign in with over SSO, to LOOM_PLATFORM_ADMINS in the deployment's environment, - and they sign in again. + and they sign in again. With SSO, members of the identity provider's group named by{" "} + LOOM_OIDC_PLATFORM_ADMIN_GROUP sign in as platform admins + too; Loom keeps no group membership, so they carry no badge here.
)} diff --git a/loom.example.yaml b/loom.example.yaml index 8e6094f6578..89ff7d5d380 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -740,10 +740,9 @@ settings: # email. [restart] # oidc_jit_email_domains: "" - # An identity-provider group whose members sign in as platform_admin: an exact entry - # of the verified ID token's `groups` claim. Each refresh reads the ID token the - # provider issues with it, so a person taken out of the group loses the role at their - # session's next refresh. Empty = no group confers a role. [restart] + # An IdP group whose members sign in as platform_admin, matched exactly in the + # verified ID token's `groups` claim at sign-in and every refresh. Empty = no group + # confers it. [restart] # oidc_platform_admin_group: "" # Seconds one call to an identity provider may take: OIDC discovery, the token and diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 9e61b5b73be..74e6914f5b6 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6114,7 +6114,7 @@ "oidc_platform_admin_group": { "default": "", "type": "string", - "description": "An identity-provider group whose members sign in as platform_admin: an exact entry of the verified ID token's `groups` claim. Each refresh reads the ID token the provider issues with it, so a person taken out of the group loses the role at their session's next refresh. Empty = no group confers a role." + "description": "An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it." }, "openai_base_url": { "default": "https://api.openai.com/v1", diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 7e6fdb25827..6bae19a9917 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -4,7 +4,8 @@ the token and revocation endpoints, the IdP callback and the dashboard's SSO sign-in; `connect_router` adds MCP one-click connect when `LOOM_OAUTH_ENABLED=true`. Loom issues its own JWTs; under -`LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP only authenticates (oidc.py). State +`LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP authenticates the person (oidc.py), and +one group of it may confer platform_admin (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`). State lives in oauth_store.py. The flows, sessions and threat model are in docs/architecture/security.md ("OIDC and OAuth"). """ @@ -26,6 +27,7 @@ from urllib.parse import parse_qs, urlencode, urlsplit import httpx +import jwt from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response @@ -1565,12 +1567,14 @@ async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: if not id_token or not email: return False try: - claims = await oidc.verify_refreshed_id_token(id_token) + id_claims = await oidc.verify_refreshed_id_token(id_token) + except (jwt.PyJWKClientConnectionError, httpx.HTTPError): + raise # the provider's keys are away: the refresh is retried with its token put back except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) return False - same = scim.normalized(oidc.verified_email(claims)) == email - return same and oidc.in_platform_admin_group(claims) + same = scim.normalized(oidc.verified_email(id_claims)) == email + return same and oidc.in_platform_admin_group(id_claims) def _refused(e: machines.Refused) -> OAuthError: diff --git a/server/auth/oidc.py b/server/auth/oidc.py index bafb9d053fc..30053aa62e7 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -110,12 +110,17 @@ async def build_authorize_url( ) -> str: """The IdP authorize URL loom redirects the browser to (auth-code flow). `offline` asks for an IdP refresh token, for a sign-in whose Loom session - refreshes; some IdPs reject a scope they don't list, so only where the - discovery document advertises `offline_access`.""" + refreshes. With `LOOM_OIDC_PLATFORM_ADMIN_GROUP` set it asks for `groups` too, + which a provider may need before it puts the claim in the ID token. Some IdPs + reject a scope they don't list, so each only where the discovery document + advertises it.""" doc = await _discover() + listed = doc.get("scopes_supported") or [] scope = "openid email profile" - if offline and "offline_access" in (doc.get("scopes_supported") or []): + if offline and "offline_access" in listed: scope += " offline_access" + if settings.oidc_platform_admin_group and "groups" in listed: + scope += " groups" params = { "response_type": "code", "client_id": settings.oidc_client_id, @@ -262,16 +267,21 @@ async def verify_id_token(id_token: str, *, nonce: str) -> dict[str, Any]: """Verify the IdP id_token (signature against JWKS with an algorithm the IdP lists, iss, aud, exp) and the nonce, returning the claims. Raises on any failure.""" - claims = await verify_refreshed_id_token(id_token) + claims = await _verified_claims(id_token) if not nonce or not secrets.compare_digest(str(claims.get("nonce") or ""), nonce): raise ValueError("id_token nonce mismatch") return claims async def verify_refreshed_id_token(id_token: str) -> dict[str, Any]: - """`verify_id_token` without the nonce, for the ID token a refresh returns: that one - carries the sign-in's nonce or none (OpenID Connect Core 12.2), and this process no - longer holds the sign-in's.""" + """`verify_id_token` without the nonce, for the ID token a refresh returns. That one + carries the sign-in's nonce or none (OpenID Connect Core 12.2), and it answers Loom's + own back-channel token request, so no browser can replay one into it.""" + return await _verified_claims(id_token) + + +async def _verified_claims(id_token: str) -> dict[str, Any]: + """The claims of an IdP ID token whose signature, issuer, audience and expiry hold.""" doc = await _discover() algorithms = id_token_algorithms(doc) key = await asyncio.to_thread(signing_key, doc["jwks_uri"], id_token, sign_in=True) diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 7de65701723..077d1330333 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -269,10 +269,8 @@ def _check_default_namespace(self) -> AuthSettings: oidc_jit_org: str = "" # Comma-separated email domains JIT provisioning admits; empty admits any verified email. oidc_jit_email_domains: str = "" - # An identity-provider group whose members sign in as platform_admin: an exact entry of - # the verified ID token's `groups` claim. Each refresh reads the ID token the provider - # issues with it, so a person taken out of the group loses the role at their session's - # next refresh. Empty = no group confers a role. + # An IdP group whose members sign in as platform_admin, matched exactly in the verified + # ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it. oidc_platform_admin_group: str = "" # Seconds one call to an identity provider may take: OIDC discovery, the token and # revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index acaf56def46..f840342cde2 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -544,6 +544,7 @@ async def verify(token: str, *, nonce: str) -> dict[str, Any]: "email_verified": True, "iss": "https://idp.example", **({"hd": idp["hd"]} if "hd" in idp else {}), + **({"groups": idp["groups"]} if "groups" in idp else {}), } async def issuer_ok(iss: str) -> bool: @@ -740,6 +741,34 @@ async def no_jit(email: str) -> None: assert denied and "ask your" not in str(denied[-1]) # the bare reason, not the page's advice +@pytest.mark.parametrize("decision", ["link", "not_mine"]) +def test_a_sign_in_finished_on_the_link_page_keeps_the_platform_admin_group( + sso, bobs_password_account, monkeypatch, decision: str +) -> None: + # The link page finishes from the stored sign-in, after the ID token is gone. + from server.settings import settings + + async def jit_account(email: str) -> Any: + return ("u-bob-1a2b3c4d", "corp", ["u-bob-1a2b3c4d"], ["writer"]) + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") + monkeypatch.setattr(settings, "oidc_jit_org", "corp") + monkeypatch.setattr(jit, "jit_provision_for_email", jit_account) + sso["groups"] = ["loom-admins"] + c = _client() + grant = _start(c) + page = _sso_round_trip(c, grant["user_code"]) + if decision == "link": + r = _link(c, page.text, "bobpw") + else: + r = c.post("/oauth/link", data={"ticket": _ticket(page.text), "decision": "not_mine"}) + assert r.status_code == 200, r.text + _approve(c, grant["user_code"], r.text) + tokens = _poll(c, grant["device_code"]).json() + claims = pyjwt.decode(tokens["access_token"], options={"verify_signature": False}) + assert claims["roles"] == ["platform_admin"] + + def test_declining_while_jit_cannot_read_starts_again(bobs_password_account, monkeypatch) -> None: from server.auth.login import SignInUnavailable from server.settings import settings diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 0b0856d9ddd..9fb812b7a5d 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -16,6 +16,8 @@ import time from typing import Any +import httpx +import jwt import pytest from fastapi.testclient import TestClient @@ -509,6 +511,25 @@ async def verify(token: str) -> dict[str, Any]: assert await oauth._still_in_admin_group(grant, id_token) is want # type: ignore[arg-type] +@pytest.mark.parametrize( + "away", [jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider")] +) +async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( + monkeypatch: pytest.MonkeyPatch, away: Exception +) -> None: + # Re-raised, the refresh answers 503 with its token put back instead of ending the role. + from server.auth import oidc + from server.settings import settings + + async def verify(token: str) -> dict[str, Any]: + raise away + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") + monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + with pytest.raises(type(away)): + await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + + class _RowCH: def __init__(self, row: dict[str, object] | None) -> None: self.row = row diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 219e2785531..435e1c8034d 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -87,7 +87,7 @@ def _id_token(priv: Any, **overrides: Any) -> str: "nonce": "the-nonce", } claims.update(overrides) - return pyjwt.encode(claims, priv, algorithm="RS256") + return pyjwt.encode({k: v for k, v in claims.items() if v is not None}, priv, algorithm="RS256") def _inject(monkeypatch: pytest.MonkeyPatch, pub: Any) -> None: @@ -144,6 +144,56 @@ async def test_verify_id_token_rejects_wrong_signer(_signing_key, monkeypatch) - ) # ...token signed by `other` +@pytest.mark.parametrize( + ("overrides", "accepted"), + [ + ({"nonce": None}, True), # a refresh's ID token may carry no nonce + ({"nonce": None, "aud": "someone-else"}, False), + ({"nonce": None, "iss": "https://other.example"}, False), + ({"nonce": None, "exp": int(time.time()) - 10}, False), + ], +) +async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( + _signing_key, monkeypatch, overrides: dict[str, Any], accepted: bool +) -> None: + priv, pub = _signing_key + _inject(monkeypatch, pub) + token = _id_token(priv, **overrides) + if accepted: + assert (await oidc.verify_refreshed_id_token(token))["email"] == "user@example.com" + else: + with pytest.raises(pyjwt.PyJWTError): + await oidc.verify_refreshed_id_token(token) + + +@pytest.mark.parametrize( + ("group", "listed", "asked"), + [ + ("loom-admins", ["openid", "groups"], True), + ("loom-admins", ["openid"], False), # a provider may refuse a scope it does not list + ("", ["openid", "groups"], False), + ], +) +async def test_the_groups_scope_is_asked_only_for_a_group_the_provider_lists( + monkeypatch, group: str, listed: list[str], asked: bool +) -> None: + from urllib.parse import parse_qs, urlsplit + + async def doc() -> dict[str, Any]: + return {"authorization_endpoint": f"{_ISS}/authorize", "scopes_supported": listed} + + monkeypatch.setattr(oidc, "_discover", doc) + monkeypatch.setattr(settings, "oidc_platform_admin_group", group) + url = await oidc.build_authorize_url( + redirect_uri="https://loom.example/oauth/callback", + state="s", + nonce="n", + code_challenge="c", + offline=False, + ) + assert ("groups" in parse_qs(urlsplit(url).query)["scope"][0].split()) is asked + + # ── email → loom identity mapping ────────────────────────────────────────── async def test_resolve_identity_for_email_maps_rows(monkeypatch) -> None: rows = [ From b5d7eee43f4e3964527d703e5dd54db3a8e9c5c3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:02:16 +0530 Subject: [PATCH 03/23] auth: check the admin group only where the admin list left the role A refresh asks the provider's ID token about the group only when LOOM_PLATFORM_ADMINS did not keep platform_admin, so listed admins never depend on the provider's keys. The docs name every way to the role, the groups scope, each provider's groups claim format and what the previous build does with a group-conferred admin. Tests cover a listed admin, a key outage that answers 503 and keeps the token, a cleared setting, an unverified email and the MCP connect sign-in. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 4 +- docs/operations/deployment.md | 2 +- docs/operations/monitoring.md | 4 +- docs/operations/sso.md | 22 ++++++-- docs/reference/configuration.md | 2 +- loom.example.yaml | 2 +- schemas/loom-settings.schema.json | 2 +- server/auth/oauth.py | 11 ++-- server/auth/oidc.py | 7 +-- server/settings/catalog.py | 4 +- tests/unit/test_oauth.py | 83 +++++++++++++++++++++++++++++++ tests/unit/test_oidc.py | 9 +++- 12 files changed, 126 insertions(+), 26 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 66a5c88d192..d5c889afbf7 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -310,8 +310,8 @@ namespace, and step 8 has none to read) and the token's own role decides. It ask that clones, stores and embeds a repository and can run its build code. A sign-in (password, OIDC, the device grant) and a sign-up (self-signup, agent sign-up) mint `writer`, or `platform_admin` for a name in `LOOM_PLATFORM_ADMINS` or a member of -`LOOM_OIDC_PLATFORM_ADMIN_GROUP`, so any member adds -a repository. A token whose own role is `viewer` does not, and neither does a token +`LOOM_OIDC_PLATFORM_ADMIN_GROUP`, so any signed-in member adds a repository. A token +whose own role is `viewer` does not, and neither does a token scoped to namespaces (step 1). The ops on an existing index (`code.repo.add_branch`, `code.repo.set_access`, `code.repo.set_source`, `code.repo.remove`) ask for `admin` of its namespace. The server cannot tell a coding agent that runs on a member's token from diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 2e25c311e50..e353012184a 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -309,7 +309,7 @@ back. | `LOOM_SELF_SIGNUP_ORG` | `dev` | You want signed-up accounts in your own org. | | `LOOM_DEFAULT_NAMESPACE` | `local` | Renaming the one namespace `single-user` mode serves. Ignored when auth is required. | | `LOOM_JWT_SECRET` | the checked-in development secret | Always, when auth is on. | -| `LOOM_PLATFORM_ADMINS` | empty | Naming the operators. With SSO, `LOOM_OIDC_PLATFORM_ADMIN_GROUP` is the other path to `platform_admin`. | +| `LOOM_PLATFORM_ADMINS` | empty | Naming the operators. With SSO, `LOOM_OIDC_PLATFORM_ADMIN_GROUP` also confers `platform_admin`. | | `LOOM_TRUSTED_CALLERS` | empty | In `gateway` mode, a subject may send `X-Loom-On-Behalf-Of` to act for an end user. | - **`LOOM_JWT_SECRET`** is the root secret: it signs tokens as kid `default` (HS256) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index f5a21576003..eed1f3999f0 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -27,8 +27,8 @@ environment and `.env`. `loom --help` documents every flag, and the [CLI reference](../reference/cli.md) lists them all. Org-wide views (cost across namespaces, `ops.health`) need `ORG_ADMIN` or -`PLATFORM_ADMIN`, which only `LOOM_PLATFORM_ADMINS` and `LOOM_OIDC_PLATFORM_ADMIN_GROUP` grant -([deployment](./deployment.md#required-environment)). The deployment-wide `/v1/admin/*` +`PLATFORM_ADMIN`, which `LOOM_PLATFORM_ADMINS`, `LOOM_OIDC_PLATFORM_ADMIN_GROUP` and a bot +registered `--platform-admin` confer ([deployment](./deployment.md#required-environment)). The deployment-wide `/v1/admin/*` routes need `PLATFORM_ADMIN`; `token.mint`, `namespace.adopt` and `claim_release` need `ORG_ADMIN` in the org they act on. A namespace `admin` reaches none of them. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 0e8a7a14d67..708f1b75af2 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -46,7 +46,8 @@ a platform-admin group is set. ### Scopes and claims Loom asks for `openid email profile`, plus `offline_access` when the -provider's discovery document lists it (Okta's does). It needs: +provider's discovery document lists it (Okta's does), and `groups` when it +lists that and a [platform-admin group](#platform-admins) is set. It needs: - `email` with `email_verified: true` — the account key. A sign-in without a verified email is refused. @@ -917,6 +918,13 @@ one you revoked shows up once that one is revoked. Stop when it lists only tokens made from subjects you minted. While the previous build still serves, a token it lists, revokes or reuses the name of records no lineage. +The previous build confers no role from `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. A +sign-in it starts does not ask for `groups`, so an Okta org authorization +server sends no groups claim and the person signs in as a member, and a +refresh it serves demotes a group-conferred platform admin, who stays a +member until they sign in again. Set the group once every replica runs this +build. + A browser sign-in whose steps land on both builds (a code exchanged, an identity provider's callback) fails and is started again. The SDK and `loom login` ride it out: this build marks its token and device sign-in answers with @@ -958,7 +966,13 @@ The same settings work with any OIDC provider that serves discovery at - **Microsoft Entra ID:** `LOOM_OIDC_ISSUER=https://login.microsoftonline.com//v2.0`. Its ID tokens often carry no `email_verified`, and Loom refuses those. - Use a provider configuration that asserts it. + Use a provider configuration that asserts it. Its `groups` claim lists + group object IDs, so set `LOOM_OIDC_PLATFORM_ADMIN_GROUP` to the group's + object ID, and emit only the groups assigned to the application: a member + of more than 200 groups gets no `groups` claim. - **Google:** `LOOM_OIDC_ISSUER=https://accounts.google.com`. Google issues - no refresh token to Loom, so sessions last an hour. -- **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. + no refresh token to Loom, so sessions last an hour. Its ID tokens carry no + `groups` claim, so no group confers `platform_admin`. +- **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. Its group + membership mapper sends full paths by default (`/loom-platform-admin`): + turn **Full group path** off, or set the group to its path. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 966b64bddcb..a0539c7c38d 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 names nobody here; `oidc_platform_admin_group` is the other way to the role. | +| `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 names nobody here; `oidc_platform_admin_group` also confers the role. | | `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 89ff7d5d380..e3194093d14 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -671,7 +671,7 @@ settings: # 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 names - # nobody here; `oidc_platform_admin_group` is the other way to the role. [restart] + # nobody here; `oidc_platform_admin_group` also confers the role. [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 74e6914f5b6..2794a7904fc 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6470,7 +6470,7 @@ "platform_admins": { "default": "", "type": "string", - "description": "Comma-separated login handles and emails promoted to platform_admin (org-wide visibility). A handle matches a password account's subject; an email matches only an IdP-verified (OIDC) email, never the unverified self-signup address. Empty names nobody here; `oidc_platform_admin_group` is the other way to the role." + "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 names nobody here; `oidc_platform_admin_group` also confers the role." }, "policy_cache_ttl_seconds": { "default": 30, diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 6bae19a9917..13bd90881a2 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -675,8 +675,6 @@ async def _exchange_at_idp( refuses raises _StartAgain and counts against `address`; a fault on its side (its outage, a rejected client secret) answers 502 and counts not. Its keys away once the code is spent raise _Spent: a reload cannot finish.""" - import jwt - from server.auth import oidc try: @@ -1530,11 +1528,9 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: grant["subject"], org=grant["org"], verified_email=grant.get("verified_email", "") ): raise _invalid_grant("this person cannot sign in under the cell's provisioning policy") - in_admin_group = False + id_token = "" if settings.oauth_login_provider == "oidc": - refreshed = await _ask_identity_provider(grant, refresh_token) - grant["upstream_refresh"] = refreshed.refresh_token - in_admin_group = await _still_in_admin_group(grant, refreshed.id_token) + grant["upstream_refresh"], id_token = await _ask_identity_provider(grant, refresh_token) elif grant["upstream_refresh"]: # Signed in through SSO, now off: nothing vouches for the user any more. raise _invalid_grant("single sign-on is off here; sign in again") @@ -1545,7 +1541,8 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: if roles is None: await end_session(grant, "account no longer active") raise _invalid_grant() - if in_admin_group: # asked only of a platform admin's session: it never promotes + # Asked only when LOOM_PLATFORM_ADMINS did not keep the role, of a session that held it. + if roles != ["platform_admin"] and await _still_in_admin_group(grant, id_token): roles = ["platform_admin"] return await issue_tokens( {**grant, "roles": roles}, diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 30053aa62e7..9639577d638 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -89,9 +89,10 @@ async def _discover() -> dict[str, Any]: return doc -# The whole IdP leg of a Loom refresh (discovery and the token call): the -# SDK waits longer than this for a refresh, so it never gives up on one the -# server is still answering. +# The whole IdP leg of a Loom refresh (discovery and the token call; the key +# fetch a platform-admin group check needs comes after, under the refresh's own +# deadline): the SDK waits longer than this for a refresh, so it never gives up +# on one the server is still answering. _REFRESH_DEADLINE_S = 20 diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 077d1330333..93e5f1b6743 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -153,8 +153,8 @@ class AuthSettings(BaseModel): # 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 names nobody here; `oidc_platform_admin_group` is the other - # way to the role. + # self-signup address. Empty names nobody here; `oidc_platform_admin_group` also confers + # the role. platform_admins: str = "" @property diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 9fb812b7a5d..b43043f977c 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -475,6 +475,69 @@ async def still(grant: dict[str, Any], id_token: str) -> bool: assert [r.name for r in verify_token(tok["access_token"]).roles] == want +def test_a_listed_platform_admin_refreshes_without_the_group_check( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # LOOM_PLATFORM_ADMINS keeps the role, so the provider's keys are never needed. + from server.auth import oidc + from server.auth.jwt import verify_token + from server.settings import settings + + async def listed(subject: str, org: str, roles: list[str]) -> list[str]: + return ["platform_admin"] + + async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: + return oidc.Refreshed("idp-next", "idp-id-token") + + async def never(grant: dict[str, Any], id_token: str) -> bool: + raise AssertionError("a listed platform admin needs no group check") + + c = _client() + rt = _refresh_token(c, roles=["platform_admin"]) + monkeypatch.setattr(settings, "oauth_login_provider", "oidc") + monkeypatch.setattr(login, "refreshed_roles", listed) + monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) + monkeypatch.setattr(oauth, "_still_in_admin_group", never) + tok = _refresh(c, rt).json() + assert [r.name for r in verify_token(tok["access_token"]).roles] == ["PLATFORM_ADMIN"] + + +def test_a_key_outage_at_the_group_check_answers_503_and_keeps_the_token( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.auth import oidc + from server.auth.jwt import verify_token + from server.settings import settings + + sent: list[str] = [] + keys_away = [False, True] # popped from the end: away once, then back + + async def demoted(subject: str, org: str, roles: list[str]) -> list[str]: + return ["writer"] + + async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: + sent.append(grant["upstream_refresh"]) + return oidc.Refreshed(f"idp-{len(sent)}", "idp-id-token") + + async def still(grant: dict[str, Any], id_token: str) -> bool: + if keys_away.pop(): + raise jwt.PyJWKClientConnectionError("keys") + return True + + c = _client() + rt = _refresh_token(c, roles=["platform_admin"]) + monkeypatch.setattr(settings, "oauth_login_provider", "oidc") + monkeypatch.setattr(login, "refreshed_roles", demoted) + monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) + monkeypatch.setattr(oauth, "_still_in_admin_group", still) + assert _refresh(c, rt).status_code == 503 + again = _refresh(c, rt) # the same token works again + assert again.status_code == 200, again.text + assert sent[1] == "idp-1" # with the IdP token the first refresh rotated + roles = verify_token(again.json()["access_token"]).roles + assert [r.name for r in roles] == ["PLATFORM_ADMIN"] + + def _admin_grant(roles: list[str], email: str = "ada@example.com") -> dict[str, Any]: return {"roles": roles, "verified_email": email} @@ -489,6 +552,12 @@ def _admin_grant(roles: list[str], email: str = "ada@example.com") -> dict[str, (_admin_grant(["platform_admin"]), "", {"groups": ["admins"]}, False), # none sent (_admin_grant(["platform_admin"], ""), "t", {"groups": ["admins"], "email": ""}, False), (_admin_grant(["platform_admin"]), "t", None, False), # it fails verification + ( + _admin_grant(["platform_admin"]), + "t", + {"groups": ["admins"], "email_verified": False}, + False, + ), ], ) async def test_still_in_admin_group_fails_closed( @@ -511,6 +580,20 @@ async def verify(token: str) -> dict[str, Any]: assert await oauth._still_in_admin_group(grant, id_token) is want # type: ignore[arg-type] +async def test_a_cleared_group_ends_the_role_at_the_next_refresh( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.auth import oidc + from server.settings import settings + + async def verify(token: str) -> dict[str, Any]: + return {"email": "ada@example.com", "email_verified": True, "groups": ["admins"]} + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "") + monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + + @pytest.mark.parametrize( "away", [jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider")] ) diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 435e1c8034d..541cc67192f 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -736,6 +736,7 @@ class _Req: ) +@pytest.mark.parametrize("kind", ["dashboard", "mcp"]) @pytest.mark.parametrize( ("groups", "carried", "want"), [ @@ -747,14 +748,14 @@ class _Req: ], ) async def test_the_platform_admin_group_signs_its_members_in_as_platform_admin( - monkeypatch, groups: Any, carried: bool, want: list[str] + monkeypatch, groups: Any, carried: bool, want: list[str], kind: str ) -> None: from unittest.mock import AsyncMock from fastapi import Response monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") - pending = {"kind": "dashboard", "nonce": "n", "code_verifier": "v", "state": "s"} + pending = {"kind": kind, "nonce": "n", "code_verifier": "v", "state": "s"} if carried: pending["platform_admin_group"] = True # type: ignore[assignment] signed_in: dict[str, Any] = {} @@ -772,6 +773,9 @@ async def dashboard(identity: login.Identity, *_a: Any, **_k: Any) -> Response: signed_in["roles"] = identity[3] return Response(status_code=302) + async def connect(_p: Any, identity: login.Identity, *_a: Any, **_k: Any) -> Response: + return await dashboard(identity) # the identity the consent page stores for the code + class _Req: client = None query_params = {"code": "c", "state": "s"} @@ -782,6 +786,7 @@ class _Req: monkeypatch.setattr(oidc, "verify_id_token", claims) monkeypatch.setattr(oauth, "_account_for", account) monkeypatch.setattr(oauth, "_dashboard_signed_in", dashboard) + monkeypatch.setattr(oauth, "_connect_consent", connect) monkeypatch.setattr(oauth.scim, "refuses_subject", AsyncMock(return_value=False)) monkeypatch.setattr(oauth.sso_links, "attest_domain", AsyncMock()) assert (await oauth.oidc_callback(_Req())).status_code == 302 # type: ignore[arg-type] From 9b9eee93865faf438c8c734bd148aa4dc5563546 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:23:49 +0530 Subject: [PATCH 04/23] auth: tolerate clock skew on the provider's ID tokens A refreshed ID token is checked moments after the provider mints it, so a provider clock a few seconds ahead of Loom's made its iat look future and silently ended a group-conferred platform_admin. ID tokens now get the same LOOM_JWT_LEEWAY_SECONDS tolerance as Loom's own tokens. The docs say an unreachable provider keeps the role through a retried refresh, and that leaving the group does not disable the platform-admin bots a person registered. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 2 ++ docs/operations/sso.md | 9 ++++++--- docs/reference/configuration.md | 2 +- loom.example.yaml | 4 ++-- schemas/loom-settings.schema.json | 2 +- server/auth/oidc.py | 1 + server/settings/catalog.py | 4 ++-- tests/unit/test_oidc.py | 5 +++-- 8 files changed, 18 insertions(+), 11 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index d5c889afbf7..fe5ac44d1c9 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -253,6 +253,8 @@ Each op declares `required_role`. conferred only while the ID token the provider issues with it verifies, names the same email and still lists the group (`_still_in_admin_group` in `server/auth/oauth.py`); that ID token carries no nonce check, since it answers Loom's own back-channel token request. + While the provider's keys or discovery cannot be reached the refresh answers 503 and puts + its token back, so an outage ends no role. A bot registered `--platform-admin` gets it in every machine token, as a flat token over every namespace (`_machine_tokens` in `server/auth/oauth.py`); such a bot names no namespace, tells no agents apart and, as a trust, matches every claim exactly. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 708f1b75af2..1247173769a 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -163,9 +163,12 @@ custom authorization server, define the groups claim on that server and include it in the ID token. Each refresh, at most an hour apart, reads the ID token the provider issues with it: the role lasts while those ID tokens list the group. A refresh that brings no ID token Loom can verify for the same -email refreshes without the role. A refresh never adds the role: a person -added to the group signs in again to get it. The provider grants nothing else: -namespace roles come from Loom's own grants. +email refreshes without the role; while the provider's keys or discovery +cannot be reached, the refresh answers 503 and is retried with the role kept. +A refresh never adds the role: a person added to the group signs in again to +get it. The provider grants nothing else: namespace roles come from Loom's own +grants. Taking someone out of the group leaves the `--platform-admin` bots +they registered working: disable those with `loom bot disable`. ## Bots and CI diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index a0539c7c38d..8fe2397b4a2 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -126,7 +126,7 @@ Authentication, tokens and identity providers. | `LOOM_JWT_AUDIENCE` | `str` | `'loom-platform'` | | The `aud` claim stamped on minted tokens and required on every verified token. | | `LOOM_JWT_TRUSTED_ISSUERS` | `str` | `''` | | Extra accepted `iss` values, for a gateway minting Loom-shaped JWTs with a key in `jwt_public_keys_json`. Loom's own tokens (iss = jwt_issuer) pass. | | `LOOM_JWT_PUBLIC_KEYS_JSON` | `str` | *(unset)* | | JSON (or base64 JSON) map kid → PEM public key of a gateway whose RS256 tokens this deployment accepts (a non-loopback bind refuses an RSA key under 2048 bits). Loom's own keys live in loom.signing_keys. | -| `LOOM_JWT_LEEWAY_SECONDS` | `int` | `30` | | Clock-skew tolerance on iat/exp, seconds; small enough to give replay no useful post-exp window. | +| `LOOM_JWT_LEEWAY_SECONDS` | `int` | `30` | | Clock-skew tolerance on iat/exp of Loom's tokens and the identity provider's ID tokens, seconds; small enough to give replay no useful post-exp window. | | `LOOM_JWT_REVOCATION_CACHE_TTL_SECONDS` | `float` | `30.0` | | Seconds the `loom.revoked_tokens` snapshot is cached; verify checks both jti and sub against it, so a revocation takes effect on other processes within this TTL (at once on the one that wrote it). | | `LOOM_JWT_REVOCATION_MAX_STALE_SECONDS` | `float` | `600.0` | | Oldest revocation snapshot a process still trusts, seconds. Past it (refreshes keep failing) every bearer is refused with a retryable 503. A subject's cached grants are trusted as long when a re-read fails. | | `LOOM_GRANT_CACHE_TTL_SECONDS` | `float` | `10.0` | | Seconds a subject's grant rows are cached for the namespace gate, which caps a token's claim at the grant it holds there. The backstop: a grant change reaches other processes through the per-org grant watermark (acl_watermark_poll_seconds), and this bounds one whose watermark row was never written. SCIM and bot final decisions use this TTL from read start. A complete enforced-cell SCIM check has a separate 30-second ceiling, so its cross-process observation bound is the larger of this TTL and that check's budget; a smaller positive read timeout reduces the latter. | diff --git a/loom.example.yaml b/loom.example.yaml index e3194093d14..ad66eec1360 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -830,8 +830,8 @@ settings: # `jwt_public_keys_json`. Loom's own tokens (iss = jwt_issuer) pass. [restart] # jwt_trusted_issuers: "" - # Clock-skew tolerance on iat/exp, seconds; small enough to give replay no useful - # post-exp window. [restart] + # Clock-skew tolerance on iat/exp of Loom's tokens and the identity provider's ID + # tokens, seconds; small enough to give replay no useful post-exp window. [restart] # jwt_leeway_seconds: 30 # Seconds the `loom.revoked_tokens` snapshot is cached; verify checks both jti and sub diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 2794a7904fc..a5c99d249c2 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -3328,7 +3328,7 @@ "jwt_leeway_seconds": { "default": 30, "type": "integer", - "description": "Clock-skew tolerance on iat/exp, seconds; small enough to give replay no useful post-exp window." + "description": "Clock-skew tolerance on iat/exp of Loom's tokens and the identity provider's ID tokens, seconds; small enough to give replay no useful post-exp window." }, "jwt_revocation_cache_ttl_seconds": { "default": 30.0, diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 9639577d638..79ec77af5ec 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -292,6 +292,7 @@ async def _verified_claims(id_token: str) -> dict[str, Any]: algorithms=algorithms, audience=settings.oidc_client_id, issuer=doc["issuer"], + leeway=settings.jwt_leeway_seconds, # the provider's clock may run ahead of Loom's options={"require": ["exp", "iat", "aud", "iss"]}, ) return claims diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 93e5f1b6743..890312e20ba 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -414,8 +414,8 @@ def trusted_issuers(self) -> set[str]: # tokens this deployment accepts (a non-loopback bind refuses an RSA key under 2048 # bits). Loom's own keys live in loom.signing_keys. jwt_public_keys_json: str = "" - # Clock-skew tolerance on iat/exp, seconds; small enough to give replay no - # useful post-exp window. + # Clock-skew tolerance on iat/exp of Loom's tokens and the identity provider's ID + # tokens, seconds; small enough to give replay no useful post-exp window. jwt_leeway_seconds: int = 30 # Seconds the `loom.revoked_tokens` snapshot is cached; verify checks both diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 541cc67192f..219a679b73a 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -128,7 +128,7 @@ async def test_verify_id_token_rejects_wrong_audience(_signing_key, monkeypatch) async def test_verify_id_token_rejects_expired(_signing_key, monkeypatch) -> None: priv, pub = _signing_key _inject(monkeypatch, pub) - stale = _id_token(priv, exp=int(time.time()) - 10) + stale = _id_token(priv, exp=int(time.time()) - settings.jwt_leeway_seconds - 10) with pytest.raises(_VERIFY_ERRORS): await oidc.verify_id_token(stale, nonce="the-nonce") @@ -150,7 +150,8 @@ async def test_verify_id_token_rejects_wrong_signer(_signing_key, monkeypatch) - ({"nonce": None}, True), # a refresh's ID token may carry no nonce ({"nonce": None, "aud": "someone-else"}, False), ({"nonce": None, "iss": "https://other.example"}, False), - ({"nonce": None, "exp": int(time.time()) - 10}, False), + ({"nonce": None, "exp": int(time.time()) - 60}, False), # past the 30 s leeway + ({"nonce": None, "iat": int(time.time()) + 10}, True), # the provider's clock ahead ], ) async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( From 2cafd9923e99563c399fd6c404b92a83ba1b29f6 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:41:51 +0530 Subject: [PATCH 05/23] auth: keep the admin role through any transport error at the key fetch PyJWT wraps only some transport errors in PyJWKClientConnectionError, so a connection reset or TLS error while reading the provider's keys ended a group-conferred platform_admin; any OSError now retries the refresh. The clock-skew test takes its times when it runs, not at collection, and pins the leeway at both edges. A test checks that oidc.refresh returns the provider's ID token. The docs say how to create the groups claim in Entra and Keycloak, that Okta's filter matches names from every source, and name every way to platform_admin. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 2 +- docs/operations/monitoring.md | 5 +++-- docs/operations/sso.md | 21 +++++++++++++-------- server/auth/oauth.py | 6 ++++-- tests/unit/test_oauth.py | 7 ++++++- tests/unit/test_oidc.py | 25 +++++++++++++++++-------- tests/unit/test_oidc_backchannel.py | 6 ++++-- 7 files changed, 48 insertions(+), 24 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index fe5ac44d1c9..e24596dbf05 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -252,7 +252,7 @@ Each op declares `required_role`. group at the provider decides who administers the platform. A refresh keeps a role so conferred only while the ID token the provider issues with it verifies, names the same email and still lists the group (`_still_in_admin_group` in `server/auth/oauth.py`); that - ID token carries no nonce check, since it answers Loom's own back-channel token request. + ID token is checked without a nonce, since it answers Loom's own back-channel token request. While the provider's keys or discovery cannot be reached the refresh answers 503 and puts its token back, so an outage ends no role. A bot registered `--platform-admin` gets it in every machine token, as a flat token over diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index eed1f3999f0..45aa7f74b5c 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -27,8 +27,9 @@ environment and `.env`. `loom --help` documents every flag, and the [CLI reference](../reference/cli.md) lists them all. Org-wide views (cost across namespaces, `ops.health`) need `ORG_ADMIN` or -`PLATFORM_ADMIN`, which `LOOM_PLATFORM_ADMINS`, `LOOM_OIDC_PLATFORM_ADMIN_GROUP` and a bot -registered `--platform-admin` confer ([deployment](./deployment.md#required-environment)). The deployment-wide `/v1/admin/*` +`PLATFORM_ADMIN`, which `LOOM_PLATFORM_ADMINS`, `LOOM_OIDC_PLATFORM_ADMIN_GROUP`, a bot +registered `--platform-admin` and `loom mint-token --platform-admin` confer +([roles](../concepts/identities-and-namespaces.md#roles)). The deployment-wide `/v1/admin/*` routes need `PLATFORM_ADMIN`; `token.mint`, `namespace.adopt` and `claim_release` need `ORG_ADMIN` in the org they act on. A namespace `admin` reaches none of them. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 1247173769a..072289a8b40 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -28,7 +28,9 @@ with their Loom password and approves. Nothing here needs configuring. See 5. Optionally, a platform-admin group: assign it to the app too, and under **Sign On → OpenID Connect ID Token** set the groups claim to type **Filter**, name `groups`, matching only that group. Its members sign in as - platform admins ([below](#platform-admins)). + platform admins ([below](#platform-admins)). The filter matches group names + from every source, imported directories included, so pick a name no + connected directory can create. 6. Copy the client ID and secret, then set: ```bash @@ -969,13 +971,16 @@ The same settings work with any OIDC provider that serves discovery at - **Microsoft Entra ID:** `LOOM_OIDC_ISSUER=https://login.microsoftonline.com//v2.0`. Its ID tokens often carry no `email_verified`, and Loom refuses those. - Use a provider configuration that asserts it. Its `groups` claim lists - group object IDs, so set `LOOM_OIDC_PLATFORM_ADMIN_GROUP` to the group's - object ID, and emit only the groups assigned to the application: a member - of more than 200 groups gets no `groups` claim. + Use a provider configuration that asserts it. For a platform-admin group, + add a groups claim to the ID token (**Token configuration → Add groups + claim**) with **Groups assigned to the application**, since a member of more + than 200 groups otherwise gets no `groups` claim. It lists group object + IDs: set `LOOM_OIDC_PLATFORM_ADMIN_GROUP` to the group's object ID. - **Google:** `LOOM_OIDC_ISSUER=https://accounts.google.com`. Google issues no refresh token to Loom, so sessions last an hour. Its ID tokens carry no `groups` claim, so no group confers `platform_admin`. -- **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. Its group - membership mapper sends full paths by default (`/loom-platform-admin`): - turn **Full group path** off, or set the group to its path. +- **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. For a + platform-admin group, add a **Group Membership** mapper to the client with + claim name `groups` and **Add to ID token** on. It sends full paths by + default (`/loom-platform-admin`): turn **Full group path** off, or set the + group to its path. diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 13bd90881a2..c2fde2cb1f4 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1565,8 +1565,10 @@ async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: return False try: id_claims = await oidc.verify_refreshed_id_token(id_token) - except (jwt.PyJWKClientConnectionError, httpx.HTTPError): - raise # the provider's keys are away: the refresh is retried with its token put back + except (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError): + # The provider's keys or discovery are away (PyJWT wraps only some transport errors): + # the refresh is retried with its token put back. + raise except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) return False diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index b43043f977c..3904d9e8516 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -595,7 +595,12 @@ async def verify(token: str) -> dict[str, Any]: @pytest.mark.parametrize( - "away", [jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider")] + "away", + [ + jwt.PyJWKClientConnectionError("keys"), + httpx.ConnectError("provider"), + ConnectionResetError("reading the keys"), + ], ) async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( monkeypatch: pytest.MonkeyPatch, away: Exception diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 219a679b73a..621f23a1e79 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -145,21 +145,30 @@ async def test_verify_id_token_rejects_wrong_signer(_signing_key, monkeypatch) - @pytest.mark.parametrize( - ("overrides", "accepted"), + ("overrides", "when", "accepted"), [ - ({"nonce": None}, True), # a refresh's ID token may carry no nonce - ({"nonce": None, "aud": "someone-else"}, False), - ({"nonce": None, "iss": "https://other.example"}, False), - ({"nonce": None, "exp": int(time.time()) - 60}, False), # past the 30 s leeway - ({"nonce": None, "iat": int(time.time()) + 10}, True), # the provider's clock ahead + ({}, "now", True), # a refresh's ID token may carry no nonce + ({"aud": "someone-else"}, "now", False), + ({"iss": "https://other.example"}, "now", False), + ({}, "expired", False), # past the leeway + ({}, "ahead", True), # the provider's clock a little ahead of Loom's + ({}, "too_far_ahead", False), ], ) async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( - _signing_key, monkeypatch, overrides: dict[str, Any], accepted: bool + _signing_key, monkeypatch, overrides: dict[str, Any], when: str, accepted: bool ) -> None: priv, pub = _signing_key _inject(monkeypatch, pub) - token = _id_token(priv, **overrides) + leeway = settings.jwt_leeway_seconds + iat, exp = { # seconds from now, taken when the test runs rather than at collection + "now": (0, 300), + "expired": (-600, -leeway - 10), + "ahead": (10, 300), + "too_far_ahead": (leeway + 10, 300), + }[when] + now = int(time.time()) + token = _id_token(priv, nonce=None, iat=now + iat, exp=now + exp, **overrides) if accepted: assert (await oidc.verify_refreshed_id_token(token))["email"] == "user@example.com" else: diff --git a/tests/unit/test_oidc_backchannel.py b/tests/unit/test_oidc_backchannel.py index 97bf7bbc00c..34662907e99 100644 --- a/tests/unit/test_oidc_backchannel.py +++ b/tests/unit/test_oidc_backchannel.py @@ -131,10 +131,12 @@ async def test_the_token_and_revocation_calls_go_to_the_base(monkeypatch) -> Non def respond(request: httpx.Request) -> httpx.Response: if request.url.path.endswith("openid-configuration"): return httpx.Response(200, json=_doc()) - return httpx.Response(200, json={"access_token": "a", "token_type": "Bearer"}) + return httpx.Response( + 200, json={"access_token": "a", "token_type": "Bearer", "id_token": "idp-id"} + ) seen = _serve(monkeypatch, respond) - assert (await oidc.refresh("idp-refresh")).refresh_token == "idp-refresh" + assert await oidc.refresh("idp-refresh") == oidc.Refreshed("idp-refresh", "idp-id") await oidc.revoke("idp-refresh") calls = [(str(r.url), r.headers["host"]) for r in seen[1:]] assert calls == [ From 4b883d8efaeadffdb2233f7f656aa52cd1a0faa0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:59:09 +0530 Subject: [PATCH 06/23] auth: a key rotated in retries the refresh rather than ending the role PyJWT fetches the provider's keys again only after a cooldown, so a refreshed ID token signed with a key rotated in moments before raised PyJWKClientError and silently ended a group-conferred platform_admin. Every PyJWKClientError now answers 503 with the token put back, and the retry finds the key. The docs give the refresh interval as the access token lifetime it is, and two paragraphs are rewrapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 9 ++++--- docs/concepts/identities-and-namespaces.md | 4 +-- docs/operations/sso.md | 31 ++++++++++++---------- server/auth/oauth.py | 7 ++--- tests/unit/test_oauth.py | 1 + 5 files changed, 29 insertions(+), 23 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index e24596dbf05..0ff18be3beb 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -253,8 +253,9 @@ Each op declares `required_role`. conferred only while the ID token the provider issues with it verifies, names the same email and still lists the group (`_still_in_admin_group` in `server/auth/oauth.py`); that ID token is checked without a nonce, since it answers Loom's own back-channel token request. - While the provider's keys or discovery cannot be reached the refresh answers 503 and puts - its token back, so an outage ends no role. + While discovery or the provider's keys cannot be fetched, or the token names a key + rotated in since the last fetch, the refresh answers 503 and puts its token back, so + neither an outage nor a key rotation ends the role. A bot registered `--platform-admin` gets it in every machine token, as a flat token over every namespace (`_machine_tokens` in `server/auth/oauth.py`); such a bot names no namespace, tells no agents apart and, as a trust, matches every claim exactly. @@ -313,8 +314,8 @@ that clones, stores and embeds a repository and can run its build code. A sign-i (password, OIDC, the device grant) and a sign-up (self-signup, agent sign-up) mint `writer`, or `platform_admin` for a name in `LOOM_PLATFORM_ADMINS` or a member of `LOOM_OIDC_PLATFORM_ADMIN_GROUP`, so any signed-in member adds a repository. A token -whose own role is `viewer` does not, and neither does a token -scoped to namespaces (step 1). The ops on an existing index (`code.repo.add_branch`, +whose own role is `viewer` does not, and neither does a token scoped to namespaces +(step 1). The ops on an existing index (`code.repo.add_branch`, `code.repo.set_access`, `code.repo.set_source`, `code.repo.remove`) ask for `admin` of its namespace. The server cannot tell a coding agent that runs on a member's token from the member, so the role keeps an agent from adding a repository only where the agent diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 47dc3ae2ceb..cbe330d93fd 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -148,8 +148,8 @@ operation declares the minimum role it needs (`GET /v1/operations` lists it). 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, in the identity provider's platform-admin group or at bot registration, not something a token can -carry away. Code namespaces have readers -(`viewer`) and maintainers (`admin`) and no `writer`. +carry away. Code namespaces have readers (`viewer`) and maintainers (`admin`) and no +`writer`. ## Who may call what diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 072289a8b40..d8960733a49 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -53,11 +53,12 @@ lists that and a [platform-admin group](#platform-admins) is set. It needs: - `email` with `email_verified: true` — the account key. A sign-in without a verified email is refused. -- An Okta refresh token (from `offline_access`). Every Loom refresh, at most an - hour apart, spends it at Okta first. A user deactivated in Okta, or signed - out with **End all sessions**, therefore loses Loom at their next refresh. - A provider that issues no refresh token gets no Loom refresh token either: - its sessions end when the hour-long access token does. +- An Okta refresh token (from `offline_access`). Every Loom refresh, at most + one access-token lifetime apart (`LOOM_OAUTH_ACCESS_TOKEN_TTL_SECONDS`, an + hour by default), spends it at Okta first. A user deactivated in Okta, or + signed out with **End all sessions**, therefore loses Loom at their next + refresh. A provider that issues no refresh token gets no Loom refresh token + either: its sessions end when the access token does. One group claim can be read: the `groups` entry `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names ([platform admins](#platform-admins)). Namespace access comes from @@ -162,15 +163,17 @@ LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin With the group set, sign-in asks for the `groups` scope where the provider's discovery document lists it (Okta's org authorization server needs it). With a custom authorization server, define the groups claim on that server and -include it in the ID token. Each refresh, at most an hour apart, reads the ID -token the provider issues with it: the role lasts while those ID tokens list -the group. A refresh that brings no ID token Loom can verify for the same -email refreshes without the role; while the provider's keys or discovery -cannot be reached, the refresh answers 503 and is retried with the role kept. -A refresh never adds the role: a person added to the group signs in again to -get it. The provider grants nothing else: namespace roles come from Loom's own -grants. Taking someone out of the group leaves the `--platform-admin` bots -they registered working: disable those with `loom bot disable`. +include it in the ID token. Each refresh, at most one access-token lifetime +apart (`LOOM_OAUTH_ACCESS_TOKEN_TTL_SECONDS`, an hour by default), reads the +ID token the provider issues with it: the role lasts while those ID tokens +list the group. A refresh that brings no ID token Loom can verify for the same +email refreshes without the role; while discovery or the provider's keys +cannot be fetched, or the token names a key rotated in since the last fetch, +the refresh answers 503 and is retried with the role kept. A refresh never +adds the role: a person added to the group signs in again to get it. The +provider grants nothing else: namespace roles come from Loom's own grants. +Taking someone out of the group leaves the `--platform-admin` bots they +registered working: disable those with `loom bot disable`. ## Bots and CI diff --git a/server/auth/oauth.py b/server/auth/oauth.py index c2fde2cb1f4..1c21cb6410f 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1565,9 +1565,10 @@ async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: return False try: id_claims = await oidc.verify_refreshed_id_token(id_token) - except (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError): - # The provider's keys or discovery are away (PyJWT wraps only some transport errors): - # the refresh is retried with its token put back. + except (jwt.PyJWKClientError, httpx.HTTPError, OSError): + # Discovery or the provider's keys are away (PyJWT wraps only some transport errors), + # or the token names a key rotated in since the last fetch, which PyJWT fetches again + # only after a cooldown: the refresh is retried with its token put back. raise except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 3904d9e8516..93d845b24d4 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -600,6 +600,7 @@ async def verify(token: str) -> dict[str, Any]: jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider"), ConnectionResetError("reading the keys"), + jwt.PyJWKClientError('Unable to find a signing key that matches: "rotated-in"'), ], ) async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( From 2b7cde4552ca9e2ad364f04375eb5b618c070ebc Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:26:30 +0530 Subject: [PATCH 07/23] auth: fetch a sign-in key rotated in at once, retry only outages PyJWT 2.14 waits 30 s before fetching keys again for an unknown key id, so a key the provider rotated in moments before refused a sign-in and stalled a platform admin's refresh. Sign-in's ID tokens come from Loom's own token request, so no caller picks their key id: that key client now refetches at once. A bot trust's client keeps the cooldown. Sign-in and the refresh's group check now retry the same outages (oidc.KEYS_AWAY), and any token that fails a check ends the role. The PyJWT floor moves to 2.14, where the cooldown and its argument appeared. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 6 ++-- docs/operations/sso.md | 18 +++++------ pyproject.toml | 2 +- server/auth/oauth.py | 12 +++----- server/auth/oidc.py | 14 +++++++-- tests/unit/test_call_site_knobs.py | 2 +- tests/unit/test_oauth.py | 25 ++++++++++++++- tests/unit/test_oidc.py | 47 +++++++++++++++++++++++++++-- tests/unit/test_oidc_backchannel.py | 12 +++++--- tests/unit/test_oidc_hardening.py | 2 +- uv.lock | 2 +- 11 files changed, 108 insertions(+), 34 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 0ff18be3beb..180a1b40403 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -253,9 +253,9 @@ Each op declares `required_role`. conferred only while the ID token the provider issues with it verifies, names the same email and still lists the group (`_still_in_admin_group` in `server/auth/oauth.py`); that ID token is checked without a nonce, since it answers Loom's own back-channel token request. - While discovery or the provider's keys cannot be fetched, or the token names a key - rotated in since the last fetch, the refresh answers 503 and puts its token back, so - neither an outage nor a key rotation ends the role. + While discovery or the provider's keys cannot be fetched the refresh answers 503 and puts + its token back, so an outage ends no role; a key the cache lacks is fetched at once + (`oidc.signing_key`), so a key rotation ends none either. A bot registered `--platform-admin` gets it in every machine token, as a flat token over every namespace (`_machine_tokens` in `server/auth/oauth.py`); such a bot names no namespace, tells no agents apart and, as a trust, matches every claim exactly. diff --git a/docs/operations/sso.md b/docs/operations/sso.md index d8960733a49..1865ac29ed2 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -168,12 +168,11 @@ apart (`LOOM_OAUTH_ACCESS_TOKEN_TTL_SECONDS`, an hour by default), reads the ID token the provider issues with it: the role lasts while those ID tokens list the group. A refresh that brings no ID token Loom can verify for the same email refreshes without the role; while discovery or the provider's keys -cannot be fetched, or the token names a key rotated in since the last fetch, -the refresh answers 503 and is retried with the role kept. A refresh never -adds the role: a person added to the group signs in again to get it. The -provider grants nothing else: namespace roles come from Loom's own grants. -Taking someone out of the group leaves the `--platform-admin` bots they -registered working: disable those with `loom bot disable`. +cannot be fetched, the refresh answers 503 and is retried with the role kept. +A refresh never adds the role: a person added to the group signs in again to +get it. The provider grants nothing else: namespace roles come from Loom's own +grants. Taking someone out of the group leaves the `--platform-admin` bots +they registered working: disable those with `loom bot disable`. ## Bots and CI @@ -979,9 +978,10 @@ The same settings work with any OIDC provider that serves discovery at claim**) with **Groups assigned to the application**, since a member of more than 200 groups otherwise gets no `groups` claim. It lists group object IDs: set `LOOM_OIDC_PLATFORM_ADMIN_GROUP` to the group's object ID. -- **Google:** `LOOM_OIDC_ISSUER=https://accounts.google.com`. Google issues - no refresh token to Loom, so sessions last an hour. Its ID tokens carry no - `groups` claim, so no group confers `platform_admin`. +- **Google:** `LOOM_OIDC_ISSUER=https://accounts.google.com`. Google issues no + refresh token to Loom, so a session lasts one access token + (`LOOM_OAUTH_ACCESS_TOKEN_TTL_SECONDS`, an hour by default). Its ID tokens + carry no `groups` claim, so no group confers `platform_admin`. - **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. For a platform-admin group, add a **Group Membership** mapper to the client with claim name `groups` and **Add to ID token** on. It sends full paths by diff --git a/pyproject.toml b/pyproject.toml index 08f4b9dd1fe..f61f0696c02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ dependencies = [ "jsonschema>=4.20", "referencing>=0.37.0", "tenacity>=9.0", - "pyjwt[crypto]>=2.10", + "pyjwt[crypto]>=2.14", # Application Default Credentials for the native Vertex AI client. "google-auth[requests]>=2.40,<3", # OpenTelemetry: ship spans + logs to HyperDX / ClickStack's OTLP diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 1c21cb6410f..67061b02b4e 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -5,7 +5,7 @@ sign-in; `connect_router` adds MCP one-click connect when `LOOM_OAUTH_ENABLED=true`. Loom issues its own JWTs; under `LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP authenticates the person (oidc.py), and -one group of it may confer platform_admin (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`). State +members of one of its groups (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`) sign in as platform_admin. State lives in oauth_store.py. The flows, sessions and threat model are in docs/architecture/security.md ("OIDC and OAuth"). """ @@ -27,7 +27,6 @@ from urllib.parse import parse_qs, urlencode, urlsplit import httpx -import jwt from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response @@ -704,7 +703,7 @@ async def _exchange_at_idp( raise OAuthError("oidc_error") from e try: id_claims = await oidc.verify_id_token(tokens.get("id_token", ""), nonce=pending["nonce"]) - except jwt.PyJWKClientConnectionError as e: + except oidc.KEYS_AWAY as e: log.warning("oidc callback: the identity provider's keys are away: %s", e) await oidc.revoke(str(tokens.get("refresh_token") or "")) raise _Spent from e @@ -1565,11 +1564,8 @@ async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: return False try: id_claims = await oidc.verify_refreshed_id_token(id_token) - except (jwt.PyJWKClientError, httpx.HTTPError, OSError): - # Discovery or the provider's keys are away (PyJWT wraps only some transport errors), - # or the token names a key rotated in since the last fetch, which PyJWT fetches again - # only after a cooldown: the refresh is retried with its token put back. - raise + except oidc.KEYS_AWAY: + raise # the refresh is retried with its token put back except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) return False diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 79ec77af5ec..b0d513a3f36 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -240,13 +240,23 @@ async def check_callback_issuer(iss: str) -> bool: return iss.rstrip("/") == str(doc["issuer"]).rstrip("/") +# What verifying an ID token raises when discovery or the provider's keys cannot be fetched, +# rather than a token that fails: PyJWT wraps only some transport errors. +KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError) + + def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: - """Cache rotating keys per endpoint; only sign-in uses the back channel.""" + """Cache rotating keys per endpoint; only sign-in uses the back channel. Sign-in's ID + tokens come from Loom's own token request, so no caller picks their key id: a key the + cache lacks is fetched at once, with no cooldown, and a key rotated in just now verifies.""" client = _jwk_clients.get((jwks_uri, sign_in)) if client is None: url, headers = _route(jwks_uri) if sign_in else (jwks_uri, {}) client = _jwk_clients[(jwks_uri, sign_in)] = PyJWKClient( - url, headers=headers, timeout=settings.identity_provider_timeout_s + url, + headers=headers, + timeout=settings.identity_provider_timeout_s, + cooldown_duration=0 if sign_in else 30, # 30: PyJWT's own ) return client.get_signing_key_from_jwt(id_token).key diff --git a/tests/unit/test_call_site_knobs.py b/tests/unit/test_call_site_knobs.py index 8be53c26c5a..a7379924271 100644 --- a/tests/unit/test_call_site_knobs.py +++ b/tests/unit/test_call_site_knobs.py @@ -63,7 +63,7 @@ async def _discover() -> dict[str, str]: await oidc._token_request({"grant_type": "authorization_code"}) class _Jwk: - def __init__(self, uri: str, *, timeout: float, headers: dict[str, str]) -> None: + def __init__(self, uri: str, *, timeout: float, headers: dict[str, str], **_: Any) -> None: seen.append(timeout) def get_signing_key_from_jwt(self, token: str) -> Any: diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 93d845b24d4..30a59b59c00 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -580,6 +580,30 @@ async def verify(token: str) -> dict[str, Any]: assert await oauth._still_in_admin_group(grant, id_token) is want # type: ignore[arg-type] +@pytest.mark.parametrize( + "refused", + [ + jwt.InvalidSignatureError("signature"), + jwt.ExpiredSignatureError("expired"), + jwt.PyJWKSetError("no usable keys"), + jwt.PyJWKClientError('Unable to find a signing key that matches: "never-published"'), + ], +) +async def test_a_token_that_fails_verification_ends_the_role( + monkeypatch: pytest.MonkeyPatch, refused: Exception +) -> None: + # Only an outage is retried: a token that fails a check answers no, never a 503 loop. + from server.auth import oidc + from server.settings import settings + + async def verify(token: str) -> dict[str, Any]: + raise refused + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") + monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + + async def test_a_cleared_group_ends_the_role_at_the_next_refresh( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -600,7 +624,6 @@ async def verify(token: str) -> dict[str, Any]: jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider"), ConnectionResetError("reading the keys"), - jwt.PyJWKClientError('Unable to find a signing key that matches: "rotated-in"'), ], ) async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 621f23a1e79..4ce27124108 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -9,9 +9,11 @@ from __future__ import annotations +import io import json import sys import time +import urllib.request from pathlib import Path from typing import Any @@ -176,6 +178,43 @@ async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( await oidc.verify_refreshed_id_token(token) +@pytest.mark.parametrize("sign_in", [True, False]) +def test_a_sign_in_key_rotated_in_since_the_last_fetch_is_fetched_at_once( + monkeypatch, sign_in: bool +) -> None: + # Sign-in's ID tokens come from Loom's own token request, so no caller picks their key + # id. A bot trust's tokens come from the caller: that client keeps PyJWT's cooldown. + from jwt.algorithms import RSAAlgorithm + + first, rotated = (rsa.generate_private_key(public_exponent=65537, key_size=2048) for _ in "ab") + published = {"k1": first} + + class _Endpoint: # the provider's JWKS endpoint, under PyJWT's own fetch and cache + def __init__(self, *_handlers: Any) -> None: + pass + + def open(self, _request: Any, timeout: float) -> io.BytesIO: + keys = [ + {**RSAAlgorithm.to_jwk(k.public_key(), as_dict=True), "kid": kid, "use": "sig"} + for kid, k in published.items() + ] + return io.BytesIO(json.dumps({"keys": keys}).encode()) + + def token(key: Any, kid: str) -> str: + return pyjwt.encode({"sub": "s"}, key, algorithm="RS256", headers={"kid": kid}) + + monkeypatch.setattr(oidc, "_jwk_clients", {}) + monkeypatch.setattr(urllib.request, "build_opener", _Endpoint) + oidc.signing_key(f"{_ISS}/jwks", token(first, "k1"), sign_in=sign_in) + published["k2"] = rotated + if sign_in: + key = oidc.signing_key(f"{_ISS}/jwks", token(rotated, "k2"), sign_in=True) + assert key.public_numbers() == rotated.public_key().public_numbers() + else: + with pytest.raises(pyjwt.PyJWKClientError): + oidc.signing_key(f"{_ISS}/jwks", token(rotated, "k2")) + + @pytest.mark.parametrize( ("group", "listed", "asked"), [ @@ -723,7 +762,9 @@ async def claims(*_a: Any, **_k: Any) -> dict[str, Any]: class _Req: client = None query_params = {"code": "c", "state": "s"} - cookies = {oauth._state_cookie("s"): oauth.seal_pending(pending | {"exp": 2**31 - 1})} + cookies = { + oauth._state_cookie("s"): oauth.seal_pending(pending | {"exp": int(time.time()) + 600}) + } monkeypatch.setattr(oauth, "store", store) monkeypatch.setattr(oidc, "exchange_code", exchange) @@ -789,7 +830,9 @@ async def connect(_p: Any, identity: login.Identity, *_a: Any, **_k: Any) -> Res class _Req: client = None query_params = {"code": "c", "state": "s"} - cookies = {oauth._state_cookie("s"): oauth.seal_pending(pending | {"exp": 2**31 - 1})} + cookies = { + oauth._state_cookie("s"): oauth.seal_pending(pending | {"exp": int(time.time()) + 600}) + } monkeypatch.setattr(oauth, "store", MemoryOAuthStore()) monkeypatch.setattr(oidc, "exchange_code", exchange) diff --git a/tests/unit/test_oidc_backchannel.py b/tests/unit/test_oidc_backchannel.py index 34662907e99..f2596f21432 100644 --- a/tests/unit/test_oidc_backchannel.py +++ b/tests/unit/test_oidc_backchannel.py @@ -254,11 +254,13 @@ def test_a_signing_key_fetch_follows_no_redirect(key_server: str) -> None: def test_a_bot_trusts_keys_never_go_through_the_base(monkeypatch) -> None: """A trust's https `jwks_uri` on the issuer's host is fetched from that address, never over the base: only the sign-in's own keys are rerouted.""" - built: list[tuple[str, dict[str, str]]] = [] + built: list[tuple[str, dict[str, str], float]] = [] class _Client: - def __init__(self, uri: str, *, timeout: float, headers: dict[str, str]) -> None: - built.append((uri, headers)) + def __init__( + self, uri: str, *, timeout: float, headers: dict[str, str], cooldown_duration: float + ) -> None: + built.append((uri, headers, cooldown_duration)) def get_signing_key_from_jwt(self, token: str) -> Any: return type("K", (), {"key": "k"})() @@ -267,6 +269,6 @@ def get_signing_key_from_jwt(self, token: str) -> Any: oidc.signing_key(f"{_ISS}/jwks.json", "t") # as `machines` asks for a trust's keys oidc.signing_key(f"{_ISS}/jwks.json", "t", sign_in=True) assert built == [ - (f"{_ISS}/jwks.json", {}), - (f"{_BASE}/oauth/jwks.json", {"Host": "idp.example"}), + (f"{_ISS}/jwks.json", {}, 30), # a caller picks a trust token's key id: PyJWT's cooldown + (f"{_BASE}/oauth/jwks.json", {"Host": "idp.example"}, 0), ] diff --git a/tests/unit/test_oidc_hardening.py b/tests/unit/test_oidc_hardening.py index 2b289c4ab3b..c41507ad023 100644 --- a/tests/unit/test_oidc_hardening.py +++ b/tests/unit/test_oidc_hardening.py @@ -86,7 +86,7 @@ def test_one_jwk_client_per_jwks_uri(monkeypatch: pytest.MonkeyPatch) -> None: built: list[str] = [] class _Client: - def __init__(self, uri: str, timeout: int, headers: dict[str, str]) -> None: + def __init__(self, uri: str, timeout: int, headers: dict[str, str], **_: Any) -> None: built.append(uri) assert headers == {} # no back-channel base set: the issuer's own address diff --git a/uv.lock b/uv.lock index 9181e25e3c7..64a3860087e 100644 --- a/uv.lock +++ b/uv.lock @@ -931,7 +931,7 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'extractor'", specifier = ">=26,<27" }, { name = "pydantic", specifier = ">=2.9" }, { name = "pydantic-settings", specifier = ">=2.5" }, - { name = "pyjwt", extras = ["crypto"], specifier = ">=2.10" }, + { name = "pyjwt", extras = ["crypto"], specifier = ">=2.14" }, { name = "pymdown-extensions", marker = "extra == 'dev'", specifier = "==12.3" }, { name = "pypdf", marker = "extra == 'extractor'", specifier = ">=6.21,<7" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, From 9865e54b2333b0a7e23529bb1b027dd0543fac7f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:41:37 +0530 Subject: [PATCH 08/23] test(auth): a sign-in whose discovery or keys are away is retried uncounted The callback's verify step now retries every outage in oidc.KEYS_AWAY; the test drives a key-fetch error, a discovery connect error and a reset while reading keys, and checks each answers the start-again page without counting against the person's address. The docstring and log line name discovery too. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/oauth.py | 4 ++-- tests/unit/test_oidc.py | 4 +++- tests/unit/test_oidc_hardening.py | 26 ++++++++++++++++++-------- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 67061b02b4e..0d7a53b4027 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -673,7 +673,7 @@ async def _exchange_at_idp( """The IdP's tokens and verified id_token claims for `code`. A code it refuses raises _StartAgain and counts against `address`; a fault on its side (its outage, a rejected client secret) answers 502 and counts not. - Its keys away once the code is spent raise _Spent: a reload cannot finish.""" + Its discovery or keys away once the code is spent raise _Spent: a reload cannot finish.""" from server.auth import oidc try: @@ -704,7 +704,7 @@ async def _exchange_at_idp( try: id_claims = await oidc.verify_id_token(tokens.get("id_token", ""), nonce=pending["nonce"]) except oidc.KEYS_AWAY as e: - log.warning("oidc callback: the identity provider's keys are away: %s", e) + log.warning("oidc callback: the identity provider's discovery or keys are away: %s", e) await oidc.revoke(str(tokens.get("refresh_token") or "")) raise _Spent from e except Exception as e: # any other verify failure refuses the login (re-raised) diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 4ce27124108..3911c70fab8 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -186,7 +186,9 @@ def test_a_sign_in_key_rotated_in_since_the_last_fetch_is_fetched_at_once( # id. A bot trust's tokens come from the caller: that client keeps PyJWT's cooldown. from jwt.algorithms import RSAAlgorithm - first, rotated = (rsa.generate_private_key(public_exponent=65537, key_size=2048) for _ in "ab") + first, rotated = ( + rsa.generate_private_key(public_exponent=65537, key_size=2048) for _ in range(2) + ) published = {"k1": first} class _Endpoint: # the provider's JWKS endpoint, under PyJWT's own fetch and cache diff --git a/tests/unit/test_oidc_hardening.py b/tests/unit/test_oidc_hardening.py index c41507ad023..031624cb951 100644 --- a/tests/unit/test_oidc_hardening.py +++ b/tests/unit/test_oidc_hardening.py @@ -390,14 +390,24 @@ async def keeper_away(key: str, expires_at: int) -> bool: assert page.status_code == 503 and "Max-Age=0" in page.headers["set-cookie"] assert b'href="/oauth/authorize?' in page.body - async def keys_away(token: str, *, nonce: str) -> dict[str, Any]: - raise jwt.PyJWKClientConnectionError("jwks down") - - monkeypatch.setattr(oidc, "verify_id_token", keys_away) - page = await oauth.oidc_callback(_Req()) # type: ignore[arg-type] - # Past the exchange too: the IdP's keys being away is no reason to reload. - assert page.status_code == 503 and "Max-Age=0" in page.headers["set-cookie"] - assert b'href="/oauth/authorize?' in page.body + # Past the exchange too: the IdP's discovery or keys being away is no reason to reload, + # and no failed sign-in of the person's (one counted would refuse the next with a 429). + monkeypatch.setattr( + oauth, "_failed_callbacks_by_address", oauth.Attempts("oidc.failed_callback", 1, 900) + ) + for away_error in ( + jwt.PyJWKClientConnectionError("jwks down"), + httpx.ConnectError("discovery down"), + ConnectionResetError("reading the keys"), + ): + + async def keys_away(token: str, *, nonce: str, error: Exception = away_error) -> Any: + raise error + + monkeypatch.setattr(oidc, "verify_id_token", keys_away) + page = await oauth.oidc_callback(_Req()) # type: ignore[arg-type] + assert page.status_code == 503 and "Max-Age=0" in page.headers["set-cookie"] + assert b'href="/oauth/authorize?' in page.body def test_a_restart_begins_each_sign_in_where_it_began() -> None: From 58163b7d578622ecf6896f573505177153be3b38 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:59:55 +0530 Subject: [PATCH 09/23] docs(sso): keep Keycloak's full group path for the platform-admin group Keycloak keeps group names unique only among siblings, so a short name matches a subgroup of that name anywhere in the realm, and whoever can create one could make platform admins: set the group to its full path. The listed-admin refresh test now drives the real group check with the provider's keys away and expects the role, instead of stubbing the check. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 7 ++++--- tests/unit/test_oauth.py | 16 +++++++++------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 1865ac29ed2..9e63349b0dc 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -984,6 +984,7 @@ The same settings work with any OIDC provider that serves discovery at carry no `groups` claim, so no group confers `platform_admin`. - **Keycloak:** `LOOM_OIDC_ISSUER=https:///realms/`. For a platform-admin group, add a **Group Membership** mapper to the client with - claim name `groups` and **Add to ID token** on. It sends full paths by - default (`/loom-platform-admin`): turn **Full group path** off, or set the - group to its path. + claim name `groups` and **Add to ID token** on. Keep **Full group path** on + and set the group to its path (`/loom-platform-admin`): Keycloak keeps names + unique only among siblings, so a short name would match a subgroup of that + name anywhere in the realm. diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 30a59b59c00..e447e847f48 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -475,10 +475,10 @@ async def still(grant: dict[str, Any], id_token: str) -> bool: assert [r.name for r in verify_token(tok["access_token"]).roles] == want -def test_a_listed_platform_admin_refreshes_without_the_group_check( +def test_a_listed_platform_admin_refreshes_while_the_providers_keys_are_away( monkeypatch: pytest.MonkeyPatch, ) -> None: - # LOOM_PLATFORM_ADMINS keeps the role, so the provider's keys are never needed. + # LOOM_PLATFORM_ADMINS keeps the role, so the group check, which needs the keys, never runs. from server.auth import oidc from server.auth.jwt import verify_token from server.settings import settings @@ -489,17 +489,19 @@ async def listed(subject: str, org: str, roles: list[str]) -> list[str]: async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: return oidc.Refreshed("idp-next", "idp-id-token") - async def never(grant: dict[str, Any], id_token: str) -> bool: - raise AssertionError("a listed platform admin needs no group check") + async def keys_away(token: str) -> dict[str, Any]: + raise jwt.PyJWKClientConnectionError("keys") c = _client() rt = _refresh_token(c, roles=["platform_admin"]) monkeypatch.setattr(settings, "oauth_login_provider", "oidc") + monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") monkeypatch.setattr(login, "refreshed_roles", listed) monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) - monkeypatch.setattr(oauth, "_still_in_admin_group", never) - tok = _refresh(c, rt).json() - assert [r.name for r in verify_token(tok["access_token"]).roles] == ["PLATFORM_ADMIN"] + monkeypatch.setattr(oidc, "verify_refreshed_id_token", keys_away) + r = _refresh(c, rt) + assert r.status_code == 200, r.text + assert [x.name for x in verify_token(r.json()["access_token"]).roles] == ["PLATFORM_ADMIN"] def test_a_key_outage_at_the_group_check_answers_503_and_keeps_the_token( From 83823556280f646f640aae85971c529d98b65352 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:17:10 +0530 Subject: [PATCH 10/23] test(auth): seed a verified email so the listed-admin refresh test bites The test's grant had no verified email, so the group check returned before it reached the provider's keys and the test passed whatever the guard did. It now seeds one and runs both ways: a listed admin refreshes while the keys are away, a group-conferred admin is retried with a 503. The pending sign-in key is named in_platform_admin_group, after the bool it holds; the group check's docstring names the outage path; the Users hint no longer says Loom keeps no group membership (SCIM keeps groups). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- frontend/src/views/admin/Users.tsx | 2 +- server/auth/oauth.py | 9 +++++---- tests/unit/test_oauth.py | 26 ++++++++++++++++---------- tests/unit/test_oidc.py | 2 +- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/frontend/src/views/admin/Users.tsx b/frontend/src/views/admin/Users.tsx index 5c866be726b..06710490371 100644 --- a/frontend/src/views/admin/Users.tsx +++ b/frontend/src/views/admin/Users.tsx @@ -259,7 +259,7 @@ export function Users() { SSO, to LOOM_PLATFORM_ADMINS in the deployment's environment, and they sign in again. With SSO, members of the identity provider's group named by{" "} LOOM_OIDC_PLATFORM_ADMIN_GROUP sign in as platform admins - too; Loom keeps no group membership, so they carry no badge here. + too; Loom does not record who is in that group, so they carry no badge here. )} diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 0d7a53b4027..e2ce2e7f900 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -755,7 +755,7 @@ async def _finish_oidc_login(request: Request) -> Response: _exchanging.discard(state) # Set here, from the verified ID token, whatever the sealed round trip carried: an account # link finishes from the stored sign-in, without the token. - pending["platform_admin_group"] = oidc.in_platform_admin_group(id_claims) + pending["in_platform_admin_group"] = oidc.in_platform_admin_group(id_claims) upstream = str(tokens.get("refresh_token") or "") # The IdP vouched for this person: only now is the round trip marked used, # so a callback nobody signed in for writes nothing. @@ -845,7 +845,7 @@ async def _signed_in_as( identity[0], pending, upstream, org=identity[1], verified_email=email ): return refused - if pending.get("platform_admin_group"): + if pending.get("in_platform_admin_group"): identity = (identity[0], identity[1], identity[2], ["platform_admin"]) if verified_claims is not None: try: @@ -1553,8 +1553,9 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: """Whether the ID token the IdP issued with this refresh still puts the session's person - in `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. Only a platform admin's refresh asks. A missing or - unverifiable token, or one for another verified email, answers no: the role ends.""" + in `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. Only a platform admin's refresh asks. A missing token, + one that fails verification or one for another verified email answers no: the role ends. + Discovery or the provider's keys away raise `oidc.KEYS_AWAY`, and the refresh is retried.""" from server.auth import oidc if "platform_admin" not in grant["roles"] or not settings.oidc_platform_admin_group: diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index e447e847f48..71bc75f4298 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -397,10 +397,12 @@ def test_consent_page_names_where_the_code_goes() -> None: assert "Claude<b>" in page # control chars dropped, markup escaped -def _refresh_token(c: TestClient, roles: list[str] | None = None) -> str: +def _refresh_token(c: TestClient, roles: list[str] | None = None, **fields: Any) -> str: code, verifier = _seed_code() if roles is not None: - oauth.store.change("code", roles=roles) + fields["roles"] = roles + if fields: + oauth.store.change("code", **fields) return c.post( "/oauth/token", data={ @@ -475,16 +477,18 @@ async def still(grant: dict[str, Any], id_token: str) -> bool: assert [r.name for r in verify_token(tok["access_token"]).roles] == want +@pytest.mark.parametrize(("listed", "status"), [(True, 200), (False, 503)]) def test_a_listed_platform_admin_refreshes_while_the_providers_keys_are_away( - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, listed: bool, status: int ) -> None: - # LOOM_PLATFORM_ADMINS keeps the role, so the group check, which needs the keys, never runs. + # LOOM_PLATFORM_ADMINS keeps the role, so the group check, which needs the keys, never + # runs; a group-conferred admin's refresh reaches the keys and is retried. from server.auth import oidc from server.auth.jwt import verify_token from server.settings import settings - async def listed(subject: str, org: str, roles: list[str]) -> list[str]: - return ["platform_admin"] + async def re_derived(subject: str, org: str, roles: list[str]) -> list[str]: + return ["platform_admin"] if listed else ["writer"] async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: return oidc.Refreshed("idp-next", "idp-id-token") @@ -493,15 +497,17 @@ async def keys_away(token: str) -> dict[str, Any]: raise jwt.PyJWKClientConnectionError("keys") c = _client() - rt = _refresh_token(c, roles=["platform_admin"]) + rt = _refresh_token(c, roles=["platform_admin"], verified_email="alice@example.com") monkeypatch.setattr(settings, "oauth_login_provider", "oidc") monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") - monkeypatch.setattr(login, "refreshed_roles", listed) + monkeypatch.setattr(login, "refreshed_roles", re_derived) monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) monkeypatch.setattr(oidc, "verify_refreshed_id_token", keys_away) r = _refresh(c, rt) - assert r.status_code == 200, r.text - assert [x.name for x in verify_token(r.json()["access_token"]).roles] == ["PLATFORM_ADMIN"] + assert r.status_code == status, r.text + if listed: + roles = verify_token(r.json()["access_token"]).roles + assert [x.name for x in roles] == ["PLATFORM_ADMIN"] def test_a_key_outage_at_the_group_check_answers_503_and_keeps_the_token( diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 3911c70fab8..be16da53dad 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -810,7 +810,7 @@ async def test_the_platform_admin_group_signs_its_members_in_as_platform_admin( monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") pending = {"kind": kind, "nonce": "n", "code_verifier": "v", "state": "s"} if carried: - pending["platform_admin_group"] = True # type: ignore[assignment] + pending["in_platform_admin_group"] = True # type: ignore[assignment] signed_in: dict[str, Any] = {} async def exchange(**_k: Any) -> dict[str, str]: From cf9e56a7fe914745c98485c117169fda58504e2b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:35:18 +0530 Subject: [PATCH 11/23] auth: retry an incomplete key read under PyJWT 2.14 too PyJWT 2.14 wraps URLError and TimeoutError but not http.client's errors, so on the floor version an incomplete read of the provider's keys ended a group-conferred role instead of retrying; KEYS_AWAY now names http.client.HTTPException. The refresh verifier is one function again, the sign-in leeway has its own test, and sso.md says to pick a group only the provider's administrators can create and fill. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 6 ++++++ server/auth/oauth.py | 9 +++++---- server/auth/oidc.py | 16 +++++++--------- server/settings/catalog.py | 4 ++-- tests/unit/test_oauth.py | 2 ++ tests/unit/test_oidc.py | 9 +++++++++ 6 files changed, 31 insertions(+), 15 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 9e63349b0dc..ed437cbc997 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -160,6 +160,12 @@ group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, exactly: LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin ``` +Loom matches the name exactly as the provider sends it, so pick a group only +the provider's administrators can create and fill: on a provider that lets +members create groups, any member who creates one of that name signs in as a +platform admin. The Okta step above and the Keycloak note below name their +cases. + With the group set, sign-in asks for the `groups` scope where the provider's discovery document lists it (Okta's org authorization server needs it). With a custom authorization server, define the groups claim on that server and diff --git a/server/auth/oauth.py b/server/auth/oauth.py index e2ce2e7f900..6cebb4c6c2d 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -4,9 +4,9 @@ the token and revocation endpoints, the IdP callback and the dashboard's SSO sign-in; `connect_router` adds MCP one-click connect when `LOOM_OAUTH_ENABLED=true`. Loom issues its own JWTs; under -`LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP authenticates the person (oidc.py), and -members of one of its groups (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`) sign in as platform_admin. State -lives in oauth_store.py. The flows, sessions and threat model are in +`LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP authenticates the person (oidc.py), +and members of one of its groups (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`) sign in as +platform_admin. State lives in oauth_store.py. The flows, sessions and threat model are in docs/architecture/security.md ("OIDC and OAuth"). """ @@ -673,7 +673,8 @@ async def _exchange_at_idp( """The IdP's tokens and verified id_token claims for `code`. A code it refuses raises _StartAgain and counts against `address`; a fault on its side (its outage, a rejected client secret) answers 502 and counts not. - Its discovery or keys away once the code is spent raise _Spent: a reload cannot finish.""" + Its discovery or keys away once the code is spent raise _Spent: a reload + cannot finish.""" from server.auth import oidc try: diff --git a/server/auth/oidc.py b/server/auth/oidc.py index b0d513a3f36..c694b1b6788 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -21,6 +21,7 @@ from __future__ import annotations import asyncio +import http.client import logging import secrets import time @@ -241,8 +242,9 @@ async def check_callback_issuer(iss: str) -> bool: # What verifying an ID token raises when discovery or the provider's keys cannot be fetched, -# rather than a token that fails: PyJWT wraps only some transport errors. -KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError) +# rather than a token that fails. PyJWT wraps URLError and TimeoutError (http.client's errors +# only from 2.15), so a reset or TLS error while it reads the body comes through raw. +KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError, http.client.HTTPException) def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: @@ -278,21 +280,17 @@ async def verify_id_token(id_token: str, *, nonce: str) -> dict[str, Any]: """Verify the IdP id_token (signature against JWKS with an algorithm the IdP lists, iss, aud, exp) and the nonce, returning the claims. Raises on any failure.""" - claims = await _verified_claims(id_token) + claims = await verify_refreshed_id_token(id_token) if not nonce or not secrets.compare_digest(str(claims.get("nonce") or ""), nonce): raise ValueError("id_token nonce mismatch") return claims async def verify_refreshed_id_token(id_token: str) -> dict[str, Any]: - """`verify_id_token` without the nonce, for the ID token a refresh returns. That one + """The claims of an IdP ID token whose signature, issuer, audience and expiry hold: + `verify_id_token` without the nonce, for the ID token a refresh returns. That one carries the sign-in's nonce or none (OpenID Connect Core 12.2), and it answers Loom's own back-channel token request, so no browser can replay one into it.""" - return await _verified_claims(id_token) - - -async def _verified_claims(id_token: str) -> dict[str, Any]: - """The claims of an IdP ID token whose signature, issuer, audience and expiry hold.""" doc = await _discover() algorithms = id_token_algorithms(doc) key = await asyncio.to_thread(signing_key, doc["jwks_uri"], id_token, sign_in=True) diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 890312e20ba..b55ffac50f8 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -153,8 +153,8 @@ class AuthSettings(BaseModel): # 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 names nobody here; `oidc_platform_admin_group` also confers - # the role. + # self-signup address. Empty names nobody here; `oidc_platform_admin_group` + # also confers the role. platform_admins: str = "" @property diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 71bc75f4298..67b00f18975 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -11,6 +11,7 @@ import asyncio import base64 import hashlib +import http.client import json import secrets import time @@ -632,6 +633,7 @@ async def verify(token: str) -> dict[str, Any]: jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider"), ConnectionResetError("reading the keys"), + http.client.IncompleteRead(b"{"), # PyJWT 2.14 does not wrap it ], ) async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index be16da53dad..b89e09f043d 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -127,6 +127,15 @@ async def test_verify_id_token_rejects_wrong_audience(_signing_key, monkeypatch) await oidc.verify_id_token(_id_token(priv, aud="someone-else"), nonce="the-nonce") +async def test_verify_id_token_allows_the_providers_clock_a_little_ahead( + _signing_key, monkeypatch +) -> None: + priv, pub = _signing_key + _inject(monkeypatch, pub) + ahead = _id_token(priv, iat=int(time.time()) + 10) + assert (await oidc.verify_id_token(ahead, nonce="the-nonce"))["email"] == "user@example.com" + + async def test_verify_id_token_rejects_expired(_signing_key, monkeypatch) -> None: priv, pub = _signing_key _inject(monkeypatch, pub) From 9942ac4a883376e79fe44a2155f9ea1d6c220e27 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:52:57 +0530 Subject: [PATCH 12/23] auth: require PyJWT 2.15, the version the lock and CI run 2.15 wraps http.client's errors in PyJWKClientConnectionError, so the outage list no longer names them, and the floor now matches what is tested. The nonce-free verifier is named verify_id_token_without_nonce, which reads right at sign-in and at refresh. The MCP reference says a refresh drops platform_admin only once neither the list nor the group names the subject. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/mcp.md | 6 +++--- pyproject.toml | 2 +- server/auth/oauth.py | 2 +- server/auth/oidc.py | 15 +++++++-------- tests/unit/test_oauth.py | 12 +++++------- tests/unit/test_oidc.py | 4 ++-- uv.lock | 2 +- 7 files changed, 20 insertions(+), 23 deletions(-) diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index a14cf867c80..4c0a94de200 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -209,9 +209,9 @@ connect by browser sign-in instead of a pasted token (`server/auth/oauth.py`): to a loopback host, or an app scheme (`cursor://…`). The sign-in page names the host the authorization goes to. - Each refresh re-checks that the account is still active and re-derives its - roles, so a released account, or a subject removed from - `LOOM_PLATFORM_ADMINS` or from the group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` - names, does not keep its access by refreshing. + roles, so a released account, or a subject that neither + `LOOM_PLATFORM_ADMINS` nor the group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names + any more, does not keep its access by refreshing. [Security](../architecture/security.md) covers the token model behind this. diff --git a/pyproject.toml b/pyproject.toml index f61f0696c02..6aa25cdaef5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ dependencies = [ "jsonschema>=4.20", "referencing>=0.37.0", "tenacity>=9.0", - "pyjwt[crypto]>=2.14", + "pyjwt[crypto]>=2.15", # Application Default Credentials for the native Vertex AI client. "google-auth[requests]>=2.40,<3", # OpenTelemetry: ship spans + logs to HyperDX / ClickStack's OTLP diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 6cebb4c6c2d..1774a90067e 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1565,7 +1565,7 @@ async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: if not id_token or not email: return False try: - id_claims = await oidc.verify_refreshed_id_token(id_token) + id_claims = await oidc.verify_id_token_without_nonce(id_token) except oidc.KEYS_AWAY: raise # the refresh is retried with its token put back except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role diff --git a/server/auth/oidc.py b/server/auth/oidc.py index c694b1b6788..004557c74ec 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -21,7 +21,6 @@ from __future__ import annotations import asyncio -import http.client import logging import secrets import time @@ -242,9 +241,9 @@ async def check_callback_issuer(iss: str) -> bool: # What verifying an ID token raises when discovery or the provider's keys cannot be fetched, -# rather than a token that fails. PyJWT wraps URLError and TimeoutError (http.client's errors -# only from 2.15), so a reset or TLS error while it reads the body comes through raw. -KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError, http.client.HTTPException) +# rather than a token that fails. PyJWT wraps only URLError, TimeoutError and http.client's +# errors, so a reset or TLS error while it reads the body comes through raw. +KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError) def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: @@ -280,15 +279,15 @@ async def verify_id_token(id_token: str, *, nonce: str) -> dict[str, Any]: """Verify the IdP id_token (signature against JWKS with an algorithm the IdP lists, iss, aud, exp) and the nonce, returning the claims. Raises on any failure.""" - claims = await verify_refreshed_id_token(id_token) + claims = await verify_id_token_without_nonce(id_token) if not nonce or not secrets.compare_digest(str(claims.get("nonce") or ""), nonce): raise ValueError("id_token nonce mismatch") return claims -async def verify_refreshed_id_token(id_token: str) -> dict[str, Any]: - """The claims of an IdP ID token whose signature, issuer, audience and expiry hold: - `verify_id_token` without the nonce, for the ID token a refresh returns. That one +async def verify_id_token_without_nonce(id_token: str) -> dict[str, Any]: + """The claims of an IdP ID token whose signature, issuer, audience and expiry hold; + `verify_id_token` adds the nonce. A refresh's ID token is checked with this alone: it carries the sign-in's nonce or none (OpenID Connect Core 12.2), and it answers Loom's own back-channel token request, so no browser can replay one into it.""" doc = await _discover() diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 67b00f18975..2b2da2e6448 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -11,7 +11,6 @@ import asyncio import base64 import hashlib -import http.client import json import secrets import time @@ -503,7 +502,7 @@ async def keys_away(token: str) -> dict[str, Any]: monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") monkeypatch.setattr(login, "refreshed_roles", re_derived) monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) - monkeypatch.setattr(oidc, "verify_refreshed_id_token", keys_away) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", keys_away) r = _refresh(c, rt) assert r.status_code == status, r.text if listed: @@ -585,7 +584,7 @@ async def verify(token: str) -> dict[str, Any]: return {"email": "ada@example.com", "email_verified": True, **claims} monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") - monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) assert await oauth._still_in_admin_group(grant, id_token) is want # type: ignore[arg-type] @@ -609,7 +608,7 @@ async def verify(token: str) -> dict[str, Any]: raise refused monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") - monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] @@ -623,7 +622,7 @@ async def verify(token: str) -> dict[str, Any]: return {"email": "ada@example.com", "email_verified": True, "groups": ["admins"]} monkeypatch.setattr(settings, "oidc_platform_admin_group", "") - monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] @@ -633,7 +632,6 @@ async def verify(token: str) -> dict[str, Any]: jwt.PyJWKClientConnectionError("keys"), httpx.ConnectError("provider"), ConnectionResetError("reading the keys"), - http.client.IncompleteRead(b"{"), # PyJWT 2.14 does not wrap it ], ) async def test_still_in_admin_group_lets_a_provider_outage_retry_the_refresh( @@ -647,7 +645,7 @@ async def verify(token: str) -> dict[str, Any]: raise away monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") - monkeypatch.setattr(oidc, "verify_refreshed_id_token", verify) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) with pytest.raises(type(away)): await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index b89e09f043d..9cd1380d46d 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -181,10 +181,10 @@ async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( now = int(time.time()) token = _id_token(priv, nonce=None, iat=now + iat, exp=now + exp, **overrides) if accepted: - assert (await oidc.verify_refreshed_id_token(token))["email"] == "user@example.com" + assert (await oidc.verify_id_token_without_nonce(token))["email"] == "user@example.com" else: with pytest.raises(pyjwt.PyJWTError): - await oidc.verify_refreshed_id_token(token) + await oidc.verify_id_token_without_nonce(token) @pytest.mark.parametrize("sign_in", [True, False]) diff --git a/uv.lock b/uv.lock index 64a3860087e..e7c28b822f8 100644 --- a/uv.lock +++ b/uv.lock @@ -931,7 +931,7 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'extractor'", specifier = ">=26,<27" }, { name = "pydantic", specifier = ">=2.9" }, { name = "pydantic-settings", specifier = ">=2.5" }, - { name = "pyjwt", extras = ["crypto"], specifier = ">=2.14" }, + { name = "pyjwt", extras = ["crypto"], specifier = ">=2.15" }, { name = "pymdown-extensions", marker = "extra == 'dev'", specifier = "==12.3" }, { name = "pypdf", marker = "extra == 'extractor'", specifier = ">=6.21,<7" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, From 1724f4f364f2642fa9a247aa4a8b7551380a1bed Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:13:05 +0530 Subject: [PATCH 13/23] auth: the approval audit rows name the roles a sign-in minted With the provider's group conferring platform_admin, the admins are no longer readable from configuration. auth.device_approved and auth.connect_approved now carry the roles, as auth.sso_signin already did, so the audit log names who signed in as a platform admin and when, and a refresh that ends the role logs the session. The refresh-deadline comment names the deadline it means. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 5 +++++ server/auth/device.py | 1 + server/auth/oauth.py | 8 +++++++- server/auth/oidc.py | 7 ++++--- tests/unit/test_device_login.py | 4 +++- 5 files changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index ed437cbc997..80962973102 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -166,6 +166,11 @@ members create groups, any member who creates one of that name signs in as a platform admin. The Okta step above and the Keycloak note below name their cases. +Loom does not keep the group's members, but each sign-in's audit row +(`auth.sso_signin`, `auth.device_approved`, `auth.connect_approved`) carries +the roles it minted, so the audit log names who signed in as a platform admin +and when. + With the group set, sign-in asks for the `groups` scope where the provider's discovery document lists it (Okta's org authorization server needs it). With a custom authorization server, define the groups claim on that server and diff --git a/server/auth/device.py b/server/auth/device.py index 519571aa003..21cc997827d 100644 --- a/server/auth/device.py +++ b/server/auth/device.py @@ -410,6 +410,7 @@ async def device_approve(request: Request) -> Response: subject={ "client_id": DEVICE_CLIENT_ID, "family": device["family"], + "roles": device["roles"], "requested_from": device["address"], "approved_from": client_address(request), }, diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 1774a90067e..d09c1c77b59 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1185,7 +1185,11 @@ async def _decide_connect(f: dict[str, str]) -> Response: org=org, namespace="-", actor=subject, - subject={"client_id": pending["client_id"], "redirect_uri": pending["redirect_uri"]}, + subject={ + "client_id": pending["client_id"], + "redirect_uri": pending["redirect_uri"], + "roles": roles, + }, ) if answer is not None: return answer @@ -1544,6 +1548,8 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: # Asked only when LOOM_PLATFORM_ADMINS did not keep the role, of a session that held it. if roles != ["platform_admin"] and await _still_in_admin_group(grant, id_token): roles = ["platform_admin"] + elif roles != ["platform_admin"] and "platform_admin" in grant["roles"]: + log.info("oauth refresh: session %s refreshes without platform_admin", grant["family"]) return await issue_tokens( {**grant, "roles": roles}, grant["client_id"], diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 004557c74ec..37e9b44d05f 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -90,9 +90,10 @@ async def _discover() -> dict[str, Any]: # The whole IdP leg of a Loom refresh (discovery and the token call; the key -# fetch a platform-admin group check needs comes after, under the refresh's own -# deadline): the SDK waits longer than this for a refresh, so it never gives up -# on one the server is still answering. +# fetch a platform-admin group check needs comes after, under +# `oauth._REFRESH_DEADLINE_S`, which answers a slow one 503): the SDK waits +# longer than this for a refresh, so it never gives up on one the server is +# still answering. _REFRESH_DEADLINE_S = 20 diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index f840342cde2..35e5bb0e745 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -743,7 +743,7 @@ async def no_jit(email: str) -> None: @pytest.mark.parametrize("decision", ["link", "not_mine"]) def test_a_sign_in_finished_on_the_link_page_keeps_the_platform_admin_group( - sso, bobs_password_account, monkeypatch, decision: str + sso, bobs_password_account, _world, monkeypatch, decision: str ) -> None: # The link page finishes from the stored sign-in, after the ID token is gone. from server.settings import settings @@ -767,6 +767,8 @@ async def jit_account(email: str) -> Any: tokens = _poll(c, grant["device_code"]).json() claims = pyjwt.decode(tokens["access_token"], options={"verify_signature": False}) assert claims["roles"] == ["platform_admin"] + approved = [kw for name, kw in _world["events"] if name == "auth.device_approved"] + assert approved[-1]["subject"]["roles"] == ["platform_admin"] # the log names the admin def test_declining_while_jit_cannot_read_starts_again(bobs_password_account, monkeypatch) -> None: From 3e6a6ce9af618650570dbc83746b0d28646ba04c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:37:28 +0530 Subject: [PATCH 14/23] test(auth): a group admin's connect approval row names the role The MCP connect approval row's roles are now asserted, as the device row's are. The refresh's group guard tests its condition once, the deadline comment is two plain sentences, and the Users hint is formatted as the format job expects. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- frontend/src/views/admin/Users.tsx | 4 ++-- server/auth/oauth.py | 9 +++++---- server/auth/oidc.py | 9 ++++----- tests/unit/test_device_login.py | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/frontend/src/views/admin/Users.tsx b/frontend/src/views/admin/Users.tsx index 06710490371..085ffeb9334 100644 --- a/frontend/src/views/admin/Users.tsx +++ b/frontend/src/views/admin/Users.tsx @@ -258,8 +258,8 @@ export function Users() { To make someone a platform admin, an operator adds their login handle, or the email they sign in with over SSO, to LOOM_PLATFORM_ADMINS in the deployment's environment, and they sign in again. With SSO, members of the identity provider's group named by{" "} - LOOM_OIDC_PLATFORM_ADMIN_GROUP sign in as platform admins - too; Loom does not record who is in that group, so they carry no badge here. + LOOM_OIDC_PLATFORM_ADMIN_GROUP sign in as platform admins too; + Loom does not record who is in that group, so they carry no badge here. )} diff --git a/server/auth/oauth.py b/server/auth/oauth.py index d09c1c77b59..4d0095f179f 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1546,10 +1546,11 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: await end_session(grant, "account no longer active") raise _invalid_grant() # Asked only when LOOM_PLATFORM_ADMINS did not keep the role, of a session that held it. - if roles != ["platform_admin"] and await _still_in_admin_group(grant, id_token): - roles = ["platform_admin"] - elif roles != ["platform_admin"] and "platform_admin" in grant["roles"]: - log.info("oauth refresh: session %s refreshes without platform_admin", grant["family"]) + if roles != ["platform_admin"] and "platform_admin" in grant["roles"]: + if await _still_in_admin_group(grant, id_token): + roles = ["platform_admin"] + else: + log.info("oauth refresh: session %s refreshes without platform_admin", grant["family"]) return await issue_tokens( {**grant, "roles": roles}, grant["client_id"], diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 37e9b44d05f..ad8997492da 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -89,11 +89,10 @@ async def _discover() -> dict[str, Any]: return doc -# The whole IdP leg of a Loom refresh (discovery and the token call; the key -# fetch a platform-admin group check needs comes after, under -# `oauth._REFRESH_DEADLINE_S`, which answers a slow one 503): the SDK waits -# longer than this for a refresh, so it never gives up on one the server is -# still answering. +# The whole IdP leg of a Loom refresh (discovery and the token call): the +# SDK waits longer than this for a refresh, so it never gives up on one the +# server is still answering. A platform-admin group check's key fetch runs +# after it, under `oauth._REFRESH_DEADLINE_S`. _REFRESH_DEADLINE_S = 20 diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index 35e5bb0e745..f2b49242d71 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -1123,6 +1123,24 @@ def test_mcp_connect_under_sso_asks_before_it_sends_a_code(sso, _world) -> None: assert "auth.connect_approved" in [n for n, _ in _world["events"]] +def test_a_group_admins_connect_approval_names_the_role(sso, _world, monkeypatch) -> None: + # Loom keeps no copy of the group: the approval row is where the admin shows up. + from server.settings import settings + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") + sso["groups"] = ["loom-admins"] + c = _client() + ticket = _ticket(_connect_through_sso(c).text) + r = c.post( + "/oauth/authorize/approve", + data={"ticket": ticket, "decision": "approve"}, + follow_redirects=False, + ) + assert r.status_code == 302 and "code=" in r.headers["location"] + approved = [kw for name, kw in _world["events"] if name == "auth.connect_approved"] + assert approved[-1]["subject"]["roles"] == ["platform_admin"] + + def test_a_connect_approved_after_a_minute_still_gives_a_live_code( sso, _world, monkeypatch ) -> None: From 1fc71679d52ce7e7ed669ca527370b8db59fa312 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:57:13 +0530 Subject: [PATCH 15/23] auth: a link page finished after the group setting is cleared grants no role The callback's group decision rides the link ticket for up to ten minutes; it now confers platform_admin only while the setting is still set. The never-promotes guard lives once, in the refresh, with a test at that level, and the outage tuple is named PROVIDER_AWAY, since it covers discovery as well as keys. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/oauth.py | 15 ++++++++------- server/auth/oidc.py | 2 +- tests/unit/test_device_login.py | 10 +++++++--- tests/unit/test_oauth.py | 27 ++++++++++++++++++++++++++- 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 4d0095f179f..7c72abc7131 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -704,7 +704,7 @@ async def _exchange_at_idp( raise OAuthError("oidc_error") from e try: id_claims = await oidc.verify_id_token(tokens.get("id_token", ""), nonce=pending["nonce"]) - except oidc.KEYS_AWAY as e: + except oidc.PROVIDER_AWAY as e: log.warning("oidc callback: the identity provider's discovery or keys are away: %s", e) await oidc.revoke(str(tokens.get("refresh_token") or "")) raise _Spent from e @@ -846,7 +846,7 @@ async def _signed_in_as( identity[0], pending, upstream, org=identity[1], verified_email=email ): return refused - if pending.get("in_platform_admin_group"): + if pending.get("in_platform_admin_group") and settings.oidc_platform_admin_group: identity = (identity[0], identity[1], identity[2], ["platform_admin"]) if verified_claims is not None: try: @@ -1561,19 +1561,20 @@ async def _refresh_session(grant: Grant, refresh_token: str) -> dict[str, Any]: async def _still_in_admin_group(grant: Grant, id_token: str) -> bool: """Whether the ID token the IdP issued with this refresh still puts the session's person - in `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. Only a platform admin's refresh asks. A missing token, - one that fails verification or one for another verified email answers no: the role ends. - Discovery or the provider's keys away raise `oidc.KEYS_AWAY`, and the refresh is retried.""" + in `LOOM_OIDC_PLATFORM_ADMIN_GROUP`. Asked only of a session that held platform_admin + (`_refresh_session`), so it never promotes. A missing token, one that fails verification + or one for another verified email answers no: the role ends. Discovery or the provider's + keys away raise `oidc.PROVIDER_AWAY`, and the refresh is retried.""" from server.auth import oidc - if "platform_admin" not in grant["roles"] or not settings.oidc_platform_admin_group: + if not settings.oidc_platform_admin_group: return False email = scim.normalized(str(grant.get("verified_email") or "")) if not id_token or not email: return False try: id_claims = await oidc.verify_id_token_without_nonce(id_token) - except oidc.KEYS_AWAY: + except oidc.PROVIDER_AWAY: raise # the refresh is retried with its token put back except Exception as e: # noqa: BLE001 — an ID token that cannot be verified confers no role log.warning("oauth refresh: the refreshed id_token was refused: %s", type(e).__name__) diff --git a/server/auth/oidc.py b/server/auth/oidc.py index ad8997492da..c69ad4761c9 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -243,7 +243,7 @@ async def check_callback_issuer(iss: str) -> bool: # What verifying an ID token raises when discovery or the provider's keys cannot be fetched, # rather than a token that fails. PyJWT wraps only URLError, TimeoutError and http.client's # errors, so a reset or TLS error while it reads the body comes through raw. -KEYS_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError) +PROVIDER_AWAY = (jwt.PyJWKClientConnectionError, httpx.HTTPError, OSError) def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index f2b49242d71..b009d152d32 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -741,9 +741,10 @@ async def no_jit(email: str) -> None: assert denied and "ask your" not in str(denied[-1]) # the bare reason, not the page's advice +@pytest.mark.parametrize("cleared", [False, True]) @pytest.mark.parametrize("decision", ["link", "not_mine"]) def test_a_sign_in_finished_on_the_link_page_keeps_the_platform_admin_group( - sso, bobs_password_account, _world, monkeypatch, decision: str + sso, bobs_password_account, _world, monkeypatch, decision: str, cleared: bool ) -> None: # The link page finishes from the stored sign-in, after the ID token is gone. from server.settings import settings @@ -758,6 +759,8 @@ async def jit_account(email: str) -> Any: c = _client() grant = _start(c) page = _sso_round_trip(c, grant["user_code"]) + if cleared: # the operator cleared the setting while the link page was open + monkeypatch.setattr(settings, "oidc_platform_admin_group", "") if decision == "link": r = _link(c, page.text, "bobpw") else: @@ -766,9 +769,10 @@ async def jit_account(email: str) -> Any: _approve(c, grant["user_code"], r.text) tokens = _poll(c, grant["device_code"]).json() claims = pyjwt.decode(tokens["access_token"], options={"verify_signature": False}) - assert claims["roles"] == ["platform_admin"] + want = ["writer"] if cleared else ["platform_admin"] + assert claims["roles"] == want approved = [kw for name, kw in _world["events"] if name == "auth.device_approved"] - assert approved[-1]["subject"]["roles"] == ["platform_admin"] # the log names the admin + assert approved[-1]["subject"]["roles"] == want # the log names the admin def test_declining_while_jit_cannot_read_starts_again(bobs_password_account, monkeypatch) -> None: diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 2b2da2e6448..3137b73d179 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -477,6 +477,32 @@ async def still(grant: dict[str, Any], id_token: str) -> bool: assert [r.name for r in verify_token(tok["access_token"]).roles] == want +def test_a_refresh_never_promotes_a_member_the_group_lists(monkeypatch: pytest.MonkeyPatch) -> None: + # A person added to the group signs in again to get the role. + from server.auth import oidc + from server.auth.jwt import verify_token + from server.settings import settings + + async def member(subject: str, org: str, roles: list[str]) -> list[str]: + return ["writer"] + + async def upstream(grant: dict[str, Any], refresh_token: str) -> oidc.Refreshed: + return oidc.Refreshed("idp-next", "idp-id-token") + + async def listed(grant: dict[str, Any], id_token: str) -> bool: + return True + + c = _client() + rt = _refresh_token(c, roles=["writer"], verified_email="alice@example.com") + monkeypatch.setattr(settings, "oauth_login_provider", "oidc") + monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") + monkeypatch.setattr(login, "refreshed_roles", member) + monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) + monkeypatch.setattr(oauth, "_still_in_admin_group", listed) + tok = _refresh(c, rt).json() + assert [r.name for r in verify_token(tok["access_token"]).roles] == ["WRITER"] + + @pytest.mark.parametrize(("listed", "status"), [(True, 200), (False, 503)]) def test_a_listed_platform_admin_refreshes_while_the_providers_keys_are_away( monkeypatch: pytest.MonkeyPatch, listed: bool, status: int @@ -556,7 +582,6 @@ def _admin_grant(roles: list[str], email: str = "ada@example.com") -> dict[str, (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"]}, True), (_admin_grant(["platform_admin"]), "t", {"groups": ["eng"]}, False), (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"], "email": "eve@x.io"}, False), - (_admin_grant(["writer"]), "t", {"groups": ["admins"]}, False), # never promotes (_admin_grant(["platform_admin"]), "", {"groups": ["admins"]}, False), # none sent (_admin_grant(["platform_admin"], ""), "t", {"groups": ["admins"], "email": ""}, False), (_admin_grant(["platform_admin"]), "t", None, False), # it fails verification From e95878a41eeb5f885a2fbab0619093a40067fbfd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:11:20 +0530 Subject: [PATCH 16/23] test(auth): name the link-page test for both its cases The fail-closed helper no longer takes the roles the group check stopped reading, the link-page test is named for its cleared-setting case too, sso.md names a linked password account's handle among the ways to the role, and the groups-claim docstring promises only the list check it makes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 5 +++-- server/auth/oidc.py | 2 +- tests/unit/test_device_login.py | 2 +- tests/unit/test_oauth.py | 24 ++++++++++++------------ 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 80962973102..2497b725a53 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -153,8 +153,9 @@ For a person with no account: ### Platform admins A person signs in as a platform admin when `LOOM_PLATFORM_ADMINS` lists their -verified email, or when their verified ID token's `groups` claim holds the -group `LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, exactly: +verified email or the login handle of the password account they linked, or when +their verified ID token's `groups` claim holds the group +`LOOM_OIDC_PLATFORM_ADMIN_GROUP` names, exactly: ```bash LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin diff --git a/server/auth/oidc.py b/server/auth/oidc.py index c69ad4761c9..f1ede177d40 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -307,7 +307,7 @@ async def verify_id_token_without_nonce(id_token: str) -> dict[str, Any]: def in_platform_admin_group(claims: dict[str, Any]) -> bool: """Whether verified ID token `claims` list `LOOM_OIDC_PLATFORM_ADMIN_GROUP` in their - `groups` claim, exactly. A `groups` that is not a list of names lists nothing.""" + `groups` claim, exactly. A `groups` that is not a list lists nothing.""" group = settings.oidc_platform_admin_group groups = claims.get("groups") return bool(group) and isinstance(groups, list) and group in groups diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index b009d152d32..574f4dd04f9 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -743,7 +743,7 @@ async def no_jit(email: str) -> None: @pytest.mark.parametrize("cleared", [False, True]) @pytest.mark.parametrize("decision", ["link", "not_mine"]) -def test_a_sign_in_finished_on_the_link_page_keeps_the_platform_admin_group( +def test_a_link_page_sign_in_gets_the_group_role_only_while_the_group_is_set( sso, bobs_password_account, _world, monkeypatch, decision: str, cleared: bool ) -> None: # The link page finishes from the stored sign-in, after the ID token is gone. diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 3137b73d179..6bea1f7822e 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -572,21 +572,21 @@ async def still(grant: dict[str, Any], id_token: str) -> bool: assert [r.name for r in roles] == ["PLATFORM_ADMIN"] -def _admin_grant(roles: list[str], email: str = "ada@example.com") -> dict[str, Any]: - return {"roles": roles, "verified_email": email} +def _admin_grant(email: str = "ada@example.com") -> dict[str, Any]: + return {"roles": ["platform_admin"], "verified_email": email} @pytest.mark.parametrize( ("grant", "id_token", "claims", "want"), [ - (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"]}, True), - (_admin_grant(["platform_admin"]), "t", {"groups": ["eng"]}, False), - (_admin_grant(["platform_admin"]), "t", {"groups": ["admins"], "email": "eve@x.io"}, False), - (_admin_grant(["platform_admin"]), "", {"groups": ["admins"]}, False), # none sent - (_admin_grant(["platform_admin"], ""), "t", {"groups": ["admins"], "email": ""}, False), - (_admin_grant(["platform_admin"]), "t", None, False), # it fails verification + (_admin_grant(), "t", {"groups": ["admins"]}, True), + (_admin_grant(), "t", {"groups": ["eng"]}, False), + (_admin_grant(), "t", {"groups": ["admins"], "email": "eve@x.io"}, False), + (_admin_grant(), "", {"groups": ["admins"]}, False), # none sent + (_admin_grant(""), "t", {"groups": ["admins"], "email": ""}, False), + (_admin_grant(), "t", None, False), # it fails verification ( - _admin_grant(["platform_admin"]), + _admin_grant(), "t", {"groups": ["admins"], "email_verified": False}, False, @@ -634,7 +634,7 @@ async def verify(token: str) -> dict[str, Any]: monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) - assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + assert not await oauth._still_in_admin_group(_admin_grant(), "t") # type: ignore[arg-type] async def test_a_cleared_group_ends_the_role_at_the_next_refresh( @@ -648,7 +648,7 @@ async def verify(token: str) -> dict[str, Any]: monkeypatch.setattr(settings, "oidc_platform_admin_group", "") monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) - assert not await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + assert not await oauth._still_in_admin_group(_admin_grant(), "t") # type: ignore[arg-type] @pytest.mark.parametrize( @@ -672,7 +672,7 @@ async def verify(token: str) -> dict[str, Any]: monkeypatch.setattr(settings, "oidc_platform_admin_group", "admins") monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) with pytest.raises(type(away)): - await oauth._still_in_admin_group(_admin_grant(["platform_admin"]), "t") # type: ignore[arg-type] + await oauth._still_in_admin_group(_admin_grant(), "t") # type: ignore[arg-type] class _RowCH: From 76aada7a2dd2623c67cb5f13f6aa1dc0b5487773 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:28:11 +0530 Subject: [PATCH 17/23] auth: a link page grants the group role only for the group still named The callback now keeps which group matched, not a bool, so a link page finished after the operator changed the setting to another group grants no role, as one finished after clearing it already did. Denied device and connect rows carry no roles, since nothing was minted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/device.py | 2 +- server/auth/oauth.py | 10 +++++++--- tests/unit/test_device_login.py | 11 ++++++----- tests/unit/test_oidc.py | 2 +- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/server/auth/device.py b/server/auth/device.py index 21cc997827d..c7d7d49c65f 100644 --- a/server/auth/device.py +++ b/server/auth/device.py @@ -410,9 +410,9 @@ async def device_approve(request: Request) -> Response: subject={ "client_id": DEVICE_CLIENT_ID, "family": device["family"], - "roles": device["roles"], "requested_from": device["address"], "approved_from": client_address(request), + **({"roles": device["roles"]} if approved else {}), # what the approval minted }, ) if not approved: diff --git a/server/auth/oauth.py b/server/auth/oauth.py index 7c72abc7131..a0005ee0cab 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -756,7 +756,8 @@ async def _finish_oidc_login(request: Request) -> Response: _exchanging.discard(state) # Set here, from the verified ID token, whatever the sealed round trip carried: an account # link finishes from the stored sign-in, without the token. - pending["in_platform_admin_group"] = oidc.in_platform_admin_group(id_claims) + matched = oidc.in_platform_admin_group(id_claims) + pending["matched_admin_group"] = settings.oidc_platform_admin_group if matched else "" upstream = str(tokens.get("refresh_token") or "") # The IdP vouched for this person: only now is the round trip marked used, # so a callback nobody signed in for writes nothing. @@ -846,7 +847,10 @@ async def _signed_in_as( identity[0], pending, upstream, org=identity[1], verified_email=email ): return refused - if pending.get("in_platform_admin_group") and settings.oidc_platform_admin_group: + # The group the callback matched, while it is still the one named: a link page can be + # finished after the operator changed or cleared the setting. + matched = pending.get("matched_admin_group") + if matched and matched == settings.oidc_platform_admin_group: identity = (identity[0], identity[1], identity[2], ["platform_admin"]) if verified_claims is not None: try: @@ -1188,7 +1192,7 @@ async def _decide_connect(f: dict[str, str]) -> Response: subject={ "client_id": pending["client_id"], "redirect_uri": pending["redirect_uri"], - "roles": roles, + **({"roles": roles} if approved else {}), # what the approval minted }, ) if answer is not None: diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index 574f4dd04f9..94450973e73 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -328,6 +328,7 @@ def test_denied_grant_ends_with_access_denied(_world) -> None: _approve(c, grant["user_code"], page, decision="deny") assert _error(_poll(c, grant["device_code"])) == "access_denied" assert [n for n, _ in _world["events"]] == ["auth.device_denied"] + assert "roles" not in _world["events"][0][1]["subject"] # nothing was minted def test_a_replayed_device_code_ends_the_session(_world, monkeypatch) -> None: @@ -741,10 +742,10 @@ async def no_jit(email: str) -> None: assert denied and "ask your" not in str(denied[-1]) # the bare reason, not the page's advice -@pytest.mark.parametrize("cleared", [False, True]) +@pytest.mark.parametrize("named_later", ["loom-admins", "", "other-admins"]) @pytest.mark.parametrize("decision", ["link", "not_mine"]) def test_a_link_page_sign_in_gets_the_group_role_only_while_the_group_is_set( - sso, bobs_password_account, _world, monkeypatch, decision: str, cleared: bool + sso, bobs_password_account, _world, monkeypatch, decision: str, named_later: str ) -> None: # The link page finishes from the stored sign-in, after the ID token is gone. from server.settings import settings @@ -759,8 +760,8 @@ async def jit_account(email: str) -> Any: c = _client() grant = _start(c) page = _sso_round_trip(c, grant["user_code"]) - if cleared: # the operator cleared the setting while the link page was open - monkeypatch.setattr(settings, "oidc_platform_admin_group", "") + # The operator keeps, clears or changes the setting while the link page is open. + monkeypatch.setattr(settings, "oidc_platform_admin_group", named_later) if decision == "link": r = _link(c, page.text, "bobpw") else: @@ -769,7 +770,7 @@ async def jit_account(email: str) -> Any: _approve(c, grant["user_code"], r.text) tokens = _poll(c, grant["device_code"]).json() claims = pyjwt.decode(tokens["access_token"], options={"verify_signature": False}) - want = ["writer"] if cleared else ["platform_admin"] + want = ["platform_admin"] if named_later == "loom-admins" else ["writer"] assert claims["roles"] == want approved = [kw for name, kw in _world["events"] if name == "auth.device_approved"] assert approved[-1]["subject"]["roles"] == want # the log names the admin diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 9cd1380d46d..23822ab3364 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -819,7 +819,7 @@ async def test_the_platform_admin_group_signs_its_members_in_as_platform_admin( monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") pending = {"kind": kind, "nonce": "n", "code_verifier": "v", "state": "s"} if carried: - pending["in_platform_admin_group"] = True # type: ignore[assignment] + pending["matched_admin_group"] = "loom-admins" # type: ignore[assignment] signed_in: dict[str, Any] = {} async def exchange(**_k: Any) -> dict[str, str]: From 41785d36f82a45d904a825dc16b835cc0ffb120a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:45:34 +0530 Subject: [PATCH 18/23] docs(settings): a refresh keeps the group role, it never adds it The setting's description read as if a refresh could grant the role to someone newly in the group; it says now that only sign-in grants it and a refresh keeps it while the group is listed. The connect denial's audit row is pinned to carry no roles, and the back-channel routing test checks routing only, since the rotation test covers the cooldowns. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/configuration.md | 2 +- loom.example.yaml | 5 +++-- schemas/loom-settings.schema.json | 2 +- server/settings/catalog.py | 3 ++- tests/unit/test_device_login.py | 2 ++ tests/unit/test_oidc_backchannel.py | 12 +++++------- 6 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 8fe2397b4a2..1aee6869744 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -101,7 +101,7 @@ Authentication, tokens and identity providers. | `LOOM_OIDC_JIT_PROVISION` | `bool` | `False` | | JIT provisioning: a first OIDC sign-in with no account creates a personal namespace in oidc_jit_org instead of being rejected. Off = fail closed. oidc_jit_email_domains (comma-separated) restricts it; empty admits any verified email the IdP authenticates. | | `LOOM_OIDC_JIT_ORG` | `str` | `''` | | Org that JIT-provisioned accounts are created in; required when `oidc_jit_provision` is on. | | `LOOM_OIDC_JIT_EMAIL_DOMAINS` | `str` | `''` | | Comma-separated email domains JIT provisioning admits; empty admits any verified email. | -| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it. | +| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed ID token still lists it, and never adds it. Empty = no group confers it. | | `LOOM_IDENTITY_PROVIDER_TIMEOUT_S` | `float` | `10.0` | live | Seconds one call to an identity provider may take: OIDC discovery, the token and revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user issuer's JWKS fetch. | | `LOOM_SCIM_TOKEN` | `str` | *(unset)* | | Bearer tokens (comma-separated, any one accepted) an identity provider presents to deactivate and reactivate people over SCIM 2.0 (/scim/v2). Empty = off; needs auth on, oidc. With LOOM_CELL set, at most two entries, named for that cell; only the observed first cell also accepts unnamed tokens. Generate one with `loom cell scim-token new --cell NAME`. Enforced cells also require active provisioning for every nonexempt person. | | `LOOM_JWT_SECRET` | `str` | *(set)* | | The root secret, and the one secret a deployment carries: it signs tokens as kid `default` and seals every stored credential and every signing key in loom.signing_keys (`loom signing-key rotate` adds those). Required when auth is on. The default is the checked-in DEV secret anyone can mint with: a deployment with auth on refuses to start with it, except the `make dev` stack (`loom doctor` warns everywhere else). A non-loopback bind refuses an HMAC secret under 32 bytes or an RSA key under 2048 bits. | diff --git a/loom.example.yaml b/loom.example.yaml index ad66eec1360..9ac678d1a66 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -741,8 +741,9 @@ settings: # oidc_jit_email_domains: "" # An IdP group whose members sign in as platform_admin, matched exactly in the - # verified ID token's `groups` claim at sign-in and every refresh. Empty = no group - # confers it. [restart] + # verified ID token's `groups` claim at sign-in; a refresh keeps the role only while + # the refreshed ID token still lists it, and never adds it. Empty = no group confers + # it. [restart] # oidc_platform_admin_group: "" # Seconds one call to an identity provider may take: OIDC discovery, the token and diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index a5c99d249c2..b1a82b6470d 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6114,7 +6114,7 @@ "oidc_platform_admin_group": { "default": "", "type": "string", - "description": "An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it." + "description": "An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed ID token still lists it, and never adds it. Empty = no group confers it." }, "openai_base_url": { "default": "https://api.openai.com/v1", diff --git a/server/settings/catalog.py b/server/settings/catalog.py index b55ffac50f8..f8bd9ad04c5 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -270,7 +270,8 @@ def _check_default_namespace(self) -> AuthSettings: # Comma-separated email domains JIT provisioning admits; empty admits any verified email. oidc_jit_email_domains: str = "" # An IdP group whose members sign in as platform_admin, matched exactly in the verified - # ID token's `groups` claim at sign-in and every refresh. Empty = no group confers it. + # ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed + # ID token still lists it, and never adds it. Empty = no group confers it. oidc_platform_admin_group: str = "" # Seconds one call to an identity provider may take: OIDC discovery, the token and # revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user diff --git a/tests/unit/test_device_login.py b/tests/unit/test_device_login.py index 94450973e73..f5134883813 100644 --- a/tests/unit/test_device_login.py +++ b/tests/unit/test_device_login.py @@ -1171,6 +1171,8 @@ def test_denying_mcp_connect_sends_the_client_an_error(sso, _world) -> None: follow_redirects=False, ) assert "error=access_denied" in r.headers["location"] and not _world["store"].records("code") + denied = [kw for name, kw in _world["events"] if name == "auth.connect_denied"] + assert "roles" not in denied[-1]["subject"] # nothing was minted async def test_logout_survives_an_unreachable_identity_provider(monkeypatch) -> None: diff --git a/tests/unit/test_oidc_backchannel.py b/tests/unit/test_oidc_backchannel.py index f2596f21432..ec1a7054c40 100644 --- a/tests/unit/test_oidc_backchannel.py +++ b/tests/unit/test_oidc_backchannel.py @@ -254,13 +254,11 @@ def test_a_signing_key_fetch_follows_no_redirect(key_server: str) -> None: def test_a_bot_trusts_keys_never_go_through_the_base(monkeypatch) -> None: """A trust's https `jwks_uri` on the issuer's host is fetched from that address, never over the base: only the sign-in's own keys are rerouted.""" - built: list[tuple[str, dict[str, str], float]] = [] + built: list[tuple[str, dict[str, str]]] = [] class _Client: - def __init__( - self, uri: str, *, timeout: float, headers: dict[str, str], cooldown_duration: float - ) -> None: - built.append((uri, headers, cooldown_duration)) + def __init__(self, uri: str, *, timeout: float, headers: dict[str, str], **_: Any) -> None: + built.append((uri, headers)) def get_signing_key_from_jwt(self, token: str) -> Any: return type("K", (), {"key": "k"})() @@ -269,6 +267,6 @@ def get_signing_key_from_jwt(self, token: str) -> Any: oidc.signing_key(f"{_ISS}/jwks.json", "t") # as `machines` asks for a trust's keys oidc.signing_key(f"{_ISS}/jwks.json", "t", sign_in=True) assert built == [ - (f"{_ISS}/jwks.json", {}, 30), # a caller picks a trust token's key id: PyJWT's cooldown - (f"{_BASE}/oauth/jwks.json", {"Host": "idp.example"}, 0), + (f"{_ISS}/jwks.json", {}), + (f"{_BASE}/oauth/jwks.json", {"Host": "idp.example"}), ] From 830c9ae1505135bc06ced6e87e33733e9228e17e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:06:55 +0530 Subject: [PATCH 19/23] auth: treat a key set that is not JSON as a provider outage PyJWT wraps a failed fetch but not a body it cannot parse, so a proxy's error page demoted a group-conferred platform admin instead of answering 503. Bot trusts now share the same outage errors, so a reset while reading their keys refuses as unavailable too. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/configuration.md | 2 +- loom.example.yaml | 7 +++---- schemas/loom-settings.schema.json | 2 +- server/auth/machines.py | 2 +- server/auth/oidc.py | 7 ++++++- server/settings/catalog.py | 5 ++--- tests/unit/test_machines.py | 7 +++++-- tests/unit/test_oidc.py | 17 +++++++++++++++++ 8 files changed, 36 insertions(+), 13 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 1aee6869744..9b207c1ce63 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -101,7 +101,7 @@ Authentication, tokens and identity providers. | `LOOM_OIDC_JIT_PROVISION` | `bool` | `False` | | JIT provisioning: a first OIDC sign-in with no account creates a personal namespace in oidc_jit_org instead of being rejected. Off = fail closed. oidc_jit_email_domains (comma-separated) restricts it; empty admits any verified email the IdP authenticates. | | `LOOM_OIDC_JIT_ORG` | `str` | `''` | | Org that JIT-provisioned accounts are created in; required when `oidc_jit_provision` is on. | | `LOOM_OIDC_JIT_EMAIL_DOMAINS` | `str` | `''` | | Comma-separated email domains JIT provisioning admits; empty admits any verified email. | -| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed ID token still lists it, and never adds it. Empty = no group confers it. | +| `LOOM_OIDC_PLATFORM_ADMIN_GROUP` | `str` | `''` | | An IdP group whose members sign in as platform_admin (an exact `groups` entry in the verified ID token); a refresh keeps the role while listed, never adds it. Empty = none. | | `LOOM_IDENTITY_PROVIDER_TIMEOUT_S` | `float` | `10.0` | live | Seconds one call to an identity provider may take: OIDC discovery, the token and revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user issuer's JWKS fetch. | | `LOOM_SCIM_TOKEN` | `str` | *(unset)* | | Bearer tokens (comma-separated, any one accepted) an identity provider presents to deactivate and reactivate people over SCIM 2.0 (/scim/v2). Empty = off; needs auth on, oidc. With LOOM_CELL set, at most two entries, named for that cell; only the observed first cell also accepts unnamed tokens. Generate one with `loom cell scim-token new --cell NAME`. Enforced cells also require active provisioning for every nonexempt person. | | `LOOM_JWT_SECRET` | `str` | *(set)* | | The root secret, and the one secret a deployment carries: it signs tokens as kid `default` and seals every stored credential and every signing key in loom.signing_keys (`loom signing-key rotate` adds those). Required when auth is on. The default is the checked-in DEV secret anyone can mint with: a deployment with auth on refuses to start with it, except the `make dev` stack (`loom doctor` warns everywhere else). A non-loopback bind refuses an HMAC secret under 32 bytes or an RSA key under 2048 bits. | diff --git a/loom.example.yaml b/loom.example.yaml index 9ac678d1a66..b10d33326bd 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -740,10 +740,9 @@ settings: # email. [restart] # oidc_jit_email_domains: "" - # An IdP group whose members sign in as platform_admin, matched exactly in the - # verified ID token's `groups` claim at sign-in; a refresh keeps the role only while - # the refreshed ID token still lists it, and never adds it. Empty = no group confers - # it. [restart] + # An IdP group whose members sign in as platform_admin (an exact `groups` entry in the + # verified ID token); a refresh keeps the role while listed, never adds it. Empty = + # none. [restart] # oidc_platform_admin_group: "" # Seconds one call to an identity provider may take: OIDC discovery, the token and diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index b1a82b6470d..19bcbe49b04 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6114,7 +6114,7 @@ "oidc_platform_admin_group": { "default": "", "type": "string", - "description": "An IdP group whose members sign in as platform_admin, matched exactly in the verified ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed ID token still lists it, and never adds it. Empty = no group confers it." + "description": "An IdP group whose members sign in as platform_admin (an exact `groups` entry in the verified ID token); a refresh keeps the role while listed, never adds it. Empty = none." }, "openai_base_url": { "default": "https://api.openai.com/v1", diff --git a/server/auth/machines.py b/server/auth/machines.py index f89609d0088..93bd2c7e8db 100644 --- a/server/auth/machines.py +++ b/server/auth/machines.py @@ -394,7 +394,7 @@ async def _signed(token: str, m: Machine) -> dict[str, Any]: options={"require": ["exp", "iat", "iss", "aud", "sub"]}, leeway=_LEEWAY_S, ) - except (httpx.HTTPError, jwt.PyJWKClientConnectionError, _Undiscovered) as e: + except (*oidc.PROVIDER_AWAY, _Undiscovered) as e: # The answer is unauthenticated: the keys' URL and the network error are logged. log.warning( "workload token: the issuer's keys could not be read: %s: %s", type(e).__name__, e diff --git a/server/auth/oidc.py b/server/auth/oidc.py index f1ede177d40..b283ecb9114 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -21,6 +21,7 @@ from __future__ import annotations import asyncio +import json import logging import secrets import time @@ -259,7 +260,11 @@ def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: timeout=settings.identity_provider_timeout_s, cooldown_duration=0 if sign_in else 30, # 30: PyJWT's own ) - return client.get_signing_key_from_jwt(id_token).key + try: + return client.get_signing_key_from_jwt(id_token).key + except json.JSONDecodeError as e: # a key set cut short, or a proxy's page: the token's + # own header errors come out as jwt.DecodeError, so only the fetch raises this + raise jwt.PyJWKClientConnectionError(f"the key set is not JSON: {e}") from e def id_token_algorithms(doc: dict[str, Any]) -> list[str]: diff --git a/server/settings/catalog.py b/server/settings/catalog.py index f8bd9ad04c5..20992b4bd11 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -269,9 +269,8 @@ def _check_default_namespace(self) -> AuthSettings: oidc_jit_org: str = "" # Comma-separated email domains JIT provisioning admits; empty admits any verified email. oidc_jit_email_domains: str = "" - # An IdP group whose members sign in as platform_admin, matched exactly in the verified - # ID token's `groups` claim at sign-in; a refresh keeps the role only while the refreshed - # ID token still lists it, and never adds it. Empty = no group confers it. + # An IdP group whose members sign in as platform_admin (an exact `groups` entry in the + # verified ID token); a refresh keeps the role while listed, never adds it. Empty = none. oidc_platform_admin_group: str = "" # Seconds one call to an identity provider may take: OIDC discovery, the token and # revocation endpoints, its signing keys, a machine issuer's discovery, and an end-user diff --git a/tests/unit/test_machines.py b/tests/unit/test_machines.py index 690fb5f6efa..ea30a6ba13d 100644 --- a/tests/unit/test_machines.py +++ b/tests/unit/test_machines.py @@ -634,11 +634,14 @@ def signing_key(uri: str, token: str) -> Any: assert r.status_code == 200 and fetched == ["https://keys.example/jwks.json"] -def test_unreadable_keys_refuse_without_naming_their_address(bots, monkeypatch) -> None: +@pytest.mark.parametrize("raw", [False, True]) +def test_unreadable_keys_refuse_without_naming_their_address(bots, monkeypatch, raw) -> None: """`/oauth/token` answers without a token: the keys' URL and the network error - are logged, never quoted.""" + are logged, never quoted. A reset while PyJWT reads the body is not wrapped.""" def signing_key(uri: str, token: str) -> Any: + if raw: + raise ConnectionResetError(f"{uri} reset (10.0.0.7:8443)") raise pyjwt.PyJWKClientConnectionError( f"Fail to fetch data from the url, err: {uri} refused (10.0.0.7:8443)" ) diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 23822ab3364..6d8c29d2abc 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -226,6 +226,23 @@ def token(key: Any, kid: str) -> str: oidc.signing_key(f"{_ISS}/jwks", token(rotated, "k2")) +def test_a_key_set_that_is_not_json_is_an_outage(monkeypatch) -> None: + # A body cut short, or a proxy's page: PyJWT does not wrap the parse error. + class _Endpoint: + def __init__(self, *_handlers: Any) -> None: + pass + + def open(self, _request: Any, timeout: float) -> io.BytesIO: + return io.BytesIO(b"bad gateway") + + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + token = pyjwt.encode({"sub": "s"}, key, algorithm="RS256", headers={"kid": "k1"}) + monkeypatch.setattr(oidc, "_jwk_clients", {}) + monkeypatch.setattr(urllib.request, "build_opener", _Endpoint) + with pytest.raises(pyjwt.PyJWKClientConnectionError): + oidc.signing_key(f"{_ISS}/jwks", token, sign_in=True) + + @pytest.mark.parametrize( ("group", "listed", "asked"), [ From 4c43e0bbcdfa3a86a5500884cd0cb4cbf7d8aba7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:26:29 +0530 Subject: [PATCH 20/23] auth: treat a key set that is not UTF-8 as a provider outage too json.load decodes the body before it parses it, so a Latin-1 or compressed proxy page raised UnicodeDecodeError past the outage check. The callback test now reads the roles back from the token the dashboard receives. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/oidc.py | 5 +++-- tests/unit/test_oidc.py | 23 +++++++++++++---------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/server/auth/oidc.py b/server/auth/oidc.py index b283ecb9114..1e1f0899eb7 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -262,8 +262,9 @@ def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: ) try: return client.get_signing_key_from_jwt(id_token).key - except json.JSONDecodeError as e: # a key set cut short, or a proxy's page: the token's - # own header errors come out as jwt.DecodeError, so only the fetch raises this + # A key set cut short or a proxy's page; only the fetch raises these, since the token's + # own header errors come out as jwt.DecodeError. + except (json.JSONDecodeError, UnicodeDecodeError) as e: raise jwt.PyJWKClientConnectionError(f"the key set is not JSON: {e}") from e diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 6d8c29d2abc..013fc5dcdf8 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -30,6 +30,7 @@ sys.path.insert(0, str(ROOT)) from server.auth import jit, login, oauth, oidc, revocation, self_signup, sso_links # noqa: E402 +from server.auth.jwt import verify_token # noqa: E402 from server.core.secrets_at_rest import unseal # noqa: E402 from server.settings import settings # noqa: E402 @@ -226,14 +227,15 @@ def token(key: Any, kid: str) -> str: oidc.signing_key(f"{_ISS}/jwks", token(rotated, "k2")) -def test_a_key_set_that_is_not_json_is_an_outage(monkeypatch) -> None: - # A body cut short, or a proxy's page: PyJWT does not wrap the parse error. +@pytest.mark.parametrize("body", [b"bad gateway", "é".encode("latin-1")]) +def test_a_key_set_that_is_not_json_is_an_outage(monkeypatch, body: bytes) -> None: + # A body cut short, or a proxy's page: PyJWT does not wrap the parse or decode error. class _Endpoint: def __init__(self, *_handlers: Any) -> None: pass def open(self, _request: Any, timeout: float) -> io.BytesIO: - return io.BytesIO(b"bad gateway") + return io.BytesIO(body) key = rsa.generate_private_key(public_exponent=65537, key_size=2048) token = pyjwt.encode({"sub": "s"}, key, algorithm="RS256", headers={"kid": "k1"}) @@ -848,12 +850,9 @@ async def claims(*_a: Any, **_k: Any) -> dict[str, Any]: async def account(*_a: Any) -> login.Identity: return ("bob", "acme", ["bob"], ["writer"]) - async def dashboard(identity: login.Identity, *_a: Any, **_k: Any) -> Response: - signed_in["roles"] = identity[3] - return Response(status_code=302) - async def connect(_p: Any, identity: login.Identity, *_a: Any, **_k: Any) -> Response: - return await dashboard(identity) # the identity the consent page stores for the code + signed_in["roles"] = identity[3] # the identity the consent page stores for the code + return Response(status_code=302) class _Req: client = None @@ -866,11 +865,15 @@ class _Req: monkeypatch.setattr(oidc, "exchange_code", exchange) monkeypatch.setattr(oidc, "verify_id_token", claims) monkeypatch.setattr(oauth, "_account_for", account) - monkeypatch.setattr(oauth, "_dashboard_signed_in", dashboard) monkeypatch.setattr(oauth, "_connect_consent", connect) monkeypatch.setattr(oauth.scim, "refuses_subject", AsyncMock(return_value=False)) monkeypatch.setattr(oauth.sso_links, "attest_domain", AsyncMock()) - assert (await oauth.oidc_callback(_Req())).status_code == 302 # type: ignore[arg-type] + monkeypatch.setattr(oauth.audit, "emit", AsyncMock()) + resp = await oauth.oidc_callback(_Req()) # type: ignore[arg-type] + assert resp.status_code == 302 + if kind == "dashboard": # the token delivered at /me + token = verify_token(resp.headers["location"].split("#token=")[1]) + signed_in["roles"] = [r.name.lower() for r in token.roles] assert signed_in["roles"] == want From b44b1cef60b87ff6f82064f48ca87c9f129e06ba Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:42:28 +0530 Subject: [PATCH 21/23] auth: name the group check's key outage in the refresh retry comment Also runs the not-JSON key set case against a bot trust's key client. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/auth/oauth.py | 4 +++- tests/unit/test_oidc.py | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/server/auth/oauth.py b/server/auth/oauth.py index a0005ee0cab..defea82feb3 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -1516,7 +1516,9 @@ async def _refresh_token_grant(f: dict[str, str]) -> dict[str, Any]: except asyncio.CancelledError: # cancelled at shutdown: the token is the client's again await put_back(store.save_refresh(refresh_token, grant)) raise - except Exception as e: # Loom's own failure (or too slow): unspend the token for the retry + # Loom's own failure, too slow, or the provider's keys away at the platform-admin group + # check (`oidc.PROVIDER_AWAY`): unspend the token for the retry. + except Exception as e: log.warning("oauth: refreshing a session failed: %r", e) await put_back(store.save_refresh(refresh_token, grant)) # with the IdP token it rotated raise _unavailable() from e diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 013fc5dcdf8..3b13be96d46 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -227,8 +227,9 @@ def token(key: Any, kid: str) -> str: oidc.signing_key(f"{_ISS}/jwks", token(rotated, "k2")) +@pytest.mark.parametrize("sign_in", [True, False]) # False: a bot trust's keys @pytest.mark.parametrize("body", [b"bad gateway", "é".encode("latin-1")]) -def test_a_key_set_that_is_not_json_is_an_outage(monkeypatch, body: bytes) -> None: +def test_a_key_set_that_is_not_json_is_an_outage(monkeypatch, body: bytes, sign_in: bool) -> None: # A body cut short, or a proxy's page: PyJWT does not wrap the parse or decode error. class _Endpoint: def __init__(self, *_handlers: Any) -> None: @@ -242,7 +243,7 @@ def open(self, _request: Any, timeout: float) -> io.BytesIO: monkeypatch.setattr(oidc, "_jwk_clients", {}) monkeypatch.setattr(urllib.request, "build_opener", _Endpoint) with pytest.raises(pyjwt.PyJWKClientConnectionError): - oidc.signing_key(f"{_ISS}/jwks", token, sign_in=True) + oidc.signing_key(f"{_ISS}/jwks", token, sign_in=sign_in) @pytest.mark.parametrize( From f314e73d6a2300908b25f7c00fac907e9dcd21ad Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:03:51 +0530 Subject: [PATCH 22/23] docs: keep the platform-admin group small, since the role spans every org Also names both cases of two parametrized tests. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 5 +++-- tests/unit/test_oauth.py | 2 +- tests/unit/test_oidc.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index 2497b725a53..a08ca74fb7f 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -161,8 +161,9 @@ their verified ID token's `groups` claim holds the group LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin ``` -Loom matches the name exactly as the provider sends it, so pick a group only -the provider's administrators can create and fill: on a provider that lets +A platform admin administers every org, so keep the group to as few people as +you can. Loom matches the name exactly as the provider sends it, so pick a +group only the provider's administrators can create and fill: on a provider that lets members create groups, any member who creates one of that name signs in as a platform admin. The Okta step above and the Keycloak note below name their cases. diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index 6bea1f7822e..bcdd97110dc 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -504,7 +504,7 @@ async def listed(grant: dict[str, Any], id_token: str) -> bool: @pytest.mark.parametrize(("listed", "status"), [(True, 200), (False, 503)]) -def test_a_listed_platform_admin_refreshes_while_the_providers_keys_are_away( +def test_while_the_providers_keys_are_away_a_listed_admin_refreshes_and_a_group_admin_retries( monkeypatch: pytest.MonkeyPatch, listed: bool, status: int ) -> None: # LOOM_PLATFORM_ADMINS keeps the role, so the group check, which needs the keys, never diff --git a/tests/unit/test_oidc.py b/tests/unit/test_oidc.py index 3b13be96d46..ce129819cf6 100644 --- a/tests/unit/test_oidc.py +++ b/tests/unit/test_oidc.py @@ -189,7 +189,7 @@ async def test_a_refreshed_id_token_is_verified_but_for_the_nonce( @pytest.mark.parametrize("sign_in", [True, False]) -def test_a_sign_in_key_rotated_in_since_the_last_fetch_is_fetched_at_once( +def test_a_rotated_in_key_is_fetched_at_once_at_sign_in_while_a_bot_trust_keeps_the_cooldown( monkeypatch, sign_in: bool ) -> None: # Sign-in's ID tokens come from Loom's own token request, so no caller picks their key From df48e8bab30d2345f5f5741c309b34e9dd309b7e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:22:40 +0530 Subject: [PATCH 23/23] auth: name only the error type when wrapping a key set that is not JSON The exception-text ratchet counts a formatted exception outside a log call; the cause is chained already. Also puts the refresh's broad-except reason back on its line, reflows two lines, and proves a cleared group setting never reads the refreshed ID token. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/sso.md | 8 ++++---- server/auth/oauth.py | 8 +++----- server/auth/oidc.py | 2 +- tests/unit/test_oauth.py | 6 +++++- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/operations/sso.md b/docs/operations/sso.md index a08ca74fb7f..30ffa2fbd86 100644 --- a/docs/operations/sso.md +++ b/docs/operations/sso.md @@ -163,10 +163,10 @@ LOOM_OIDC_PLATFORM_ADMIN_GROUP=loom-platform-admin A platform admin administers every org, so keep the group to as few people as you can. Loom matches the name exactly as the provider sends it, so pick a -group only the provider's administrators can create and fill: on a provider that lets -members create groups, any member who creates one of that name signs in as a -platform admin. The Okta step above and the Keycloak note below name their -cases. +group only the provider's administrators can create and fill: on a provider +that lets members create groups, any member who creates one of that name signs +in as a platform admin. The Okta step above and the Keycloak note below name +their cases. Loom does not keep the group's members, but each sign-in's audit row (`auth.sso_signin`, `auth.device_approved`, `auth.connect_approved`) carries diff --git a/server/auth/oauth.py b/server/auth/oauth.py index defea82feb3..0ec8936fa92 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -6,8 +6,8 @@ `LOOM_OAUTH_ENABLED=true`. Loom issues its own JWTs; under `LOOM_OAUTH_LOGIN_PROVIDER=oidc` the IdP authenticates the person (oidc.py), and members of one of its groups (`LOOM_OIDC_PLATFORM_ADMIN_GROUP`) sign in as -platform_admin. State lives in oauth_store.py. The flows, sessions and threat model are in -docs/architecture/security.md ("OIDC and OAuth"). +platform_admin. State lives in oauth_store.py. The flows, sessions and threat +model are in docs/architecture/security.md ("OIDC and OAuth"). """ from __future__ import annotations @@ -1516,9 +1516,7 @@ async def _refresh_token_grant(f: dict[str, str]) -> dict[str, Any]: except asyncio.CancelledError: # cancelled at shutdown: the token is the client's again await put_back(store.save_refresh(refresh_token, grant)) raise - # Loom's own failure, too slow, or the provider's keys away at the platform-admin group - # check (`oidc.PROVIDER_AWAY`): unspend the token for the retry. - except Exception as e: + except Exception as e: # Loom's failure, too slow, or the group check's provider away: retry log.warning("oauth: refreshing a session failed: %r", e) await put_back(store.save_refresh(refresh_token, grant)) # with the IdP token it rotated raise _unavailable() from e diff --git a/server/auth/oidc.py b/server/auth/oidc.py index 1e1f0899eb7..9da7a7993d9 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -265,7 +265,7 @@ def signing_key(jwks_uri: str, id_token: str, *, sign_in: bool = False) -> Any: # A key set cut short or a proxy's page; only the fetch raises these, since the token's # own header errors come out as jwt.DecodeError. except (json.JSONDecodeError, UnicodeDecodeError) as e: - raise jwt.PyJWKClientConnectionError(f"the key set is not JSON: {e}") from e + raise jwt.PyJWKClientConnectionError(f"the key set is not JSON: {type(e).__name__}") from e def id_token_algorithms(doc: dict[str, Any]) -> list[str]: diff --git a/tests/unit/test_oauth.py b/tests/unit/test_oauth.py index bcdd97110dc..98fbaff18c0 100644 --- a/tests/unit/test_oauth.py +++ b/tests/unit/test_oauth.py @@ -593,7 +593,7 @@ def _admin_grant(email: str = "ada@example.com") -> dict[str, Any]: ), ], ) -async def test_still_in_admin_group_fails_closed( +async def test_still_in_admin_group_answers_yes_only_for_a_verified_same_email_listing( monkeypatch: pytest.MonkeyPatch, grant: dict[str, Any], id_token: str, @@ -643,12 +643,16 @@ async def test_a_cleared_group_ends_the_role_at_the_next_refresh( from server.auth import oidc from server.settings import settings + verified: list[str] = [] + async def verify(token: str) -> dict[str, Any]: + verified.append(token) return {"email": "ada@example.com", "email_verified": True, "groups": ["admins"]} monkeypatch.setattr(settings, "oidc_platform_admin_group", "") monkeypatch.setattr(oidc, "verify_id_token_without_nonce", verify) assert not await oauth._still_in_admin_group(_admin_grant(), "t") # type: ignore[arg-type] + assert verified == [] # the ID token is not even read @pytest.mark.parametrize(