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
add token exchange oauth client
Thiago Araujo da Silvad12fb17e5acf
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 453b42ffb3..8e7aafaf6d 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -173,6 +173,30 @@ 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 minted by the `oauth-client` module. Same JWT shape and session+ binding as `JWT`, distinguished only by an `oauthClientId` claim. **Opt-in per route**: `verify-auth.ts`+ rejects them on every route that does not list `AuthMode.OAUTH`, because a route that authenticates on+ bare `userId` (account self-management) never builds the permission that enforces delegation.++**Delegated OAuth 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 these (`applyOauthScopeToOrgRules` / `applyOauthScopeToProjectRules`).+- `delegation: "full"`: from the RFC 8693 token exchange grant, which has no scope concept and carries+ the user's effective authorization unnarrowed.++**Absence of both must keep meaning zero permissions.** `inject-identity.ts` sets+`RequestContextKey.OauthScopes` for every scope-narrowed token (even to `[]`, which denies everything)+and leaves it unset only for `delegation: "full"`. `getDelegatedOauthScopes` in `permission-service.ts`+reads an unset key as "no narrowing". Matching the full-delegation marker positively is what makes a+dropped claim fail closed instead of silently promoting the token to unrestricted.++**Token exchange's trust anchor is the org's OIDC SSO config**, not per-client configuration+(`oauth-token-exchange-fns.ts`). The set of issuers that can vouch for a user through exchange is+exactly the set that can already log them in, under the permission that already governs it. The one+per-application field is `tokenExchangeAudience`, and it is the control that does the security work:+without it, any token that issuer signed for any application in the customer's estate is exchangeable.+Enabling the grant or changing the audience therefore requires `OrgPermissionSsoActions.Edit` on top of+the usual `OauthClients` check.**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.diff --git a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.tsnew file mode 100644index 0000000000..b26d6dc464--- /dev/null+++ b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts@@ -0,0 +1,277 @@+import jwt from "jsonwebtoken";++import { seedData1 } from "@app/db/seed-data";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";+import { OauthDelegationMode, OauthGrantType, OauthTokenType } from "@app/services/oauth-client/oauth-client-types";++const TOKEN_EXCHANGE_GRANT = OauthGrantType.TokenExchange;++const createClient = async (body: Record<string, unknown>) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/oauth/clients",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body+ });++const deleteClient = async (clientDbId: string) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/oauth/clients/${clientDbId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });++const postToken = async (body: Record<string, string>) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/oauth/token",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ payload: new URLSearchParams(body).toString()+ });++describe("OAuth client grant type registration", async () => {+ test("registering a redirect-flow application still works without sending grantTypes", async () => {+ const res = await createClient({+ name: "e2e-legacy-redirect-client",+ redirectUris: ["https://app.example.com/callback"]+ });++ expect(res.statusCode).toBe(200);+ const { client } = JSON.parse(res.payload) as { client: { id: string; grantTypes: string[] } };+ expect(client.grantTypes).toEqual([OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken]);++ await deleteClient(client.id);+ });++ test("the authorization code grant still requires a redirect URI", async () => {+ const res = await createClient({+ name: "e2e-no-redirect-uri",+ grantTypes: [OauthGrantType.AuthorizationCode],+ redirectUris: []+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("At least one redirect URI is required");+ });++ test("the refresh token grant cannot be registered on its own", async () => {+ const res = await createClient({+ name: "e2e-refresh-only",+ grantTypes: [OauthGrantType.RefreshToken],+ redirectUris: ["https://app.example.com/callback"]+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("requires the 'authorization_code' grant");+ });++ test("the token exchange grant requires an audience", async () => {+ const res = await createClient({+ name: "e2e-exchange-no-audience",+ grantTypes: [TOKEN_EXCHANGE_GRANT],+ redirectUris: []+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("token exchange audience is required");+ });++ test("PKCE cannot be required on an exchange-only application", async () => {+ const res = await createClient({+ name: "e2e-exchange-pkce",+ grantTypes: [TOKEN_EXCHANGE_GRANT],+ redirectUris: [],+ requirePkce: true,+ tokenExchangeAudience: "api://e2e-mcp"+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("PKCE only applies");+ });++ test("an audience cannot be set on a redirect-only application", async () => {+ const res = await createClient({+ name: "e2e-redirect-with-audience",+ grantTypes: [OauthGrantType.AuthorizationCode],+ redirectUris: ["https://app.example.com/callback"],+ tokenExchangeAudience: "api://e2e-mcp"+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("audience only applies");+ });++ // The seed org has no OIDC config, and that config 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",+ grantTypes: [TOKEN_EXCHANGE_GRANT],+ redirectUris: [],+ tokenExchangeAudience: "api://e2e-mcp"+ });++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("OIDC SSO");+ });+});++describe("POST /api/v1/oauth/token, token exchange grant", async () => {+ let clientId: string;+ let clientSecret: string;+ let clientDbId: string;++ beforeAll(async () => {+ // Authenticates fine but is not registered for the exchange grant, which the cases below need.+ const res = await createClient({+ name: "e2e-token-endpoint-client",+ redirectUris: ["https://app.example.com/callback"]+ });++ const { client, clientSecret: secret } = JSON.parse(res.payload) as {+ client: { id: string; clientId: string };+ clientSecret: string;+ };++ clientDbId = client.id;+ clientId = client.clientId;+ clientSecret = secret;+ });++ afterAll(async () => {+ await deleteClient(clientDbId);+ });++ const exchangeBody = (overrides: Record<string, string> = {}) => ({+ grant_type: TOKEN_EXCHANGE_GRANT,+ subject_token: "eyJhbGciOiJSUzI1NiJ9.e30.signature",+ subject_token_type: OauthTokenType.Jwt,+ client_id: clientId,+ client_secret: clientSecret,+ ...overrides+ });++ test("rejects invalid client credentials", async () => {+ const res = await postToken(exchangeBody({ client_secret: "not-the-secret" }));++ expect(res.statusCode).toBe(401);+ expect(res.payload).toContain("Invalid OAuth client credentials");+ });++ test("rejects a client that is not registered for the exchange grant", async () => {+ const res = await postToken(exchangeBody());++ expect(res.statusCode).toBe(401);+ expect(res.payload).toContain(TOKEN_EXCHANGE_GRANT);+ });++ test("requires a subject token", async () => {+ const body = exchangeBody();+ delete (body as Record<string, string>).subject_token;++ const res = await postToken(body);++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("subject_token");+ });++ test("requires a subject token type", async () => {+ const body = exchangeBody();+ delete (body as Record<string, string>).subject_token_type;++ const res = await postToken(body);++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("subject_token_type");+ });++ test("rejects an unsupported requested token type", async () => {+ const res = await postToken(exchangeBody({ requested_token_type: OauthTokenType.IdToken }));++ expect(res.statusCode).toBe(400);+ 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.+ test("rejects a scope parameter rather than ignoring it", async () => {+ const res = await postToken(exchangeBody({ scope: "secrets:read" }));++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("'scope' parameter is not supported");+ });++ test("rejects an audience parameter rather than ignoring it", async () => {+ const res = await postToken(exchangeBody({ audience: "api://something-else" }));++ expect(res.statusCode).toBe(400);+ expect(res.payload).toContain("not supported");+ });+});++// 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.+const signDelegatedToken = (markers: { scopes?: string[]; delegation?: OauthDelegationMode }) =>+ jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId: seedData1.id,+ tokenVersionId: seedData1.token.id,+ authMethod: AuthMethod.OIDC,+ organizationId: seedData1.organization.id,+ accessVersion: 1,+ oauthClientId: "oauth_client_e2e_exchange",+ ...markers+ },+ process.env.AUTH_SECRET ?? "something-random",+ { expiresIn: "1h" }+ );++const readSecrets = async (token: string) =>+ testServer.inject({+ method: "GET",+ url: `/api/v3/secrets/raw`,+ headers: { authorization: `Bearer ${token}` },+ query: {+ workspaceId: seedData1.projectV3.id,+ environment: seedData1.environment.slug,+ secretPath: "/"+ }+ });++describe("Full delegation marker on a delegated OAuth token", async () => {+ test("a fully-delegated token carries the user's own permissions, unnarrowed", async () => {+ const token = signDelegatedToken({ delegation: OauthDelegationMode.Full });++ const res = await readSecrets(token);+ expect(res.statusCode).toBe(200);+ });++ // The invariant that makes the marker safe: dropping the claim by mistake cannot promote a token.+ test("a token carrying neither marker is denied", async () => {+ const token = signDelegatedToken({});++ const res = await readSecrets(token);+ expect(res.statusCode).toBe(403);+ });++ test("an empty scope list is still denied", async () => {+ const token = signDelegatedToken({ scopes: [] });++ const res = await readSecrets(token);+ 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.+ test("a fully-delegated token is still rejected on a JWT-only account route", async () => {+ const token = signDelegatedToken({ delegation: OauthDelegationMode.Full });++ const res = await testServer.inject({+ method: "GET",+ url: `/api/v1/user/me/totp`,+ headers: { authorization: `Bearer ${token}` }+ });++ expect(res.statusCode).toBe(403);+ });+});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.tsnew file mode 100644index 0000000000..3572947e1a--- /dev/null+++ b/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts@@ -0,0 +1,58 @@+import { Knex } from "knex";++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[]";++export async function up(knex: Knex): Promise<void> {+ const hasGrantTypes = await knex.schema.hasColumn(TableName.OauthClient, "grantTypes");+ const hasTokenExchangeAudience = await knex.schema.hasColumn(TableName.OauthClient, "tokenExchangeAudience");+ const hasTokenExchangeIdpSatisfiesMfa = await knex.schema.hasColumn(+ TableName.OauthClient,+ "tokenExchangeIdpSatisfiesMfa"+ );++ 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.+ 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.+ 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.+ if (!hasTokenExchangeIdpSatisfiesMfa) {+ t.boolean("tokenExchangeIdpSatisfiesMfa").notNullable().defaultTo(false);+ }+ });++ if (!hasGrantTypes) {+ await knex.raw('ALTER TABLE ?? ALTER COLUMN "grantTypes" DROP DEFAULT', [TableName.OauthClient]);+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasGrantTypes = await knex.schema.hasColumn(TableName.OauthClient, "grantTypes");+ const hasTokenExchangeAudience = await knex.schema.hasColumn(TableName.OauthClient, "tokenExchangeAudience");+ const hasTokenExchangeIdpSatisfiesMfa = await knex.schema.hasColumn(+ TableName.OauthClient,+ "tokenExchangeIdpSatisfiesMfa"+ );++ if (!hasGrantTypes && !hasTokenExchangeAudience && !hasTokenExchangeIdpSatisfiesMfa) return;++ await knex.schema.alterTable(TableName.OauthClient, (t) => {+ if (hasGrantTypes) t.dropColumn("grantTypes");+ if (hasTokenExchangeAudience) t.dropColumn("tokenExchangeAudience");+ if (hasTokenExchangeIdpSatisfiesMfa) t.dropColumn("tokenExchangeIdpSatisfiesMfa");+ });+}diff --git a/backend/src/db/schemas/oauth-clients.ts b/backend/src/db/schemas/oauth-clients.tsindex 00f49538c7..5a421a5dc7 100644--- a/backend/src/db/schemas/oauth-clients.ts+++ b/backend/src/db/schemas/oauth-clients.ts@@ -18,7 +18,10 @@ export const OauthClientsSchema = z.object({redirectUris: z.string().array(),requirePkce: z.boolean().default(false),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ grantTypes: z.string().array(),+ tokenExchangeAudience: z.string().nullable().optional(),+ tokenExchangeIdpSatisfiesMfa: z.boolean().default(false)});export type TOauthClients = z.infer<typeof OauthClientsSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 29df81cef6..284d600084 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -846,6 +846,7 @@ export enum EventType {DELETE_OAUTH_CLIENT = "delete-oauth-client",ROTATE_OAUTH_CLIENT_SECRET = "rotate-oauth-client-secret",OAUTH_CLIENT_AUTHORIZE = "oauth-client-authorize",+ OAUTH_CLIENT_TOKEN_EXCHANGE = "oauth-client-token-exchange",// Email DomainsCREATE_EMAIL_DOMAIN = "create-email-domain",@@ -6747,6 +6748,7 @@ interface CreateOauthClientEvent {clientDbId: string;clientId: string;name: string;+ grantTypes: string[];};}@@ -6756,6 +6758,9 @@ interface UpdateOauthClientEvent {clientDbId: string;clientId: string;name: string;+ grantTypes: string[];+ tokenExchangeAudience?: string | null;+ tokenExchangeIdpSatisfiesMfa: boolean;};}@@ -6785,6 +6790,18 @@ interface OauthClientAuthorizeEvent {};}+interface OauthClientTokenExchangeEvent {+ type: EventType.OAUTH_CLIENT_TOKEN_EXCHANGE;+ metadata: {+ clientDbId: string;+ clientId: string;+ clientName: string;+ subjectUserId: string;+ subjectExternalId: string;+ tokenVersionId: string;+ };+}+interface CreateEmailDomainEvent {type: EventType.CREATE_EMAIL_DOMAIN;metadata: {@@ -7706,6 +7723,7 @@ export type Event =| DeleteOauthClientEvent| RotateOauthClientSecretEvent| OauthClientAuthorizeEvent+ | OauthClientTokenExchangeEvent| CreateEmailDomainEvent| VerifyEmailDomainEvent| DeleteEmailDomainEventdiff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex 1a5539c8a8..db7db4dda6 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -89,9 +89,12 @@ import {ProjectPermissionSub} from "./project-permission";-// Returns the delegated OAuth scopes for the current request, or undefined when this is not an-// OAuth-delegated request. The distinction matters: a returned array (even empty) means scope-// narrowing applies, while undefined means a first-party session / background job is untouched.+// 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.+//+// 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.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 cb075120a4..217bd095e6 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -21,6 +21,7 @@ import {TRelayAccessTokenJwtPayload} from "@app/services/auth/auth-type";import { TIdentityAccessTokenJwtPayload } from "@app/services/identity-access-token/identity-access-token-types";+import { OauthDelegationMode } from "@app/services/oauth-client/oauth-client-types";import { getServerCfg } from "@app/services/super-admin/super-admin-service";export type TAuthMode =@@ -306,9 +307,9 @@ export const injectIdentity = fp(await server.services.authToken.fnValidateJwtIdentity(token);requestContext.set(RequestContextKey.OrgId, orgId);requestContext.set(RequestContextKey.OrgName, orgName);- // Always set (even as []) so permission-service can distinguish a delegated OAuth request- // that must be scope-narrowed from a first-party session that must not be.- requestContext.set(RequestContextKey.OauthScopes, token.scopes ?? []);+ if (token.delegation !== OauthDelegationMode.Full) {+ requestContext.set(RequestContextKey.OauthScopes, token.scopes ?? []);+ }requestContext.set(RequestContextKey.UserAuthInfo, { userId: user.id, email: user.email || "" });req.auth = {authMode: AuthMode.OAUTH,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3664cc5262..a5fc50cf36 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -853,14 +853,6 @@ export const registerRoutes = async (});const oauthClientDAL = oauthClientDALFactory(db);- const oauthClientService = oauthClientServiceFactory({- oauthClientDAL,- permissionService,- keyStore,- tokenService,- orgDAL,- userDAL- });const alertChannelRecipientDAL = alertChannelRecipientDALFactory(db);@@ -1106,6 +1098,19 @@ export const registerRoutes = async (pamAccountDAL})});++ const oauthClientService = oauthClientServiceFactory({+ oauthClientDAL,+ permissionService,+ keyStore,+ tokenService,+ orgDAL,+ userDAL,+ oidcConfigDAL,+ userAliasDAL,+ auditLogService+ });+const secretApprovalPolicyService = secretApprovalPolicyServiceFactory({projectEnvDAL,secretApprovalPolicyApproverDAL: sapApproverDAL,diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.tsindex 60b41d5439..de2a96888c 100644--- a/backend/src/server/routes/v1/oauth-router.ts+++ b/backend/src/server/routes/v1/oauth-router.ts@@ -7,6 +7,12 @@ import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimimport { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { isAllowedRedirectUri, parseBasicAuthHeader } from "@app/services/oauth-client/oauth-client-fns";+import {+ ACCEPTED_SUBJECT_TOKEN_TYPES,+ DEFAULT_OAUTH_GRANT_TYPES,+ OauthGrantType,+ OauthTokenType+} from "@app/services/oauth-client/oauth-client-types";const SanitizedOauthClientSchema = OauthClientsSchema.omit({ clientSecretHash: true });@@ -18,6 +24,28 @@ const redirectUriSchema = z"Redirect URI must use https:// (http:// is only allowed for loopback addresses such as localhost)");+const grantTypesSchema = z+ .nativeEnum(OauthGrantType)+ .array()+ .min(1)+ .max(Object.keys(OauthGrantType).length)+ .describe(+ "The OAuth grant types this application may use. Redirect URIs apply only to authorization_code; the token exchange audience applies only to the token-exchange grant."+ );++const tokenExchangeAudienceSchema = z+ .string()+ .trim()+ .min(1)+ .max(255)+ .describe("The expected 'aud' claim of subject tokens presented to the token exchange grant.");++const tokenExchangeIdpSatisfiesMfaSchema = z+ .boolean()+ .describe(+ "Declares that authentication at the identity provider satisfies this organization's MFA requirement. Required for token exchange in an organization that enforces MFA."+ );+export const registerOAuthRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -30,8 +58,11 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {body: z.object({name: z.string().trim().min(1).max(64),description: z.string().trim().max(256).optional(),- redirectUris: redirectUriSchema.array().min(1),- requirePkce: z.boolean().optional()+ grantTypes: grantTypesSchema.default([...DEFAULT_OAUTH_GRANT_TYPES]),+ redirectUris: redirectUriSchema.array().max(32).default([]),+ requirePkce: z.boolean().optional(),+ tokenExchangeAudience: tokenExchangeAudienceSchema.optional(),+ tokenExchangeIdpSatisfiesMfa: tokenExchangeIdpSatisfiesMfaSchema.optional()}),response: {200: z.object({@@ -52,7 +83,8 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {metadata: {clientDbId: client.id,clientId: client.clientId,- name: client.name+ name: client.name,+ grantTypes: client.grantTypes}}});@@ -69,6 +101,12 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {},schema: {operationId: "listOauthClients",+ querystring: z.object({+ grantType: z+ .nativeEnum(OauthGrantType)+ .optional()+ .describe("Return only applications registered for this grant type.")+ }),response: {200: z.object({clients: SanitizedOauthClientSchema.array()@@ -77,7 +115,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const clients = await server.services.oauthClient.listOauthClients(req.permission);+ const clients = await server.services.oauthClient.listOauthClients(req.permission, req.query.grantType);return { clients };}});@@ -120,8 +158,11 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {body: z.object({name: z.string().trim().min(1).max(64).optional(),description: z.string().trim().max(256).nullable().optional(),- redirectUris: redirectUriSchema.array().min(1).optional(),- requirePkce: z.boolean().optional()+ grantTypes: grantTypesSchema.optional(),+ redirectUris: redirectUriSchema.array().max(32).optional(),+ requirePkce: z.boolean().optional(),+ tokenExchangeAudience: tokenExchangeAudienceSchema.nullable().optional(),+ tokenExchangeIdpSatisfiesMfa: tokenExchangeIdpSatisfiesMfaSchema.optional()}),response: {200: z.object({@@ -144,7 +185,10 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {metadata: {clientDbId: client.id,clientId: client.clientId,- name: client.name+ name: client.name,+ grantTypes: client.grantTypes,+ tokenExchangeAudience: client.tokenExchangeAudience,+ tokenExchangeIdpSatisfiesMfa: client.tokenExchangeIdpSatisfiesMfa}}});@@ -371,21 +415,28 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {},schema: {body: z.object({- grant_type: z.enum(["authorization_code", "refresh_token"]),- code: z.string().optional(),- redirect_uri: z.string().optional(),- code_verifier: z.string().optional(),- refresh_token: z.string().optional(),- client_id: z.string().optional(),- client_secret: z.string().optional()+ grant_type: z.nativeEnum(OauthGrantType),+ code: z.string().max(256).optional(),+ redirect_uri: z.string().max(2048).optional(),+ code_verifier: z.string().max(256).optional(),+ refresh_token: z.string().max(8192).optional(),+ client_id: z.string().max(256).optional(),+ client_secret: z.string().max(256).optional(),+ subject_token: z.string().max(8192).optional(),+ subject_token_type: z.nativeEnum(OauthTokenType).optional(),+ requested_token_type: z.nativeEnum(OauthTokenType).optional(),+ audience: z.string().max(255).optional(),+ resource: z.string().max(2048).optional(),+ scope: z.string().max(2048).optional()}),response: {200: z.object({access_token: z.string(),token_type: z.string(),expires_in: z.number(),- refresh_token: z.string(),- scope: z.string()+ refresh_token: z.string().optional(),+ scope: z.string().optional(),+ issued_token_type: z.nativeEnum(OauthTokenType).optional()})}},@@ -397,11 +448,11 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {void res.header("Cache-Control", "no-store");void res.header("Pragma", "no-cache");- if (req.body.grant_type === "authorization_code") {+ if (req.body.grant_type === OauthGrantType.AuthorizationCode) {if (!req.body.code) throw new BadRequestError({ message: "Missing authorization code" });return server.services.oauthClient.exchangeToken({- grantType: "authorization_code",+ grantType: OauthGrantType.AuthorizationCode,code: req.body.code,redirectUri: req.body.redirect_uri,codeVerifier: req.body.code_verifier,@@ -410,10 +461,56 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {});}+ if (req.body.grant_type === OauthGrantType.TokenExchange) {+ if (!req.body.subject_token) {+ throw new BadRequestError({ message: "Missing 'subject_token'" });+ }++ if (!req.body.subject_token_type) {+ throw new BadRequestError({ message: "Missing 'subject_token_type'" });+ }++ if (!ACCEPTED_SUBJECT_TOKEN_TYPES.includes(req.body.subject_token_type)) {+ throw new BadRequestError({+ message: `Unsupported 'subject_token_type'. Supported values are: ${ACCEPTED_SUBJECT_TOKEN_TYPES.join(", ")}`+ });+ }++ if (req.body.requested_token_type && req.body.requested_token_type !== OauthTokenType.AccessToken) {+ throw new BadRequestError({+ message: `Unsupported 'requested_token_type'. Only '${OauthTokenType.AccessToken}' can be issued.`+ });+ }++ if (req.body.scope) {+ throw new BadRequestError({+ message:+ "The 'scope' parameter is not supported on the token exchange grant. The issued token carries the user's own permissions."+ });+ }++ if (req.body.audience || req.body.resource) {+ throw new BadRequestError({+ message:+ "The 'audience' and 'resource' parameters are not supported. The expected subject token audience is configured on the application."+ });+ }++ return server.services.oauthClient.exchangeToken({+ grantType: OauthGrantType.TokenExchange,+ subjectToken: req.body.subject_token,+ subjectTokenType: req.body.subject_token_type,+ clientId,+ clientSecret,+ ip: req.realIp,+ userAgent: req.headers["user-agent"]+ });+ }+if (!req.body.refresh_token) throw new BadRequestError({ message: "Missing refresh token" });return server.services.oauthClient.exchangeToken({- grantType: "refresh_token",+ grantType: OauthGrantType.RefreshToken,refreshToken: req.body.refresh_token,clientId,clientSecretdiff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex 4a986a89d7..fe3e38ca45 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -107,6 +107,9 @@ 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.+ delegation?: string;};export type AuthModeMfaJwtTokenPayload = {diff --git a/backend/src/services/oauth-client/oauth-client-fns.test.ts b/backend/src/services/oauth-client/oauth-client-fns.test.tsindex cec4f2ea09..2e7f2acdd8 100644--- a/backend/src/services/oauth-client/oauth-client-fns.test.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.test.ts@@ -1,11 +1,14 @@import crypto from "node:crypto";import {+ assertValidOauthClientGrantConfig,computePkceChallenge,+ dedupeGrantTypes,isAllowedRedirectUri,isRegisteredRedirectUri,parseBasicAuthHeader} from "./oauth-client-fns";+import { OauthGrantType } from "./oauth-client-types";describe("parseBasicAuthHeader", () => {test("parses a valid Basic auth header", () => {@@ -119,3 +122,144 @@ describe("isRegisteredRedirectUri", () => {).toBe(false);});});++describe("dedupeGrantTypes", () => {+ test("removes duplicates while preserving order", () => {+ expect(+ dedupeGrantTypes([+ OauthGrantType.AuthorizationCode,+ OauthGrantType.RefreshToken,+ OauthGrantType.AuthorizationCode+ ])+ ).toEqual([OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken]);+ });+});++describe("assertValidOauthClientGrantConfig", () => {+ const redirectFlow = {+ grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],+ resolved: { redirectUris: ["https://app.example.com/callback"] },+ supplied: { redirectUris: ["https://app.example.com/callback"], requirePkce: true }+ };++ const exchangeFlow = {+ grantTypes: [OauthGrantType.TokenExchange],+ resolved: { redirectUris: [], tokenExchangeAudience: "api://mcp" },+ supplied: { tokenExchangeAudience: "api://mcp", tokenExchangeIdpSatisfiesMfa: true }+ };++ test("accepts a redirect-flow application", () => {+ expect(() => assertValidOauthClientGrantConfig(redirectFlow)).not.toThrow();+ });++ test("accepts a token-exchange-only application", () => {+ expect(() => assertValidOauthClientGrantConfig(exchangeFlow)).not.toThrow();+ });++ test("accepts an application registered for both grants", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken, OauthGrantType.TokenExchange],+ resolved: { redirectUris: ["https://app.example.com/callback"], tokenExchangeAudience: "api://mcp" },+ supplied: { redirectUris: ["https://app.example.com/callback"], tokenExchangeAudience: "api://mcp" }+ })+ ).not.toThrow();+ });++ test("rejects an empty grant type list", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({ grantTypes: [], resolved: { redirectUris: [] }, supplied: {} })+ ).toThrow(/At least one grant type/);+ });++ test("rejects refresh_token without authorization_code", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.RefreshToken],+ resolved: { redirectUris: ["https://app.example.com/callback"] },+ supplied: {}+ })+ ).toThrow(/requires the 'authorization_code' grant/);+ });++ test("rejects authorization_code with no redirect URI", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.AuthorizationCode],+ resolved: { redirectUris: [] },+ supplied: {}+ })+ ).toThrow(/At least one redirect URI is required/);+ });++ test("rejects redirect URIs supplied without a redirect-based grant", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.TokenExchange],+ resolved: { redirectUris: ["https://app.example.com/callback"], tokenExchangeAudience: "api://mcp" },+ supplied: { redirectUris: ["https://app.example.com/callback"] }+ })+ ).toThrow(/Redirect URIs only apply/);+ });++ test("rejects requirePkce supplied without a redirect-based grant", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.TokenExchange],+ resolved: { redirectUris: [], tokenExchangeAudience: "api://mcp" },+ supplied: { requirePkce: true }+ })+ ).toThrow(/PKCE only applies/);+ });++ test("rejects the token exchange grant with no audience", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.TokenExchange],+ resolved: { redirectUris: [] },+ supplied: {}+ })+ ).toThrow(/token exchange audience is required/);+ });++ test("rejects a whitespace-only audience", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.TokenExchange],+ resolved: { redirectUris: [], tokenExchangeAudience: " " },+ supplied: { tokenExchangeAudience: " " }+ })+ ).toThrow(/token exchange audience is required/);+ });++ test("rejects an audience supplied without the token exchange grant", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.AuthorizationCode],+ resolved: { redirectUris: ["https://app.example.com/callback"], tokenExchangeAudience: "api://mcp" },+ supplied: { tokenExchangeAudience: "api://mcp" }+ })+ ).toThrow(/audience only applies/);+ });++ test("rejects the IdP MFA declaration without the token exchange grant", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.AuthorizationCode],+ resolved: { redirectUris: ["https://app.example.com/callback"] },+ supplied: { tokenExchangeIdpSatisfiesMfa: true }+ })+ ).toThrow(/MFA declaration only applies/);+ });++ // Dropping a grant must not force the caller to null out that grant's fields in the same request.+ test("allows dropping the token exchange grant while its stored audience is still set", () => {+ expect(() =>+ assertValidOauthClientGrantConfig({+ grantTypes: [OauthGrantType.AuthorizationCode],+ resolved: { redirectUris: ["https://app.example.com/callback"], tokenExchangeAudience: "api://mcp" },+ supplied: { grantTypes: [OauthGrantType.AuthorizationCode] } as never+ })+ ).not.toThrow();+ });+});diff --git a/backend/src/services/oauth-client/oauth-client-fns.ts b/backend/src/services/oauth-client/oauth-client-fns.tsindex a91f724515..68d3281dc0 100644--- a/backend/src/services/oauth-client/oauth-client-fns.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.ts@@ -1,5 +1,9 @@import crypto from "node:crypto";+import { BadRequestError } from "@app/lib/errors";++import { OauthGrantType, REDIRECT_BASED_GRANT_TYPES } from "./oauth-client-types";+export const parseBasicAuthHeader = (authorizationHeader?: string): { clientId: string; clientSecret: string } | null => {@@ -75,3 +79,76 @@ export const isRegisteredRedirectUri = (registeredUris: string[], redirectUri: sreturn false;}});++export const dedupeGrantTypes = (grantTypes: OauthGrantType[]) => [...new Set(grantTypes)];++export const hasRedirectBasedGrant = (grantTypes: OauthGrantType[]) =>+ grantTypes.some((grantType) => REDIRECT_BASED_GRANT_TYPES.includes(grantType));++export const hasTokenExchangeGrant = (grantTypes: OauthGrantType[]) =>+ grantTypes.includes(OauthGrantType.TokenExchange);++type TOauthClientGrantConfig = {+ grantTypes: OauthGrantType[];+ resolved: {+ redirectUris: string[];+ tokenExchangeAudience?: string | null;+ };+ supplied: {+ redirectUris?: string[];+ requirePkce?: boolean;+ tokenExchangeAudience?: string | null;+ tokenExchangeIdpSatisfiesMfa?: boolean;+ };+};++export const assertValidOauthClientGrantConfig = ({ grantTypes, resolved, supplied }: TOauthClientGrantConfig) => {+ if (!grantTypes.length) {+ throw new BadRequestError({ message: "At least one grant type must be enabled for an application." });+ }++ const isRedirectBased = hasRedirectBasedGrant(grantTypes);+ const isTokenExchange = hasTokenExchangeGrant(grantTypes);++ if (grantTypes.includes(OauthGrantType.RefreshToken) && !grantTypes.includes(OauthGrantType.AuthorizationCode)) {+ throw new BadRequestError({+ message: `The '${OauthGrantType.RefreshToken}' grant requires the '${OauthGrantType.AuthorizationCode}' grant, because refresh tokens are only issued by the authorization code flow.`+ });+ }++ if (isRedirectBased && !resolved.redirectUris.length) {+ throw new BadRequestError({+ message: `At least one redirect URI is required for the '${OauthGrantType.AuthorizationCode}' grant.`+ });+ }++ if (!isRedirectBased && supplied.redirectUris?.length) {+ throw new BadRequestError({+ message: `Redirect URIs only apply to the '${OauthGrantType.AuthorizationCode}' grant. Enable that grant or remove the redirect URIs.`+ });+ }++ if (!isRedirectBased && supplied.requirePkce) {+ throw new BadRequestError({+ message: `PKCE only applies to the '${OauthGrantType.AuthorizationCode}' grant. Enable that grant or turn off the PKCE requirement.`+ });+ }++ if (isTokenExchange && !resolved.tokenExchangeAudience?.trim()) {+ throw new BadRequestError({+ message: `A token exchange audience is required for the '${OauthGrantType.TokenExchange}' grant. Set it to the audience your identity provider puts in tokens it issues for this application.`+ });+ }++ if (!isTokenExchange && supplied.tokenExchangeAudience?.trim()) {+ throw new BadRequestError({+ message: `The token exchange audience only applies to the '${OauthGrantType.TokenExchange}' grant. Enable that grant or remove the audience.`+ });+ }++ if (!isTokenExchange && supplied.tokenExchangeIdpSatisfiesMfa) {+ throw new BadRequestError({+ message: `The identity provider MFA declaration only applies to the '${OauthGrantType.TokenExchange}' grant. Enable that grant or turn the declaration off.`+ });+ }+};diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 0ea9c00d15..4cb8b929ed 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -1,7 +1,13 @@import { ForbiddenError } from "@casl/ability";-import { OrganizationActionScope, TOauthClients } from "@app/db/schemas";-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { OrganizationActionScope, TOauthClients, TOrganizations } from "@app/db/schemas";+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";+import {+ OrgPermissionActions,+ OrgPermissionSsoActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";@@ -15,16 +21,25 @@ import { ActorType, AuthMethod, AuthTokenType, MfaMethod } from "@app/services/aimport { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TUserDALFactory } from "@app/services/user/user-dal";+import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";+import { UserAliasType } from "@app/services/user-alias/user-alias-types";import { TOauthClientDALFactory } from "./oauth-client-dal";import {+ assertValidOauthClientGrantConfig,computePkceChallenge,+ dedupeGrantTypes,getOauthClientSessionUserAgent,+ hasRedirectBasedGrant,+ hasTokenExchangeGrant,isRegisteredRedirectUri,PKCE_CODE_VERIFIER_REGEX} from "./oauth-client-fns";import {OauthAuthorizationCodePayloadSchema,+ OauthDelegationMode,+ OauthGrantType,+ OauthTokenType,TCreateOauthClientDTO,TOauthAuthorizeInfoDTO,TOauthConsentDTO,@@ -33,6 +48,7 @@ import {TUpdateOauthClientDTO} from "./oauth-client-types";import { getOauthScopeDescriptions, parseOauthScopeString } from "./oauth-scope";+import { verifySubjectToken } from "./oauth-token-exchange-fns";type TOauthClientServiceFactoryDep = {oauthClientDAL: TOauthClientDALFactory;@@ -48,6 +64,9 @@ type TOauthClientServiceFactoryDep = {>;orgDAL: Pick<TOrgDALFactory, "findById">;userDAL: Pick<TUserDALFactory, "findById">;+ oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne">;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;};export type TOauthClientServiceFactory = ReturnType<typeof oauthClientServiceFactory>;@@ -67,8 +86,7 @@ type TOauthTokenClaims = {organizationId: string;isMfaVerified?: boolean;mfaMethod?: MfaMethod;- scopes: string[];-};+} & ({ scopes: string[]; delegation?: never } | { delegation: OauthDelegationMode.Full; scopes?: never });const signOauthToken = (claims: TOauthTokenClaims & {@@ -95,9 +113,10 @@ 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,- // Granted delegation scopes. permission-service intersects the user's ability with these,- // so the token can never exceed what the user consented to.- scopes: claims.scopes+ // 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.+ ...(claims.delegation ? { delegation: claims.delegation } : { scopes: claims.scopes })},appCfg.AUTH_SECRET,{ expiresIn }@@ -110,7 +129,10 @@ export const oauthClientServiceFactory = ({keyStore,tokenService,orgDAL,- userDAL+ userDAL,+ oidcConfigDAL,+ userAliasDAL,+ auditLogService}: TOauthClientServiceFactoryDep) => {const checkOauthClientPermission = async (actor: OrgServiceActor, action: OrgPermissionActions) => {const { permission } = await permissionService.getOrgPermission({@@ -125,6 +147,22 @@ export const oauthClientServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.OauthClients);};+ // Enabling this grant, or changing the audience it accepts, decides whose externally-issued tokens+ // become Infisical user tokens. That is a change to the org's federation trust, so it needs the+ // permission that already owns the SSO configuration.+ const checkSsoConfigPermission = async (actor: OrgServiceActor) => {+ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: actor.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.ParentOrganization+ });++ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Edit, OrgPermissionSubjects.Sso);+ };+// Loads a client scoped to the actor's org (so one org can never address another's client) and// throws a 404 when it is missing. Shared by every management method that operates on an existing// client by its database id.@@ -134,9 +172,64 @@ export const oauthClientServiceFactory = ({return client;};+ // MFA enforcement, the OIDC SSO configuration and OIDC user aliases all live on the root+ // organization, matching the login flow.+ const getClientRootOrg = async (orgId: string): Promise<TOrganizations> => {+ const clientOrg = await orgDAL.findById(orgId);+ if (!clientOrg) throw new NotFoundError({ message: "OAuth client organization not found" });++ const isSubOrganization = Boolean(clientOrg.rootOrgId && clientOrg.id !== clientOrg.rootOrgId);+ if (!isSubOrganization) return clientOrg;++ const rootOrg = await orgDAL.findById(clientOrg.rootOrgId as string);+ if (!rootOrg) throw new NotFoundError({ message: "OAuth client organization not found" });+ return rootOrg;+ };++ // 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.+ const getActiveOidcConfigOrThrow = async (orgId: string) => {+ const rootOrg = await getClientRootOrg(orgId);+ const oidcConfig = await oidcConfigDAL.findOne({ orgId: rootOrg.id });++ if (!oidcConfig) {+ throw new BadRequestError({+ message:+ "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization has no OIDC SSO configuration. Set one up under Settings > SSO & Provisioning first."+ });+ }++ if (!oidcConfig.isActive) {+ throw new BadRequestError({+ message:+ "Token exchange verifies user tokens against your organization's OIDC SSO issuer, and your organization's OIDC SSO is disabled. Enable it under Settings > SSO & Provisioning first."+ });+ }++ return { oidcConfig, rootOrg };+ };+const createOauthClient = async (dto: TCreateOauthClientDTO, actor: OrgServiceActor) => {await checkOauthClientPermission(actor, OrgPermissionActions.Create);+ const grantTypes = dedupeGrantTypes(dto.grantTypes);+ const enablesTokenExchange = hasTokenExchangeGrant(grantTypes);++ if (enablesTokenExchange) await checkSsoConfigPermission(actor);++ assertValidOauthClientGrantConfig({+ grantTypes,+ resolved: { redirectUris: dto.redirectUris, tokenExchangeAudience: dto.tokenExchangeAudience },+ supplied: {+ redirectUris: dto.redirectUris,+ requirePkce: dto.requirePkce,+ tokenExchangeAudience: dto.tokenExchangeAudience,+ tokenExchangeIdpSatisfiesMfa: dto.tokenExchangeIdpSatisfiesMfa+ }+ });++ if (enablesTokenExchange) await getActiveOidcConfigOrThrow(actor.orgId);+const appCfg = getConfig();const clientId = `oauth_client_${crypto.randomBytes(16).toString("hex")}`;const clientSecret = crypto.randomBytes(32).toString("hex");@@ -149,18 +242,27 @@ export const oauthClientServiceFactory = ({clientId,clientSecretHash,clientSecretPrefix: clientSecret.slice(0, 4),+ grantTypes,redirectUris: dto.redirectUris,- requirePkce: dto.requirePkce ?? false+ requirePkce: dto.requirePkce ?? false,+ tokenExchangeAudience: enablesTokenExchange ? dto.tokenExchangeAudience : null,+ tokenExchangeIdpSatisfiesMfa: enablesTokenExchange ? (dto.tokenExchangeIdpSatisfiesMfa ?? false) : false});return { client: sanitizeOauthClient(client), clientSecret };};- const listOauthClients = async (actor: OrgServiceActor) => {+ // `grantType` narrows the list to one grant. The SSO page uses it to show which applications depend+ // on the org's OIDC issuer.+ const listOauthClients = async (actor: OrgServiceActor, grantType?: OauthGrantType) => {await checkOauthClientPermission(actor, OrgPermissionActions.Read);const clients = await oauthClientDAL.find({ orgId: actor.orgId });- return clients.map(sanitizeOauthClient);+ const filtered = grantType+ ? clients.filter((client) => (client.grantTypes as OauthGrantType[]).includes(grantType))+ : clients;++ return filtered.map(sanitizeOauthClient);};const getOauthClientById = async (clientDbId: string, actor: OrgServiceActor) => {@@ -176,11 +278,43 @@ export const oauthClientServiceFactory = ({const client = await getOrgClientOrThrow(dto.clientDbId, actor.orgId);+ const grantTypes = dedupeGrantTypes(dto.grantTypes ?? (client.grantTypes as OauthGrantType[]));+ const isTokenExchangeEnabled = hasTokenExchangeGrant(grantTypes);+ const isRedirectBased = hasRedirectBasedGrant(grantTypes);++ const resolvedRedirectUris = dto.redirectUris ?? client.redirectUris;+ const resolvedTokenExchangeAudience =+ dto.tokenExchangeAudience !== undefined ? dto.tokenExchangeAudience : client.tokenExchangeAudience;+ const resolvedIdpSatisfiesMfa = dto.tokenExchangeIdpSatisfiesMfa ?? client.tokenExchangeIdpSatisfiesMfa;++ const touchesTokenExchangeConfig =+ dto.grantTypes !== undefined ||+ dto.tokenExchangeAudience !== undefined ||+ dto.tokenExchangeIdpSatisfiesMfa !== undefined;++ if (isTokenExchangeEnabled && touchesTokenExchangeConfig) await checkSsoConfigPermission(actor);++ assertValidOauthClientGrantConfig({+ grantTypes,+ resolved: { redirectUris: resolvedRedirectUris, tokenExchangeAudience: resolvedTokenExchangeAudience },+ supplied: {+ redirectUris: dto.redirectUris,+ requirePkce: dto.requirePkce,+ tokenExchangeAudience: dto.tokenExchangeAudience,+ tokenExchangeIdpSatisfiesMfa: dto.tokenExchangeIdpSatisfiesMfa+ }+ });++ if (isTokenExchangeEnabled && touchesTokenExchangeConfig) await getActiveOidcConfigOrThrow(actor.orgId);+const updatedClient = await oauthClientDAL.updateById(client.id, {name: dto.name,description: dto.description,- redirectUris: dto.redirectUris,- requirePkce: dto.requirePkce+ grantTypes: dto.grantTypes ? grantTypes : undefined,+ redirectUris: isRedirectBased ? dto.redirectUris : [],+ requirePkce: isRedirectBased ? dto.requirePkce : false,+ tokenExchangeAudience: isTokenExchangeEnabled ? resolvedTokenExchangeAudience : null,+ tokenExchangeIdpSatisfiesMfa: isTokenExchangeEnabled ? resolvedIdpSatisfiesMfa : false});return sanitizeOauthClient(updatedClient);@@ -218,10 +352,20 @@ export const oauthClientServiceFactory = ({return { client: sanitizeOauthClient(updatedClient), clientSecret };};+ const assertGrantEnabled = (client: TOauthClients, grantType: OauthGrantType) => {+ if (!(client.grantTypes as OauthGrantType[]).includes(grantType)) {+ throw new UnauthorizedError({+ message: `This application is not registered for the '${grantType}' grant type`+ });+ }+ };+const getAuthorizeInfo = async ({ clientId, redirectUri, scope }: TOauthAuthorizeInfoDTO) => {const client = await oauthClientDAL.findOne({ clientId });if (!client) throw new UnauthorizedError({ message: "OAuth client not found" });+ assertGrantEnabled(client, OauthGrantType.AuthorizationCode);+if (!isRegisteredRedirectUri(client.redirectUris, redirectUri)) {throw new BadRequestError({ message: "Redirect URI is not registered for this OAuth client" });}@@ -246,6 +390,8 @@ export const oauthClientServiceFactory = ({const client = await oauthClientDAL.findOne({ clientId: dto.clientId });if (!client) throw new UnauthorizedError({ message: "OAuth client not found" });+ assertGrantEnabled(client, OauthGrantType.AuthorizationCode);+if (!isRegisteredRedirectUri(client.redirectUris, dto.redirectUri)) {throw new BadRequestError({ message: "Redirect URI is not registered for this OAuth client" });}@@ -279,14 +425,8 @@ export const oauthClientServiceFactory = ({// completed). Issuing a delegation code from such a session would let anyone holding only the// password mint OAuth tokens, bypassing MFA entirely. So we re-derive whether MFA is required// for this user in the client's organization and reject the request unless the session actually- // completed the matching MFA challenge. MFA enforcement lives on the root organization (matching- // the login flow), so resolve it when the client belongs to a sub-organization.- const clientOrg = await orgDAL.findById(client.orgId);- if (!clientOrg) throw new NotFoundError({ message: "OAuth client organization not found" });-- const isSubOrganization = Boolean(clientOrg.rootOrgId && clientOrg.id !== clientOrg.rootOrgId);- const rootOrg = isSubOrganization ? await orgDAL.findById(clientOrg.rootOrgId as string) : clientOrg;- if (!rootOrg) throw new NotFoundError({ message: "OAuth client organization not found" });+ // completed the matching MFA challenge.+ const rootOrg = await getClientRootOrg(client.orgId);const user = await userDAL.findById(dto.userId);if (!user) throw new UnauthorizedError({ message: "User not found" });@@ -359,10 +499,134 @@ export const oauthClientServiceFactory = ({return { accessTokenExpiresIn, refreshTokenExpiresIn };};+ // 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.+ const exchangeSubjectToken = async (+ client: TOauthClients,+ dto: Extract<TOauthTokenExchangeDTO, { grantType: OauthGrantType.TokenExchange }>+ ) => {+ assertGrantEnabled(client, OauthGrantType.TokenExchange);++ if (!client.tokenExchangeAudience) {+ throw new BadRequestError({+ message:+ "This application has no token exchange audience configured, so subject tokens cannot be verified. Set one on the application under Organization Settings > OAuth Applications."+ });+ }++ const { oidcConfig, rootOrg } = await getActiveOidcConfigOrThrow(client.orgId);++ const { subject } = await verifySubjectToken({+ subjectToken: dto.subjectToken,+ oidcConfig,+ expectedAudience: client.tokenExchangeAudience+ });++ const userAlias = await userAliasDAL.findOne({+ externalId: subject,+ orgId: rootOrg.id,+ aliasType: UserAliasType.OIDC+ });++ if (!userAlias) {+ throw new UnauthorizedError({+ message:+ "The user this token identifies has not signed in to Infisical through your organization's OIDC SSO yet. They need to complete a browser sign-in once before an application can act on their behalf."+ });+ }++ const user = await userDAL.findById(userAlias.userId);+ if (!user) {+ throw new UnauthorizedError({ message: "The user this token identifies no longer has an Infisical account." });+ }++ await permissionService.getOrgPermission({+ actor: ActorType.USER,+ actorId: user.id,+ orgId: client.orgId,+ actorAuthMethod: AuthMethod.OIDC,+ actorOrgId: client.orgId,+ scope: OrganizationActionScope.ParentOrganization+ });++ const { isMfaRequired } = getRequiredMfaMethod(rootOrg, user);+ if (isMfaRequired && !client.tokenExchangeIdpSatisfiesMfa) {+ throw new UnauthorizedError({+ message:+ "Multi-factor authentication is required for this user, and this application has not been marked as relying on an identity provider that enforces it. An organization admin can enable that on the application under Organization Settings > OAuth Applications."+ });+ }++ const tokenSession = await tokenService.getUserTokenSession({+ userId: user.id,+ ip: dto.ip,+ userAgent: getOauthClientSessionUserAgent(client.clientId)+ });+ if (!tokenSession) throw new BadRequestError({ message: "Failed to create user token session" });++ const { accessTokenExpiresIn } = await getTokenLifetimes(client.orgId);++ const accessToken = signOauthToken(+ {+ authMethod: AuthMethod.OIDC,+ userId: user.id,+ tokenVersionId: tokenSession.id,+ organizationId: client.orgId,+ isMfaVerified: client.tokenExchangeIdpSatisfiesMfa || undefined,+ delegation: OauthDelegationMode.Full,+ tokenType: AuthTokenType.ACCESS_TOKEN,+ version: tokenSession.accessVersion,+ oauthClientId: client.clientId+ },+ accessTokenExpiresIn+ );++ await auditLogService.createAuditLog({+ ipAddress: dto.ip,+ userAgent: dto.userAgent,+ orgId: client.orgId,+ actor: {+ type: ActorType.USER,+ metadata: {+ userId: user.id,+ email: user.email,+ username: user.username,+ authMethod: AuthMethod.OIDC+ }+ },+ event: {+ type: EventType.OAUTH_CLIENT_TOKEN_EXCHANGE,+ metadata: {+ clientDbId: client.id,+ clientId: client.clientId,+ clientName: client.name,+ subjectUserId: user.id,+ subjectExternalId: subject,+ tokenVersionId: tokenSession.id+ }+ }+ });++ return {+ access_token: accessToken,+ issued_token_type: OauthTokenType.AccessToken,+ token_type: "Bearer" as const,+ expires_in: expiresInToSeconds(accessTokenExpiresIn)+ };+ };+const exchangeToken = async (dto: TOauthTokenExchangeDTO) => {const client = await authenticateClient(dto.clientId, dto.clientSecret);- if (dto.grantType === "authorization_code") {+ if (dto.grantType === OauthGrantType.TokenExchange) {+ return exchangeSubjectToken(client, dto);+ }++ if (dto.grantType === OauthGrantType.AuthorizationCode) {+ assertGrantEnabled(client, OauthGrantType.AuthorizationCode);+const codeKey = KeyStorePrefixes.OauthAuthorizationCode(dto.code);const codePayloadRaw = await keyStore.getItem(codeKey);if (!codePayloadRaw) {@@ -442,6 +706,8 @@ export const oauthClientServiceFactory = ({};}+ assertGrantEnabled(client, OauthGrantType.RefreshToken);+const { decodedToken, tokenVersion, isGraceHit } = await tokenService.validateRefreshToken(dto.refreshToken, {allowOauthClientToken: true});diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.tsindex 7cff5c6dc5..ed3d77c2fd 100644--- a/backend/src/services/oauth-client/oauth-client-types.ts+++ b/backend/src/services/oauth-client/oauth-client-types.ts@@ -2,19 +2,63 @@ 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.+export enum OauthGrantType {+ AuthorizationCode = "authorization_code",+ RefreshToken = "refresh_token",+ TokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"+}++// Grants that mint tokens through a browser redirect, so they need registered redirect URIs.+export const REDIRECT_BASED_GRANT_TYPES: readonly OauthGrantType[] = [OauthGrantType.AuthorizationCode];++// Applied as the create default so an API caller written before this feature, which sends no+// `grantTypes`, keeps registering redirect-flow applications.+export const DEFAULT_OAUTH_GRANT_TYPES: readonly OauthGrantType[] = [+ OauthGrantType.AuthorizationCode,+ OauthGrantType.RefreshToken+];++// RFC 8693 section 3 token type identifiers.+export enum OauthTokenType {+ Jwt = "urn:ietf:params:oauth:token-type:jwt",+ IdToken = "urn:ietf:params:oauth:token-type:id_token",+ 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.+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.+export enum OauthDelegationMode {+ Full = "full"+}+export type TCreateOauthClientDTO = {name: string;description?: string;+ grantTypes: OauthGrantType[];redirectUris: string[];requirePkce?: boolean;+ tokenExchangeAudience?: string;+ tokenExchangeIdpSatisfiesMfa?: boolean;};export type TUpdateOauthClientDTO = {clientDbId: string;name?: string;description?: string | null;+ grantTypes?: OauthGrantType[];redirectUris?: string[];requirePkce?: boolean;+ tokenExchangeAudience?: string | null;+ tokenExchangeIdpSatisfiesMfa?: boolean;};export type TOauthAuthorizeInfoDTO = {@@ -42,15 +86,22 @@ export type TOauthTokenExchangeDTO = {clientSecret?: string;} & (| {- grantType: "authorization_code";+ grantType: OauthGrantType.AuthorizationCode;code: string;redirectUri?: string;codeVerifier?: string;}| {- grantType: "refresh_token";+ grantType: OauthGrantType.RefreshToken;refreshToken: string;}+ | {+ grantType: OauthGrantType.TokenExchange;+ subjectToken: string;+ subjectTokenType: OauthTokenType;+ ip: string;+ userAgent?: string;+ });export const OauthAuthorizationCodePayloadSchema = z.object({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.tsnew file mode 100644index 0000000000..d4113e6184--- /dev/null+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts@@ -0,0 +1,324 @@+import nodeCrypto from "node:crypto";++import jwt from "jsonwebtoken";++import { TOidcConfigs } from "@app/db/schemas";+import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";+import { crypto } from "@app/lib/crypto";++import { resolveOidcTrustAnchor, verifySubjectToken } from "./oauth-token-exchange-fns";++const { publicKey, privateKey } = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });+const otherKeyPair = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });++const PUBLIC_KEY_PEM = publicKey.export({ type: "spki", format: "pem" }).toString();+const PRIVATE_KEY_PEM = privateKey.export({ type: "pkcs8", format: "pem" }).toString();+const OTHER_PRIVATE_KEY_PEM = otherKeyPair.privateKey.export({ type: "pkcs8", format: "pem" }).toString();++const getSigningKey = vi.fn<(kid: string) => Promise<{ getPublicKey: () => string }>>();++vi.mock("jwks-rsa", () => ({+ JwksClient: class {+ getSigningKey = getSigningKey;+ }+}));++const safeGet = vi.fn<(url: string) => Promise<{ data: { jwks_uri?: string; issuer?: string } }>>();+const buildSsrfSafeAgent = vi.fn<(url: string) => Promise<undefined>>();+vi.mock("@app/lib/validator/safe-request", () => ({+ safeRequest: { get: (url: string) => safeGet(url) },+ buildSsrfSafeAgent: (url: string) => buildSsrfSafeAgent(url)+}));++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ sanitizeUrlForLog: (url: string) => url+}));++const ISSUER = "https://adfs.example.com/adfs";+const AUDIENCE = "api://paychex-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.+let jwksUriCounter = 0;+const nextJwksUri = () => {+ jwksUriCounter += 1;+ return `https://adfs.example.com/adfs/discovery/keys?case=${jwksUriCounter}`;+};++const buildOidcConfig = (overrides: Partial<TOidcConfigs> = {}): TOidcConfigs =>+ ({+ id: "11111111-1111-1111-1111-111111111111",+ orgId: "22222222-2222-2222-2222-222222222222",+ configurationType: OIDCConfigurationType.CUSTOM,+ issuer: ISSUER,+ jwksUri: nextJwksUri(),+ discoveryURL: null,+ authorizationEndpoint: `${ISSUER}/authorize`,+ tokenEndpoint: `${ISSUER}/token`,+ userinfoEndpoint: `${ISSUER}/userinfo`,+ allowedEmailDomains: null,+ isActive: true,+ manageGroupMemberships: false,+ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.RS256,+ ...overrides+ }) as TOidcConfigs;++type TSignOptions = {+ privateKeyPem?: string;+ audience?: string | string[];+ issuer?: string;+ algorithm?: jwt.Algorithm;+ expiresIn?: string | number;+ notBefore?: string | number;+ subject?: string | null;+ keyId?: string | null;+};++const signSubjectToken = ({+ privateKeyPem = PRIVATE_KEY_PEM,+ audience = AUDIENCE,+ issuer = ISSUER,+ algorithm = "RS256",+ expiresIn = "10m",+ notBefore,+ subject = SUBJECT,+ keyId = "adfs-key-1"+}: TSignOptions = {}) =>+ jwt.sign({ ...(subject ? { sub: subject } : {}) }, privateKeyPem, {+ algorithm,+ audience,+ issuer,+ expiresIn,+ ...(notBefore !== undefined ? { notBefore } : {}),+ ...(keyId ? { keyid: keyId } : {})+ });++beforeAll(async () => {+ process.env.FIPS_ENABLED = "false";+ await crypto.initialize({} as never, {} as never, {} as never);+});++afterAll(() => {+ delete process.env.FIPS_ENABLED;+});++beforeEach(() => {+ vi.clearAllMocks();+ buildSsrfSafeAgent.mockResolvedValue(undefined);+ getSigningKey.mockResolvedValue({ getPublicKey: () => PUBLIC_KEY_PEM });+});++describe("resolveOidcTrustAnchor", () => {+ test("uses the stored issuer and JWKS URI for a custom configuration", async () => {+ const oidcConfig = buildOidcConfig();++ await expect(resolveOidcTrustAnchor(oidcConfig)).resolves.toEqual({+ issuer: ISSUER,+ jwksUri: oidcConfig.jwksUri,+ algorithm: OIDCJWTSignatureAlgorithm.RS256+ });+ });++ test("rejects a symmetric signature algorithm", async () => {+ const oidcConfig = buildOidcConfig({ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.HS256 });++ await expect(resolveOidcTrustAnchor(oidcConfig)).rejects.toThrow(/asymmetric JWT signature algorithm/);+ });++ test("rejects a custom configuration with no issuer", async () => {+ await expect(resolveOidcTrustAnchor(buildOidcConfig({ issuer: null }))).rejects.toThrow(+ /missing an issuer or JWKS URI/+ );+ });++ test("rejects a custom configuration with no JWKS URI", async () => {+ await expect(resolveOidcTrustAnchor(buildOidcConfig({ jwksUri: null }))).rejects.toThrow(+ /missing an issuer or JWKS URI/+ );+ });++ test("resolves the JWKS URI through discovery when configured that way", async () => {+ const discoveredJwksUri = nextJwksUri();+ safeGet.mockResolvedValue({ data: { jwks_uri: discoveredJwksUri, issuer: ISSUER } });++ const oidcConfig = buildOidcConfig({+ configurationType: OIDCConfigurationType.DISCOVERY_URL,+ discoveryURL: `${ISSUER}/.well-known/openid-configuration`,+ issuer: null,+ jwksUri: null+ });++ await expect(resolveOidcTrustAnchor(oidcConfig)).resolves.toEqual({+ issuer: ISSUER,+ jwksUri: discoveredJwksUri,+ algorithm: OIDCJWTSignatureAlgorithm.RS256+ });+ expect(safeGet).toHaveBeenCalledWith(oidcConfig.discoveryURL);+ });++ test("appends the well-known path when the discovery URL is an issuer base", async () => {+ safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });++ await resolveOidcTrustAnchor(+ buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL: `${ISSUER}/` })+ );++ expect(safeGet).toHaveBeenCalledWith(`${ISSUER}/.well-known/openid-configuration`);+ });++ test("prefers the stored issuer over the discovered one", async () => {+ safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: "https://attacker.example.com" } });++ const anchor = await resolveOidcTrustAnchor(+ buildOidcConfig({+ configurationType: OIDCConfigurationType.DISCOVERY_URL,+ discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ })+ );++ expect(anchor.issuer).toEqual(ISSUER);+ });++ test("reports an unreachable identity provider without leaking the transport error", async () => {+ safeGet.mockRejectedValue(new Error("ECONNREFUSED 10.0.0.5:443"));++ await expect(+ resolveOidcTrustAnchor(+ buildOidcConfig({+ configurationType: OIDCConfigurationType.DISCOVERY_URL,+ discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ })+ )+ ).rejects.toThrow(/Could not reach your organization's identity provider/);+ });++ test("rejects a discovery document with no jwks_uri", async () => {+ safeGet.mockResolvedValue({ data: { issuer: ISSUER } });++ await expect(+ resolveOidcTrustAnchor(+ buildOidcConfig({+ configurationType: OIDCConfigurationType.DISCOVERY_URL,+ discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ })+ )+ ).rejects.toThrow(/did not publish a 'jwks_uri'/);+ });++ test("rejects a discovery configuration with no discovery URL", async () => {+ await expect(+ resolveOidcTrustAnchor(+ buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL: null })+ )+ ).rejects.toThrow(/no discovery URL/);+ });+});++describe("verifySubjectToken", () => {+ const verify = (subjectToken: string, oidcConfig = buildOidcConfig(), expectedAudience = AUDIENCE) =>+ verifySubjectToken({ subjectToken, oidcConfig, expectedAudience });++ test("returns the subject of a valid token", async () => {+ await expect(verify(signSubjectToken())).resolves.toEqual({ subject: SUBJECT, issuer: ISSUER });+ });++ test("accepts a token whose audience list contains the expected audience", async () => {+ const token = signSubjectToken({ audience: ["api://other-app", AUDIENCE] });++ await expect(verify(token)).resolves.toMatchObject({ subject: SUBJECT });+ });++ // The control that stops any token the issuer signed, for any application, being replayed here.+ test("rejects a token minted for a different application", async () => {+ const token = signSubjectToken({ audience: "api://expenses-app" });++ await expect(verify(token)).rejects.toThrow(/audience does not match/);+ });++ test("rejects a token from a different issuer", async () => {+ const token = signSubjectToken({ issuer: "https://attacker.example.com" });++ await expect(verify(token)).rejects.toThrow(/not issued by your organization's configured OIDC SSO issuer/);+ });++ test("rejects an expired token", async () => {+ const token = signSubjectToken({ expiresIn: -60 });++ await expect(verify(token)).rejects.toThrow(/has expired/);+ });++ test("rejects a token that is not yet valid", async () => {+ const token = signSubjectToken({ notBefore: 600 });++ await expect(verify(token)).rejects.toThrow(/not valid yet/);+ });++ test("rejects a token signed by a key the provider does not publish", async () => {+ const token = signSubjectToken({ privateKeyPem: OTHER_PRIVATE_KEY_PEM });++ await expect(verify(token)).rejects.toThrow(/could not be verified against your organization/);+ });++ // Pinning `algorithms` closes this off. jsonwebtoken reports it as a missing signature rather than an+ // algorithm mismatch, so assert on the generic message.+ test("rejects an unsigned (alg: none) token", async () => {+ const token = jwt.sign({ sub: SUBJECT, aud: AUDIENCE, iss: ISSUER }, "", {+ algorithm: "none",+ keyid: "adfs-key-1"+ });++ await expect(verify(token)).rejects.toThrow(/could not be verified against your organization/);+ });++ test("rejects a token signed with an algorithm the configuration does not expect", async () => {+ const token = signSubjectToken({ algorithm: "RS512" });++ await expect(verify(token)).rejects.toThrow(/not signed with the algorithm/);+ });++ test("rejects a token with no kid header", async () => {+ const token = signSubjectToken({ keyId: null });++ await expect(verify(token)).rejects.toThrow(/no 'kid' header/);+ });++ test("rejects a token whose kid the provider does not publish", async () => {+ const notFound = new Error("key not found");+ notFound.name = "SigningKeyNotFoundError";+ getSigningKey.mockRejectedValue(notFound);++ await expect(verify(signSubjectToken())).rejects.toThrow(/does not publish/);+ });++ test("reports a JWKS fetch failure without leaking the transport error", async () => {+ getSigningKey.mockRejectedValue(new Error("connect ETIMEDOUT 10.0.0.5:443"));++ await expect(verify(signSubjectToken())).rejects.toThrow(/Could not load signing keys/);+ });++ test("rejects a token with no sub claim", async () => {+ const token = signSubjectToken({ subject: null });++ await expect(verify(token)).rejects.toThrow(/no 'sub' claim/);+ });++ test("rejects a malformed token without echoing the parser error", async () => {+ await expect(verify("not-a-jwt")).rejects.toThrow(/not a well-formed JWT/);+ });++ test("pins the JWKS connection to the validated IPs", async () => {+ const oidcConfig = buildOidcConfig();++ await verify(signSubjectToken(), oidcConfig);++ expect(buildSsrfSafeAgent).toHaveBeenCalledWith(oidcConfig.jwksUri);+ });++ test("rejects a JWKS URI that resolves to a private address", async () => {+ buildSsrfSafeAgent.mockRejectedValue(new Error("Local IPs not allowed as URL"));++ await expect(verify(signSubjectToken())).rejects.toThrow(/Could not load signing keys/);+ });+});diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.tsnew file mode 100644index 0000000000..1172d59f81--- /dev/null+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts@@ -0,0 +1,241 @@+import jwt, { JwtPayload } from "jsonwebtoken";+import { JwksClient } from "jwks-rsa";++import { TOidcConfigs } from "@app/db/schemas";+import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";+import { crypto } from "@app/lib/crypto";+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { buildSsrfSafeAgent, safeRequest } from "@app/lib/validator/safe-request";++const 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.+const ASYMMETRIC_SIGNATURE_ALGORITHMS: readonly string[] = [+ OIDCJWTSignatureAlgorithm.RS256,+ OIDCJWTSignatureAlgorithm.RS512,+ OIDCJWTSignatureAlgorithm.EDDSA+];++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.+const buildDiscoveryDocumentUrl = (discoveryUrl: string) => {+ const url = new URL(discoveryUrl);+ if (url.pathname.includes("/.well-known/")) return url.toString();++ url.pathname = `${url.pathname.replace(/\/$/, "")}${WELL_KNOWN_OPENID_CONFIGURATION}`;+ return url.toString();+};++// 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.+const JWKS_CLIENT_TTL_MS = 10 * 60 * 1000;+const MAX_CACHED_JWKS_CLIENTS = 512;+const jwksClientCache = new Map<string, { client: JwksClient; expiresAt: number }>();++const getJwksClient = async (jwksUri: string) => {+ const now = Date.now();+ const cached = jwksClientCache.get(jwksUri);+ if (cached && cached.expiresAt > now) return cached.client;++ if (jwksClientCache.size >= MAX_CACHED_JWKS_CLIENTS) jwksClientCache.clear();++ const requestAgent = await buildSsrfSafeAgent(jwksUri, { keepAlive: true });++ const client = new JwksClient({+ jwksUri,+ requestAgent,+ cache: true,+ cacheMaxEntries: 5,+ cacheMaxAge: JWKS_CLIENT_TTL_MS,+ rateLimit: true,+ jwksRequestsPerMinute: 30,+ timeout: 10_000+ });++ jwksClientCache.set(jwksUri, { client, expiresAt: now + JWKS_CLIENT_TTL_MS });+ return client;+};++export type TOidcTrustAnchor = {+ issuer: string;+ jwksUri: string;+ 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.+export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<TOidcTrustAnchor> => {+ const algorithm = oidcConfig.jwtSignatureAlgorithm || OIDCJWTSignatureAlgorithm.RS256;++ if (!ASYMMETRIC_SIGNATURE_ALGORITHMS.includes(algorithm)) {+ throw new BadRequestError({+ message: `Token exchange requires an OIDC SSO configuration that uses an asymmetric JWT signature algorithm, but yours uses '${algorithm}'. Switch it to one of ${ASYMMETRIC_SIGNATURE_ALGORITHMS.join(", ")}. ${SSO_TAB_HINT}`+ });+ }++ if (oidcConfig.configurationType === OIDCConfigurationType.DISCOVERY_URL) {+ if (!oidcConfig.discoveryURL) {+ throw new BadRequestError({+ message: `Your organization's OIDC SSO configuration has no discovery URL, so the identity provider's signing keys cannot be located. ${SSO_TAB_HINT}`+ });+ }++ let metadata: { jwks_uri?: string; issuer?: string };+ try {+ const { data } = await safeRequest.get<{ jwks_uri?: string; issuer?: string }>(+ buildDiscoveryDocumentUrl(oidcConfig.discoveryURL),+ { timeout: 10_000 }+ );+ metadata = data;+ } catch (error) {+ logger.error(+ { error, orgId: oidcConfig.orgId },+ `OIDC discovery failed during token exchange [orgId=${oidcConfig.orgId}]`+ );+ throw new BadRequestError({+ message: `Could not reach your organization's identity provider to load its signing keys. ${SSO_TAB_HINT}`+ });+ }++ const jwksUri = metadata.jwks_uri;+ if (!jwksUri) {+ throw new BadRequestError({+ message: `Your organization's identity provider did not publish a 'jwks_uri' in its discovery document, so subject tokens cannot be verified. ${SSO_TAB_HINT}`+ });+ }++ const issuer = oidcConfig.issuer || metadata.issuer;+ if (!issuer) {+ throw new BadRequestError({+ message: `Your organization's identity provider did not publish an issuer in its discovery document. ${SSO_TAB_HINT}`+ });+ }++ return { issuer, jwksUri, algorithm };+ }++ if (!oidcConfig.issuer || !oidcConfig.jwksUri) {+ throw new BadRequestError({+ message: `Your organization's OIDC SSO configuration is missing an issuer or JWKS URI, so subject tokens cannot be verified. ${SSO_TAB_HINT}`+ });+ }++ return { issuer: oidcConfig.issuer, jwksUri: oidcConfig.jwksUri, algorithm };+};++// jsonwebtoken reports failures with terse developer-facing text ("jwt audience invalid"). Translate to+// something the caller can act on without leaking the raw message.+const toSubjectTokenError = (error: unknown, anchor: TOidcTrustAnchor, expectedAudience: string) => {+ if (error instanceof jwt.TokenExpiredError) {+ return new UnauthorizedError({ message: "The subject token has expired." });+ }++ if (error instanceof jwt.NotBeforeError) {+ return new UnauthorizedError({ message: "The subject token is not valid yet (its 'nbf' claim is in the future)." });+ }++ if (error instanceof jwt.JsonWebTokenError) {+ const reason = error.message;++ if (reason.includes("audience")) {+ return new UnauthorizedError({+ message: `The subject token's audience does not match this application's configured token exchange audience ('${expectedAudience}').`+ });+ }++ if (reason.includes("issuer")) {+ return new UnauthorizedError({+ message: `The subject token was not issued by your organization's configured OIDC SSO issuer ('${anchor.issuer}').`+ });+ }++ if (reason.includes("algorithm")) {+ return new UnauthorizedError({+ message: `The subject token is not signed with the algorithm your organization's OIDC SSO configuration expects ('${anchor.algorithm}').`+ });+ }++ return new UnauthorizedError({+ message: "The subject token could not be verified against your organization's identity provider."+ });+ }++ return null;+};++type TVerifySubjectTokenDTO = {+ subjectToken: string;+ oidcConfig: TOidcConfigs;+ 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);++ const decoded = crypto.jwt().decode(subjectToken, { complete: true });+ if (!decoded) {+ throw new UnauthorizedError({ message: "The subject token is not a well-formed JWT." });+ }++ const { kid } = decoded.header;+ if (!kid) {+ throw new UnauthorizedError({+ message:+ "The subject token has no 'kid' header, so the signing key to verify it with cannot be identified. Configure your identity provider to include a key id."+ });+ }++ let signingKey;+ try {+ const jwksClient = await getJwksClient(anchor.jwksUri);+ signingKey = await jwksClient.getSigningKey(kid);+ } catch (error) {+ logger.error(+ { error, orgId: oidcConfig.orgId, kid },+ `Subject token signing key lookup failed during token exchange [orgId=${oidcConfig.orgId}] [kid=${kid}]`+ );++ if (error instanceof Error && error.name === "SigningKeyNotFoundError") {+ throw new UnauthorizedError({+ message: `The subject token was signed with a key ('${kid}') that your organization's identity provider does not publish. The token may be from a different provider, or the provider's keys may have rotated.`+ });+ }++ throw new BadRequestError({+ message: `Could not load signing keys from your organization's identity provider. ${SSO_TAB_HINT}`+ });+ }++ let claims: JwtPayload;+ try {+ claims = crypto.jwt().verify(subjectToken, signingKey.getPublicKey(), {+ issuer: anchor.issuer,+ audience: expectedAudience,+ algorithms: [anchor.algorithm as jwt.Algorithm]+ }) as JwtPayload;+ } catch (error) {+ logger.error(+ { error, orgId: oidcConfig.orgId },+ `Subject token verification failed during token exchange [orgId=${oidcConfig.orgId}]`+ );+ throw toSubjectTokenError(error, anchor, expectedAudience) ?? error;+ }++ if (!claims.sub) {+ throw new UnauthorizedError({+ message: "The subject token has no 'sub' claim, so it does not identify a user."+ });+ }++ return { subject: claims.sub, issuer: anchor.issuer };+};diff --git a/docs/docs.json b/docs/docs.jsonindex afbda7a845..8f0e7f1116 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -87,6 +87,7 @@]},"documentation/platform/oauth-applications",+ "documentation/platform/oauth-token-exchange",{"group": "Access control","pages": [diff --git a/docs/documentation/platform/oauth-applications.mdx b/docs/documentation/platform/oauth-applications.mdxindex c98f90b485..f083c4cabf 100644--- a/docs/documentation/platform/oauth-applications.mdx+++ b/docs/documentation/platform/oauth-applications.mdx@@ -7,6 +7,10 @@ description: "Let external platforms request delegated access to Infisical on aA common use case is wiring Infisical into a developer platform as an External Auth provider, so that `infisical run` can fetch secrets at runtime inside a remote development environment using the developer's own permissions.+<Info>+ This page covers the browser-based authorization code flow, where each user approves the application on a consent screen. If you are registering trusted middleware that acts on behalf of many users and has no browser to redirect through, see [OAuth Token Exchange](/documentation/platform/oauth-token-exchange).+</Info>+<Note>A delegated OAuth token can never do more than the user who authorized it. Scopes only **narrow** what the token can do; they never grant access the user does not already have. When the user's access changes or their session is revoked, every token issued for them through OAuth is affected immediately.</Note>@@ -62,10 +66,11 @@ OAuth applications are managed at the organization level. You need permission toHead to **Organization Settings** and open **OAuth Applications** from the sidebar.</Step><Step title="Add an application">- Press **Add OAuth application** and fill in the details:+ Press **Add Application** and fill in the details:- **Name** (required): A friendly name shown to users on the consent screen.- **Description** (optional): A short note about what the application is used for. Also shown on the consent screen.+ - **Flow**: Leave **Authorization code** selected. See [OAuth Token Exchange](/documentation/platform/oauth-token-exchange) for the other flow.- **Redirect URIs** (required): One URI per line. The authorization flow will only ever redirect to one of these exact URIs. Each must use `https://`; `http://` is allowed only for loopback addresses such as `localhost`, `127.0.0.1`, and `::1`.- **Require PKCE (S256)**: When enabled, authorization requests that do not include a PKCE code challenge are rejected. Recommended for public clients.</Step>diff --git a/docs/documentation/platform/oauth-token-exchange.mdx b/docs/documentation/platform/oauth-token-exchange.mdxnew file mode 100644index 0000000000..09e40b3529--- /dev/null+++ b/docs/documentation/platform/oauth-token-exchange.mdx@@ -0,0 +1,206 @@+---+title: OAuth Token Exchange+description: "Let trusted middleware act on behalf of your users in Infisical using tokens from your own identity provider."+---++**Token exchange** lets a trusted service you run present a user's token from your identity provider and receive an Infisical token for that same user. The service acts as the user rather than as a shared service account, so every action in Infisical is attributed to the real person and bounded by their own access.++This is the pattern behind AI coding assistants, internal developer portals, API gateways, and any middleware that has to call Infisical "as the user who asked." Those tools have no browser to redirect through and no way to show each user a consent screen, so the standard [OAuth Applications](/documentation/platform/oauth-applications) authorization code flow does not fit them.++<Info>+ This page is for organization admins registering middleware that acts on behalf of many users. If you are wiring up a platform that can redirect a user's browser, use the authorization code flow on [OAuth Applications](/documentation/platform/oauth-applications) instead.+</Info>++<Note>+ Token exchange requires an active **OIDC** SSO configuration for your organization. Infisical verifies the tokens your middleware presents against that same identity provider, so there is nothing to trust until OIDC SSO is set up. See [SSO overview](/documentation/platform/sso/overview).+</Note>++## Why not a shared machine identity++A single [machine identity](/documentation/platform/identities/machine-identities) shared by every user of your middleware collapses the authorization boundary in two ways:++- **Attribution is lost.** Every audit log entry reads as the service account, so you cannot tell which person triggered an action.+- **Least privilege is lost.** Every user gets whatever the shared identity can reach, rather than what they personally can reach.++Token exchange fixes both. The token Infisical issues belongs to one user, carries that user's permissions, and appears in the audit log under their name alongside the application that requested it.++## When to use token exchange++<CardGroup cols={2}>+ <Card title="AI assistants and agents" icon="robot">+ An MCP server or agent platform reading secrets on behalf of the engineer who asked.+ </Card>+ <Card title="Internal developer portals" icon="window">+ A portal that shows each developer the secrets they personally can see.+ </Card>+ <Card title="API gateways" icon="shield">+ A gateway that already validates your identity provider's tokens and needs to forward the user's identity downstream.+ </Card>+ <Card title="CI middleware" icon="gears">+ Automation that runs a step on a named person's behalf rather than as a shared account.+ </Card>+</CardGroup>++## How it works++Three parties are involved:++- **Your identity provider** issues a token proving who the user is. This is the same provider your users already sign in to Infisical with.+- **Your middleware** holds an Infisical client ID and client secret, and presents the user's token.+- **Infisical** verifies that token, resolves it to the matching Infisical user, and issues a short-lived access token for them.++```mermaid+sequenceDiagram+ participant User as User+ participant MW as Your Middleware+ participant IdP as Your Identity Provider+ participant Infis as Infisical++ User->>MW: Request (already signed in via your IdP)+ MW->>IdP: Validate the user's token+ MW->>Infis: POST /api/v1/oauth/token (client credentials + user's token)+ Infis->>IdP: Fetch signing keys+ Infis->>Infis: Verify signature, issuer, audience, expiry+ Infis->>Infis: Resolve the token's subject to an Infisical user+ Infis->>MW: Short-lived access token for that user+ MW->>Infis: API request with the access token+ Infis->>MW: Response, limited to that user's permissions+```++Structurally, this is your organization's OIDC sign-in with the token handed over directly instead of collected through a browser redirect.++### What the issued token can do++The issued token carries the user's **full effective permissions**, not a narrowed subset. There is no consent screen and no scope list, so an organization admin approves the delegation once when registering the application rather than each user approving it individually.++Two things it deliberately cannot do:++- **It cannot manage the user's account.** Changing MFA, revoking sessions, and other account self-management actions are never reachable with a delegated token, however it was obtained.+- **It cannot outlive its access token.** No refresh token is issued. Your middleware exchanges again against the still-valid identity provider token.++<Warning>+ A token issued through exchange is a bearer credential held by your middleware, protected by that service rather than by the user's hardware key or device trust. Treat the middleware as a system that can act as any of its users, and secure it accordingly.+</Warning>++## Before you start++- **OIDC SSO must be configured and enabled** for your organization.+- **Your identity provider must sign tokens with an asymmetric algorithm** (RS256, RS512, or EdDSA) and publish a key ID (`kid`) in the token header.+- **Each user must have signed in to Infisical through OIDC SSO at least once.** Infisical matches the token's subject to the account created on that first sign-in, so a user who has only ever used your middleware cannot be resolved yet. Treat one browser sign-in as an onboarding step.+- **You need a dedicated registration for your middleware in your identity provider**, so its tokens carry an audience distinct from Infisical's own.++## Registering your middleware++You need permission to manage both OAuth applications and SSO in the organization, because enabling token exchange decides whose externally issued tokens Infisical will convert into user tokens.++<Steps>+ <Step title="Open the OAuth Applications page">+ Head to **Organization Settings** and open **OAuth Applications**.+ </Step>+ <Step title="Add an application">+ Press **Add Application** and fill in the details:++ - **Name** (required): A friendly name for the middleware.+ - **Description** (optional): A short note about what it is used for.+ - **Flow**: Select **Token exchange**.+ - **Audience** (required): The audience your identity provider puts in tokens it issues for this middleware, for example `api://internal-mcp`. Infisical rejects any token carrying a different audience.+ - **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.++ There is no issuer to set here. Infisical always verifies against your organization's OIDC SSO provider, which is configured once on the **SSO** page and cannot be overridden per application.+ </Step>+ <Step title="Store the credentials">+ On creation, Infisical shows the **Client ID** and **Client Secret**.++ <Warning>+ The client secret is shown only once. Store it securely. If it is lost, you can rotate it from the application's menu, but you cannot retrieve the original value.+ </Warning>+ </Step>+</Steps>++### Why the audience matters++The audience is the control that does the real work. Your identity provider signs tokens for every application in your estate, and without an expected audience any of those tokens could be presented to Infisical and come back as a working Infisical token. Binding the application to one audience is what stops a token minted for an expenses app becoming a secrets-read credential.++Set it to your middleware's own registration in your identity provider, never to Infisical's.++## Exchanging a token++Token exchange follows [RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693) on the existing token endpoint, so any RFC 8693-aware client library works. Client credentials may be sent as HTTP Basic auth or in the request body.++```bash+curl -X POST https://app.infisical.com/api/v1/oauth/token \+ -u "<client_id>:<client_secret>" \+ --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \+ --data-urlencode "subject_token=<user's token from your identity provider>" \+ --data-urlencode "subject_token_type=urn:ietf:params:oauth:token-type:jwt"+```++Parameters:++| Parameter | Value |+| -------------------- | ---------------------------------------------------------------------------------------------------------------- |+| `grant_type` | `urn:ietf:params:oauth:grant-type:token-exchange` |+| `subject_token` | The user's token from your identity provider |+| `subject_token_type` | `urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token` |++The response is a short-lived access token for the user the subject token identified:++```json+{+ "access_token": "...",+ "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",+ "token_type": "Bearer",+ "expires_in": 3600+}+```++Access token lifetime follows your organization's user token expiration setting, falling back to the platform default.++<Note>+ `scope`, `audience`, and `resource` 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.+</Note>++Use the access token as a standard Bearer token:++```bash+curl https://app.infisical.com/api/v4/secrets \+ -H "Authorization: Bearer <access_token>" \+ --get \+ --data-urlencode "workspaceId=<project-id>" \+ --data-urlencode "environment=dev"+```++<Note>+ Delegated tokens are currently accepted on the read-only secret-fetch endpoints. Endpoint coverage is expanding; if your integration needs an endpoint that rejects a delegated token, let us know which one.+</Note>++## What Infisical verifies++Every exchange checks all of the following, and fails the request with a message naming the problem if any of them does not hold:++- The **signature** validates against your identity provider's published keys.+- The **issuer** matches your organization's configured OIDC SSO issuer.+- The **audience** matches the audience configured on the application.+- The token is **not expired** and not used before its `nbf` time.+- The **signing algorithm** matches your OIDC SSO configuration.+- The token's **subject** resolves to a user who has signed in through your organization's OIDC SSO and is an active member of the organization.+- **MFA** requirements are satisfied, either because none apply or because the application declares that the identity provider enforces them.++## Audit trail++Each exchange records an audit event attributed to the **subject user**, with the requesting application recorded alongside it. Because the issued token belongs to that user, every later action taken with it appears under the same person, and can be traced back to the exchange that authorized it.++## Dependency on SSO++Token exchange has no trust anchor of its own. It relies on your organization's OIDC SSO configuration, which means:++- **Disabling OIDC SSO stops token exchange working.** So does deleting the configuration.+- **Changing the issuer changes who can vouch for your users.** Migrating identity providers moves both browser sign-in and token exchange at once.++The **SSO** page lists the applications that depend on the issuer, so you can see the blast radius before changing it.++## Revoking access++Deleting the application from the **OAuth Applications** page immediately revokes every token it issued, so they stop working on the next request rather than living until expiry. Rotating the client secret stops the middleware obtaining new tokens until it is updated.++Because no refresh tokens are issued, the exposure from a compromised middleware is bounded by the remaining lifetime of the access tokens it currently holds.diff --git a/frontend/src/hooks/api/oauthClients/mutations.tsx b/frontend/src/hooks/api/oauthClients/mutations.tsxindex 335f399c5f..e25f2792c8 100644--- a/frontend/src/hooks/api/oauthClients/mutations.tsx+++ b/frontend/src/hooks/api/oauthClients/mutations.tsx@@ -24,7 +24,7 @@ export const useCreateOauthClient = () => {},onSuccess: ({ client }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.list(client.orgId)+ queryKey: oauthClientKeys.allLists(client.orgId)});}});@@ -42,7 +42,7 @@ export const useUpdateOauthClient = () => {},onSuccess: ({ orgId }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.list(orgId)+ queryKey: oauthClientKeys.allLists(orgId)});}});@@ -59,7 +59,7 @@ export const useDeleteOauthClient = () => {},onSuccess: ({ orgId }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.list(orgId)+ queryKey: oauthClientKeys.allLists(orgId)});}});@@ -76,7 +76,7 @@ export const useRotateOauthClientSecret = () => {},onSuccess: ({ client }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.list(client.orgId)+ queryKey: oauthClientKeys.allLists(client.orgId)});}});diff --git a/frontend/src/hooks/api/oauthClients/queries.tsx b/frontend/src/hooks/api/oauthClients/queries.tsxindex 07b268b839..4fd6caabd1 100644--- a/frontend/src/hooks/api/oauthClients/queries.tsx+++ b/frontend/src/hooks/api/oauthClients/queries.tsx@@ -2,19 +2,25 @@ import { useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { TOauthAuthorizeInfo, TOauthClient } from "./types";+import { OauthGrantType, TOauthAuthorizeInfo, TOauthClient } from "./types";export const oauthClientKeys = {- list: (orgId: string) => [{ orgId }, "oauth-clients"] as const,+ allLists: (orgId: string) => [{ orgId }, "oauth-clients"] as const,+ list: (orgId: string, grantType?: OauthGrantType) =>+ [...oauthClientKeys.allLists(orgId), grantType ?? ""] as const,authorizeInfo: (clientId: string, redirectUri: string, scope?: string) =>["oauth-authorize-info", clientId, redirectUri, scope ?? ""] as const};-export const useGetOauthClients = (orgId: string) => {+// `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.+export const useGetOauthClients = (orgId: string, grantType?: OauthGrantType) => {return useQuery({- queryKey: oauthClientKeys.list(orgId),+ queryKey: oauthClientKeys.list(orgId, grantType),queryFn: async () => {- const { data } = await apiRequest.get<{ clients: TOauthClient[] }>("/api/v1/oauth/clients");+ const { data } = await apiRequest.get<{ clients: TOauthClient[] }>("/api/v1/oauth/clients", {+ params: grantType ? { grantType } : undefined+ });return data.clients;},enabled: Boolean(orgId)diff --git a/frontend/src/hooks/api/oauthClients/types.ts b/frontend/src/hooks/api/oauthClients/types.tsindex abdb5d9d46..a431b83cd1 100644--- a/frontend/src/hooks/api/oauthClients/types.ts+++ b/frontend/src/hooks/api/oauthClients/types.ts@@ -1,3 +1,10 @@+// Redirect URIs and PKCE apply only to AuthorizationCode, the audience only to TokenExchange.+export enum OauthGrantType {+ AuthorizationCode = "authorization_code",+ RefreshToken = "refresh_token",+ TokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"+}+export type TOauthClient = {id: string;orgId: string;@@ -5,8 +12,11 @@ export type TOauthClient = {description?: string | null;clientId: string;clientSecretPrefix: string;+ grantTypes: OauthGrantType[];redirectUris: string[];requirePkce: boolean;+ tokenExchangeAudience?: string | null;+ tokenExchangeIdpSatisfiesMfa: boolean;createdAt: string;updatedAt: string;};@@ -14,16 +24,22 @@ export type TOauthClient = {export type TCreateOauthClientDTO = {name: string;description?: string;+ grantTypes: OauthGrantType[];redirectUris: string[];requirePkce?: boolean;+ tokenExchangeAudience?: string;+ tokenExchangeIdpSatisfiesMfa?: boolean;};export type TUpdateOauthClientDTO = {clientDbId: string;name?: string;description?: string | null;+ grantTypes?: OauthGrantType[];redirectUris?: string[];requirePkce?: boolean;+ tokenExchangeAudience?: string | null;+ tokenExchangeIdpSatisfiesMfa?: boolean;};export type TDeleteOauthClientDTO = {diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsxindex 92fda2b5b7..b6cab9760e 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx@@ -1,28 +1,43 @@import { useEffect } from "react";-import { Controller, useForm } from "react-hook-form";+import { Controller, useForm, useWatch } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";+import { Link } from "@tanstack/react-router";+import { AlertTriangle, Info } from "lucide-react";import { z } from "zod";import { createNotification } from "@app/components/notifications";import {+ Alert,+ AlertDescription,Button,- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,Field,FieldContent,FieldDescription,FieldError,+ FieldGroup,FieldLabel,FieldTitle,Input,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,Switch,+ Tabs,+ TabsList,+ TabsTrigger,TextArea} from "@app/components/v3";-import { TOauthClient, useCreateOauthClient, useUpdateOauthClient } from "@app/hooks/api";+import { useOrganization } from "@app/context";+import {+ TOauthClient,+ useCreateOauthClient,+ useGetOIDCConfig,+ useUpdateOauthClient+} from "@app/hooks/api";+import { OauthGrantType } from "@app/hooks/api/oauthClients/types";import { UsePopUpState } from "@app/hooks/usePopUp";const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1"]);@@ -40,31 +55,70 @@ const isValidRedirectUri = (uri: string) => {}};-const oauthClientFormSchema = z.object({- name: z.string().trim().min(1, "Name is required").max(64),- description: z.string().trim().max(256).optional(),- redirectUris: z- .string()- .trim()- .min(1, "At least one redirect URI is required")- .superRefine((value, ctx) => {- const uris = value- .split("\n")- .map((uri) => uri.trim())- .filter(Boolean);+const splitRedirectUris = (value: string) =>+ value+ .split("\n")+ .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.+enum OauthClientFlow {+ AuthorizationCode = "authorization-code",+ TokenExchange = "token-exchange"+}++const oauthClientFormSchema = z+ .object({+ name: z.string().trim().min(1, "Name is required").max(64),+ description: z.string().trim().max(256).optional(),+ flow: z.nativeEnum(OauthClientFlow),+ redirectUris: z.string().trim(),+ requirePkce: z.boolean(),+ tokenExchangeAudience: z.string().trim().max(255),+ tokenExchangeIdpSatisfiesMfa: z.boolean()+ })+ .superRefine((data, ctx) => {+ if (data.flow === OauthClientFlow.AuthorizationCode) {+ const uris = splitRedirectUris(data.redirectUris);++ if (!uris.length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["redirectUris"],+ message: "At least one redirect URI is required"+ });+ }+const invalidUri = uris.find((uri) => !isValidRedirectUri(uri));if (invalidUri) {ctx.addIssue({code: z.ZodIssueCode.custom,+ path: ["redirectUris"],message: `Invalid redirect URI: ${invalidUri}`});}- }),- requirePkce: z.boolean()-});+ }++ if (data.flow === OauthClientFlow.TokenExchange && !data.tokenExchangeAudience) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["tokenExchangeAudience"],+ message: "An audience is required"+ });+ }+ });type TOauthClientForm = z.infer<typeof oauthClientFormSchema>;+const FLOW_DESCRIPTIONS: Record<OauthClientFlow, string> = {+ [OauthClientFlow.AuthorizationCode]:+ "RFC 6749. The user signs in and approves the application in their browser. The token is limited to the scopes they consent to.",+ [OauthClientFlow.TokenExchange]:+ "RFC 8693. The application presents a user's token from your identity provider and receives that user's Infisical token. No browser and no consent screen, and the token carries that user's full permissions."+};+type Props = {popUp: UsePopUpState<["clientForm"]>;handlePopUpClose: (popUpName: keyof UsePopUpState<["clientForm"]>) => void;@@ -81,23 +135,39 @@ export const OauthClientModal = ({const editingClient = popUp?.clientForm?.data as TOauthClient | undefined;const isEditing = Boolean(editingClient);+ const { currentOrg } = useOrganization();+ const { data: oidcConfig, isPending: isOidcConfigPending } = useGetOIDCConfig(+ currentOrg?.id ?? ""+ );+ const hasActiveOidcSso = Boolean(oidcConfig?.isActive);+const { control, handleSubmit, reset } = useForm<TOauthClientForm>({resolver: zodResolver(oauthClientFormSchema),defaultValues: {name: "",description: "",+ flow: OauthClientFlow.AuthorizationCode,redirectUris: "",- requirePkce: false+ requirePkce: false,+ tokenExchangeAudience: "",+ tokenExchangeIdpSatisfiesMfa: false}});+ const flow = useWatch({ control, name: "flow" });+useEffect(() => {if (popUp?.clientForm?.isOpen) {reset({name: editingClient?.name ?? "",description: editingClient?.description ?? "",+ flow: editingClient?.grantTypes?.includes(OauthGrantType.TokenExchange)+ ? OauthClientFlow.TokenExchange+ : OauthClientFlow.AuthorizationCode,redirectUris: editingClient?.redirectUris?.join("\n") ?? "",- requirePkce: editingClient?.requirePkce ?? false+ requirePkce: editingClient?.requirePkce ?? false,+ tokenExchangeAudience: editingClient?.tokenExchangeAudience ?? "",+ tokenExchangeIdpSatisfiesMfa: editingClient?.tokenExchangeIdpSatisfiesMfa ?? false});}}, [popUp?.clientForm?.isOpen]);@@ -105,25 +175,26 @@ export const OauthClientModal = ({const { mutateAsync: createOauthClient, isPending: isCreating } = useCreateOauthClient();const { mutateAsync: updateOauthClient, isPending: isUpdating } = useUpdateOauthClient();- const onFormSubmit = async ({- name,- description,- redirectUris,- requirePkce- }: TOauthClientForm) => {- const parsedRedirectUris = redirectUris- .split("\n")- .map((uri) => uri.trim())- .filter(Boolean);+ const onFormSubmit = async (form: TOauthClientForm) => {+ const isTokenExchange = form.flow === OauthClientFlow.TokenExchange;++ const payload = {+ name: form.name,+ grantTypes: isTokenExchange+ ? [OauthGrantType.TokenExchange]+ : [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],+ redirectUris: isTokenExchange ? [] : splitRedirectUris(form.redirectUris),+ requirePkce: isTokenExchange ? false : form.requirePkce,+ tokenExchangeIdpSatisfiesMfa: isTokenExchange ? form.tokenExchangeIdpSatisfiesMfa : false+ };try {if (isEditing && editingClient) {await updateOauthClient({+ ...payload,clientDbId: editingClient.id,- name,- description: description || null,- redirectUris: parsedRedirectUris,- requirePkce+ description: form.description || null,+ tokenExchangeAudience: isTokenExchange ? form.tokenExchangeAudience : null});createNotification({text: "Successfully updated OAuth application",@@ -131,10 +202,9 @@ export const OauthClientModal = ({});} else {const { client, clientSecret } = await createOauthClient({- name,- description: description || undefined,- redirectUris: parsedRedirectUris,- requirePkce+ ...payload,+ description: form.description || undefined,+ tokenExchangeAudience: isTokenExchange ? form.tokenExchangeAudience : undefined});createNotification({text: "Successfully created OAuth application",@@ -155,96 +225,207 @@ export const OauthClientModal = ({};return (- <Dialog+ <Sheetopen={popUp?.clientForm?.isOpen}onOpenChange={(isOpen) => {handlePopUpToggle("clientForm", isOpen);if (!isOpen) reset();}}>- <DialogContent className="sm:max-w-lg">- <DialogHeader>- <DialogTitle>- {isEditing ? "Edit OAuth application" : "Add OAuth application"}- </DialogTitle>- <DialogDescription>- External platforms use this application to request delegated access to Infisical on a- user's behalf via OAuth 2.0, limited to that user's permissions.- </DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit(onFormSubmit)} className="flex flex-col gap-6">- <Controller- control={control}- name="name"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="oauth-client-name">Name</FieldLabel>- <Input- id="oauth-client-name"- placeholder="e.g. Coder"- isError={Boolean(error)}- {...field}- />- <FieldError>{error?.message}</FieldError>- </Field>- )}- />- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="oauth-client-description">Description (optional)</FieldLabel>- <Input- id="oauth-client-description"- placeholder="What this application is used for"- isError={Boolean(error)}- {...field}- />- <FieldError>{error?.message}</FieldError>- </Field>- )}- />- <Controller- control={control}- name="redirectUris"- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="oauth-client-redirect-uris">Redirect URIs</FieldLabel>- <TextArea- id="oauth-client-redirect-uris"- placeholder="https://coder.example.com/external-auth/infisical/callback"- rows={3}- {...field}- />- <FieldDescription>- One URI per line. The authorization flow only redirects to these exact URIs.- </FieldDescription>- <FieldError>{error?.message}</FieldError>- </Field>- )}- />- <Controller- control={control}- name="requirePkce"- render={({ field: { value, onChange } }) => (- <Field orientation="horizontal">- <FieldContent>- <FieldTitle>Require PKCE (S256)</FieldTitle>- <FieldDescription>- Reject authorization requests that do not include a PKCE code challenge.- </FieldDescription>- </FieldContent>- <Switch- id="oauth-client-require-pkce"- variant="org"- checked={value}- onCheckedChange={onChange}- />- </Field>- )}- />- <DialogFooter>+ <SheetContent className="sm:max-w-xl">+ <form onSubmit={handleSubmit(onFormSubmit)} className="flex h-full min-h-0 flex-col">+ <SheetHeader>+ <SheetTitle>+ {isEditing ? "Edit OAuth application" : "Add OAuth application"}+ </SheetTitle>+ <SheetDescription>+ External platforms use this application to request delegated access to Infisical on a+ user's behalf via OAuth 2.0, limited to that user's permissions.+ </SheetDescription>+ </SheetHeader>+ <div className="min-h-0 thin-scrollbar flex-1 overflow-y-auto p-4">+ <FieldGroup>+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="oauth-client-name">Name</FieldLabel>+ <Input+ id="oauth-client-name"+ placeholder="e.g. Coder"+ isError={Boolean(error)}+ {...field}+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="oauth-client-description">+ Description (optional)+ </FieldLabel>+ <Input+ id="oauth-client-description"+ placeholder="What this application is used for"+ isError={Boolean(error)}+ {...field}+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="flow"+ render={({ field: { value, onChange } }) => (+ <Field>+ <FieldLabel>Flow</FieldLabel>+ <Tabs value={value} onValueChange={onChange}>+ <TabsList variant="filled" className="w-full">+ <TabsTrigger value={OauthClientFlow.AuthorizationCode}>+ Authorization code+ </TabsTrigger>+ <TabsTrigger value={OauthClientFlow.TokenExchange}>+ Token exchange+ </TabsTrigger>+ </TabsList>+ </Tabs>+ <FieldDescription>{FLOW_DESCRIPTIONS[value]}</FieldDescription>+ </Field>+ )}+ />+ {flow === OauthClientFlow.TokenExchange && !isOidcConfigPending && (+ <Alert variant={hasActiveOidcSso ? "default" : "warning"}>+ {hasActiveOidcSso ? <Info /> : <AlertTriangle />}+ <AlertDescription className="text-xs">+ {hasActiveOidcSso ? (+ <p>+ User tokens are verified against the OIDC SSO issuer configured under{" "}+ <Link+ to="/organizations/$orgId/sso"+ params={{ orgId: currentOrg?.id ?? "" }}+ className="underline underline-offset-2 hover:text-foreground"+ >+ Organization Settings > SSO+ </Link>+ . Disabling OIDC SSO stops token exchange working.+ </p>+ ) : (+ <p>+ Token exchange verifies user tokens against your organization's OIDC+ SSO issuer. Set one up under{" "}+ <Link+ to="/organizations/$orgId/sso"+ params={{ orgId: currentOrg?.id ?? "" }}+ className="underline underline-offset-2 hover:text-foreground"+ >+ Organization Settings > SSO+ </Link>{" "}+ first.+ </p>+ )}+ </AlertDescription>+ </Alert>+ )}+ {flow === OauthClientFlow.AuthorizationCode && (+ <>+ <Controller+ control={control}+ name="redirectUris"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="oauth-client-redirect-uris">Redirect URIs</FieldLabel>+ <TextArea+ id="oauth-client-redirect-uris"+ placeholder="https://coder.example.com/external-auth/infisical/callback"+ rows={3}+ {...field}+ />+ <FieldDescription>+ One URI per line. The authorization flow only redirects to these exact+ URIs.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="requirePkce"+ render={({ field: { value, onChange } }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>Require PKCE (S256)</FieldTitle>+ <FieldDescription>+ Reject authorization requests that do not include a PKCE code challenge.+ </FieldDescription>+ </FieldContent>+ <Switch+ id="oauth-client-require-pkce"+ variant="org"+ checked={value}+ onCheckedChange={onChange}+ />+ </Field>+ )}+ />+ </>+ )}+ {flow === OauthClientFlow.TokenExchange && (+ <>+ <Controller+ control={control}+ name="tokenExchangeAudience"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="oauth-client-token-exchange-audience">+ Audience+ </FieldLabel>+ <Input+ id="oauth-client-token-exchange-audience"+ placeholder="e.g. api://paychex-mcp"+ isError={Boolean(error)}+ {...field}+ />+ <FieldDescription>+ The audience your identity provider puts in tokens it issues for this+ application.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="tokenExchangeIdpSatisfiesMfa"+ render={({ field: { value, onChange } }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>Identity provider enforces MFA</FieldTitle>+ <FieldDescription>+ Token exchange has no Infisical MFA challenge to run. Turn this on to+ declare that your identity provider already enforces MFA.+ </FieldDescription>+ </FieldContent>+ <Switch+ id="oauth-client-token-exchange-idp-mfa"+ variant="org"+ checked={value}+ onCheckedChange={onChange}+ />+ </Field>+ )}+ />+ </>+ )}+ </FieldGroup>+ </div>+ <SheetFooter className="justify-end border-t"><Button variant="ghost" type="button" onClick={() => handlePopUpClose("clientForm")}>Cancel</Button>@@ -256,9 +437,9 @@ export const OauthClientModal = ({>{isEditing ? "Save Changes" : "Create Application"}</Button>- </DialogFooter>+ </SheetFooter></form>- </DialogContent>- </Dialog>+ </SheetContent>+ </Sheet>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsxindex 6f87d3b6e9..ca0c3d0c67 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx@@ -56,6 +56,7 @@ import {useGetOauthClients,useRotateOauthClientSecret} from "@app/hooks/api";+import { OauthGrantType } from "@app/hooks/api/oauthClients/types";import { OauthClientModal } from "./OauthClientModal";import { OauthClientSecretModal } from "./OauthClientSecretModal";@@ -188,6 +189,7 @@ export const OrgOauthClientsTab = () => {<TableRow><TableHead>Name</TableHead><TableHead>Client ID</TableHead>+ <TableHead>Flow</TableHead><TableHead>PKCE</TableHead><TableHead>Created</TableHead><TableHead className="w-px text-right" aria-label="Actions" />@@ -198,88 +200,111 @@ export const OrgOauthClientsTab = () => {Array.from({ length: 3 }).map((_, idx) => (// eslint-disable-next-line react/no-array-index-key<TableRow key={`oauth-client-skeleton-${idx}`}>- <TableCell colSpan={5}>+ <TableCell colSpan={6}><Skeleton className="h-5 w-full" /></TableCell></TableRow>))}- {filteredClients.map((client) => (- <TableRow key={client.id}>- <TableCell className="font-medium text-foreground">{client.name}</TableCell>- <TableCell>- <div className="flex items-center gap-1">- <span className="font-mono text-xs">{client.clientId}</span>- <CopyButton value={client.clientId} ariaLabel="Copy client ID" />- </div>- </TableCell>- <TableCell>- {client.requirePkce ? (- <Badge variant="success">Required</Badge>- ) : (- <span className="text-muted">Optional</span>- )}- </TableCell>- <TableCell>{format(new Date(client.createdAt), "MMM d, yyyy")}</TableCell>- <TableCell className="text-right">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- variant="ghost"- size="xs"- aria-label={`Actions for ${client.name}`}- >- <MoreHorizontal />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-44">- <OrgPermissionCan- I={OrgPermissionActions.Edit}- a={OrgPermissionSubjects.OauthClients}- >- {(isAllowed) => (- <DropdownMenuItem- isDisabled={!isAllowed}- onClick={() => handlePopUpOpen("clientForm", client)}- >- <Pencil />- Edit- </DropdownMenuItem>- )}- </OrgPermissionCan>- <OrgPermissionCan- I={OrgPermissionActions.Edit}- a={OrgPermissionSubjects.OauthClients}- >- {(isAllowed) => (- <DropdownMenuItem- isDisabled={!isAllowed}- onClick={() => handlePopUpOpen("rotateSecret", client)}- >- <RefreshCw />- Rotate Secret- </DropdownMenuItem>- )}- </OrgPermissionCan>- <OrgPermissionCan- I={OrgPermissionActions.Delete}- a={OrgPermissionSubjects.OauthClients}- >- {(isAllowed) => (- <DropdownMenuItem- variant="danger"- isDisabled={!isAllowed}- onClick={() => handlePopUpOpen("deleteClient", client)}- >- <Trash2 />- Delete- </DropdownMenuItem>- )}- </OrgPermissionCan>- </DropdownMenuContent>- </DropdownMenu>- </TableCell>- </TableRow>- ))}+ {filteredClients.map((client) => {+ const usesAuthorizationCode = client.grantTypes.includes(+ OauthGrantType.AuthorizationCode+ );+ const usesTokenExchange = client.grantTypes.includes(+ OauthGrantType.TokenExchange+ );++ return (+ <TableRow key={client.id}>+ <TableCell className="font-medium text-foreground">+ {client.name}+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1">+ <span className="font-mono text-xs">{client.clientId}</span>+ <CopyButton value={client.clientId} ariaLabel="Copy client ID" />+ </div>+ </TableCell>+ <TableCell>+ <div className="flex flex-wrap gap-1">+ {usesAuthorizationCode && (+ <Badge variant="neutral">Authorization code</Badge>+ )}+ {usesTokenExchange && <Badge variant="info">Token exchange</Badge>}+ </div>+ </TableCell>+ <TableCell>+ {!usesAuthorizationCode && (+ <span className="text-muted">Not applicable</span>+ )}+ {usesAuthorizationCode && client.requirePkce && (+ <Badge variant="success">Required</Badge>+ )}+ {usesAuthorizationCode && !client.requirePkce && (+ <span className="text-muted">Optional</span>+ )}+ </TableCell>+ <TableCell>{format(new Date(client.createdAt), "MMM d, yyyy")}</TableCell>+ <TableCell className="text-right">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label={`Actions for ${client.name}`}+ >+ <MoreHorizontal />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <OrgPermissionCan+ I={OrgPermissionActions.Edit}+ a={OrgPermissionSubjects.OauthClients}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ isDisabled={!isAllowed}+ onClick={() => handlePopUpOpen("clientForm", client)}+ >+ <Pencil />+ Edit+ </DropdownMenuItem>+ )}+ </OrgPermissionCan>+ <OrgPermissionCan+ I={OrgPermissionActions.Edit}+ a={OrgPermissionSubjects.OauthClients}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ isDisabled={!isAllowed}+ onClick={() => handlePopUpOpen("rotateSecret", client)}+ >+ <RefreshCw />+ Rotate Secret+ </DropdownMenuItem>+ )}+ </OrgPermissionCan>+ <OrgPermissionCan+ I={OrgPermissionActions.Delete}+ a={OrgPermissionSubjects.OauthClients}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ variant="danger"+ isDisabled={!isAllowed}+ onClick={() => handlePopUpOpen("deleteClient", client)}+ >+ <Trash2 />+ Delete+ </DropdownMenuItem>+ )}+ </OrgPermissionCan>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}</TableBody></Table>)}diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsxindex 5db0978e92..81984730eb 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgOIDCSection.tsx@@ -1,3 +1,4 @@+import { Link } from "@tanstack/react-router";import { AlertTriangle, ArrowLeftRight, Info, MoreHorizontal, Pencil } from "lucide-react";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";@@ -7,6 +8,7 @@ import {Alert,AlertDescription,AlertTitle,+ Badge,Card,CardAction,CardContent,@@ -32,9 +34,11 @@ import {OrgPermissionActions,OrgPermissionSubjects,useOrganization,+ useOrgPermission,useSubscription} from "@app/context";-import { useGetOIDCConfig } from "@app/hooks/api";+import { useGetOauthClients, useGetOIDCConfig } from "@app/hooks/api";+import { OauthGrantType } from "@app/hooks/api/oauthClients/types";import { useUpdateOIDCConfig } from "@app/hooks/api/oidcConfig/mutations";import { usePopUp } from "@app/hooks/usePopUp";@@ -47,10 +51,20 @@ type Props = {export const OrgOIDCSection = ({ onSwitchProvider }: Props): JSX.Element => {const { currentOrg } = useOrganization();const { subscription } = useSubscription();+ const { permission } = useOrgPermission();const { data, isPending } = useGetOIDCConfig(currentOrg?.id ?? "");const { mutateAsync } = useUpdateOIDCConfig();+ const canReadApplications = permission.can(+ OrgPermissionActions.Read,+ OrgPermissionSubjects.OauthClients+ );+ const { data: tokenExchangeClients } = useGetOauthClients(+ canReadApplications ? (currentOrg?.id ?? "") : "",+ OauthGrantType.TokenExchange+ );+const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp(["addOIDC","upgradePlan"@@ -231,6 +245,37 @@ export const OrgOIDCSection = ({ onSwitchProvider }: Props): JSX.Element => {)}</OrgPermissionCan></Field>+ {Boolean(tokenExchangeClients?.length) && (+ <Alert variant="info">+ <Info />+ <AlertTitle>+ {tokenExchangeClients?.length === 1+ ? "1 application depends on this issuer"+ : `${tokenExchangeClients?.length} applications depend on this issuer`}+ </AlertTitle>+ <AlertDescription>+ <p>+ These applications use OAuth token exchange to act on behalf of your users, and+ verify the tokens they present against this issuer. Disabling OIDC SSO or+ changing the issuer stops them working.+ </p>+ <div className="mt-2 flex flex-wrap gap-1">+ {tokenExchangeClients?.map((client) => (+ <Badge key={client.id} variant="neutral">+ {client.name}+ </Badge>+ ))}+ </div>+ <Link+ to="/organizations/$orgId/oauth-applications"+ params={{ orgId: currentOrg?.id ?? "" }}+ className="mt-2 inline-block underline underline-offset-2 hover:text-foreground"+ >+ Manage OAuth applications+ </Link>+ </AlertDescription>+ </Alert>+ )}</FieldGroup></CardContent></Card>