diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 2299dadb8b..180a1b4040 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -246,10 +246,19 @@ Each op declares `required_role`. 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 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 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. 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 @@ -303,9 +312,10 @@ 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 -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`, +`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`, `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 @@ -583,7 +593,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. @@ -653,7 +664,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 3c441a44e1..cbe330d93f 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -137,18 +137,19 @@ 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 -(`viewer`) and maintainers (`admin`) and no `writer`. +`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/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md index 74aa988bfa..3c9f34e25e 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 1aaabb0e94..e353012184 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` 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) @@ -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 1dca93dd08..45aa7f74b5 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 only `LOOM_PLATFORM_ADMINS` grants -([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 5720c18859..30ffa2fbd8 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 @@ -24,7 +25,13 @@ 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)). 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 LOOM_OAUTH_LOGIN_PROVIDER=oidc @@ -35,22 +42,27 @@ 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 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. -- 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. -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 +150,42 @@ 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 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 +``` + +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. + +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 +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, 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 @@ -892,6 +938,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 @@ -933,7 +986,18 @@ 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. -- **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/`. + 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 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. 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/docs/reference/configuration.md b/docs/reference/configuration.md index 266815d77d..9b207c1ce6 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` 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. | @@ -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 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. | @@ -125,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/docs/reference/mcp.md b/docs/reference/mcp.md index d6a0a73c24..4c0a94de20 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -209,8 +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`, 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/frontend/src/views/admin/Users.tsx b/frontend/src/views/admin/Users.tsx index 34ca28cdc6..085ffeb933 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 does not record who is in that group, so they carry no badge here.
)} diff --git a/loom.example.yaml b/loom.example.yaml index ffb7b922b6..b10d33326b 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` also confers the role. [restart] # platform_admins: "" # True: every operation requires a valid bearer JWT. False (laptop demos only): @@ -740,6 +740,11 @@ settings: # email. [restart] # oidc_jit_email_domains: "" + # 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 # revocation endpoints, its signing keys, a machine issuer's discovery, and an # end-user issuer's JWKS fetch. [live] @@ -825,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/pyproject.toml b/pyproject.toml index 08f4b9dd1f..6aa25cdaef 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.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/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 483984c3f5..19bcbe49b0 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, @@ -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 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", "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` also confers the role." }, "policy_cache_ttl_seconds": { "default": 30, diff --git a/server/auth/device.py b/server/auth/device.py index 519571aa00..c7d7d49c65 100644 --- a/server/auth/device.py +++ b/server/auth/device.py @@ -412,6 +412,7 @@ async def device_approve(request: Request) -> Response: "family": device["family"], "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/machines.py b/server/auth/machines.py index f89609d008..93bd2c7e8d 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/oauth.py b/server/auth/oauth.py index 1a8c8103ee..0ec8936fa9 100644 --- a/server/auth/oauth.py +++ b/server/auth/oauth.py @@ -4,9 +4,10 @@ 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 -lives in oauth_store.py. The flows, sessions and threat model are in -docs/architecture/security.md ("OIDC and OAuth"). +`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"). """ from __future__ import annotations @@ -50,6 +51,7 @@ from server.settings import settings if TYPE_CHECKING: + from server.auth import oidc from server.auth.login import Identity log = logging.getLogger(__name__) @@ -671,9 +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 keys away once the code is spent raise _Spent: a reload cannot finish.""" - import jwt - + Its discovery or keys away once the code is spent raise _Spent: a reload + cannot finish.""" from server.auth import oidc try: @@ -703,8 +704,8 @@ 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: - log.warning("oidc callback: the identity provider's keys are away: %s", 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 except Exception as e: # any other verify failure refuses the login (re-raised) @@ -753,6 +754,10 @@ 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. + 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. @@ -842,6 +847,11 @@ async def _signed_in_as( identity[0], pending, upstream, org=identity[1], verified_email=email ): return refused + # 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: await sso_links.attest_domain(email, identity[1], identity[0], verified_claims) @@ -1179,7 +1189,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 approved else {}), # what the approval minted + }, ) if answer is not None: return answer @@ -1420,10 +1434,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"]: @@ -1502,7 +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 - except Exception as e: # Loom's own failure (or too slow): unspend the token for the retry + 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 @@ -1522,8 +1536,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") + id_token = "" if settings.oauth_login_provider == "oidc": - grant["upstream_refresh"] = await _ask_identity_provider(grant, refresh_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") @@ -1534,6 +1549,12 @@ 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() + # Asked only when LOOM_PLATFORM_ADMINS did not keep the role, of a session that held it. + 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"], @@ -1542,6 +1563,30 @@ 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`. 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 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.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__) + return False + 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: 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 925e48f7be..9da7a7993d 100644 --- a/server/auth/oidc.py +++ b/server/auth/oidc.py @@ -21,10 +21,11 @@ from __future__ import annotations import asyncio +import json import logging import secrets import time -from typing import Any +from typing import Any, NamedTuple from urllib.parse import urlencode, urlsplit, urlunsplit import httpx @@ -91,7 +92,8 @@ async def _discover() -> dict[str, Any]: # 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. +# server is still answering. A platform-admin group check's key fetch runs +# after it, under `oauth._REFRESH_DEADLINE_S`. _REFRESH_DEADLINE_S = 20 @@ -110,12 +112,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, @@ -166,9 +173,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 +194,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: @@ -226,15 +241,31 @@ 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 URLError, TimeoutError and http.client's +# errors, so a reset or TLS error while it reads the body comes through raw. +PROVIDER_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 + try: + return client.get_signing_key_from_jwt(id_token).key + # 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: {type(e).__name__}") from e def id_token_algorithms(doc: dict[str, Any]) -> list[str]: @@ -254,6 +285,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 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_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() algorithms = id_token_algorithms(doc) key = await asyncio.to_thread(signing_key, doc["jwks_uri"], id_token, sign_in=True) @@ -263,13 +305,20 @@ async def verify_id_token(id_token: str, *, nonce: 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"]}, ) - 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 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 f5314b8345..20992b4bd1 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` + # also confers the role. platform_admins: str = "" @property @@ -268,6 +269,9 @@ 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 (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 # issuer's JWKS fetch. @@ -410,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/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 6a9bed5912..c3c7c984a8 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_call_site_knobs.py b/tests/unit/test_call_site_knobs.py index 8be53c26c5..a737992427 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_device_login.py b/tests/unit/test_device_login.py index 7c5eeb0b71..f513488381 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: @@ -544,17 +545,18 @@ 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: 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 @@ -740,6 +742,40 @@ 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("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, named_later: 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"]) + # 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: + 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}) + 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 + + 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 @@ -1092,6 +1128,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: @@ -1117,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_machines.py b/tests/unit/test_machines.py index 690fb5f6ef..ea30a6ba13 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_oauth.py b/tests/unit/test_oauth.py index 52f148c9d2..98fbaff18c 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 @@ -395,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={ @@ -445,6 +449,236 @@ 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 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_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 + # 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 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") + + async def keys_away(token: str) -> dict[str, Any]: + raise jwt.PyJWKClientConnectionError("keys") + + c = _client() + 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", re_derived) + monkeypatch.setattr(oauth, "_ask_identity_provider", upstream) + monkeypatch.setattr(oidc, "verify_id_token_without_nonce", keys_away) + r = _refresh(c, rt) + 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( + 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(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(), "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(), + "t", + {"groups": ["admins"], "email_verified": False}, + False, + ), + ], +) +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, + 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_id_token_without_nonce", verify) + 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_id_token_without_nonce", verify) + 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( + monkeypatch: pytest.MonkeyPatch, +) -> None: + 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( + "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 +) -> 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_id_token_without_nonce", verify) + with pytest.raises(type(away)): + await oauth._still_in_admin_group(_admin_grant(), "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 942302ce95..ce129819cf 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 @@ -28,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 @@ -87,7 +90,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: @@ -125,10 +128,19 @@ 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) - 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") @@ -144,6 +156,124 @@ async def test_verify_id_token_rejects_wrong_signer(_signing_key, monkeypatch) - ) # ...token signed by `other` +@pytest.mark.parametrize( + ("overrides", "when", "accepted"), + [ + ({}, "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], when: str, accepted: bool +) -> None: + priv, pub = _signing_key + _inject(monkeypatch, pub) + 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_id_token_without_nonce(token))["email"] == "user@example.com" + else: + with pytest.raises(pyjwt.PyJWTError): + await oidc.verify_id_token_without_nonce(token) + + +@pytest.mark.parametrize("sign_in", [True, False]) +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 + # 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 range(2) + ) + 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("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, 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: + pass + + def open(self, _request: Any, timeout: float) -> io.BytesIO: + 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"}) + 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=sign_in) + + +@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 = [ @@ -663,7 +793,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) @@ -684,3 +816,68 @@ class _Req: "someone", # the identity resolver's owner, not the JIT account name {"email": "bob@acme.com", "email_verified": True}, ) + + +@pytest.mark.parametrize("kind", ["dashboard", "mcp"]) +@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], kind: str +) -> None: + from unittest.mock import AsyncMock + + from fastapi import Response + + monkeypatch.setattr(settings, "oidc_platform_admin_group", "loom-admins") + pending = {"kind": kind, "nonce": "n", "code_verifier": "v", "state": "s"} + if carried: + pending["matched_admin_group"] = "loom-admins" # 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 connect(_p: Any, identity: login.Identity, *_a: Any, **_k: Any) -> Response: + signed_in["roles"] = identity[3] # the identity the consent page stores for the code + 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": int(time.time()) + 600}) + } + + 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, "_connect_consent", connect) + monkeypatch.setattr(oauth.scim, "refuses_subject", AsyncMock(return_value=False)) + monkeypatch.setattr(oauth.sso_links, "attest_domain", AsyncMock()) + 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 + + +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 0e42696def..ec1a7054c4 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") == "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 == [ @@ -255,7 +257,7 @@ def test_a_bot_trusts_keys_never_go_through_the_base(monkeypatch) -> None: built: list[tuple[str, dict[str, str]]] = [] class _Client: - 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: built.append((uri, headers)) def get_signing_key_from_jwt(self, token: str) -> Any: diff --git a/tests/unit/test_oidc_hardening.py b/tests/unit/test_oidc_hardening.py index 2b289c4ab3..031624cb95 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 @@ -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: diff --git a/tests/unit/test_scim_sessions.py b/tests/unit/test_scim_sessions.py index 3b1d741ae7..e64e29273f 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()) diff --git a/uv.lock b/uv.lock index 9181e25e3c..e7c28b822f 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.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" },