Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
update docs
Thiago Araujo da Silva912665f2ab29
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 9efada9f79..ac8ddc8efc 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -173,185 +173,8 @@ Auth extraction happens in `src/server/plugins/auth/`:- **JWT** — user browser sessions (decoded from `Authorization: Bearer` header)- **IDENTITY_ACCESS_TOKEN** — machine-to-machine identity tokens- **SCIM_TOKEN** — SCIM provisioning tokens-- **OAUTH**: delegated user tokens from the `oauth-client` module. Same JWT shape and session binding as- `JWT`, told apart by an `oauthClientId` claim. Opt-in per route: `verify-auth.ts` rejects them anywhere- that doesn't list `AuthMode.OAUTH`, because a route authenticating on bare `userId` never builds the- permission that enforces delegation. Most `AuthMode.JWT` routes now list `AuthMode.OAUTH` too. The- exceptions, none of which can be scope-narrowed, stay first-party only:- - account self-management (user, password, MFA, sessions, login, signup, notifications, announcements)- - super-admin routes (`v1/admin-router.ts`, `ee/v1/rate-limit-router.ts`), gated by `verifySuperAdmin`,- which reads `user.superAdmin` rather than a CASL ability- - OAuth client CRUD + consent (`v1/oauth-router.ts`), `ee/v1/assume-privilege-router.ts`, and- `POST /v1/organization-admin/projects/:projectId/grant-admin-access`, where a delegated token could- widen its own grant. The last one is the durable half of privilege assumption: it checks a CASL- ability, so scopes do narrow it, but it writes the caller a permanent project-admin membership that- outlives the delegation, so revoking the application does not take the access back- - **creating or deleting an organization**, parent or sub, held back individually and commented as such:- `POST /v2/organizations`, `DELETE /v2/organizations/:organizationId`, `POST /v1/sub-orgs`,- `DELETE /v1/sub-orgs/:subOrgId`. Updating a sub-org and managing its memberships stay open — it is- creation and deletion that a delegation should not reach- - the org reads that return more than the token's org, held back individually and commented as such:- `GET /v1/organization`, `GET /v1/organization/accessible-with-sub-orgs`,- `GET /v1/organization/:organizationId`- - `POST /v2/organizations/privilege-system-upgrade`, which gates on `hasRole(Admin)` rather than a CASL- ability and one-way-switches the org's whole privilege model- - **every route that mints a long-lived credential**: identity token-auth tokens- (`POST /v1/auth/token-auth/identities/:identityId/tokens`), universal-auth client secrets- (`POST /v1/auth/universal-auth/identities/:identityId/client-secrets`), service tokens- (`POST /v2/service-token`), SCIM tokens (`POST /v1/scim/scim-tokens`), KMIP client certificates- (`POST /v1/kmip/clients/:id/certificates`), and the gateway / relay / KMIP-server enrollment tokens- (`POST .../token-auth/generate-enrollment-token`). Only the issuing route is held back: listing and- revoking these credentials return no secret material and stay open. See below.-- Rough proxy: nothing passing `requireOrg: false` accepts `AuthMode.OAUTH`, since with no org there's no- ability to narrow. Before adding `AuthMode.OAUTH` to a route, check the handler actually builds an- org/project/resource permission.-- **Building a permission isn't the same as checking one, and only the check is narrowed.** A handler that- calls `getOrgPermission`/`getProjectPermission` and throws the ability away is using it as a membership- gate: the intersection with granted scopes happens inside, but nothing reads the result, so a scoped- token passes like a first-party session. That's why `GET /v1/organization/:organizationId` came back off- the list. Gating on `hasRole(...)` from the same return value has the same problem and is easier to miss,- since it reads like an authorization check: the role comes from the actor's memberships, not from the- narrowed ability, so no scope ever touches it. That's why `POST /v2/organizations/privilege-system-upgrade`- is first-party. The membership-only reads that keep `AuthMode.OAUTH` return project metadata a secrets client- needs to operate rather than org or security config: `getAProject` (clients resolve environment slugs- before reading secrets) and `getProjectKmsKeys`. A CASL gate isn't the fix there, since the operation has- no subject, any member with an identity token can already call it, and a gate would change first-party- behaviour. Weigh a route in this position on what it returns.-- **A route that mints a credential can't accept a delegated one either.** Everything the revocation story- rests on (deleting the application, rotating its secret, withdrawing its grant, deactivating the user)- reaches only the OAuth sessions tagged with `getOauthClientSessionUserAgent`. An identity access token, a- universal-auth client secret, a service token, a SCIM token, a KMIP client certificate, or a redeemed- enrollment token is a separate row with its own lifetime, so a compromised client could mint one (token- auth accepts a TTL of years, SCIM tokens up to 730 days) and keep the access after every handle we have- on it is pulled. The credential also outranks its minter: it authenticates as a machine identity whose- permissions no OAuth scope intersects, or in the SCIM case one that can create and delete the org's- members. This is why credential issuance is on the exception list above regardless of how well the route- builds its permission, and why a new issuance route starts first-party only.-- **A route that mints session tokens can't accept a delegated one.** `DELETE /v2/organizations/:organizationId`- deletes the org the caller's token points at, so it reissues the user's session through- `loginService.generateUserTokens` and returns it. `generateUserTokens` has no oauthClientId, scopes or- delegation parameter, so the reissued pair is a first-party session regardless of what came in: a- delegated caller would exit with credentials good for account management and org creation, the families- deliberately closed to OAuth. Weigh any route that issues credentials the same way.--**Delegated tokens carry exactly one delegation marker, never both** (`oauth-client-types.ts`):-- `scopes: [...]` from the authorization code grant. `permission-service` intersects the user's CASL rules- with them (`applyOauthScopeToOrgRules` / `applyOauthScopeToProjectRules`).-- `delegation: "full"` from the RFC 8693 token exchange grant, which has no scopes and carries the user's- authorization unnarrowed.--**Absence of both has to keep meaning zero permissions.** `inject-identity.ts` sets-`RequestContextKey.OauthScopes` for every scope-narrowed token (even `[]`, which denies everything) and-leaves it unset only for `delegation: "full"`; `getDelegatedOauthScopes` reads an unset key as "no-narrowing". Matching full delegation positively is what makes a dropped claim fail closed instead of-quietly promoting the token.--**The token endpoint answers failures in RFC 6749 terms, not the house envelope.** `POST /v1/oauth/token`-is the one route that does, because its contract is the RFC rather than our API conventions: generic OAuth-client libraries branch on the `error` code, and `{ statusCode, message, error: "UnauthorizedError" }`-leaves them unable to tell "rotate the client secret" from "re-authenticate the user" from "retry later".-`OauthTokenError` (`oauth-token-error.ts`) carries the code, derives the status from it (400 for-everything, 401 for `invalid_client`, 500 for `server_error`), and the shared error handler renders-`{ error, error_description }` for it. When extending this:-- **The handler's `try`/`catch` is the endpoint's only exit**, and every `return` inside it is awaited —- a bare `return promise` would resolve outside the `catch` and escape in the house envelope.-- **The code a rejected grant earns depends on the grant.** RFC 8693 section 2.2.2 overrides RFC 6749 for- token exchange, and not in the direction you would guess: a `subject_token` "invalid for any reason, or- unacceptable based on policy" MUST be `invalid_request`, where the same class of failure on the redirect- and refresh grants is `invalid_grant`. So the exchange collapses "your token is bad" into "your request- is bad", and never returns `invalid_grant` at all. `REJECTED_GRANT_CODE_BY_GRANT_TYPE` holds this, and- `toOauthTokenError` takes the grant type to pick it. Client authentication stays `invalid_client` under- both, because there it is the client that failed rather than the token.-- **`toOauthTokenError` defaults by error class**, never by message text: `UnauthorizedError` means a grant- we won't act on (the grant-dependent code above), `BadRequestError` a request we can't use- (`invalid_request`), and anything else is a bug or an outage, so it becomes a generic `server_error`- whose response carries no detail and whose original is logged. Throw `OauthTokenError` directly wherever- that default is wrong:- client authentication (`invalid_client`), a grant the client doesn't hold (`unauthorized_client`), a- mismatched redirect URI or PKCE verifier (`invalid_grant`, not `invalid_request`), the unsupported- `scope` (`invalid_scope`) and `audience`/`resource` (`invalid_target`) parameters, and org- misconfiguration or identity provider outages (`server_error`, since the request was fine).- `unauthorized_client` and `invalid_scope` are deliberate reads of RFC 8693's blanket "the request itself- is not valid" clause: both are the more specific RFC 6749 code for what actually went wrong, and worth- more to a caller than a third flavour of `invalid_request`. `invalid_target` is RFC 8693's own SHOULD.-- **The route sets `attachValidation`** so a schema failure reaches the handler instead of being answered- by Fastify in the house envelope. An unrecognized `grant_type` earns `unsupported_grant_type`.-- **`error_description` is sanitized, not trusted.** RFC 6749 section 5.2 allows only printable ASCII- without `"` or `\`, and our messages are written for humans; `toErrorDescription` normalises and bounds- them at the render boundary so no throw site has to remember.-- Messages shared with a management route (the OIDC-config checks) take an error factory rather than- throwing, since registering an application and exchanging a token owe the same explanation in different- envelopes.--**Token exchange trusts the org's OIDC SSO config, not per-client configuration**-(`oauth-token-exchange-fns.ts`), so the issuers that can vouch for a user through exchange are exactly the-ones that can already log them in. The one per-application field is `tokenExchangeAudience`, and it does-the security work: without it, any token that issuer signed for any application in the customer's estate-is exchangeable. Enabling the grant, changing the audience, or rotating the secret of an exchange-application all need `OrgPermissionSsoActions.Edit` on top of the usual `OauthClients` check-(`checkSsoConfigPermission`). Rotation counts because its response hands back a working credential for-acting as any of the org's users, so leaving it out would make the create/update check a speed bump. Any-future operation that establishes this trust or hands out a credential for it goes through the same gate.--**`getOrgPermission` is not a membership check.** It builds a CASL ability from the actor's roles, and the-org-scope query in `permission-dal.ts` filters on org, actor and scope without ever reading-`Membership.isActive` or `Membership.status`. Every other user-token route got its token from a browser-login, where `selectOrganization` (`auth-login-service.ts`) rejects an inactive membership. Token exchange-mints a user token with no login in front of it, so `exchangeSubjectToken` checks membership state itself.-Without that, deactivating a member doesn't revoke their access. Any future non-interactive way of minting-a user token needs the same check.--**Withdrawing an exchange application's authority has to revoke the tokens it already issued.** Deleting-the client and rotating its secret both call `revokeSessionsByUserAgent`, and so does any update that-narrows the exchange's trust: removing the grant, changing `tokenExchangeAudience`, or switching-`tokenExchangeIdpSatisfiesMfa` off (`hasWithdrawnTokenExchangeTrust`). These are the same fields-`hasClientAuthorityChanged` guards, and for the same reason, so a new field belongs in both. An admin-narrowing any of them is responding to a problem, so it has to reach the tokens already out there rather-than wait for them to expire. The test is whether the field carries federation trust, not merely whether-it can be narrowed: `accessTokenTTL` is deliberately in neither, because it decides how long a new token-lasts rather than whose tokens are exchangeable or which MFA requirement may be skipped. Shortening it on-a live application is routine tuning, so revoking every user's session would be a surprising side effect,-and putting it in `hasClientAuthorityChanged` would fail in-flight exchanges on a harmless edit. An admin-who does want the issued tokens gone rotates the secret. Widening does not revoke: turning the MFA-declaration on grants more without invalidating anything already issued. Sessions are tagged with-`getOauthClientSessionUserAgent(clientId)`, the only handle we have on them. Rotation revokes only on-exchange applications: there the secret alone mints tokens for any user, whereas in the redirect flow it-has to be paired with an authorization code or refresh token and blanket revocation would just sign-everyone out. The tag is per client, not per grant, which is unambiguous because a client cannot hold-both flows: `assertValidOauthClientGrantConfig` rejects the token-exchange grant alongside-`authorization_code`, in the API as well as the UI, so an application is either a redirect-flow client or-an exchange client. A service needing both registers twice.--**That sweep only reaps sessions that already exist, so the exchange rechecks the client after creating-its own.** `exchangeSubjectToken` authenticates the client, then spends provider discovery, JWKS-verification and several DB reads before inserting a session, long enough for a revocation to land in-between and delete nothing. So once the session exists it re-reads the client via-`oauthClientDAL.findByIdOnPrimary` and rejects (re-running the sweep) if the secret hash changed, the-grant is gone, the row is gone, or either field carrying the exchange's federation trust has been narrowed-(`tokenExchangeAudience` and `tokenExchangeIdpSatisfiesMfa`, both read off the replica). Anything a future-field grants the exchange belongs in `hasClientAuthorityChanged` for the same reason. Two things make this-sufficient: every withdrawal path commits its write to the client *before* deleting sessions, so a session-that survived the delete belongs to a request whose client row is already stale; and the re-read hits the-**primary**, since the replica `authenticateClient` reads can still be serving the pre-revocation row.-Only the exchange grant needs it, because the authorization code and refresh branches read an existing-session instead of creating one, so a racing revoke either fails them closed or kills the session behind-the token they just signed.--**Everything the exchange fetches from the IdP is cached for 10 minutes, and nothing read from our own-database is.** A middleware typically exchanges once per request it serves, so the discovery document and-the `JwksClient` are cached per URL in `oauth-token-exchange-fns.ts`; without that the provider becomes a-synchronous dependency of every Infisical call the middleware makes. When extending it:-- **Don't cache the resolved trust anchor.** The signature algorithm and preferred issuer come from- `oidc_configs`, and an admin editing either has to take effect on the next request.-- **Failed fetches are evicted, not cached**, so a provider blip lasts as long as the blip. Caching the- failure turns a 5-second outage into 10 minutes of them.-- **Entries hold the in-flight promise**, so concurrent callers on a cold entry coalesce onto one fetch.-- Expiry also rebuilds the SSRF-pinned agent, which is what lets a legitimate DNS change at the provider- get picked up at all.+- **OAUTH** — delegated user tokens from the `oauth-client` module. Same JWT shape and session binding as+ `JWT`, told apart by an `oauthClientId` claim. See [Delegated OAuth tokens](#delegated-oauth-tokens).**Deprecated auth modes (do not use in new code):**- **API_KEY** — user API keys (from `x-api-key` header). Deprecated — use identity access tokens instead.@@ -361,6 +184,118 @@ If you encounter `API_KEY` or `SERVICE_TOKEN` in existing code, do not replicateToken detection logic in `inject-identity.ts` checks `x-api-key` header first, then parses `Authorization: Bearer` and inspects JWT `authTokenType` field to determine mode.+#### Delegated OAuth tokens++Two grants issue them: the authorization code flow (consented `scopes`) and the RFC 8693 token exchange+(`delegation: "full"`, no scopes).++**Opting a route in.** `verify-auth.ts` rejects `AuthMode.OAUTH` on any route that doesn't list it; most+`AuthMode.JWT` routes now do. Before adding it, check the handler actually **checks** a CASL ability:+that check is where the granted scopes get intersected in. Building an ability and throwing it away+(`getOrgPermission` used as a membership gate), or reading `hasRole(...)` off its return value, narrows+nothing; `hasRole` is the easy one to miss because it reads like authorization. Rough proxy: nothing+passing `requireOrg: false` accepts `AuthMode.OAUTH`.++First-party only:+- account self-management (user, password, MFA, sessions, login, signup, notifications, announcements)+- super-admin routes (`v1/admin-router.ts`, `ee/v1/rate-limit-router.ts`), where `verifySuperAdmin` reads+ `user.superAdmin` rather than an ability+- OAuth client CRUD + consent (`v1/oauth-router.ts`) and `ee/v1/assume-privilege-router.ts`, where a+ delegated token could widen its own grant, plus+ `POST /v1/organization-admin/projects/:projectId/grant-admin-access`, which writes a permanent+ project-admin membership that outlives the delegation+- creating or deleting an org, parent or sub: `POST /v2/organizations`,+ `DELETE /v2/organizations/:organizationId`, `POST /v1/sub-orgs`, `DELETE /v1/sub-orgs/:subOrgId`.+ Updating a sub-org and managing its memberships stay open+- `POST /v2/organizations/privilege-system-upgrade`, which gates on `hasRole(Admin)`+- the org reads that return more than the token's org: `GET /v1/organization`,+ `GET /v1/organization/accessible-with-sub-orgs`, `GET /v1/organization/:organizationId`+- routes that **mint a long-lived credential**: identity token-auth tokens, universal-auth client+ secrets, service tokens, SCIM tokens, KMIP client certificates, and gateway / relay / KMIP-server+ enrollment tokens. Issuance only: listing and revoking return no secret material and stay open+- routes that **register an identity auth method**: attach (`POST`) and update (`PATCH`) on all thirteen+ `identity-*-auth-router.ts`. `GET`, `DELETE`, `clear-lockouts` and `refresh-bundle` stay open++The last two are one rule: **a route that leaves behind something able to authenticate later can't accept+a delegated token.** Revocation reaches only the sessions tagged with `getOauthClientSessionUserAgent`, so+an identity token, service token, client secret, or an auth method bound to a key the caller holds all+survive deleting the application and rotating its secret, and authenticate as an identity no OAuth scope+intersects. Whether the route hands secret material back is beside the point, so start any new route that+writes a trust anchor (bound issuer, signing key, CA, cloud principal) first-party. Same test for a route+that reissues the caller's session: `DELETE /v2/organizations/:organizationId` returns a fresh pair from+`loginService.generateUserTokens`, which takes no delegation parameter, so a delegated caller would exit+with a first-party session.++Membership-only reads that *keep* `AuthMode.OAUTH` return project metadata a secrets client needs+(`getAProject`, so clients can resolve environment slugs, and `getProjectKmsKeys`) rather than org or+security config. A CASL gate isn't the fix there: the operation has no subject, and any member with an+identity token can already call it. Weigh a route in this position on what it returns.++**Delegation markers.** A token carries `scopes` or `delegation: "full"`, never both+(`oauth-client-types.ts`). `permission-service` intersects the user's CASL rules with `scopes`+(`applyOauthScopeToOrgRules` / `applyOauthScopeToProjectRules`). `inject-identity.ts` sets+`RequestContextKey.OauthScopes` for every scope-narrowed token (even `[]`, which denies everything) and+leaves it unset only for full delegation. Matching full delegation **positively** is what makes a dropped+claim fail closed instead of promoting the token.++**The token endpoint's error contract is RFC 6749 §5.2, not the house envelope**, because generic OAuth+libraries branch on the `error` code. `OauthTokenError` (`oauth-token-error.ts`) carries the code and+derives the status from it (400; 401 for `invalid_client`, 500 for `server_error`), and the shared error+handler renders `{ error, error_description }`. When extending it:+- The handler's `try`/`catch` is the endpoint's only exit, and every `return` inside it is **awaited**: a+ bare `return promise` would resolve outside the `catch` and escape in the house envelope.+- `toOauthTokenError` defaults by **error class**, never message text: `UnauthorizedError` takes the+ rejected-grant code for that grant (`invalid_grant` on the redirect and refresh grants,+ `invalid_request` on token exchange, per RFC 8693 §2.2.2), `BadRequestError` takes `invalid_request`,+ and anything else becomes `server_error`, whose response carries no detail and whose original is logged.+- Throw `OauthTokenError` directly where that default is wrong: client authentication+ (`invalid_client`), a grant the client doesn't hold (`unauthorized_client`), a redirect-URI or PKCE+ mismatch (`invalid_grant`), the unsupported `scope` (`invalid_scope`) and `audience`/`resource`+ (`invalid_target`) parameters, and org misconfiguration or IdP outages (`server_error`).+- The route sets `attachValidation` so a schema failure reaches the handler; an unrecognized `grant_type`+ earns `unsupported_grant_type`.+- `toErrorDescription` sanitizes and bounds `error_description` at the render boundary, so no throw site+ has to remember RFC 6749's printable-ASCII restriction.+- Messages shared with a management route (the OIDC-config checks) take an error factory rather than+ throwing, since the two callers owe the same explanation in different envelopes.++**Token exchange trusts the org's OIDC SSO config, not per-client configuration**+(`oauth-token-exchange-fns.ts`), so the issuers that can vouch for a user are the ones that can already+log them in. The one per-application field is `tokenExchangeAudience`, and it does the security work:+without it, any token that issuer signed for anything in the estate is exchangeable. Enabling the grant,+changing the audience, and rotating the secret each need `OrgPermissionSsoActions.Edit` on top of the usual+`OauthClients` check (`checkSsoConfigPermission`), rotation included, since its response is a working+credential for acting as any of the org's users.++`getOrgPermission` is **not** a membership check: the org-scope query in `permission-dal.ts` never reads+`Membership.isActive` or `Membership.status`. Every other user token came from a browser login, where+`selectOrganization` rejects an inactive membership; the exchange has no login in front of it, so+`exchangeSubjectToken` checks membership state itself. Any future non-interactive way of minting a user+token needs the same check.++**Withdrawing an exchange application's authority revokes the tokens it already issued.** Deleting the+client, rotating its secret, and any update that narrows the exchange's trust (dropping the grant,+changing `tokenExchangeAudience`, switching `tokenExchangeIdpSatisfiesMfa` off) all call+`revokeSessionsByUserAgent`. `hasWithdrawnTokenExchangeTrust` and `hasClientAuthorityChanged` guard the+same fields, so a new field belongs in both. The test is whether it carries federation trust, not merely+whether it can be narrowed. `accessTokenTTL` is in neither: it only decides how long a new token lasts, so+revoking on a routine edit would surprise, and guarding it would fail in-flight exchanges. Widening+(turning the MFA declaration on) revokes nothing. Rotation revokes for exchange clients only, where the+secret alone mints tokens; in the redirect flow it has to be paired with a code or refresh token, so+blanket revocation would just sign everyone out. The session tag is per client, which is unambiguous+because `assertValidOauthClientGrantConfig` rejects the exchange grant alongside `authorization_code`, so+a service needing both registers twice.++That sweep only reaps sessions that already exist, so **the exchange rechecks the client on the primary+after creating its own session** (`findByIdOnPrimary` + `hasClientAuthorityChanged`, re-running the+sweep). The other grants read an existing session rather than creating one, so they don't need it.++**Everything the exchange fetches from the IdP is cached for 10 minutes; nothing read from our own+database is**, so an admin editing the SSO config takes effect on the next request while the provider+never becomes a synchronous dependency of the middleware's own request path. The cache invariants+(rejections evicted, in-flight promise shared, expiry rebuilding the SSRF-pinned agent) are documented in+`oauth-token-exchange-fns.ts`.+### Permission System (CASL)Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in `src/ee/services/permission/`:diff --git a/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts b/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.tsindex 0ad35d37c3..d8bb08759b 100644--- a/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts+++ b/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts@@ -5,8 +5,8 @@ import { TableName } from "@app/db/schemas";// Every client registered before this migration was created for the redirect flow.const REDIRECT_FLOW_GRANT_TYPES = "'{authorization_code,refresh_token}'::text[]";-// One day, in seconds. Deliberately shorter than JWT_AUTH_LIFETIME (10 days), which is what these-// tokens fell back to before the column existed.+// One day. Deliberately shorter than JWT_AUTH_LIFETIME (10 days), which is what these tokens fell back+// to before the column existed.const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 86400;export async function up(knex: Knex): Promise<void> {@@ -27,20 +27,20 @@ export async function up(knex: Knex): Promise<void> {t.specificType("grantTypes", "text[]").notNullable().defaultTo(knex.raw(REDIRECT_FLOW_GRANT_TYPES));}- // Expected `aud` of subject tokens. It's the application's own registration in the org's IdP, not- // Infisical's, so it can't be read off oidc_configs.+ // Expected `aud` of subject tokens. It is the application's own registration in the org's IdP, not+ // Infisical's, so it cannot be read off oidc_configs.if (!hasTokenExchangeAudience) {t.text("tokenExchangeAudience");}- // Token exchange has no Infisical MFA challenge to run, so an admin vouches that the IdP enforces- // it. Without that, exchanges fail for any user who requires MFA.+ // Token exchange has no Infisical MFA challenge to run, so an admin vouches that the IdP enforces it.+ // Without that, exchanges fail for any user who requires MFA.if (!hasTokenExchangeIdpSatisfiesMfa) {t.boolean("tokenExchangeIdpSatisfiesMfa").notNullable().defaultTo(false);}- // How long the access tokens this application issues stay valid. Unlike grantTypes the default is- // kept, because a create that omits it should get the product default rather than fail.+ // Unlike grantTypes, the default is kept: a create that omits it should get the product default+ // rather than fail.if (!hasAccessTokenTtl) {t.integer("accessTokenTTL").notNullable().defaultTo(DEFAULT_ACCESS_TOKEN_TTL_SECONDS);}diff --git a/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.ts b/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.tsindex f451fd57dd..75f614b15e 100644--- a/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.ts+++ b/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.ts@@ -2,29 +2,26 @@ import { Knex } from "knex";import { TableName } from "../schemas";-// auth_token_sessions carries a row per user session, so it is one of the largest tables on an-// instance, and until now the primary key was its only index. Every lookup keyed on `id` rides that-// PK (session validation on each authenticated request, refresh rotation, revoking one session), but-// three filter shapes had nothing to use and seq-scanned the whole table:+// auth_token_sessions is one of the largest tables on an instance, and the primary key was its only+// index. Lookups keyed on `id` ride that PK, but three filter shapes seq-scanned the whole table://-// {userAgent} revokeSessionsByUserAgent, the only handle OAuth client revocation has-// on the tokens a client issued. Two of its callers run inside a-// transaction, so the scan also held a pooled connection for its duration.+// {userAgent} revokeSessionsByUserAgent, the only handle OAuth client revocation has on+// the tokens a client issued. Two callers run inside a transaction, so the+// scan also held a pooled connection for its duration.// {userId, ip, userAgent} getUserTokenSession, on every login and every RFC 8693 token exchange.// {userId} listing a user's sessions, and revoking all of them.//-// The second index covers both of the userId shapes: the three-column lookup uses all of it, and the-// userId-only lookups use its leftmost column. userAgent trails rather than leads it so that the-// userAgent-only delete keeps its own tighter single-column index, which measured consistently faster-// for that query than sharing a userAgent-leading composite.+// The composite covers both userId shapes (the three-column lookup uses all of it, the userId-only+// lookups its leftmost column). userAgent trails rather than leads so the userAgent-only delete keeps+// its own single-column index, which measured consistently faster than a userAgent-leading composite.const USER_AGENT_INDEX = "idx_auth_token_sessions_user_agent";const USER_SESSION_INDEX = "idx_auth_token_sessions_user_id_ip_user_agent";const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutesconst MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 secondsexport async function up(knex: Knex): Promise<void> {- // statement_timeout / lock_timeout are session-local, so every statement here has to run on the- // same pooled connection as the CREATE INDEX CONCURRENTLY calls they are meant to govern.+ // statement_timeout / lock_timeout are session-local, so they have to run on the same pooled+ // connection as the CREATE INDEX CONCURRENTLY calls they govern.const connection = await knex.client.acquireConnection();const raw = (sql: string) => knex.raw(sql).connection(connection);diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex 4095d40e11..21d0cbfe33 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -90,11 +90,9 @@ import {} from "./project-permission";// Returns the scopes to narrow this request to, or undefined when no narrowing applies. Any array, even-// an empty one, means narrowing applies, so [] denies all scope-guarded access.-//-// undefined covers first-party sessions, background jobs and fully-delegated RFC 8693 tokens.-// inject-identity leaves the key unset only for those and always sets it for scope-narrowed delegation,-// so a token carrying neither marker still ends up with zero permissions.+// an empty one, means narrowing applies, so [] denies all scope-guarded access. undefined covers+// first-party sessions, background jobs and fully-delegated RFC 8693 tokens: inject-identity leaves the+// key unset only for those, so a token carrying neither delegation marker ends up with zero permissions.const getDelegatedOauthScopes = (): OauthScope[] | undefined => {const raw = requestContext.get(RequestContextKey.OauthScopes);if (!raw) return undefined;diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex dad3f19e87..38ab2d40f4 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -115,8 +115,8 @@ export type TAuthMode =};// A first-party session and a delegated OAuth token have the same auth shape, so a handler that only-// needs the acting user (name, email, session id) should take both instead of narrowing on AuthMode.JWT.-// Narrowing silently costs the OAuth caller its audit trail or actor metadata.+// needs the acting user (name, email, session id) should take both rather than narrow on AuthMode.JWT,+// which silently costs the OAuth caller its audit trail or actor metadata.export const isUserSessionAuth = (auth: TAuthMode): auth is Extract<TAuthMode, { authMode: AuthMode.JWT | AuthMode.OAUTH }> =>diff --git a/backend/src/server/plugins/auth/verify-auth.ts b/backend/src/server/plugins/auth/verify-auth.tsindex 7c31a5d45b..8cf7feba2d 100644--- a/backend/src/server/plugins/auth/verify-auth.ts+++ b/backend/src/server/plugins/auth/verify-auth.ts@@ -18,14 +18,11 @@ export const verifyAuth =if (!req.auth) throw new UnauthorizedError({ message: "Token missing" });// Delegated OAuth access tokens are a separate auth mode a route has to opt into by listing- // AuthMode.OAUTH, deliberately not accepted on AuthMode.JWT alone. Scopes are only enforced when a- // handler builds an org/project permission, since that's where the ability gets intersected with- // them, so a route that authenticates on userId and builds no permission would skip the narrowing- // entirely. The families that can't do that check stay on AuthMode.JWT alone: account- // self-management (/me, password, MFA, sessions, login, signup, notifications), super-admin routes- // (verifySuperAdmin reads user.superAdmin, not a CASL ability), and the OAuth client/consent routes- // themselves, where a delegated token could widen its own grant. Rough proxy: nothing passing- // `requireOrg: false` accepts AuthMode.OAUTH, since with no org there's no ability to intersect.+ // AuthMode.OAUTH, deliberately not accepted on AuthMode.JWT alone. Scopes are only enforced where a+ // handler checks an org/project ability, since that check is what intersects them, so a route+ // authenticating on bare userId would skip the narrowing entirely. Rough proxy: nothing passing+ // `requireOrg: false` accepts AuthMode.OAUTH. See "Delegated OAuth tokens" in backend/CLAUDE.md for+ // the families held back and why.const isAccessAllowed = authStrategies.some((strategy) => strategy === req.auth.authMode);if (!isAccessAllowed) {throw new ForbiddenRequestError({ name: `Forbidden access to ${req.url}` });diff --git a/backend/src/server/routes/v1/identity-alicloud-auth-router.ts b/backend/src/server/routes/v1/identity-alicloud-auth-router.tsindex 3df307bb30..ac6a443499 100644--- a/backend/src/server/routes/v1/identity-alicloud-auth-router.ts+++ b/backend/src/server/routes/v1/identity-alicloud-auth-router.ts@@ -163,7 +163,7 @@ export const registerIdentityAliCloudAuthRouter = async (server: FastifyZodProviconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachAlicloudAuth",@@ -271,7 +271,7 @@ export const registerIdentityAliCloudAuthRouter = async (server: FastifyZodProviconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateAlicloudAuth",diff --git a/backend/src/server/routes/v1/identity-aws-iam-auth-router.ts b/backend/src/server/routes/v1/identity-aws-iam-auth-router.tsindex bc29ce8570..c42616bcdf 100644--- a/backend/src/server/routes/v1/identity-aws-iam-auth-router.ts+++ b/backend/src/server/routes/v1/identity-aws-iam-auth-router.ts@@ -130,7 +130,7 @@ export const registerIdentityAwsAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachAwsAuth",@@ -242,7 +242,7 @@ export const registerIdentityAwsAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateAwsAuth",diff --git a/backend/src/server/routes/v1/identity-azure-auth-router.ts b/backend/src/server/routes/v1/identity-azure-auth-router.tsindex 891eed31a5..855535eb69 100644--- a/backend/src/server/routes/v1/identity-azure-auth-router.ts+++ b/backend/src/server/routes/v1/identity-azure-auth-router.ts@@ -125,7 +125,7 @@ export const registerIdentityAzureAuthRouter = async (server: FastifyZodProviderconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachAzureAuth",@@ -236,7 +236,7 @@ export const registerIdentityAzureAuthRouter = async (server: FastifyZodProviderconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateAzureAuth",diff --git a/backend/src/server/routes/v1/identity-gcp-auth-router.ts b/backend/src/server/routes/v1/identity-gcp-auth-router.tsindex 43b848ce34..06d23f6367 100644--- a/backend/src/server/routes/v1/identity-gcp-auth-router.ts+++ b/backend/src/server/routes/v1/identity-gcp-auth-router.ts@@ -125,7 +125,7 @@ export const registerIdentityGcpAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachGcpAuth",@@ -234,7 +234,7 @@ export const registerIdentityGcpAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateGcpAuth",diff --git a/backend/src/server/routes/v1/identity-jwt-auth-router.ts b/backend/src/server/routes/v1/identity-jwt-auth-router.tsindex 23e1bf635a..092aa8e8f3 100644--- a/backend/src/server/routes/v1/identity-jwt-auth-router.ts+++ b/backend/src/server/routes/v1/identity-jwt-auth-router.ts@@ -201,7 +201,7 @@ export const registerIdentityJwtAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachJwtAuth",@@ -286,7 +286,7 @@ export const registerIdentityJwtAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateJwtAuth",diff --git a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts b/backend/src/server/routes/v1/identity-kubernetes-auth-router.tsindex b17002bd6c..d7d5f41d4d 100644--- a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts+++ b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts@@ -148,7 +148,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvideconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachKubernetesAuth",@@ -348,7 +348,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvideconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateKubernetesAuth",diff --git a/backend/src/server/routes/v1/identity-ldap-auth-router.ts b/backend/src/server/routes/v1/identity-ldap-auth-router.tsindex bd369eab4a..2ff77d15ed 100644--- a/backend/src/server/routes/v1/identity-ldap-auth-router.ts+++ b/backend/src/server/routes/v1/identity-ldap-auth-router.ts@@ -274,7 +274,7 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachLdapAuth",@@ -481,7 +481,7 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateLdapAuth",diff --git a/backend/src/server/routes/v1/identity-oci-auth-router.ts b/backend/src/server/routes/v1/identity-oci-auth-router.tsindex 33fa76564b..5ff3d63fff 100644--- a/backend/src/server/routes/v1/identity-oci-auth-router.ts+++ b/backend/src/server/routes/v1/identity-oci-auth-router.ts@@ -142,7 +142,7 @@ export const registerIdentityOciAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachOciAuth",@@ -247,7 +247,7 @@ export const registerIdentityOciAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateOciAuth",diff --git a/backend/src/server/routes/v1/identity-oidc-auth-router.ts b/backend/src/server/routes/v1/identity-oidc-auth-router.tsindex 066695bd15..15a35d2914 100644--- a/backend/src/server/routes/v1/identity-oidc-auth-router.ts+++ b/backend/src/server/routes/v1/identity-oidc-auth-router.ts@@ -153,7 +153,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachOidcAuth",@@ -270,7 +270,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateOidcAuth",diff --git a/backend/src/server/routes/v1/identity-spiffe-auth-router.ts b/backend/src/server/routes/v1/identity-spiffe-auth-router.tsindex 45d35d819b..a3c8002eb8 100644--- a/backend/src/server/routes/v1/identity-spiffe-auth-router.ts+++ b/backend/src/server/routes/v1/identity-spiffe-auth-router.ts@@ -197,7 +197,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvideconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachSpiffeAuth",@@ -260,7 +260,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvideconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateSpiffeAuth",diff --git a/backend/src/server/routes/v1/identity-tls-cert-auth-router.ts b/backend/src/server/routes/v1/identity-tls-cert-auth-router.tsindex adf94efcec..195233ec88 100644--- a/backend/src/server/routes/v1/identity-tls-cert-auth-router.ts+++ b/backend/src/server/routes/v1/identity-tls-cert-auth-router.ts@@ -196,7 +196,7 @@ export const registerIdentityTlsCertAuthRouter = async (server: FastifyZodProvidconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachTlsCertAuth",@@ -325,7 +325,7 @@ export const registerIdentityTlsCertAuthRouter = async (server: FastifyZodProvidconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateTlsCertAuth",diff --git a/backend/src/server/routes/v1/identity-token-auth-router.ts b/backend/src/server/routes/v1/identity-token-auth-router.tsindex 3f67ea4cd2..48d4a40460 100644--- a/backend/src/server/routes/v1/identity-token-auth-router.ts+++ b/backend/src/server/routes/v1/identity-token-auth-router.ts@@ -20,7 +20,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProviderconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachTokenAuth",@@ -128,7 +128,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProviderconfig: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateTokenAuth",diff --git a/backend/src/server/routes/v1/identity-universal-auth-router.ts b/backend/src/server/routes/v1/identity-universal-auth-router.tsindex a07e187a41..753b0ac6d6 100644--- a/backend/src/server/routes/v1/identity-universal-auth-router.ts+++ b/backend/src/server/routes/v1/identity-universal-auth-router.ts@@ -152,7 +152,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "attachUniversalAuth",@@ -286,7 +286,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),schema: {hide: false,operationId: "updateUniversalAuth",diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex 1113d1c19a..b871588615 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -45,9 +45,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- // Not open to AuthMode.OAUTH, unlike the rest of this router: with no org in context there's no- // permission to build, so nothing narrows the result and a token issued for one org would- // enumerate every org the user belongs to.+ // Not open to AuthMode.OAUTH, unlike the rest of this router: with no org in context nothing narrows+ // the result, so a token issued for one org would enumerate every org the user belongs to.onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {const organizations = await server.services.org.findAllOrganizationOfUser(req.permission.id);@@ -72,9 +71,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- // Not open to AuthMode.OAUTH, unlike the rest of this router: with no org in context there's no- // permission to build, so nothing narrows the result and a token issued for one org would- // enumerate every org the user belongs to.+ // Not open to AuthMode.OAUTH, unlike the rest of this router: with no org in context nothing narrows+ // the result, so a token issued for one org would enumerate every org the user belongs to.onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {const organizations = await server.services.org.findAllAccessibleOrganizationsWithSubOrgs(req.permission.id);diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.tsindex 7cfe1b069d..caf04e0a7e 100644--- a/backend/src/server/routes/v2/organization-router.ts+++ b/backend/src/server/routes/v2/organization-router.ts@@ -428,8 +428,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {}},// Not open to AuthMode.OAUTH, unlike the rest of this router: creating an org needs no org- // permission, so nothing here is scope-narrowed and a delegated token could stand up an org the- // client was never granted anything in.+ // permission, so nothing is scope-narrowed and a delegated token could stand up an org the client+ // was never granted anything in.onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY], { requireOrg: false }),handler: async (req) => {if (req.auth.actor !== ActorType.USER) return;diff --git a/backend/src/services/oauth-client/oauth-client-fns.ts b/backend/src/services/oauth-client/oauth-client-fns.tsindex 48a64d101b..101d5bc843 100644--- a/backend/src/services/oauth-client/oauth-client-fns.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.ts@@ -77,14 +77,12 @@ type TOauthClientAuthority = Pick<>;// Whether the client has lost the authority it was granted mid-request: deleted, secret rotated, or the-// grant withdrawn. Comparing the stored hashes is enough, since a rotation writes a fresh bcrypt hash-// with a new salt.+// grant withdrawn. Comparing the stored hashes is enough, since a rotation writes a fresh bcrypt hash.//-// Token exchange also compares the two fields carrying its federation trust. The audience is all that-// stands between the caller and any token the issuer signs, and the IdP-MFA flag is what lets an-// exchange skip an MFA requirement, so narrowing either withdraws authority just as much as rotating the-// secret. The exchange reads them off a replica, so without this they'd survive the change for the-// length of the replication lag.+// Token exchange also compares the two fields carrying its federation trust: the audience is all that+// stands between the caller and any token the issuer signs, and the IdP-MFA flag is what lets an exchange+// skip an MFA requirement. The exchange reads both off a replica, so without this they'd survive the+// change for the length of the replication lag.export const hasClientAuthorityChanged = (authenticated: TOauthClientAuthority,current: TOauthClientAuthority | undefined,@@ -110,16 +108,14 @@ type TTokenExchangeTrust = {idpSatisfiesMfa?: boolean | null;};-// Whether an update takes back federation trust the client already holds, in which case the tokens-// issued under the old configuration have to go with it. Guards the same fields as-// hasClientAuthorityChanged, for the same reason: the audience is what binds the exchange to one set of-// subject tokens, and the IdP-MFA declaration is what lets an exchange skip an MFA requirement. An admin-// narrowing either is responding to a problem, so it has to reach the tokens already out there instead-// of waiting for them to expire. Rotating the secret revokes on the same grounds.+// Whether an update takes back federation trust the client already holds, in which case the tokens issued+// under the old configuration have to go with it. Guards the same fields as hasClientAuthorityChanged,+// for the same reason. An admin narrowing either is responding to a problem, so it has to reach the tokens+// already out there instead of waiting for them to expire.//-// Any audience change counts, in either direction, because tokens issued under the old one were accepted-// on a basis that no longer holds. The MFA declaration only counts when switched off: turning it on-// widens what is exchangeable without invalidating anything already issued.+// Any audience change counts, in either direction, since tokens issued under the old one were accepted on+// a basis that no longer holds. The MFA declaration only counts when switched off: turning it on widens+// what is exchangeable without invalidating anything already issued.export const hasWithdrawnTokenExchangeTrust = (previous: TTokenExchangeTrust, next: TTokenExchangeTrust) => {if (!previous.isEnabled) return false;if (!next.isEnabled) return true;diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex ed24f609d3..47faaabce9 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -160,12 +160,9 @@ export const oauthClientServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.OauthClients);};- // Token exchange turns externally-issued tokens into Infisical user tokens, so establishing that- // trust (or handing out a credential for it) changes the org's federation posture, not just an- // application. Those operations need SSO Edit on top of the usual OauthClients check.- //- // `action` goes in the error because it's not obvious why an OAuth application change wants SSO- // permission.+ // Token exchange turns externally-issued tokens into Infisical user tokens, so establishing that trust+ // (or handing out a credential for it) changes the org's federation posture, not just an application.+ // `action` goes in the error because it's not obvious why an OAuth change wants SSO permission.const checkSsoConfigPermission = async (actor: OrgServiceActor, action: string) => {const { permission } = await permissionService.getOrgPermission({actor: actor.type,@@ -192,10 +189,10 @@ export const oauthClientServiceFactory = ({return client;};- // Clients only ever live on a root org today, and that's where the things these flows read live too:- // MFA enforcement, the OIDC SSO config and OIDC user aliases, same as the login flow. Asserted rather- // than assumed, because if sub-orgs are ever allowed to own clients, an exchange would silently verify- // subject tokens against the sub-org's own OIDC config and look up aliases in the wrong org.+ // Clients only ever live on a root org, and so do the things these flows read: MFA enforcement, the+ // OIDC SSO config, OIDC user aliases. Asserted rather than assumed, because if sub-orgs are ever+ // allowed to own clients, an exchange would verify subject tokens against the sub-org's own OIDC+ // config and look up aliases in the wrong org.const getClientOrg = async (orgId: string): Promise<TOrganizations> => {const org = await orgDAL.findById(orgId);if (!org) throw new NotFoundError({ message: "OAuth client organization not found" });@@ -212,10 +209,9 @@ export const oauthClientServiceFactory = ({// Without a live OIDC config there's nothing to verify subject tokens against. Failing at config time// puts the message in front of the admin setting the application up.//- // `buildError` is a parameter because the two callers owe the same explanation in different envelopes:- // registering an application is a bad request from the admin making it, while an exchange hitting this- // is an org misconfiguration the caller can do nothing about, and the token endpoint has to say so in- // RFC 6749 terms. Keeping the wording in one place is the point.+ // `buildError` is a parameter so the wording lives in one place: registering an application is a bad+ // request from the admin making it, while an exchange hitting this is an org misconfiguration the+ // caller can do nothing about, which the token endpoint has to report in RFC 6749 terms.const getActiveOidcConfigOrThrow = async (orgId: string, buildError: (message: string) => Error) => {const org = await getClientOrg(orgId);const oidcConfig = await oidcConfigDAL.findOne({ orgId: org.id });@@ -235,11 +231,9 @@ export const oauthClientServiceFactory = ({return { oidcConfig, org };};- // Register and update ask the same questions of a grant config, an update against the stored client- // and a register against nothing, so `client` is the only difference between the two callers.- //- // The token exchange gates only fire when the request actually touches that config, so an admin with- // just OauthClients Edit can still rename an application that happens to use the grant.+ // Register and update ask the same questions of a grant config, so `client` (absent on register) is the+ // only difference between the two callers. The token exchange gates fire only when the request actually+ // touches that config, so an admin with just OauthClients Edit can still rename an exchange application.const resolveGrantConfig = async ({dto,actor,@@ -595,10 +589,9 @@ export const oauthClientServiceFactory = ({return client;};- // The application's own TTL is a ceiling on its access tokens, not an override: the instance's- // JWT_AUTH_LIFETIME and the org's session length still apply, so an application cannot hand out a- // token that outlives the org's own policy. Refresh tokens keep following the org alone, since they- // exist to outlive individual access tokens.+ // The application's own TTL is a ceiling, not an override: the instance's JWT_AUTH_LIFETIME and the+ // org's session length still apply, so an application cannot hand out a token that outlives the org's+ // policy. Refresh tokens follow the org alone, since they exist to outlive individual access tokens.const resolveTokenLifetimes = (client: Pick<TOauthClients, "accessTokenTTL">, org?: TOrganizations) => {const appCfg = getConfig();let accessTokenExpiresIn: string | number = getMinExpiresIn(appCfg.JWT_AUTH_LIFETIME, client.accessTokenTTL);@@ -616,8 +609,8 @@ export const oauthClientServiceFactory = ({resolveTokenLifetimes(client, await orgDAL.findById(orgId));// RFC 8693 token exchange is the SSO login path with the token handed to us directly instead of- // collected through a browser redirect. With no redirect URI, no PKCE and no browser session to anchor- // trust on, the audience check is all that stops any token the issuer signed being replayed here.+ // collected through a browser redirect. With no redirect URI, PKCE or browser session to anchor trust+ // on, the audience check is all that stops any token the issuer signed being replayed here.const exchangeSubjectToken = async (client: TOauthClients,dto: Extract<TOauthTokenExchangeDTO, { grantType: OauthGrantType.TokenExchange }>@@ -734,6 +727,10 @@ export const oauthClientServiceFactory = ({message: "Failed to create a session for the user this token identifies."});+ // A revocation can land between authenticating the client and inserting the session above, deleting+ // nothing because the session did not exist yet. Every withdrawal path commits its client write+ // before deleting sessions, so re-reading the client here catches it -- on the primary, since the+ // replica can still be serving the pre-revocation row.const currentClient = await oauthClientDAL.findByIdOnPrimary(client.id);if (hasClientAuthorityChanged(client, currentClient, OauthGrantType.TokenExchange)) {await tokenService.revokeSessionsByUserAgent(getOauthClientSessionUserAgent(client.clientId));diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.tsindex 02c13ae2e3..5dfb48b273 100644--- a/backend/src/services/oauth-client/oauth-client-types.ts+++ b/backend/src/services/oauth-client/oauth-client-types.ts@@ -2,8 +2,8 @@ import { z } from "zod";import { AuthMethod, AuthModeRefreshJwtTokenPayload, MfaMethod } from "@app/services/auth/auth-type";-// RFC 7591 client metadata. A client can hold several grants, and each one makes a different subset of-// the client's fields meaningful. See assertValidOauthClientGrantConfig.+// RFC 7591 client metadata. Each grant makes a different subset of the client's fields meaningful; see+// assertValidOauthClientGrantConfig.export enum OauthGrantType {AuthorizationCode = "authorization_code",RefreshToken = "refresh_token",@@ -24,13 +24,12 @@ export enum OauthTokenType {AccessToken = "urn:ietf:params:oauth:token-type:access_token"}-// Both are verified the same way, as a signed JWT from the org's OIDC SSO issuer, so the only-// difference is what the caller declares.+// Both are verified identically, as a signed JWT from the org's OIDC SSO issuer.export const ACCEPTED_SUBJECT_TOKEN_TYPES: readonly OauthTokenType[] = [OauthTokenType.Jwt, OauthTokenType.IdToken];// Marks a token as carrying the user's authorization unnarrowed, unlike the consented scopes an// authorization-code token carries. A positive marker on purpose: absence has to keep meaning zero-// permissions so a dropped claim fails closed.+// permissions, so a dropped claim fails closed.export enum OauthDelegationMode {Full = "full"}diff --git a/backend/src/services/oauth-client/oauth-token-error.ts b/backend/src/services/oauth-client/oauth-token-error.tsindex 0de331e1ae..ac6afee8f0 100644--- a/backend/src/services/oauth-client/oauth-token-error.ts+++ b/backend/src/services/oauth-client/oauth-token-error.ts@@ -2,14 +2,10 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";import { OauthGrantType } from "./oauth-client-types";-// The token endpoint answers failures in the shape RFC 6749 section 5.2 defines, extended by the-// `invalid_target` code from RFC 8693 section 2.2.2: a JSON body carrying an `error` code from a fixed-// list plus a human-readable `error_description`. Generic OAuth client libraries branch on that code,-// so the house envelope (`{ statusCode, message, error: "UnauthorizedError" }`) leaves them unable to-// tell "rotate the client secret" from "re-authenticate the user" from "retry later".-//-// This is the only endpoint that responds this way. It exists because the endpoint's contract is the-// RFC rather than our own API conventions.+// The token endpoint answers in the shape RFC 6749 §5.2 defines, extended by `invalid_target` from+// RFC 8693 §2.2.2. Generic OAuth client libraries branch on the `error` code, so the house envelope+// (`{ statusCode, message, error: "UnauthorizedError" }`) leaves them unable to tell "rotate the client+// secret" from "re-authenticate the user" from "retry later". It is the only endpoint that does this.export enum OauthTokenErrorCode {InvalidRequest = "invalid_request",InvalidClient = "invalid_client",@@ -21,9 +17,9 @@ export enum OauthTokenErrorCode {ServerError = "server_error"}-// RFC 6749 section 5.2 puts every code at 400 and allows 401 for `invalid_client` alone. `server_error`-// is not in that list (it belongs to the authorization endpoint) but is the conventional code for a-// request the server cannot fulfil, and 500 is what tells a client to retry rather than rewrite.+// RFC 6749 §5.2 puts every code at 400 and allows 401 for `invalid_client` alone. `server_error` is not+// in that list (it belongs to the authorization endpoint), but 500 is what tells a client to retry+// rather than rewrite.const STATUS_CODE_BY_ERROR_CODE: Record<OauthTokenErrorCode, number> = {[OauthTokenErrorCode.InvalidRequest]: 400,[OauthTokenErrorCode.InvalidClient]: 401,@@ -35,10 +31,9 @@ const STATUS_CODE_BY_ERROR_CODE: Record<OauthTokenErrorCode, number> = {[OauthTokenErrorCode.ServerError]: 500};-// RFC 6749 section 5.2 restricts error_description to %x20-21 / %x23-5B / %x5D-7E: printable ASCII-// without the double quote or the backslash. Messages here are written for a human reading a terminal,-// not filtered for that, so normalise at the boundary rather than constraining every throw site. The cap-// is there because a schema failure can otherwise carry an issue list of unbounded length.+// RFC 6749 §5.2 allows only printable ASCII without `"` or `\`. Messages are written for a human+// reading a terminal, so normalise at the boundary rather than constraining every throw site. The cap is+// for schema failures, whose issue list is otherwise unbounded.const MAX_ERROR_DESCRIPTION_LENGTH = 512;const DISALLOWED_DESCRIPTION_CHARS = /[^\x20-\x21\x23-\x5B\x5D-\x7E]/g;@@ -68,28 +63,24 @@ export class OauthTokenError extends Error {}}-// RFC 8693 section 2.2.2 overrides RFC 6749 for the token-exchange grant, and not in the direction you-// would guess: a `subject_token` that is "invalid for any reason, or unacceptable based on policy" MUST-// be answered with `invalid_request`, where the same class of failure on the redirect and refresh grants-// is `invalid_grant` under RFC 6749 section 5.2. So the code a rejected grant earns depends on which-// grant was used, and only the exchange collapses "your token is bad" into "your request is bad".+// RFC 8693 §2.2.2 overrides RFC 6749 for token exchange: a `subject_token` "invalid for any reason, or+// unacceptable based on policy" MUST be answered with `invalid_request`, where the same failure on the+// redirect and refresh grants is `invalid_grant`. So a rejected grant's code depends on the grant.const REJECTED_GRANT_CODE_BY_GRANT_TYPE: Record<OauthGrantType, OauthTokenErrorCode> = {[OauthGrantType.AuthorizationCode]: OauthTokenErrorCode.InvalidGrant,[OauthGrantType.RefreshToken]: OauthTokenErrorCode.InvalidGrant,[OauthGrantType.TokenExchange]: OauthTokenErrorCode.InvalidRequest};-// Translates whatever escaped the token endpoint into an RFC code. Sites where the class default is-// wrong throw `OauthTokenError` directly and pass through here untouched; the defaults below only have-// to cover the rest, so they key off the error class and never the message text.-//-// `UnauthorizedError` on this path always means a grant we will not act on (a bad authorization code,-// refresh token or subject token, or a subject we cannot resolve to a usable account), so it takes-// whichever code that grant owes. Client authentication is the exception and throws `invalid_client`-// explicitly, which RFC 8693 leaves to RFC 6749 because it is the client that failed, not the token.+// Translates whatever escaped the token endpoint into an RFC code, keying off the error class and never+// the message text. Sites where the class default is wrong throw `OauthTokenError` directly and pass+// through untouched.//-// Anything that is neither is a bug or an outage rather than a bad request, so it becomes a generic-// `server_error`: its message was written for a different envelope and could carry internals.+// `UnauthorizedError` here always means a grant we will not act on (a bad authorization code, refresh+// token or subject token, or a subject we cannot resolve to a usable account), so it takes whichever code+// that grant owes. Client authentication throws `invalid_client` explicitly instead, because there it is+// the client that failed rather than the token. Anything else is a bug or an outage, so it becomes a+// generic `server_error`: its message was written for a different envelope and could carry internals.export const toOauthTokenError = (error: unknown, grantType?: OauthGrantType): OauthTokenError => {if (error instanceof OauthTokenError) return error;diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.tsindex 81a94b9fb6..b37fe4783b 100644--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts@@ -34,8 +34,8 @@ const buildDiscoveryDocumentUrl = (discoveryUrl: string) => {type TOidcDiscoveryMetadata = { jwks_uri?: string; issuer?: string };// Entries hold the in-flight promise so concurrent callers on a cold entry coalesce onto one fetch.-// Rejections are dropped instead of cached, otherwise a 5-second provider blip becomes 10 minutes of-// them. A full cache is cleared wholesale: the bound is there to cap memory, not to be a real LRU.+// Rejections are dropped rather than cached, or a 5-second provider blip becomes 10 minutes of them. A+// full cache is cleared wholesale: the bound caps memory, it is not a real LRU.const createTtlCache = <T>({ ttlMs, maxEntries }: { ttlMs: number; maxEntries: number }) => {const entries = new Map<string, { value: Promise<T>; expiresAt: number }>();@@ -65,11 +65,10 @@ const MAX_CACHED_PROVIDER_URLS = 512;const DISCOVERY_METADATA_TTL_MS = 10 * 60 * 1000;const JWKS_CLIENT_TTL_MS = 10 * 60 * 1000;-// Nothing stops a middleware from exchanging on every request, and without this cache that would make-// the identity provider a synchronous dependency of every Infisical call it serves.-//-// Only the fetch is cached, never the resolved trust anchor: the algorithm and preferred issuer come-// from the org's own SSO config, so changing either takes effect on the next request.+// A middleware may exchange on every request, and without this cache that makes the identity provider a+// synchronous dependency of every Infisical call it serves. Only the fetch is cached, never the resolved+// trust anchor: the algorithm and preferred issuer come from the org's SSO config, so an admin's edit+// takes effect on the next request.const discoveryMetadataCache = createTtlCache<TOidcDiscoveryMetadata>({ttlMs: DISCOVERY_METADATA_TTL_MS,maxEntries: MAX_CACHED_PROVIDER_URLS@@ -81,7 +80,7 @@ const getDiscoveryMetadata = (documentUrl: string) =>);// jwks-rsa caches signing keys per instance, so one client per JWKS URI keeps a fetch off the hot path.-// Entries still expire so the agent's pinned IPs get rebuilt: otherwise a legitimate DNS change at the+// Entries still expire so the agent's pinned IPs get rebuilt, otherwise a legitimate DNS change at the// provider would never be picked up for the life of the process.const jwksClientCache = createTtlCache<JwksClient>({ttlMs: JWKS_CLIENT_TTL_MS,diff --git a/docs/documentation/platform/oauth-applications/authorization-code.mdx b/docs/documentation/platform/oauth-applications/authorization-code.mdxindex d44dc1c8c2..ba86ed11a6 100644--- a/docs/documentation/platform/oauth-applications/authorization-code.mdx+++ b/docs/documentation/platform/oauth-applications/authorization-code.mdx@@ -138,9 +138,9 @@ The response contains:}```-Access token lifetime is the shortest of the application's **access token lifetime** (1 day by default), your organization's session length, and the instance default of 10 days. Refresh tokens follow the organization's session length rather than the application's lifetime, so shortening the lifetime shortens how long each access token lasts, not how long the client can keep refreshing. Refresh tokens rotate on use, and a refresh never broadens the scopes originally granted.+Access token lifetime is the shortest of the application's **access token lifetime** (1 day by default), your organization's session length, and the instance default of 10 days. Refresh tokens follow the organization's session length instead, so shortening the application's lifetime shortens each access token, not how long the client can keep refreshing. Refresh tokens rotate on use, and a refresh never broadens the scopes originally granted.-`refresh_token` is present only when the application holds the `refresh_token` grant, which applications created in the UI always do. If you registered one through the API with `grantTypes` limited to `authorization_code`, the field is omitted and the client should exchange a new authorization code when the access token expires.+`refresh_token` is present only when the application holds the `refresh_token` grant, which applications created in the UI always do. If you registered one through the API with `grantTypes` limited to `authorization_code`, the field is omitted and the client exchanges a new authorization code when the access token expires.### Validation endpointdiff --git a/docs/documentation/platform/oauth-applications/overview.mdx b/docs/documentation/platform/oauth-applications/overview.mdxindex cbb7f035ba..35abe6c10f 100644--- a/docs/documentation/platform/oauth-applications/overview.mdx+++ b/docs/documentation/platform/oauth-applications/overview.mdx@@ -43,7 +43,7 @@ Every application gets a **Client ID** and a **Client Secret** on creation. The## What a delegated token can never do-Whichever flow issued it, a delegated token cannot manage the authorizing user's account. Password, MFA, session, TOTP, and notification endpoints reject it outright, so an integration can never use its access to take over the account behind it. The individual flow pages cover the rest of each one's limits.+Whichever flow issued it, a delegated token cannot manage the authorizing user's account: password, MFA, session, TOTP, and notification endpoints reject it outright, so an integration can never take over the account behind it. Each flow page covers the rest of its own limits.## Revoking accessdiff --git a/docs/documentation/platform/oauth-applications/token-exchange.mdx b/docs/documentation/platform/oauth-applications/token-exchange.mdxindex c214364aba..0e73b5de31 100644--- a/docs/documentation/platform/oauth-applications/token-exchange.mdx+++ b/docs/documentation/platform/oauth-applications/token-exchange.mdx@@ -58,12 +58,13 @@ Structurally, this is your organization's OIDC sign-in with the token handed oveThe issued token carries the user's **full effective permissions**, not a narrowed subset. There is no consent screen and no scope list: an organization admin approves the delegation once, when registering the application.-The token works across the Infisical API wherever the user's own permissions allow, with four deliberate exceptions:+The token works across the Infisical API wherever the user's own permissions allow, with five exceptions. Each is somewhere a delegated token could otherwise leave behind access that revoking the application would not take back:- **Managing the user's account.** Password, MFA, session, and notification endpoints are never reachable with a delegated token.-- **Creating or deleting an organization**, including a sub-organization. All four require the user's own sign-in, so a delegated token is rejected even when the user is an organization admin. Updating an organization and managing its members stay available.-- **Minting another credential.** Machine identity tokens and client secrets, service tokens, SCIM tokens, KMIP client certificates, and gateway or relay enrollment tokens all outlive the delegation that created them, so issuing one stays first-party. Listing and revoking them is still available, since neither hands back secret material. Revoking this application has to revoke everything it obtained.-- **Widening its own access.** Managing OAuth applications, instance admin settings, upgrading the organization's privilege system, and both forms of privilege assumption stay first-party. That includes an organization admin granting themselves access to a project they are not a member of, because the membership it writes outlives the delegation that asked for it.+- **Creating or deleting an organization**, including a sub-organization. All four need the user's own sign-in, even when they are an organization admin. Updating an organization and managing its members stay available.+- **Minting another credential.** Machine identity tokens and client secrets, service tokens, SCIM tokens, KMIP client certificates, and gateway or relay enrollment tokens all outlive the delegation that created them, so issuing one stays first-party. Listing and revoking them stays available, since neither returns secret material.+- **Setting up a way to sign in as a machine identity.** Adding or editing an identity's authentication method registers a signing key, trusted issuer, certificate authority, or cloud principal that can authenticate as that identity from then on. Infisical never holds it, so it would keep working after you revoked this application. Creating identities, assigning their roles, reading their authentication methods, and removing them stay available.+- **Widening its own access.** Managing OAuth applications, instance admin settings, upgrading the organization's privilege system, and both forms of privilege assumption stay first-party. That includes an organization admin granting themselves access to a project they are not a member of, since the membership it writes outlives the delegation.No refresh token is issued. When the access token expires, your middleware exchanges again against the still-valid identity provider token.@@ -76,8 +77,8 @@ No refresh token is issued. When the access token expires, your middleware excha- **OIDC SSO is configured and enabled** for your organization.- **Your identity provider signs tokens with an asymmetric algorithm** (RS256, RS512, or EdDSA), matching the algorithm on your OIDC SSO configuration, and publishes a key ID (`kid`) in the token header.- **Its tokens carry an expiry (`exp`).** Infisical rejects a token without one, since it would be replayable indefinitely.-- **Each user has signed in to Infisical through OIDC SSO at least once.** Infisical matches the token's subject to the account created on that sign-in, so treat one browser sign-in as an onboarding step. The user also has to be an active member of the organization with their account set up and unlocked.-- **Your middleware has its own registration in your identity provider**, so its tokens carry an audience distinct from Infisical's, and are addressed to that registration alone or carry an `azp` claim naming it. See [Why the audience matters](#why-the-audience-matters).+- **Each user has signed in to Infisical through OIDC SSO at least once.** Infisical matches the token's subject to the account created on that sign-in, so treat one browser sign-in as an onboarding step. The user also has to be an active member of the organization, with their account set up and unlocked.+- **Your middleware has its own registration in your identity provider**, so its tokens carry an audience distinct from Infisical's, addressed to that registration alone or carrying an `azp` claim naming it. See [Why the audience matters](#why-the-audience-matters).## Registering your middleware@@ -97,9 +98,7 @@ You need permission to manage both OAuth applications and SSO, because enabling- **Identity provider enforces MFA**: Turn this on to declare that your identity provider already requires MFA. Without it, exchanges fail for any user who requires MFA, because there is no Infisical MFA challenge to run.- **Access token lifetime**: How long the tokens this application issues stay valid, 1 day by default. These tokens act as the user and carry no refresh token, so keep it to the shortest window your middleware can re-exchange within.- There is no issuer to set here. Infisical always verifies against your organization's OIDC SSO provider, which cannot be overridden per application.-- An application uses one flow or the other, so a service that needs both needs two registrations.+ There is no issuer to set here: Infisical always verifies against your organization's OIDC SSO provider, and that cannot be overridden per application. An application uses one flow or the other, so a service needing both needs two registrations.</Step><Step title="Store the credentials">Infisical shows the **Client ID** and **Client Secret** on creation.@@ -116,7 +115,7 @@ Your identity provider signs tokens for every application in your estate. WithouSet it to your middleware's own registration in your identity provider, never to Infisical's.-Some providers can be configured to address one token to several audiences at once, which would let a token minted for another application list yours alongside its own. When a subject token carries more than one audience, Infisical requires an `azp` (authorized party) claim naming your configured audience, and rejects the token otherwise. A token addressed to a single audience needs no `azp`, but if it carries one, that claim must name your configured audience as well.+Some providers can address one token to several audiences at once, which would let a token minted for another application list yours alongside its own. So when a subject token carries more than one audience, Infisical requires an `azp` (authorized party) claim naming your configured audience. A single-audience token needs no `azp`, but if it carries one, that claim must name your audience too.## Exchanging a token@@ -171,17 +170,17 @@ Failures follow [RFC 8693 section 2.2.2](https://datatracker.ietf.org/doc/html/r| `server_error` | 500 | Your OIDC SSO configuration is incomplete, or your identity provider could not be reached. Retry. |<Warning>- RFC 8693 requires `invalid_request` for a subject token that is invalid for any reason or unacceptable by policy, so an expired token, a wrong audience, and a user who is not an active member all arrive under the same code as a malformed request. This grant never returns `invalid_grant`, which is what the authorization code flow uses for the equivalent failure.+ RFC 8693 requires `invalid_request` for a subject token that is invalid for any reason or unacceptable by policy, so an expired token, a wrong audience, and a user who is not an active member all arrive under the same code as a malformed request. This grant never returns `invalid_grant`.- The distinction lives in `error_description`, which names the specific check that failed. Branch on the description, or simply re-authenticate the user and retry once, rather than expecting a code per cause.+ The distinction lives in `error_description`, which names the check that failed. Branch on that, or re-authenticate the user and retry once, rather than expecting a code per cause.</Warning>Retry on `server_error`. `invalid_client` and `unauthorized_client` need an operator, not a retry.<Note>- `scope`, `audience`, `resource`, and `actor_token` are rejected rather than ignored. This grant has no scope concept, and the expected audience is fixed on the application, so silently dropping those parameters would leave you believing a restriction was applied when it was not.+ `scope`, `audience`, `resource`, and `actor_token` are rejected rather than ignored, so you are never left believing a restriction was applied when it was not.- `actor_token` is refused for the same reason. RFC 8693 uses it to request **delegation**, where the issued token records that your middleware is acting for the user. Infisical issues an **impersonation** token, which is indistinguishable from the user's own and names no acting party, so accepting the parameter and dropping it would answer a delegation request with something weaker than you asked for. The requesting application is still recorded, in the audit event for the exchange and in every event the issued token produces.+ `actor_token` is refused for the same reason: RFC 8693 uses it to request **delegation**, where the issued token records your middleware as acting for the user. Infisical issues an **impersonation** token, indistinguishable from the user's own, so dropping the parameter would answer a delegation request with something weaker than you asked for. The requesting application is still recorded in the audit event for the exchange and in every event the issued token produces.</Note>Use the access token as a standard Bearer token:@@ -208,7 +207,7 @@ Exchanging per request makes your identity provider a hard dependency of every I- Drop the entry when the user's session at your identity provider ends, so their Infisical access does not outlive it.<Note>- Cache wherever you run Infisical. On Infisical Cloud the token endpoint is rate limited per source IP, so every instance of your middleware behind one egress address shares a single budget, and caching correctly means roughly one exchange per user per token lifetime, which stays well inside it. A self-hosted instance applies no limit of its own, so set one at your ingress and rely on caching to keep the endpoint quiet.+ On Infisical Cloud the token endpoint is rate limited per source IP, so every instance of your middleware behind one egress address shares a budget. Caching correctly means roughly one exchange per user per token lifetime, which stays well inside it. A self-hosted instance applies no limit of its own, so set one at your ingress.</Note>## What Infisical verifies@@ -236,6 +235,6 @@ These actions revoke every token the application has issued, so they stop workin- **Changing the audience**, in either direction, since tokens already issued were accepted on a basis that no longer holds.- **Turning off Identity provider enforces MFA.** That declaration is what let those exchanges skip an MFA requirement, so withdrawing it withdraws the tokens too.-Deactivating a user's organization membership stops further exchanges for that user, and the **OAuth Applications** page lists which applications use token exchange, so you can see the blast radius before changing SSO.+Deactivating a user's organization membership stops further exchanges for that user. The **OAuth Applications** page shows which applications use token exchange, so you can see the blast radius before changing SSO.Because no refresh tokens are issued, exposure from a compromised middleware is otherwise bounded by the remaining lifetime of the access tokens it holds.diff --git a/sso.md b/sso.mdindex 1cf0723a8a..608171afd2 100644--- a/sso.md+++ b/sso.md@@ -166,11 +166,11 @@ Token exchange lets trusted middleware present a user's token from your IdP andInfisical token. Its trust anchor is the org's OIDC SSO config, so everything above has to be workingfirst. See [OAuth Token Exchange](docs/documentation/platform/oauth-applications/token-exchange) for the product docs.-No license is needed. `plan.oidcSSO` is only checked when creating or updating an OIDC config through+No license is needed: `plan.oidcSSO` is only checked when creating or updating an OIDC config throughthe API, and `make seed-dev-oidc` writes the row directly.-**1. Seed, then confirm the trust anchor resolves.** This is what decides whether the `iss` check-passes, so check it rather than debugging a 401 later:+**1. Seed, then confirm the trust anchor resolves.** This decides whether the `iss` check passes, so+check it rather than debugging a rejection later:```bashmake seed-dev-oidc@@ -181,8 +181,8 @@ docker compose -f docker-compose.dev.yml exec -T backend \```Expect the issuer `http://localhost:8088/realms/infisical` (pinned by `KC_HOSTNAME`, and what tokens-actually carry) and a `jwks_uri` on `keycloak:8080` that the backend can reach. The seeded config-stores no issuer of its own, so the backend falls back to the discovered one.+actually carry) and a `jwks_uri` on `keycloak:8080` the backend can reach. The seeded config stores no+issuer of its own, so the backend falls back to the discovered one.**2. Register the application.** Sign in at http://localhost:8080 as `[email protected]` /`password123!`, then **Organization Settings > OAuth Applications > Add Application**. Choose flow@@ -208,13 +208,13 @@ curl -s -X POST http://localhost:8080/api/v1/oauth/token \-d subject_token_type=urn:ietf:params:oauth:token-type:id_token | python3 -m json.tool```-Use the **`id_token`**, not the access token. An ID token's `aud` is the requesting client by-specification, so it is already `infisical-mcp`. The realm defines no audience mapper, so Keycloak's-access token carries no `aud` at all (only `azp`) and is rejected.+Use the **`id_token`**, not the access token: an ID token's `aud` is the requesting client by+specification, so it is already `infisical-mcp`, while the realm defines no audience mapper, so+Keycloak's access token carries no `aud` at all (only `azp`) and is rejected.The response has `access_token`, `issued_token_type`, `token_type`, `expires_in`, and deliberately no-`refresh_token` and no `scope`. Decode it and you should see `delegation: "full"`, no `scopes` claim,-and the seeded admin's `userId`.+`refresh_token` or `scope`. Decode it and you should see `delegation: "full"`, no `scopes` claim, and+the seeded admin's `userId`.**4. Check what the token can do.**@@ -240,18 +240,20 @@ show the exchange attributed to `[email protected]` with the acting application inKeycloak issues the same `sub` to both clients and the browser login wrote the alias the exchangelooks up.-**Cases worth checking:**+**Cases worth checking.** RFC 8693 requires `invalid_request` for a subject token rejected for any+reason, so most of these come back 400 with the cause in `error_description`:| Case | How | Expect || --- | --- | --- |-| Cross-application replay | subject token from `infisical-dev` | 401, audience does not match |-| Shared extra audience | add an audience mapper putting `infisical-mcp` on `infisical-dev`'s tokens, then send one | 401, issued to `infisical-dev`, not this application |-| Access token instead of ID token | send `access_token` | 401, audience does not match |-| Tampered signature | change a character in the third JWT segment | 401, could not be verified |-| `scope` supplied | add `-d scope=secrets:read` | 400, scope not supported |-| SSO disabled | `update oidc_configs set "isActive"=false;` | 400, naming the SSO settings |-| MFA required | enforce org MFA, leave the application flag off | 401, MFA required |-| Unregistered grant | use an authorization-code application's credentials | 401, not registered for the grant |+| Cross-application replay | subject token from `infisical-dev` | 400 `invalid_request`, audience does not match |+| Shared extra audience | add an audience mapper putting `infisical-mcp` on `infisical-dev`'s tokens, then send one | 400 `invalid_request`, issued to `infisical-dev`, not this application |+| Access token instead of ID token | send `access_token` | 400 `invalid_request`, audience does not match |+| Tampered signature | change a character in the third JWT segment | 400 `invalid_request`, could not be verified |+| MFA required | enforce org MFA, leave the application flag off | 400 `invalid_request`, MFA required |+| `scope` supplied | add `-d scope=secrets:read` | 400 `invalid_scope` |+| Unregistered grant | use an authorization-code application's credentials | 400 `unauthorized_client` |+| Wrong client secret | change a character in `CLIENT_SECRET` | 401 `invalid_client` |+| SSO disabled | `update oidc_configs set "isActive"=false;` | 500 `server_error`, naming the SSO settings |---