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 comments
Thiago Araujo da Silva82cce5f35766
diff --git a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.tsindex 3019889192..1babf8d793 100644--- a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts+++ b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts@@ -116,8 +116,8 @@ describe("OAuth client grant type registration", async () => {expect(res.payload).toContain("audience only applies");});- // Duplicates used to be silently accepted below the array bound and reported as "too many items" above- // it, so the same mistake failed differently depending on how many times it was repeated.+ // Duplicates used to slip through below the array bound and come back as "too many items" above it,+ // so the same mistake failed differently depending on how often it was repeated.test("reports duplicate grant types as duplicates, however many there are", async () => {const res = await createClient({name: "e2e-duplicate-grants",@@ -134,9 +134,9 @@ describe("OAuth client grant type registration", async () => {expect(res.payload).toContain("duplicate");});- // Rotation on a token exchange application needs SSO edit permission on top of OauthClients edit, but- // it must stay a plain OauthClients operation for every other application. The seed actor holds both- // permissions, so this pins the non-exchange path rather than the denial.+ // Rotation needs SSO edit on top of OauthClients edit for token exchange applications, but must stay a+ // plain OauthClients operation for everything else. The seed actor holds both, so this pins the+ // non-exchange path, not the denial.test("rotating a redirect-flow application's secret needs no SSO permission", async () => {const created = await createClient({name: "e2e-rotate-redirect-client",@@ -157,7 +157,7 @@ describe("OAuth client grant type registration", async () => {await deleteClient(client.id);});- // The seed org has no OIDC config, and that config is the only trust anchor token exchange has.+ // The seed org has no OIDC config, which is the only trust anchor token exchange has.test("the token exchange grant cannot be enabled without an active OIDC SSO configuration", async () => {const res = await createClient({name: "e2e-exchange-no-sso",@@ -247,8 +247,8 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {expect(res.payload).toContain("requested_token_type");});- // RFC 8693 permits both, but this grant has no scope concept and its audience is fixed per- // application, so silently dropping them is worse than a clear error.+ // RFC 8693 allows both, but this grant has no scopes and its audience is fixed per application, so+ // silently ignoring them is worse than a clear error.test("rejects a scope parameter rather than ignoring it", async () => {const res = await postToken(exchangeBody({ scope: "secrets:read" }));@@ -264,8 +264,8 @@ describe("POST /api/v1/oauth/token, token exchange grant", async () => {});});-// Mints a delegated token for the seed user on the same session as the working jwtAuthToken, so it-// passes signature and session validation and differs only by its delegation marker.+// Same session as the working jwtAuthToken, so it passes signature and session validation and differs+// only by its delegation marker.const signDelegatedToken = (markers: { scopes?: string[]; delegation?: OauthDelegationMode }) =>jwt.sign({@@ -302,7 +302,7 @@ describe("Full delegation marker on a delegated OAuth token", async () => {expect(res.statusCode).toBe(200);});- // The invariant that makes the marker safe: dropping the claim by mistake cannot promote a token.+ // The invariant that makes the marker safe: dropping the claim by mistake can't promote a token.test("a token carrying neither marker is denied", async () => {const token = signDelegatedToken({});@@ -317,8 +317,8 @@ describe("Full delegation marker on a delegated OAuth token", async () => {expect(res.statusCode).toBe(403);});- // Account self-management routes authenticate on userId alone and build no permission, so they must- // stay unreachable whatever delegation marker the token carries.+ // Account routes authenticate on userId alone and build no permission, so they have to stay+ // unreachable whatever delegation marker the token carries.test("a fully-delegated token is still rejected on a JWT-only account route", async () => {const token = signDelegatedToken({ delegation: OauthDelegationMode.Full });@@ -332,8 +332,8 @@ describe("Full delegation marker on a delegated OAuth token", async () => {});});-// A refresh token is only usable if the application holds the refresh_token grant, so issuing one to an-// application without it hands back a credential the token endpoint rejects on use.+// A refresh token only works if the application holds the refresh_token grant, so issuing one without it+// hands back a credential the token endpoint rejects on use.describe("Refresh token issuance follows the registered grants", async () => {const REDIRECT_URI = "https://app.example.com/callback";@@ -367,10 +367,7 @@ describe("Refresh token issuance follows the registered grants", async () => {};test("issues a refresh token when the application holds the refresh_token grant", async () => {- const { clientDbId, token } = await runCodeFlow([- OauthGrantType.AuthorizationCode,- OauthGrantType.RefreshToken- ]);+ const { clientDbId, token } = await runCodeFlow([OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken]);expect(token.statusCode).toBe(200);expect(JSON.parse(token.payload)).toHaveProperty("refresh_token");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 3572947e1a..46c0103e42 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@@ -16,20 +16,20 @@ export async function up(knex: Knex): Promise<void> {if (hasGrantTypes && hasTokenExchangeAudience && hasTokenExchangeIdpSatisfiesMfa) return;await knex.schema.alterTable(TableName.OauthClient, (t) => {- // The default only exists to backfill existing rows. It is dropped below so an insert that omits- // the column fails instead of silently picking a grant set.+ // The default is only here to backfill existing rows, and gets dropped below so an insert that+ // omits the column fails instead of silently picking a grant set.if (!hasGrantTypes) {t.specificType("grantTypes", "text[]").notNullable().defaultTo(knex.raw(REDIRECT_FLOW_GRANT_TYPES));}- // Expected `aud` of subject tokens. This is the application's own registration in the org's IdP,- // not Infisical's, so it cannot be read from oidc_configs.+ // 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.if (!hasTokenExchangeAudience) {t.text("tokenExchangeAudience");}- // Token exchange has no Infisical MFA challenge to run, so an admin declares that the IdP- // enforces it. Without the declaration, 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);}diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex db7db4dda6..4095d40e11 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -89,12 +89,12 @@ import {ProjectPermissionSub} from "./project-permission";-// Returns the scopes to narrow this request to, or undefined when no narrowing applies. A returned-// array, even empty, means narrowing applies, so [] denies all scope-guarded access.+// 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 a first-party session or background job, and a fully-delegated token from the RFC-// 8693 exchange grant. inject-identity leaves the key unset only for the latter and sets it for every-// scope-narrowed delegation, so a token carrying neither marker still ends up with zero permissions.+// 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.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 7f303aec07..dad3f19e87 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -114,9 +114,9 @@ export type TAuthMode =token: TKmipServerAccessTokenJwtPayload;};-// A first-party session and a delegated OAuth token share the same auth shape, so a handler that-// only needs the acting user (name, email, session id) should accept both rather than narrowing on-// AuthMode.JWT alone — otherwise an OAuth caller silently loses the audit trail or actor metadata.+// 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.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 41851e6800..7c31a5d45b 100644--- a/backend/src/server/plugins/auth/verify-auth.ts+++ b/backend/src/server/plugins/auth/verify-auth.ts@@ -17,19 +17,15 @@ export const verifyAuth =if (!Array.isArray(authStrategies)) throw new Error("Auth strategy must be array");if (!req.auth) throw new UnauthorizedError({ message: "Token missing" });- // Delegated OAuth access tokens are a distinct auth mode and must be opted into explicitly: a- // route only accepts them when it lists AuthMode.OAUTH. They are deliberately NOT accepted on- // the strength of AuthMode.JWT alone. OAuth scopes are enforced later, when a handler builds an- // org/project permission (the ability is intersected with the granted scopes). A route that- // authenticates on userId without building a permission never runs that scope narrowing, so- // letting a delegated token through on JWT alone would bypass scopes entirely. Listing- // AuthMode.OAUTH is therefore only safe when the handler performs a scope-narrowed permission- // check, and the route families that cannot are the ones still listing AuthMode.JWT alone:- // account self-management (/me, password, MFA, sessions, login, signup, notifications),- // instance 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.- // A useful proxy: no route passing `requireOrg: false` accepts AuthMode.OAUTH, because without an- // org in context there is no ability to intersect the granted scopes against.+ // 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.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/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex d80aaaa02e..1113d1c19a 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -45,9 +45,9 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- // Deliberately not open to AuthMode.OAUTH, unlike the rest of this router. There is no org in- // context to build a permission against, so nothing narrows the result to what the token was- // delegated — 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 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.onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {const organizations = await server.services.org.findAllOrganizationOfUser(req.permission.id);@@ -72,9 +72,9 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- // Deliberately not open to AuthMode.OAUTH, unlike the rest of this router. There is no org in- // context to build a permission against, so nothing narrows the result to what the token was- // delegated — 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 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.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 100eca4b04..30a0505eb0 100644--- a/backend/src/server/routes/v2/organization-router.ts+++ b/backend/src/server/routes/v2/organization-router.ts@@ -427,9 +427,9 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- // Deliberately 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 would be able to- // stand up an org the client was never granted anything in.+ // 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.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/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex fe3e38ca45..ba2ef5597e 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -107,8 +107,8 @@ export type AuthModeJwtTokenPayload = {// Granted OAuth delegation scopes (see OauthScope). The delegated ability is intersected with// these in permission-service; an empty/absent list denies all scope-guarded resource access.scopes?: string[];- // Present instead of `scopes` on RFC 8693 token exchange tokens, which carry the user's authorization- // unnarrowed. A token has this or `scopes`, never both. See OauthDelegationMode.+ // Set instead of `scopes` on RFC 8693 token exchange tokens, which carry the user's authorization+ // unnarrowed. Never both. See OauthDelegationMode.delegation?: string;};diff --git a/backend/src/services/oauth-client/oauth-client-fns.ts b/backend/src/services/oauth-client/oauth-client-fns.tsindex 48d9f7555f..0f17132da0 100644--- a/backend/src/services/oauth-client/oauth-client-fns.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.ts@@ -76,15 +76,15 @@ type TOauthClientAuthority = Pick<"clientSecretHash" | "grantTypes" | "tokenExchangeAudience" | "tokenExchangeIdpSatisfiesMfa">;-// Whether the client an exchange authenticated against has since lost the authority it was granted:-// deleted, secret rotated, or the grant withdrawn. Comparing the stored hashes is enough, because a-// rotation writes a fresh bcrypt hash with a new salt, so no second compareHash is needed.+// 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.//-// Token exchange also compares the two fields that carry its federation trust. The audience is the-// only thing standing between the caller and any token the issuer signs, and the IdP-MFA declaration-// is what lets an exchange skip an MFA requirement, so an admin narrowing either one has withdrawn-// authority just as much as one rotating the secret. The exchange reads them off a replica, so-// without this they would 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, 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.export const hasClientAuthorityChanged = (authenticated: TOauthClientAuthority,current: TOauthClientAuthority | undefined,diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 4fcc4b525a..65e99d35c6 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -74,8 +74,8 @@ const sanitizeOauthClient = (client: TOauthClients) => {return rest;};-// The generated schema types the column as `string[]`, since it is a plain text[] in Postgres. Every-// value written to it goes through the router's `grantTypesSchema`, so the narrowing holds.+// The column is a plain text[] in Postgres, so the generated schema types it as `string[]`. Every write+// goes through the router's `grantTypesSchema`, so the narrowing holds.const getGrantTypes = (client: TOauthClients) => client.grantTypes as OauthGrantType[];const expiresInToSeconds = (expiresIn: string | number) =>@@ -123,9 +123,9 @@ const signOauthToken = (// Marks this as a delegated OAuth token. extractAuth maps tokens carrying this claim to// AuthMode.OAUTH so they are rejected by the default first-party JWT middleware.oauthClientId: claims.oauthClientId,- // Exactly one delegation marker per token. `scopes` narrows the ability to what the user- // consented to, `delegation` carries it unnarrowed. Absence of both means zero permissions, so- // dropping either claim by mistake fails closed. See OauthDelegationMode.+ // Exactly one delegation marker per token: `scopes` narrows the ability to what the user+ // consented to, `delegation` carries it unnarrowed. Neither claim means zero permissions, so+ // dropping one by mistake fails closed. See OauthDelegationMode....(claims.delegation ? { delegation: claims.delegation } : { scopes: claims.scopes })},appCfg.AUTH_SECRET,@@ -157,13 +157,12 @@ export const oauthClientServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.OauthClients);};- // The token exchange grant converts externally-issued tokens into Infisical user tokens, so anything- // that establishes that trust or hands out a working credential for it is a change to the org's- // federation posture, not just an application edit. Those operations need the permission that already- // owns the SSO configuration on top of the usual OauthClients check.+ // 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` names the operation in the error, because the reason an OAuth application change needs SSO- // permission is not self-evident to the admin who hits it.+ // `action` goes in the error because it's not obvious why an OAuth application change wants SSO+ // permission.const checkSsoConfigPermission = async (actor: OrgServiceActor, action: string) => {const { permission } = await permissionService.getOrgPermission({actor: actor.type,@@ -190,15 +189,10 @@ export const oauthClientServiceFactory = ({return client;};- // An OAuth client always belongs to a root organization: every management method goes through- // checkOauthClientPermission, which is scoped to ParentOrganization, and an organization's rootOrgId- // is fixed when it is created. So the org that owns the client is also the one carrying everything- // these flows read off it — MFA enforcement, the OIDC SSO configuration and OIDC user aliases all- // live on the root organization, matching the login flow.- //- // Asserted rather than assumed. If sub-organizations are ever allowed to own clients, resolving the- // root organization has to become explicit here, or the exchange would silently verify subject tokens- // against a sub-organization's own OIDC configuration and look up aliases in the wrong org.+ // 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.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,8 +206,8 @@ export const oauthClientServiceFactory = ({return org;};- // Token exchange has nothing to verify a subject token against until federation is live. Failing at- // configuration time puts the message in front of the admin setting the application up.+ // 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.const getActiveOidcConfigOrThrow = async (orgId: string) => {const org = await getClientOrg(orgId);const oidcConfig = await oidcConfigDAL.findOne({ orgId: org.id });@@ -235,14 +229,11 @@ export const oauthClientServiceFactory = ({return { oidcConfig, org };};- // Registering and editing an application ask the same questions of a grant configuration: which grants- // the client ends up holding, whether the per-grant fields are coherent with them, and whether the- // actor may establish the federation trust that token exchange implies. An edit answers them against- // the stored client and a registration against nothing, so `client` is the only difference between the- // two callers.+ // 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 two token exchange gates run only when the request actually touches that configuration, so an- // admin holding OauthClients Edit alone can still rename an application that happens to use the grant.+ // 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.const resolveGrantConfig = async ({dto,actor,@@ -331,8 +322,7 @@ export const oauthClientServiceFactory = ({return { client: sanitizeOauthClient(client), clientSecret };};- // `grantType` narrows the list to one grant. The SSO page uses it to show which applications depend- // on the org's OIDC issuer.+ // The SSO page passes `grantType` to show which applications depend on the org's OIDC issuer.const listOauthClients = async (actor: OrgServiceActor, grantType?: OauthGrantType) => {await checkOauthClientPermission(actor, OrgPermissionActions.Read);@@ -576,10 +566,9 @@ export const oauthClientServiceFactory = ({const getTokenLifetimes = async (orgId: string) => resolveTokenLifetimes(await orgDAL.findById(orgId));- // RFC 8693 token exchange: the SSO login path with the token supplied directly instead of collected- // through a browser redirect, and an access token issued instead of a session cookie. With no redirect- // URI, no PKCE and no browser session to anchor trust on, the audience check below is what stops any- // token the issuer signs, for any application, being replayed here.+ // 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.const exchangeSubjectToken = async (client: TOauthClients,dto: Extract<TOauthTokenExchangeDTO, { grantType: OauthGrantType.TokenExchange }>diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.tsindex 5f43320f74..2232a0f165 100644--- a/backend/src/services/oauth-client/oauth-client-types.ts+++ b/backend/src/services/oauth-client/oauth-client-types.ts@@ -2,16 +2,16 @@ 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 grant makes a different subset-// of the client's fields meaningful. See assertValidOauthClientGrantConfig.+// 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.export enum OauthGrantType {AuthorizationCode = "authorization_code",RefreshToken = "refresh_token",TokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"}-// Applied as the create default so an API caller written before this feature, which sends no-// `grantTypes`, keeps registering redirect-flow applications.+// The create default, so callers written before this feature (which send no `grantTypes`) keep+// registering redirect-flow applications.export const DEFAULT_OAUTH_GRANT_TYPES: readonly OauthGrantType[] = [OauthGrantType.AuthorizationCode,OauthGrantType.RefreshToken@@ -24,15 +24,13 @@ export enum OauthTokenType {AccessToken = "urn:ietf:params:oauth:token-type:access_token"}-// Both are verified identically, as a signed JWT from the org's OIDC SSO issuer, so the difference is-// only what the caller declares.+// 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.export const ACCEPTED_SUBJECT_TOKEN_TYPES: readonly OauthTokenType[] = [OauthTokenType.Jwt, OauthTokenType.IdToken];-// Marks a token as carrying the user's authorization unnarrowed, as opposed to the consented scopes an-// authorization-code token carries.-//-// Deliberately a positive marker rather than an absent `scopes` claim: absence has to keep meaning zero-// permissions, so that dropping the claim by mistake fails closed.+// 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.export enum OauthDelegationMode {Full = "full"}diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.tsindex e834c9ac0c..676ea0fe0d 100644--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts@@ -43,16 +43,15 @@ const ISSUER = "https://adfs.example.com/adfs";const AUDIENCE = "api://internal-mcp";const SUBJECT = "8f7d1c22-0000-4a7b-9b1e-aaaabbbbcccc";-// A unique JWKS URI per test keeps the module-level JwksClient cache from carrying a client between-// cases.+// A unique JWKS URI per test keeps the module-level JwksClient cache from leaking between cases.let jwksUriCounter = 0;const nextJwksUri = () => {jwksUriCounter += 1;return `https://adfs.example.com/adfs/discovery/keys?case=${jwksUriCounter}`;};-// Same reason, for the discovery document cache: a case that wants its own mocked document needs its own-// URL, or it reads the previous case's cached one.+// Same for the discovery cache: a case that mocks its own document needs its own URL, or it reads the+// previous case's cached one.let discoveryCaseCounter = 0;const nextIssuerBase = () => {discoveryCaseCounter += 1;@@ -108,7 +107,7 @@ const signSubjectToken = ({...(keyId ? { keyid: keyId } : {})});-// jsonwebtoken cannot sign EdDSA, so the EdDSA cases mint their tokens with jose.+// jsonwebtoken can't sign EdDSA, so those cases mint their tokens with jose.const signEddsaSubjectToken = async ({audience = AUDIENCE,issuer = ISSUER@@ -244,8 +243,7 @@ describe("resolveOidcTrustAnchor", () => {).rejects.toThrow(/no discovery URL/);});- // Token exchange runs on every request the middleware makes, so the discovery document must not be a- // per-exchange round trip to the identity provider.+ // Middlewares can exchange per request, so this must not be a round trip to the IdP every time.test("fetches the discovery document once across repeated resolutions", async () => {safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });const discoveryURL = nextDiscoveryUrl();@@ -279,8 +277,7 @@ describe("resolveOidcTrustAnchor", () => {expect(safeGet).toHaveBeenCalledTimes(2);});- // The algorithm and the preferred issuer come from the org's own configuration, so only the fetch is- // cached: an admin editing either must not have to wait out the discovery TTL.+ // Only the fetch is cached, so an admin editing the algorithm or issuer doesn't wait out the TTL.test("does not cache configuration read from the organization's own record", async () => {safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });const discoveryURL = nextDiscoveryUrl();@@ -319,7 +316,7 @@ describe("verifySubjectToken", () => {await expect(verify(token)).resolves.toMatchObject({ subject: SUBJECT });});- // The control that stops any token the issuer signed, for any application, being replayed here.+ // The audience is what stops any token the issuer signed being replayed here.test("rejects a token minted for a different application", async () => {const token = signSubjectToken({ audience: "api://expenses-app" });@@ -373,8 +370,8 @@ describe("verifySubjectToken", () => {await expect(verify(token)).rejects.toThrow(/not signed with the algorithm/);});- // EdDSA is selectable in the OIDC SSO configuration and works for browser SSO login, so it has to work- // here too. jsonwebtoken cannot verify it at all, which is why verification runs through jose.+ // EdDSA works for browser SSO login, so it has to work here too. jsonwebtoken can't verify it at all,+ // which is why verification runs through jose.test("verifies an EdDSA-signed token for an EdDSA configuration", async () => {getSigningKey.mockResolvedValue({ getPublicKey: () => ED25519_PUBLIC_KEY_PEM });const token = await signEddsaSubjectToken();@@ -393,8 +390,8 @@ describe("verifySubjectToken", () => {).rejects.toThrow(/audience does not match/);});- // An RSA key cannot carry EdDSA. That is the provider's configuration disagreeing with itself, not a- // bad token, so it must not surface as an unhandled 500.+ // An RSA key can't carry EdDSA. That's the provider's config disagreeing with itself, not a bad+ // token, so it must not come out as a 500.test("reports a signing key that cannot carry the configured algorithm", async () => {const token = await signEddsaSubjectToken();@@ -447,8 +444,7 @@ describe("verifySubjectToken", () => {await expect(verify(signSubjectToken())).rejects.toThrow(/Could not load signing keys/);});- // Same reasoning as the discovery document: token exchange runs on every request the middleware makes,- // so building the pinned agent must not be per-exchange work.+ // Same as the discovery document: building the pinned agent must not be per-exchange work.test("builds the JWKS client once across repeated verifications", async () => {const oidcConfig = buildOidcConfig();const token = signSubjectToken();diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.tsindex 5c141c73bb..e5b700f10f 100644--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts@@ -9,8 +9,8 @@ import { buildSsrfSafeAgent, safeRequest } from "@app/lib/validator/safe-requestconst SSO_TAB_HINT = "Check Settings > SSO & Provisioning.";-// HS256 is excluded because it is symmetric: the verification key is the signing key, so anyone who-// can read the JWKS could mint a token we would accept.+// HS256 is left out because it's symmetric: the verification key is the signing key, so anyone who can+// read the JWKS could mint a token we'd accept.const ASYMMETRIC_SIGNATURE_ALGORITHMS: readonly string[] = [OIDCJWTSignatureAlgorithm.RS256,OIDCJWTSignatureAlgorithm.RS512,@@ -19,9 +19,8 @@ const ASYMMETRIC_SIGNATURE_ALGORITHMS: readonly string[] = [const WELL_KNOWN_OPENID_CONFIGURATION = "/.well-known/openid-configuration";-// Mirrors what openid-client's Issuer.discover accepts, so a configuration that works for browser SSO-// login resolves the same way here: a discovery URL may already point at the document, or be the-// issuer base that the well-known path hangs off.+// Mirrors what openid-client's Issuer.discover accepts, so a config that works for browser SSO login+// resolves the same way here: the URL may already point at the document, or be the issuer base.const buildDiscoveryDocumentUrl = (discoveryUrl: string) => {const url = new URL(discoveryUrl);if (url.pathname.includes("/.well-known/")) return url.toString();@@ -32,15 +31,9 @@ const buildDiscoveryDocumentUrl = (discoveryUrl: string) => {type TOidcDiscoveryMetadata = { jwks_uri?: string; issuer?: string };-// Everything token exchange fetches from an identity provider is cached the same way, so the mechanics-// live here once:-//-// - Entries hold the in-flight promise, so concurrent callers on a cold entry coalesce onto one fetch-// instead of stampeding the provider.-// - A rejected entry is dropped rather than kept for its TTL, so a provider blip lasts as long as the-// blip. Caching the failure would turn a 5-second outage into 10 minutes of them.-// - A full cache is cleared wholesale rather than evicted by age. A flush only costs a refetch, and the-// bound exists to cap memory against an org churning through provider URLs, not to be a working LRU.+// 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.const createTtlCache = <T>({ ttlMs, maxEntries }: { ttlMs: number; maxEntries: number }) => {const entries = new Map<string, { value: Promise<T>; expiresAt: number }>();@@ -64,19 +57,17 @@ const createTtlCache = <T>({ ttlMs, maxEntries }: { ttlMs: number; maxEntries: nreturn { getOrCreate };};-// Both caches are keyed on the URL rather than the org, so orgs on a shared provider share one entry,-// and an admin correcting a URL moves to a different key instead of waiting out the TTL.+// Keyed on the URL, not the org, so orgs on a shared provider share an entry and an admin fixing a+// typo'd URL moves to a new key instead of waiting out the TTL.const MAX_CACHED_PROVIDER_URLS = 512;const DISCOVERY_METADATA_TTL_MS = 10 * 60 * 1000;const JWKS_CLIENT_TTL_MS = 10 * 60 * 1000;-// Fetching the discovery document is a network round trip. Integrators are told to exchange once per-// user and cache the token, but we cannot enforce that, and a middleware that exchanges per request-// would otherwise make the identity provider a synchronous dependency of every Infisical call it serves.+// 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 the preferred issuer come-// from the org's own SSO configuration, so an admin changing either still takes effect on the next-// request.+// 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.const discoveryMetadataCache = createTtlCache<TOidcDiscoveryMetadata>({ttlMs: DISCOVERY_METADATA_TTL_MS,maxEntries: MAX_CACHED_PROVIDER_URLS@@ -87,11 +78,9 @@ const getDiscoveryMetadata = (documentUrl: string) =>safeRequest.get<TOidcDiscoveryMetadata>(documentUrl, { timeout: 10_000 }).then(({ data }) => data));-// jwks-rsa caches signing keys per instance, so reusing one per JWKS URI keeps a network fetch off the-// hot path. Token exchange runs on every request the middleware makes.-//-// Entries expire so the agent's pinned IPs are rebuilt periodically. Without that, a legitimate DNS-// change at the identity provider would not be picked up for the lifetime of the process.+// 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+// provider would never be picked up for the life of the process.const jwksClientCache = createTtlCache<JwksClient>({ttlMs: JWKS_CLIENT_TTL_MS,maxEntries: MAX_CACHED_PROVIDER_URLS@@ -119,8 +108,8 @@ export type TOidcTrustAnchor = {algorithm: string;};-// Uses the same configuration that governs browser SSO login, so the issuers that can vouch for a user-// through token exchange are exactly those that can already log them in.+// Reuses the config that governs browser SSO login, so the issuers that can vouch for a user here are+// exactly the ones that can already log them in.export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<TOidcTrustAnchor> => {const algorithm = oidcConfig.jwtSignatureAlgorithm || OIDCJWTSignatureAlgorithm.RS256;@@ -176,10 +165,9 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<return { issuer: oidcConfig.issuer, jwksUri: oidcConfig.jwksUri, algorithm };};-// jose reports failures with terse developer-facing text ("unexpected \"aud\" claim value"). Translate to-// something the caller can act on without leaking the raw message. Each branch keys off jose's error-// class and its `claim` field rather than the message text, so a wording change upstream cannot silently-// collapse a specific failure into the generic one.+// jose's messages are terse and developer-facing ("unexpected \"aud\" claim value"), so translate them+// into something the caller can act on. Branches key off the error class and `claim` field, never the+// message text, so a wording change upstream can't silently collapse a case into the generic one.const toSubjectTokenError = (error: unknown, anchor: TOidcTrustAnchor, expectedAudience: string) => {if (error instanceof joseErrors.JWTExpired) {return new UnauthorizedError({ message: "The subject token has expired." });@@ -233,8 +221,6 @@ type TVerifySubjectTokenDTO = {expectedAudience: string;};-// Every check deciding whether we believe this token describes this user lives here: signature, issuer,-// audience, expiry, not-before and algorithm.export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAudience }: TVerifySubjectTokenDTO) => {const anchor = await resolveOidcTrustAnchor(oidcConfig);@@ -294,8 +280,8 @@ export const verifySubjectToken = async ({ subjectToken, oidcConfig, expectedAudissuer: anchor.issuer,audience: expectedAudience,algorithms: [anchor.algorithm],- // 'exp' is optional in RFC 7519 and only checked when present, so without this a token that omits- // it is exchangeable forever.+ // 'exp' is optional in RFC 7519 and only checked when present, so without this a token that+ // omits it is exchangeable forever.requiredClaims: ["exp"]}));} catch (error) {diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 87ba93c1ea..fd8fe04ff8 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -259,9 +259,9 @@ services:keycloak:# Admin console: http://localhost:8088 (admin / admin).- # On boot it imports the pre-seeded `infisical` realm from the mounted realm file: clients- # `infisical-dev` (SSO login) and `infisical-mcp` (token exchange), users john/alice/admin.- # The container has no volume, so the realm is re-imported fresh on every start. See sso.md.+ # Imports the pre-seeded `infisical` realm on boot: clients `infisical-dev` (SSO login) and+ # `infisical-mcp` (token exchange), users john/alice/admin. No volume, so it's fresh every start.+ # See sso.md.image: quay.io/keycloak/keycloak:26.1.0restart: alwaysenvironment:diff --git a/frontend/src/hooks/api/oauthClients/queries.tsx b/frontend/src/hooks/api/oauthClients/queries.tsxindex 4fd6caabd1..b540e8a467 100644--- a/frontend/src/hooks/api/oauthClients/queries.tsx+++ b/frontend/src/hooks/api/oauthClients/queries.tsx@@ -12,8 +12,7 @@ export const oauthClientKeys = {["oauth-authorize-info", clientId, redirectUri, scope ?? ""] as const};-// `grantType` narrows the list to applications registered for one grant. The SSO page uses it to show-// which applications depend on the org's OIDC issuer.+// The SSO page passes `grantType` to show which applications depend on the org's OIDC issuer.export const useGetOauthClients = (orgId: string, grantType?: OauthGrantType) => {return useQuery({queryKey: oauthClientKeys.list(orgId, grantType),diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsxindex 5838eac8a7..4d930db22e 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx@@ -61,9 +61,8 @@ const splitRedirectUris = (value: string) =>.map((uri) => uri.trim()).filter(Boolean);-// The UI models one flow per application even though the API allows a client to hold several grants.-// The two flows share no configuration and delegate differently, so an application needing both is a-// direct API call.+// The API lets a client hold several grants, but the UI sticks to one flow per application: the two+// share no config and delegate differently, so an application needing both goes through the API.enum OauthClientFlow {AuthorizationCode = "authorization-code",TokenExchange = "token-exchange"