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 custom ttl
Thiago Araujo da Silvae492d00cae86
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 41f39f9207..e8d4d05af1 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -272,8 +272,13 @@ narrows the exchange's trust: removing the grant, changing `tokenExchangeAudienc`tokenExchangeIdpSatisfiesMfa` off (`hasWithdrawnTokenExchangeTrust`). These are the same fields`hasClientAuthorityChanged` guards, and for the same reason, so a new field belongs in both. An adminnarrowing any of them is responding to a problem, so it has to reach the tokens already out there rather-than wait for them to expire. Widening does not revoke: turning the MFA declaration on grants more without-invalidating anything already issued. Sessions are tagged with+than wait for them to expire. The test is whether the field carries federation trust, not merely whether+it can be narrowed: `accessTokenTTL` is deliberately in neither, because it decides how long a new token+lasts rather than whose tokens are exchangeable or which MFA requirement may be skipped. Shortening it on+a live application is routine tuning, so revoking every user's session would be a surprising side effect,+and putting it in `hasClientAuthorityChanged` would fail in-flight exchanges on a harmless edit. An admin+who does want the issued tokens gone rotates the secret. Widening does not revoke: turning the MFA+declaration on grants more without invalidating anything already issued. Sessions are tagged with`getOauthClientSessionUserAgent(clientId)`, the only handle we have on them. Rotation revokes only onexchange applications: there the secret alone mints tokens for any user, whereas in the redirect flow ithas to be paired with an authorization code or refresh token and blanket revocation would just signdiff --git a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.tsindex c51b11ad27..c7e5908b74 100644--- a/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts+++ b/backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts@@ -362,6 +362,119 @@ describe("Full delegation marker on a delegated OAuth token", async () => {// A refresh token only works if the application holds the refresh_token grant, so issuing one without it// hands back a credential the token endpoint rejects on use.+describe("Access token TTL is per application", async () => {+ const REDIRECT_URI = "https://app.example.com/callback";++ const issueAccessToken = async (accessTokenTTL?: number) => {+ const created = await createClient({+ name: `e2e-access-token-ttl-${accessTokenTTL ?? "default"}`,+ grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],+ redirectUris: [REDIRECT_URI],+ ...(accessTokenTTL === undefined ? {} : { accessTokenTTL })+ });++ expect(created.statusCode).toBe(200);+ const { client, clientSecret } = JSON.parse(created.payload) as {+ client: { id: string; clientId: string; accessTokenTTL: number };+ clientSecret: string;+ };++ const consented = await consent({ client_id: client.clientId, redirect_uri: REDIRECT_URI });+ const { callbackUrl } = JSON.parse(consented.payload) as { callbackUrl: string };++ const token = await postToken({+ grant_type: OauthGrantType.AuthorizationCode,+ code: new URL(callbackUrl).searchParams.get("code") as string,+ redirect_uri: REDIRECT_URI,+ client_id: client.clientId,+ client_secret: clientSecret+ });++ return { client, token };+ };++ test("defaults to one day when the field is omitted", async () => {+ const { client, token } = await issueAccessToken();++ expect(client.accessTokenTTL).toBe(86400);+ expect(token.statusCode).toBe(200);+ expect((JSON.parse(token.payload) as { expires_in: number }).expires_in).toBe(86400);++ await deleteClient(client.id);+ });++ test("a shorter TTL becomes the issued token's expires_in", async () => {+ const { client, token } = await issueAccessToken(1800);++ expect(client.accessTokenTTL).toBe(1800);+ expect(token.statusCode).toBe(200);+ expect((JSON.parse(token.payload) as { expires_in: number }).expires_in).toBe(1800);++ await deleteClient(client.id);+ });++ // The application's TTL is a ceiling, not an override, so asking for longer than the instance+ // allows must not widen it past JWT_AUTH_LIFETIME.+ test("a TTL longer than the instance lifetime is capped, not honoured", async () => {+ const { client, token } = await issueAccessToken(90 * 24 * 60 * 60);++ expect(client.accessTokenTTL).toBe(90 * 24 * 60 * 60);+ expect(token.statusCode).toBe(200);+ const { expires_in: expiresIn } = JSON.parse(token.payload) as { expires_in: number };+ expect(expiresIn).toBeLessThan(client.accessTokenTTL);++ await deleteClient(client.id);+ });++ test("rejects a TTL outside the allowed bounds", async () => {+ const tooShort = await createClient({+ name: "e2e-access-token-ttl-too-short",+ redirectUris: [REDIRECT_URI],+ accessTokenTTL: 59+ });+ expect(tooShort.statusCode).toBe(422);++ const tooLong = await createClient({+ name: "e2e-access-token-ttl-too-long",+ redirectUris: [REDIRECT_URI],+ accessTokenTTL: 90 * 24 * 60 * 60 + 1+ });+ expect(tooLong.statusCode).toBe(422);+ });++ test("an update changes the TTL of tokens issued afterwards", async () => {+ const { client } = await issueAccessToken(3600);++ const updated = await testServer.inject({+ method: "PATCH",+ url: `/api/v1/oauth/clients/${client.id}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { accessTokenTTL: 600 }+ });+ expect(updated.statusCode).toBe(200);++ const consented = await consent({ client_id: client.clientId, redirect_uri: REDIRECT_URI });+ const { callbackUrl } = JSON.parse(consented.payload) as { callbackUrl: string };++ // The secret is unchanged by the update, so a fresh code redeems against the new TTL.+ const clientSecretRes = await rotateClientSecret(client.id);+ const { clientSecret } = JSON.parse(clientSecretRes.payload) as { clientSecret: string };++ const token = await postToken({+ grant_type: OauthGrantType.AuthorizationCode,+ code: new URL(callbackUrl).searchParams.get("code") as string,+ redirect_uri: REDIRECT_URI,+ client_id: client.clientId,+ client_secret: clientSecret+ });++ expect(token.statusCode).toBe(200);+ expect((JSON.parse(token.payload) as { expires_in: number }).expires_in).toBe(600);++ await deleteClient(client.id);+ });+});+describe("Refresh token issuance follows the registered grants", async () => {const REDIRECT_URI = "https://app.example.com/callback";diff --git a/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts b/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.tsindex 46c0103e42..0ad35d37c3 100644--- a/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts+++ b/backend/src/db/migrations/20260806120000_add-oauth-client-grant-types.ts@@ -5,6 +5,10 @@ import { TableName } from "@app/db/schemas";// Every client registered before this migration was created for the redirect flow.const REDIRECT_FLOW_GRANT_TYPES = "'{authorization_code,refresh_token}'::text[]";+// One day, in seconds. Deliberately shorter than JWT_AUTH_LIFETIME (10 days), which is what these+// tokens fell back to before the column existed.+const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 86400;+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");@@ -12,8 +16,9 @@ export async function up(knex: Knex): Promise<void> {TableName.OauthClient,"tokenExchangeIdpSatisfiesMfa");+ const hasAccessTokenTtl = await knex.schema.hasColumn(TableName.OauthClient, "accessTokenTTL");- if (hasGrantTypes && hasTokenExchangeAudience && hasTokenExchangeIdpSatisfiesMfa) return;+ if (hasGrantTypes && hasTokenExchangeAudience && hasTokenExchangeIdpSatisfiesMfa && hasAccessTokenTtl) return;await knex.schema.alterTable(TableName.OauthClient, (t) => {// The default is only here to backfill existing rows, and gets dropped below so an insert that@@ -33,6 +38,12 @@ export async function up(knex: Knex): Promise<void> {if (!hasTokenExchangeIdpSatisfiesMfa) {t.boolean("tokenExchangeIdpSatisfiesMfa").notNullable().defaultTo(false);}++ // How long the access tokens this application issues stay valid. Unlike grantTypes the default is+ // kept, because a create that omits it should get the product default rather than fail.+ if (!hasAccessTokenTtl) {+ t.integer("accessTokenTTL").notNullable().defaultTo(DEFAULT_ACCESS_TOKEN_TTL_SECONDS);+ }});if (!hasGrantTypes) {@@ -47,12 +58,14 @@ export async function down(knex: Knex): Promise<void> {TableName.OauthClient,"tokenExchangeIdpSatisfiesMfa");+ const hasAccessTokenTtl = await knex.schema.hasColumn(TableName.OauthClient, "accessTokenTTL");- if (!hasGrantTypes && !hasTokenExchangeAudience && !hasTokenExchangeIdpSatisfiesMfa) return;+ if (!hasGrantTypes && !hasTokenExchangeAudience && !hasTokenExchangeIdpSatisfiesMfa && !hasAccessTokenTtl) return;await knex.schema.alterTable(TableName.OauthClient, (t) => {if (hasGrantTypes) t.dropColumn("grantTypes");if (hasTokenExchangeAudience) t.dropColumn("tokenExchangeAudience");if (hasTokenExchangeIdpSatisfiesMfa) t.dropColumn("tokenExchangeIdpSatisfiesMfa");+ if (hasAccessTokenTtl) t.dropColumn("accessTokenTTL");});}diff --git a/backend/src/db/schemas/oauth-clients.ts b/backend/src/db/schemas/oauth-clients.tsindex 5a421a5dc7..474f5171bb 100644--- a/backend/src/db/schemas/oauth-clients.ts+++ b/backend/src/db/schemas/oauth-clients.ts@@ -21,7 +21,8 @@ export const OauthClientsSchema = z.object({updatedAt: z.date(),grantTypes: z.string().array(),tokenExchangeAudience: z.string().nullable().optional(),- tokenExchangeIdpSatisfiesMfa: z.boolean().default(false)+ tokenExchangeIdpSatisfiesMfa: z.boolean().default(false),+ accessTokenTTL: z.number().default(86400)});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 ade2a21bfd..068e98bbb4 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6750,6 +6750,7 @@ interface CreateOauthClientEvent {clientId: string;name: string;grantTypes: string[];+ accessTokenTTL: number;tokenExchangeAudience?: string | null;tokenExchangeIdpSatisfiesMfa: boolean;};@@ -6762,6 +6763,7 @@ interface UpdateOauthClientEvent {clientId: string;name: string;grantTypes: string[];+ accessTokenTTL: number;tokenExchangeAudience?: string | null;tokenExchangeIdpSatisfiesMfa: boolean;};diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.tsindex 4e6bbcb935..f9928c374f 100644--- a/backend/src/server/routes/v1/oauth-router.ts+++ b/backend/src/server/routes/v1/oauth-router.ts@@ -9,7 +9,10 @@ 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_ACCESS_TOKEN_TTL_SECONDS,DEFAULT_OAUTH_GRANT_TYPES,+ MAX_OAUTH_ACCESS_TOKEN_TTL_SECONDS,+ MIN_OAUTH_ACCESS_TOKEN_TTL_SECONDS,OauthGrantType,OauthTokenType} from "@app/services/oauth-client/oauth-client-types";@@ -43,6 +46,15 @@ const tokenExchangeAudienceSchema = z.max(255).describe("The expected 'aud' claim of subject tokens presented to the token exchange grant.");+const accessTokenTtlSchema = z+ .number()+ .int()+ .min(MIN_OAUTH_ACCESS_TOKEN_TTL_SECONDS)+ .max(MAX_OAUTH_ACCESS_TOKEN_TTL_SECONDS)+ .describe(+ "How long, in seconds, the access tokens this application issues stay valid. A ceiling rather than an override: the instance and organization token lifetimes still apply, so the issued token's 'expires_in' is the shortest of the three."+ );+const tokenExchangeIdpSatisfiesMfaSchema = z.boolean().describe(@@ -64,6 +76,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {grantTypes: grantTypesSchema.default([...DEFAULT_OAUTH_GRANT_TYPES]),redirectUris: redirectUriSchema.array().max(32).default([]),requirePkce: z.boolean().optional(),+ accessTokenTTL: accessTokenTtlSchema.default(DEFAULT_OAUTH_ACCESS_TOKEN_TTL_SECONDS),tokenExchangeAudience: tokenExchangeAudienceSchema.optional(),tokenExchangeIdpSatisfiesMfa: tokenExchangeIdpSatisfiesMfaSchema.optional()}),@@ -88,6 +101,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {clientId: client.clientId,name: client.name,grantTypes: client.grantTypes,+ accessTokenTTL: client.accessTokenTTL,tokenExchangeAudience: client.tokenExchangeAudience,tokenExchangeIdpSatisfiesMfa: client.tokenExchangeIdpSatisfiesMfa}@@ -160,6 +174,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {grantTypes: grantTypesSchema.optional(),redirectUris: redirectUriSchema.array().max(32).optional(),requirePkce: z.boolean().optional(),+ accessTokenTTL: accessTokenTtlSchema.optional(),tokenExchangeAudience: tokenExchangeAudienceSchema.nullable().optional(),tokenExchangeIdpSatisfiesMfa: tokenExchangeIdpSatisfiesMfaSchema.optional()}),@@ -186,6 +201,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {clientId: client.clientId,name: client.name,grantTypes: client.grantTypes,+ accessTokenTTL: client.accessTokenTTL,tokenExchangeAudience: client.tokenExchangeAudience,tokenExchangeIdpSatisfiesMfa: client.tokenExchangeIdpSatisfiesMfa}diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 8e0e4cdcb3..d7ea278033 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -35,6 +35,7 @@ import {PKCE_CODE_VERIFIER_REGEX} from "./oauth-client-fns";import {+ DEFAULT_OAUTH_ACCESS_TOKEN_TTL_SECONDS,OauthAuthorizationCodePayloadSchema,OauthDelegationMode,OauthGrantType,@@ -316,6 +317,7 @@ export const oauthClientServiceFactory = ({grantTypes,redirectUris,requirePkce: dto.requirePkce ?? false,+ accessTokenTTL: dto.accessTokenTTL ?? DEFAULT_OAUTH_ACCESS_TOKEN_TTL_SECONDS,tokenExchangeAudience: isTokenExchangeEnabled ? tokenExchangeAudience : null,tokenExchangeIdpSatisfiesMfa: isTokenExchangeEnabled ? tokenExchangeIdpSatisfiesMfa : false});@@ -383,6 +385,7 @@ export const oauthClientServiceFactory = ({grantTypes: dto.grantTypes ? grantTypes : undefined,redirectUris: isRedirectBased ? dto.redirectUris : [],requirePkce: isRedirectBased ? dto.requirePkce : false,+ accessTokenTTL: dto.accessTokenTTL,tokenExchangeAudience: nextTokenExchangeAudience,tokenExchangeIdpSatisfiesMfa: nextTokenExchangeIdpSatisfiesMfa},@@ -582,20 +585,25 @@ export const oauthClientServiceFactory = ({return client;};- const resolveTokenLifetimes = (org?: TOrganizations) => {+ // The application's own TTL is a ceiling on its access tokens, not an override: the instance's+ // JWT_AUTH_LIFETIME and the org's session length still apply, so an application cannot hand out a+ // token that outlives the org's own policy. Refresh tokens keep following the org alone, since they+ // exist to outlive individual access tokens.+ const resolveTokenLifetimes = (client: Pick<TOauthClients, "accessTokenTTL">, org?: TOrganizations) => {const appCfg = getConfig();- let accessTokenExpiresIn: string | number = appCfg.JWT_AUTH_LIFETIME;+ let accessTokenExpiresIn: string | number = getMinExpiresIn(appCfg.JWT_AUTH_LIFETIME, client.accessTokenTTL);let refreshTokenExpiresIn: string | number = appCfg.JWT_REFRESH_LIFETIME;if (org?.userTokenExpiration) {- accessTokenExpiresIn = getMinExpiresIn(appCfg.JWT_AUTH_LIFETIME, org.userTokenExpiration);+ accessTokenExpiresIn = getMinExpiresIn(accessTokenExpiresIn, org.userTokenExpiration);refreshTokenExpiresIn = org.userTokenExpiration;}return { accessTokenExpiresIn, refreshTokenExpiresIn };};- const getTokenLifetimes = async (orgId: string) => resolveTokenLifetimes(await orgDAL.findById(orgId));+ const getTokenLifetimes = async (client: Pick<TOauthClients, "accessTokenTTL">, orgId: string) =>+ resolveTokenLifetimes(client, await orgDAL.findById(orgId));// RFC 8693 token exchange is the SSO login path with the token handed to us directly instead of// collected through a browser redirect. With no redirect URI, no PKCE and no browser session to anchor@@ -717,7 +725,7 @@ export const oauthClientServiceFactory = ({});}- const { accessTokenExpiresIn } = resolveTokenLifetimes(org);+ const { accessTokenExpiresIn } = resolveTokenLifetimes(client, org);const accessToken = signOauthToken({@@ -813,7 +821,7 @@ export const oauthClientServiceFactory = ({const tokenSession = await tokenService.getUserTokenSessionById(codePayload.tokenVersionId, codePayload.userId);if (!tokenSession) throw new UnauthorizedError({ message: "User session not found" });- const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(codePayload.orgId);+ const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(client, codePayload.orgId);const grantedScopes = codePayload.scopes ?? [];@@ -871,7 +879,10 @@ export const oauthClientServiceFactory = ({throw new UnauthorizedError({ message: "Invalid refresh token" });}- const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(decodedToken.organizationId);+ const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(+ client,+ decodedToken.organizationId+ );let { refreshToken } = dto;let { refreshVersion } = tokenVersion;diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.tsindex 36fc71ae34..02c13ae2e3 100644--- a/backend/src/services/oauth-client/oauth-client-types.ts+++ b/backend/src/services/oauth-client/oauth-client-types.ts@@ -35,12 +35,17 @@ export enum OauthDelegationMode {Full = "full"}+export const DEFAULT_OAUTH_ACCESS_TOKEN_TTL_SECONDS = 86400;+export const MIN_OAUTH_ACCESS_TOKEN_TTL_SECONDS = 60;+export const MAX_OAUTH_ACCESS_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;+export type TCreateOauthClientDTO = {name: string;description?: string;grantTypes: OauthGrantType[];redirectUris: string[];requirePkce?: boolean;+ accessTokenTTL?: number;tokenExchangeAudience?: string;tokenExchangeIdpSatisfiesMfa?: boolean;};@@ -52,6 +57,7 @@ export type TUpdateOauthClientDTO = {grantTypes?: OauthGrantType[];redirectUris?: string[];requirePkce?: boolean;+ accessTokenTTL?: number;tokenExchangeAudience?: string | null;tokenExchangeIdpSatisfiesMfa?: boolean;};diff --git a/docs/documentation/platform/oauth-applications/authorization-code.mdx b/docs/documentation/platform/oauth-applications/authorization-code.mdxindex 09e0f1c35c..d44dc1c8c2 100644--- a/docs/documentation/platform/oauth-applications/authorization-code.mdx+++ b/docs/documentation/platform/oauth-applications/authorization-code.mdx@@ -132,13 +132,13 @@ The response contains:{"access_token": "...","token_type": "Bearer",- "expires_in": 3600,+ "expires_in": 86400,"refresh_token": "...","scope": "secrets:read"}```-Access token lifetime follows your organization's user token expiration setting (falling back to the platform default). Refresh tokens rotate on use, and a refresh never broadens the scopes originally granted.+Access token lifetime is the shortest of the application's **access token lifetime** (1 day by default), your organization's session length, and the instance default of 10 days. Refresh tokens follow the organization's session length rather than the application's lifetime, so shortening the lifetime shortens how long each access token lasts, not how long the client can keep refreshing. Refresh tokens rotate on use, and a refresh never broadens the scopes originally granted.`refresh_token` is present only when the application holds the `refresh_token` grant, which applications created in the UI always do. If you registered one through the API with `grantTypes` limited to `authorization_code`, the field is omitted and the client should exchange a new authorization code when the access token expires.diff --git a/docs/documentation/platform/oauth-applications/token-exchange.mdx b/docs/documentation/platform/oauth-applications/token-exchange.mdxindex 34ab4648fd..fce2397cca 100644--- a/docs/documentation/platform/oauth-applications/token-exchange.mdx+++ b/docs/documentation/platform/oauth-applications/token-exchange.mdx@@ -95,6 +95,7 @@ You need permission to manage both OAuth applications and SSO, because enabling- **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.+ - **Access token lifetime**: How long the tokens this application issues stay valid, 1 day by default. These tokens act as the user and carry no refresh token, so keep it to the shortest window your middleware can re-exchange within.There is no issuer to set here. Infisical always verifies against your organization's OIDC SSO provider, which cannot be overridden per application.@@ -142,11 +143,11 @@ The response is an access token for the user the subject token identified:"access_token": "...","issued_token_type": "urn:ietf:params:oauth:token-type:access_token","token_type": "Bearer",- "expires_in": 3600+ "expires_in": 86400}```-Access token lifetime is the shorter of your organization's **user token expiration** setting and the platform default of 10 days. Because the middleware holds a credential that acts as the user, set a short expiration on the organization rather than relying on that default.+Access token lifetime is the shortest of the application's **access token lifetime** (1 day by default), your organization's session length, and the instance default of 10 days. The application's own value is a ceiling rather than an override: it can shorten the lifetime but never extend it past what the organization allows. Because the middleware holds a credential that acts as the user, shorten it on the application rather than relying on the 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.@@ -176,7 +177,7 @@ Exchanging per request makes your identity provider a hard dependency of every I- Drop the entry when the user's session at your identity provider ends, so their Infisical access does not outlive it.<Note>- The token endpoint is rate limited per source IP, so every instance of your middleware behind one egress address shares a single budget. Caching correctly means roughly one exchange per user per token lifetime, which stays well inside it.+ Cache wherever you run Infisical. On Infisical Cloud the token endpoint is rate limited per source IP, so every instance of your middleware behind one egress address shares a single budget, and caching correctly means roughly one exchange per user per token lifetime, which stays well inside it. A self-hosted instance applies no limit of its own, so set one at your ingress and rely on caching to keep the endpoint quiet.</Note>## What Infisical verifiesdiff --git a/frontend/src/hooks/api/oauthClients/types.ts b/frontend/src/hooks/api/oauthClients/types.tsindex 8313c16170..3be56ba184 100644--- a/frontend/src/hooks/api/oauthClients/types.ts+++ b/frontend/src/hooks/api/oauthClients/types.ts@@ -14,6 +14,7 @@ export type TOauthClient = {grantTypes: OauthGrantType[];redirectUris: string[];requirePkce: boolean;+ accessTokenTTL: number;tokenExchangeAudience?: string | null;tokenExchangeIdpSatisfiesMfa: boolean;createdAt: string;@@ -26,6 +27,7 @@ export type TCreateOauthClientDTO = {grantTypes: OauthGrantType[];redirectUris: string[];requirePkce?: boolean;+ accessTokenTTL?: number;tokenExchangeAudience?: string;tokenExchangeIdpSatisfiesMfa?: boolean;};@@ -37,6 +39,7 @@ export type TUpdateOauthClientDTO = {grantTypes?: OauthGrantType[];redirectUris?: string[];requirePkce?: boolean;+ accessTokenTTL?: number;tokenExchangeAudience?: string | null;tokenExchangeIdpSatisfiesMfa?: boolean;};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsxindex 4396bec5a6..baf373e601 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx@@ -18,6 +18,11 @@ import {FieldLabel,FieldTitle,Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,Sheet,SheetContent,SheetDescription,@@ -61,6 +66,32 @@ const splitRedirectUris = (value: string) =>.map((uri) => uri.trim()).filter(Boolean);+// Mirrors the bounds the API enforces on accessTokenTTL, so a bad value is caught before the request.+const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 86400;+const MIN_ACCESS_TOKEN_TTL_SECONDS = 60;+const MAX_ACCESS_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;++const TTL_UNITS = [+ { value: "m", label: "Minutes", seconds: 60 },+ { value: "h", label: "Hours", seconds: 60 * 60 },+ { value: "d", label: "Days", seconds: 24 * 60 * 60 },+ { value: "w", label: "Weeks", seconds: 7 * 24 * 60 * 60 }+] as const;++type TTtlUnit = (typeof TTL_UNITS)[number]["value"];++const ttlToSeconds = (value: number, unit: TTtlUnit) =>+ value * (TTL_UNITS.find((entry) => entry.value === unit)?.seconds ?? 1);++// Pick the largest unit that divides the stored seconds exactly, so a one-day TTL reads back as+// "1 Days" rather than "1440 Minutes".+const secondsToTtl = (totalSeconds: number): { value: number; unit: TTtlUnit } => {+ const unit = [...TTL_UNITS].reverse().find((entry) => totalSeconds % entry.seconds === 0);+ if (!unit) return { value: totalSeconds, unit: "m" };++ return { value: totalSeconds / unit.seconds, unit: unit.value };+};+// The API lets a client hold several grants, but the UI sticks to one flow per application: the two// share no config and delegate differently, so an application needing both goes through the API.enum OauthClientFlow {@@ -75,6 +106,10 @@ const oauthClientFormSchema = zflow: z.nativeEnum(OauthClientFlow),redirectUris: z.string().trim(),requirePkce: z.boolean(),+ accessTokenTtlValue: z.number().int().min(1, "Value must be at least 1"),+ accessTokenTtlUnit: z.enum(["m", "h", "d", "w"], {+ invalid_type_error: "Please select a valid time unit"+ }),tokenExchangeAudience: z.string().trim().max(255),tokenExchangeIdpSatisfiesMfa: z.boolean()})@@ -100,6 +135,15 @@ const oauthClientFormSchema = z}}+ const ttlSeconds = ttlToSeconds(data.accessTokenTtlValue, data.accessTokenTtlUnit);+ if (ttlSeconds < MIN_ACCESS_TOKEN_TTL_SECONDS || ttlSeconds > MAX_ACCESS_TOKEN_TTL_SECONDS) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["accessTokenTtlValue"],+ message: "Access token lifetime must be between 1 minute and 90 days"+ });+ }+if (data.flow === OauthClientFlow.TokenExchange && !data.tokenExchangeAudience) {ctx.addIssue({code: z.ZodIssueCode.custom,@@ -143,6 +187,8 @@ export const OauthClientModal = ({ popUp, handlePopUpClose, onCreated }: Props)flow: OauthClientFlow.AuthorizationCode,redirectUris: "",requirePkce: false,+ accessTokenTtlValue: secondsToTtl(DEFAULT_ACCESS_TOKEN_TTL_SECONDS).value,+ accessTokenTtlUnit: secondsToTtl(DEFAULT_ACCESS_TOKEN_TTL_SECONDS).unit,tokenExchangeAudience: "",tokenExchangeIdpSatisfiesMfa: false}@@ -165,6 +211,10 @@ export const OauthClientModal = ({ popUp, handlePopUpClose, onCreated }: Props): OauthClientFlow.AuthorizationCode,redirectUris: client?.redirectUris?.join("\n") ?? "",requirePkce: client?.requirePkce ?? false,+ accessTokenTtlValue: secondsToTtl(client?.accessTokenTTL ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS)+ .value,+ accessTokenTtlUnit: secondsToTtl(client?.accessTokenTTL ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS)+ .unit,tokenExchangeAudience: client?.tokenExchangeAudience ?? "",tokenExchangeIdpSatisfiesMfa: client?.tokenExchangeIdpSatisfiesMfa ?? false});@@ -184,6 +234,7 @@ export const OauthClientModal = ({ popUp, handlePopUpClose, onCreated }: Props): [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],redirectUris: isTokenExchange ? [] : splitRedirectUris(form.redirectUris),requirePkce: isTokenExchange ? false : form.requirePkce,+ accessTokenTTL: ttlToSeconds(form.accessTokenTtlValue, form.accessTokenTtlUnit),tokenExchangeIdpSatisfiesMfa: isTokenExchange ? form.tokenExchangeIdpSatisfiesMfa : false};@@ -279,6 +330,64 @@ export const OauthClientModal = ({ popUp, handlePopUpClose, onCreated }: Props)</Field>)}/>+ <Field>+ <div className="flex gap-4">+ <Controller+ control={control}+ name="accessTokenTtlValue"+ render={({ field, fieldState: { error } }) => (+ <Field className="flex-1">+ <FieldLabel htmlFor="oauth-client-access-token-ttl-value">+ Access token lifetime+ </FieldLabel>+ <Input+ {...field}+ id="oauth-client-access-token-ttl-value"+ type="number"+ min={1}+ step={1}+ value={field.value}+ onChange={(e) => field.onChange(parseInt(e.target.value, 10))}+ isError={Boolean(error)}+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="accessTokenTtlUnit"+ render={({ field, fieldState: { error } }) => (+ <Field className="flex-1">+ <FieldLabel htmlFor="oauth-client-access-token-ttl-unit">+ Time unit+ </FieldLabel>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger+ id="oauth-client-access-token-ttl-unit"+ className="w-full"+ isError={Boolean(error)}+ >+ <SelectValue placeholder="Select time unit" />+ </SelectTrigger>+ <SelectContent position="popper">+ {TTL_UNITS.map(({ value, label }) => (+ <SelectItem key={value} value={value}>+ {label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ </div>+ <FieldDescription>+ How long tokens issued to this application stay valid. Your organization's+ session length still applies, so the shorter of the two wins.+ </FieldDescription>+ </Field><Controllercontrol={control}name="flow"