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
fix racing condition
Thiago Araujo da Silva459a019db298
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 36eb62a0c1..c3b785cbef 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -224,6 +224,20 @@ authorization code or refresh token and blanket revocation would just sign everyper client, not per grant, so a client holding both grants loses its redirect-flow tokens too — the safedirection, and only reachable via the API.+**That sweep only reaps sessions that already exist, so the exchange rechecks the client after creating+its own.** `exchangeSubjectToken` authenticates the client, then spends provider discovery, JWKS+verification and several DB reads before inserting a session — long enough for a revocation to land in+between and delete nothing. So after the session exists it re-reads the client via+`oauthClientDAL.findByIdOnPrimary` and rejects (re-running the sweep) if the secret hash changed, the+grant is gone, or the row is. Two things make that sufficient and are load-bearing: each withdrawal path+commits its write to the client *before* deleting the sessions, so a session that survived the delete+belongs to a request whose client row is already stale; and the re-read is on the **primary**, because the+replica that `authenticateClient` reads can still be serving the pre-revocation row. Only the exchange+grant needs this — the authorization code and refresh branches read an existing session instead of+creating one, so a racing revoke either fails them closed or kills the session behind the token they just+signed. Any future non-interactive path that mints a user token after authenticating a client needs the+same recheck.+**Everything the exchange fetches from the identity provider is cached for 10 minutes, and nothing readfrom our own database is.** Token exchange sits on the caller's hot path (a middleware typically exchangesper request it serves), so the discovery document and the `JwksClient` are both cached per URL indiff --git a/backend/src/services/oauth-client/oauth-client-dal.ts b/backend/src/services/oauth-client/oauth-client-dal.tsindex f4c18c8df5..b2f2288a8e 100644--- a/backend/src/services/oauth-client/oauth-client-dal.ts+++ b/backend/src/services/oauth-client/oauth-client-dal.ts@@ -1,5 +1,6 @@import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";export type TOauthClientDALFactory = ReturnType<typeof oauthClientDALFactory>;@@ -7,5 +8,13 @@ export type TOauthClientDALFactory = ReturnType<typeof oauthClientDALFactory>;export const oauthClientDALFactory = (db: TDbClient) => {const oauthClientOrm = ormify(db, TableName.OauthClient);- return oauthClientOrm;+ const findByIdOnPrimary = async (id: string) => {+ try {+ return await db(TableName.OauthClient).where({ id }).first();+ } catch (error) {+ throw new DatabaseError({ error, name: "FindOauthClientByIdOnPrimary" });+ }+ };++ return { ...oauthClientOrm, findByIdOnPrimary };};diff --git a/backend/src/services/oauth-client/oauth-client-fns.test.ts b/backend/src/services/oauth-client/oauth-client-fns.test.tsindex 9a66283ff2..cfa4e0aacf 100644--- a/backend/src/services/oauth-client/oauth-client-fns.test.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.test.ts@@ -3,6 +3,7 @@ import crypto from "node:crypto";import {assertValidOauthClientGrantConfig,computePkceChallenge,+ hasClientAuthorityChanged,isAllowedRedirectUri,isRegisteredRedirectUri,parseBasicAuthHeader@@ -122,6 +123,51 @@ describe("isRegisteredRedirectUri", () => {});});+describe("hasClientAuthorityChanged", () => {+ const authenticated = {+ clientSecretHash: "$2b$10$oldhasholdhasholdhashol",+ grantTypes: [OauthGrantType.TokenExchange]+ };++ test("reports no change when the client is untouched", () => {+ expect(hasClientAuthorityChanged(authenticated, { ...authenticated }, OauthGrantType.TokenExchange)).toBe(false);+ });++ test("reports a change when the client secret was rotated", () => {+ expect(+ hasClientAuthorityChanged(+ authenticated,+ { ...authenticated, clientSecretHash: "$2b$10$newhashnewhashnewhashne" },+ OauthGrantType.TokenExchange+ )+ ).toBe(true);+ });++ test("reports a change when the grant was withdrawn", () => {+ expect(+ hasClientAuthorityChanged(+ authenticated,+ { ...authenticated, grantTypes: [OauthGrantType.AuthorizationCode] },+ OauthGrantType.TokenExchange+ )+ ).toBe(true);+ });++ test("reports a change when the client was deleted", () => {+ expect(hasClientAuthorityChanged(authenticated, undefined, OauthGrantType.TokenExchange)).toBe(true);+ });++ test("reports no change when an unrelated grant was added", () => {+ expect(+ hasClientAuthorityChanged(+ authenticated,+ { ...authenticated, grantTypes: [OauthGrantType.TokenExchange, OauthGrantType.AuthorizationCode] },+ OauthGrantType.TokenExchange+ )+ ).toBe(false);+ });+});+describe("assertValidOauthClientGrantConfig", () => {const redirectFlow = {grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],diff --git a/backend/src/services/oauth-client/oauth-client-fns.ts b/backend/src/services/oauth-client/oauth-client-fns.tsindex 3fba9f6a58..21465e9675 100644--- a/backend/src/services/oauth-client/oauth-client-fns.ts+++ b/backend/src/services/oauth-client/oauth-client-fns.ts@@ -1,5 +1,6 @@import crypto from "node:crypto";+import { TOauthClients } from "@app/db/schemas";import { BadRequestError } from "@app/lib/errors";import { OauthGrantType } from "./oauth-client-types";@@ -70,6 +71,18 @@ export const isAllowedRedirectUri = (uri: string) => {// so the format must stay in sync between session creation and revocation.export const getOauthClientSessionUserAgent = (clientId: string) => `Infisical OAuth - ${clientId}`;+// Whether the client an exchange authenticated against has since lost the authority it was granted:+// deleted, secret rotated, or the grant withdrawn. Comparing the stored hashes is enough, because a+// rotation writes a fresh bcrypt hash with a new salt, so no second compareHash is needed.+export const hasClientAuthorityChanged = (+ authenticated: Pick<TOauthClients, "clientSecretHash" | "grantTypes">,+ current: Pick<TOauthClients, "clientSecretHash" | "grantTypes"> | undefined,+ grantType: OauthGrantType+) =>+ !current ||+ current.clientSecretHash !== authenticated.clientSecretHash ||+ !current.grantTypes.includes(grantType);+export const isRegisteredRedirectUri = (registeredUris: string[], redirectUri: string) =>registeredUris.some((uri) => {if (uri === redirectUri) return true;diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex e7c6a25ea9..4fcc4b525a 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -29,6 +29,7 @@ import {assertValidOauthClientGrantConfig,computePkceChallenge,getOauthClientSessionUserAgent,+ hasClientAuthorityChanged,isRegisteredRedirectUri,PKCE_CODE_VERIFIER_REGEX} from "./oauth-client-fns";@@ -687,6 +688,15 @@ export const oauthClientServiceFactory = ({});if (!tokenSession) throw new BadRequestError({ message: "Failed to create user token session" });+ const currentClient = await oauthClientDAL.findByIdOnPrimary(client.id);+ if (hasClientAuthorityChanged(client, currentClient, OauthGrantType.TokenExchange)) {+ await tokenService.revokeSessionsByUserAgent(getOauthClientSessionUserAgent(client.clientId));+ throw new UnauthorizedError({+ message:+ "This application's credentials or configuration changed while the token was being issued. Retry with the application's current client secret."+ });+ }+const { accessTokenExpiresIn } = resolveTokenLifetimes(org);const accessToken = signOauthToken(