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
cache discovery
Thiago Araujo da Silva6c6f6018aa88
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex a0f01ba98f..469f788040 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -205,6 +205,21 @@ alone would otherwise be enough to rotate an existing exchange application's secthe check on create/update a speed bump. Any future operation that establishes this trust or hands out acredential for it goes through `checkSsoConfigPermission` (`oauth-client-service.ts`) as well.+**Everything the exchange fetches from the identity provider is cached for 10 minutes, and nothing read+from our own database is.** Token exchange sits on the caller's hot path (a middleware typically exchanges+per request it serves), so the discovery document and the `JwksClient` are both cached per URL in+`oauth-token-exchange-fns.ts`; without that, the provider is a synchronous dependency of every Infisical+API call the middleware makes. Consequences to keep in mind when extending it:+- **Don't widen the cache to the resolved trust anchor.** The signature algorithm and the preferred issuer+ come from `oidc_configs`, and an admin editing either has to take effect on the next request.+- **Failed discovery fetches are evicted, not cached**, so a provider blip lasts as long as the blip+ rather than the TTL. Keep that property in anything similar; caching the failure turns a 5-second+ outage into 10 minutes of them.+- **Cache entries hold the in-flight promise**, so concurrent requests on a cold entry coalesce onto one+ fetch instead of stampeding the provider.+- Entries expiring also rebuilds the SSRF-pinned agent, which is what lets a legitimate DNS change at the+ provider be picked up at all.+**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.- **SERVICE_TOKEN** — service tokens (Bearer tokens starting with `st.` prefix). Deprecated — use identity access tokens instead.diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.tsindex 8c8381d627..1fca84c6de 100644--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.test.ts@@ -51,6 +51,15 @@ const nextJwksUri = () => {return `https://adfs.example.com/adfs/discovery/keys?case=${jwksUriCounter}`;};+// Same reason, for the discovery document cache: a case that wants its own mocked document needs its own+// URL, or it reads the previous case's cached one.+let discoveryCaseCounter = 0;+const nextIssuerBase = () => {+ discoveryCaseCounter += 1;+ return `${ISSUER}/case-${discoveryCaseCounter}`;+};+const nextDiscoveryUrl = () => `${nextIssuerBase()}/.well-known/openid-configuration`;+const buildOidcConfig = (overrides: Partial<TOidcConfigs> = {}): TOidcConfigs =>({id: "11111111-1111-1111-1111-111111111111",@@ -164,7 +173,7 @@ describe("resolveOidcTrustAnchor", () => {const oidcConfig = buildOidcConfig({configurationType: OIDCConfigurationType.DISCOVERY_URL,- discoveryURL: `${ISSUER}/.well-known/openid-configuration`,+ discoveryURL: nextDiscoveryUrl(),issuer: null,jwksUri: null});@@ -179,12 +188,13 @@ describe("resolveOidcTrustAnchor", () => {test("appends the well-known path when the discovery URL is an issuer base", async () => {safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });+ const issuerBase = nextIssuerBase();await resolveOidcTrustAnchor(- buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL: `${ISSUER}/` })+ buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL: `${issuerBase}/` }));- expect(safeGet).toHaveBeenCalledWith(`${ISSUER}/.well-known/openid-configuration`);+ expect(safeGet).toHaveBeenCalledWith(`${issuerBase}/.well-known/openid-configuration`);});test("prefers the stored issuer over the discovered one", async () => {@@ -193,7 +203,7 @@ describe("resolveOidcTrustAnchor", () => {const anchor = await resolveOidcTrustAnchor(buildOidcConfig({configurationType: OIDCConfigurationType.DISCOVERY_URL,- discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ discoveryURL: nextDiscoveryUrl()}));@@ -207,7 +217,7 @@ describe("resolveOidcTrustAnchor", () => {resolveOidcTrustAnchor(buildOidcConfig({configurationType: OIDCConfigurationType.DISCOVERY_URL,- discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ discoveryURL: nextDiscoveryUrl()}))).rejects.toThrow(/Could not reach your organization's identity provider/);@@ -220,7 +230,7 @@ describe("resolveOidcTrustAnchor", () => {resolveOidcTrustAnchor(buildOidcConfig({configurationType: OIDCConfigurationType.DISCOVERY_URL,- discoveryURL: `${ISSUER}/.well-known/openid-configuration`+ discoveryURL: nextDiscoveryUrl()}))).rejects.toThrow(/did not publish a 'jwks_uri'/);@@ -233,6 +243,66 @@ describe("resolveOidcTrustAnchor", () => {)).rejects.toThrow(/no discovery URL/);});++ // Token exchange runs on every request the middleware makes, so the discovery document must not be a+ // per-exchange round trip to the identity provider.+ test("fetches the discovery document once across repeated resolutions", async () => {+ safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });+ const discoveryURL = nextDiscoveryUrl();+ const build = () => buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL });++ const [first, second, third] = await Promise.all([+ resolveOidcTrustAnchor(build()),+ resolveOidcTrustAnchor(build()),+ resolveOidcTrustAnchor(build())+ ]);+ await resolveOidcTrustAnchor(build());++ // Concurrent cold-entry callers coalesce onto one fetch rather than each opening their own.+ expect(safeGet).toHaveBeenCalledTimes(1);+ expect(second).toEqual(first);+ expect(third).toEqual(first);+ });++ // Caching a failure would stretch a provider blip into a full TTL of failures.+ test("retries after a failed discovery fetch instead of caching the failure", async () => {+ const discoveryURL = nextDiscoveryUrl();+ const build = () => buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL });++ safeGet.mockRejectedValueOnce(new Error("ECONNREFUSED 10.0.0.5:443"));+ await expect(resolveOidcTrustAnchor(build())).rejects.toThrow(/Could not reach/);++ const discoveredJwksUri = nextJwksUri();+ safeGet.mockResolvedValue({ data: { jwks_uri: discoveredJwksUri, issuer: ISSUER } });++ await expect(resolveOidcTrustAnchor(build())).resolves.toMatchObject({ jwksUri: discoveredJwksUri });+ expect(safeGet).toHaveBeenCalledTimes(2);+ });++ // The algorithm and the preferred issuer come from the org's own configuration, so only the fetch is+ // cached: an admin editing either must not have to wait out the discovery TTL.+ test("does not cache configuration read from the organization's own record", async () => {+ safeGet.mockResolvedValue({ data: { jwks_uri: nextJwksUri(), issuer: ISSUER } });+ const discoveryURL = nextDiscoveryUrl();++ const before = await resolveOidcTrustAnchor(+ buildOidcConfig({ configurationType: OIDCConfigurationType.DISCOVERY_URL, discoveryURL })+ );+ expect(before.algorithm).toEqual(OIDCJWTSignatureAlgorithm.RS256);++ const after = await resolveOidcTrustAnchor(+ buildOidcConfig({+ configurationType: OIDCConfigurationType.DISCOVERY_URL,+ discoveryURL,+ jwtSignatureAlgorithm: OIDCJWTSignatureAlgorithm.RS512,+ issuer: "https://adfs.example.com/updated"+ })+ );++ expect(after.algorithm).toEqual(OIDCJWTSignatureAlgorithm.RS512);+ expect(after.issuer).toEqual("https://adfs.example.com/updated");+ expect(safeGet).toHaveBeenCalledTimes(1);+ });});describe("verifySubjectToken", () => {diff --git a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts b/backend/src/services/oauth-client/oauth-token-exchange-fns.tsindex a1ec083903..f67d72e531 100644--- a/backend/src/services/oauth-client/oauth-token-exchange-fns.ts+++ b/backend/src/services/oauth-client/oauth-token-exchange-fns.ts@@ -30,6 +30,42 @@ const buildDiscoveryDocumentUrl = (discoveryUrl: string) => {return url.toString();};+type TOidcDiscoveryMetadata = { jwks_uri?: string; issuer?: string };++// Fetching the discovery document is a network round trip, and token exchange runs on every request the+// middleware makes, so resolving it per exchange would put the identity provider in the path of every+// Infisical API call that middleware makes, and make a blip at the provider fail all of them.+//+// Only the fetch is cached, never the resolved trust anchor. The algorithm and the preferred issuer come+// from the org's own SSO configuration, so an admin changing either still takes effect on the next+// request.+//+// Keyed on the document URL rather than the org, so orgs on a shared provider share one entry, and an+// admin correcting the discovery URL moves to a different key instead of waiting out the TTL.+const DISCOVERY_METADATA_TTL_MS = 10 * 60 * 1000;+const MAX_CACHED_DISCOVERY_DOCUMENTS = 512;+const discoveryMetadataCache = new Map<string, { metadata: Promise<TOidcDiscoveryMetadata>; expiresAt: number }>();++const getDiscoveryMetadata = (documentUrl: string) => {+ const now = Date.now();+ const cached = discoveryMetadataCache.get(documentUrl);+ if (cached && cached.expiresAt > now) return cached.metadata;++ if (discoveryMetadataCache.size >= MAX_CACHED_DISCOVERY_DOCUMENTS) discoveryMetadataCache.clear();++ const metadata = safeRequest.get<TOidcDiscoveryMetadata>(documentUrl, { timeout: 10_000 }).then(({ data }) => data);++ discoveryMetadataCache.set(documentUrl, { metadata, expiresAt: now + DISCOVERY_METADATA_TTL_MS });++ metadata.catch(() => {+ if (discoveryMetadataCache.get(documentUrl)?.metadata === metadata) {+ discoveryMetadataCache.delete(documentUrl);+ }+ });++ return metadata;+};+// 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.//@@ -87,13 +123,9 @@ export const resolveOidcTrustAnchor = async (oidcConfig: TOidcConfigs): Promise<});}- let metadata: { jwks_uri?: string; issuer?: string };+ let metadata: TOidcDiscoveryMetadata;try {- const { data } = await safeRequest.get<{ jwks_uri?: string; issuer?: string }>(- buildDiscoveryDocumentUrl(oidcConfig.discoveryURL),- { timeout: 10_000 }- );- metadata = data;+ metadata = await getDiscoveryMetadata(buildDiscoveryDocumentUrl(oidcConfig.discoveryURL));} catch (error) {logger.error({ error, orgId: oidcConfig.orgId },diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsxindex b6cab9760e..ada84a1610 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx@@ -311,7 +311,7 @@ export const OauthClientModal = ({params={{ orgId: currentOrg?.id ?? "" }}className="underline underline-offset-2 hover:text-foreground">- Organization Settings > SSO+ Settings > SSO & Provisioning</Link>. Disabling OIDC SSO stops token exchange working.</p>@@ -324,7 +324,7 @@ export const OauthClientModal = ({params={{ orgId: currentOrg?.id ?? "" }}className="underline underline-offset-2 hover:text-foreground">- Organization Settings > SSO+ Settings > SSO & Provisioning</Link>{" "}first.</p>