Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

simplify oidc issuer code and comments

DimitrisStaratzis9517445bd803
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index f1a6e4e355..0e982c97e3 100644
--- a/backend/AGENTS.md
+++ b/backend/AGENTS.md
@@ -1150,21 +1150,19 @@ failure is logged, never thrown, so the original outcome stands.
`services/oidc-issuer` signs short-lived JWTs that cloud providers exchange for access tokens, so a
connection needs no stored client secret. Each org is its own issuer at
-`/api/v1/oidc-issuer/organizations/<orgId>`, with public discovery and JWKS routes under `.well-known`. The issuer
-URL and the `sub` shape are one-way doors: customers copy both into their provider.
+`/api/v1/oidc-issuer/organizations/<orgId>`, with public discovery and JWKS routes under `.well-known`.
+The issuer URL and each consumer's `sub` format are one-way doors: customers copy both into their provider.
- **Keys are reserved `sign-verify` `kms_keys` rows named `oidc-issuer-*`, not a new `keyUsage`.** The
- CMEK router validates `keyUsage` with `z.nativeEnum(KmsKeyUsage)`, so a new value would be creatable
- through the public API. Customers cannot create reserved keys, which is what makes the name prefix safe.
-- **Keys are created on the first sign, never on a JWKS fetch.** Those routes are unauthenticated, and
- existing orgs need no backfill. An empty JWKS is sent `no-store` so the first token is never checked
- against a cached empty set.
-- **The built JWKS is cached in Redis for 10 minutes**, because deriving it decrypts every key and the route
- is anonymous. A stale set is harmless for the reason below; empty sets are never cached, and a rotation
- clears the entry.
+ CMEK router accepts any `KmsKeyUsage`, so a new value would be creatable through the public API.
+ Customers cannot create reserved keys, which is what makes the name prefix safe.
+- **Keys are created on the first sign, never on a JWKS fetch**, so existing orgs need no backfill.
- **The second newest key signs.** The newest is published a full 24h period before it takes over, and
- rotation keeps at most three keys. It runs under a Redis lock rather than an advisory lock, so no
- database connection is held while RSA keys are generated, and it re-reads keys on the primary.
+ rotation keeps at most three keys. It runs under a Redis lock, so no database connection is held while
+ RSA keys are generated.
+- **The JWKS is cached in Redis for 10 minutes**, because building it decrypts every key on an anonymous
+ route. The 24h lead makes a stale set safe. Empty sets are never cached, in Redis or over HTTP, and a
+ rotation clears the entry.
### Enterprise (EE) Features
diff --git a/backend/src/server/routes/v1/oidc-issuer-router.ts b/backend/src/server/routes/v1/oidc-issuer-router.ts
index ea02c024a9..1c5d39be37 100644
--- a/backend/src/server/routes/v1/oidc-issuer-router.ts
+++ b/backend/src/server/routes/v1/oidc-issuer-router.ts
@@ -10,9 +10,8 @@ const OrgParamsSchema = z.object({
organizationId: z.string().uuid()
});
-// Unauthenticated, and shaped by OpenID Connect Discovery 1.0 and RFC 7517 rather than the house envelope,
-// because cloud providers fetch them to verify tokens Infisical signs. These paths are part of each org's issuer
-// URL, which customers paste into their providers, so they can never move or be renamed.
+// Public and shaped by OIDC Discovery and RFC 7517, not the house envelope. The paths are part of each org's
+// issuer URL, which customers paste into their providers, so they can never move.
export const registerOidcIssuerRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
diff --git a/backend/src/services/oidc-issuer/oidc-issuer-fns.ts b/backend/src/services/oidc-issuer/oidc-issuer-fns.ts
index 875bb337c2..6b727e46d1 100644
--- a/backend/src/services/oidc-issuer/oidc-issuer-fns.ts
+++ b/backend/src/services/oidc-issuer/oidc-issuer-fns.ts
@@ -10,16 +10,18 @@ const MAX_KEYS = 3;
type TIssuerKey = { id: string; createdAt: Date };
-// Keys are ordered oldest first: previous, current, next. The newest key is published a full signing period
-// before it takes over, so a provider that cached the JWKS already has it, and the previous key stays published
-// for a period after it stops signing.
+// Keys are oldest first: previous, current, next. The next key is published a full signing period before it
+// takes over, so a provider that cached the JWKS already has it.
export const getSigningKey = <T extends TIssuerKey>(keys: T[]): T | undefined => keys[keys.length - 2];
-export const getKeyRotationPlan = (keys: TIssuerKey[], now = new Date()) => {
- if (keys.length < 2) return { keysToCreate: 2 - keys.length, keyIdsToDelete: [] as string[] };
+export const getKeyRotationPlan = (
+ keys: TIssuerKey[],
+ now = new Date()
+): { keysToCreate: number; keyIdsToDelete: string[] } => {
+ if (keys.length < 2) return { keysToCreate: 2 - keys.length, keyIdsToDelete: [] };
if (now.getTime() - keys[keys.length - 1].createdAt.getTime() < KEY_SIGNING_PERIOD_MS) {
- return { keysToCreate: 0, keyIdsToDelete: [] as string[] };
+ return { keysToCreate: 0, keyIdsToDelete: [] };
}
return { keysToCreate: 1, keyIdsToDelete: keys.slice(0, keys.length + 1 - MAX_KEYS).map(({ id }) => id) };
diff --git a/backend/src/services/oidc-issuer/oidc-issuer-service.ts b/backend/src/services/oidc-issuer/oidc-issuer-service.ts
index 52076c9b5e..b8d4186121 100644
--- a/backend/src/services/oidc-issuer/oidc-issuer-service.ts
+++ b/backend/src/services/oidc-issuer/oidc-issuer-service.ts
@@ -1,6 +1,6 @@
import { Knex } from "knex";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory, TKeyStoreLock } from "@app/keystore/keystore";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";
@@ -46,8 +46,7 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
return `${SITE_URL}/api/v1/oidc-issuer/organizations/${orgId}`;
};
- // Issuer keys are reserved, so no customer can create one; the prefix only tells them apart from the
- // org's other reserved keys.
+ // Customers cannot create reserved keys, so the prefix only separates these from the org's other reserved keys
const $listKeys = async (orgId: string, tx?: Knex) => {
const keys = await kmsDAL.find(
{ orgId, projectId: null, isReserved: true, keyUsage: KmsKeyUsage.SIGN_VERIFY },
@@ -57,22 +56,19 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
return keys.filter(({ name }) => name.startsWith(OIDC_ISSUER_KEY_NAME_PREFIX));
};
- // A Redis lock rather than an advisory lock, so no database connection is held while RSA keys are generated.
+ // A Redis lock rather than an advisory lock, so no database connection is held while RSA keys are generated
const $rotateKeys = async (orgId: string, waitForLock: boolean) => {
- let lock: TKeyStoreLock;
- try {
- lock = await keyStore.acquireLock(
+ const lock = await keyStore
+ .acquireLock(
[KeyStorePrefixes.OidcIssuerKeyRotationLock(orgId)],
KEY_ROTATION_LOCK_TTL_MS,
waitForLock ? { retryCount: 20, retryDelay: 500 } : { retryCount: 0 }
- );
- } catch {
- return null;
- }
+ )
+ .catch(() => null);
+ if (!lock) return null;
try {
- // Read on the primary, which a transaction runs on: a lagging replica would hide a rotation that another
- // request just finished, and this one would rotate again
+ // A transaction reads the primary, so a rotation another request just finished is not missed on a replica
const keys = await kmsDAL.transaction((tx) => $listKeys(orgId, tx));
const { keysToCreate, keyIdsToDelete } = getKeyRotationPlan(keys);
@@ -96,11 +92,9 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
return keys.filter(({ id }) => !keyIdsToDelete.includes(id));
} finally {
- try {
- await lock.release();
- } catch (err) {
- logger.warn(err, `OIDC issuer key rotation lock release failed [orgId=${orgId}]`);
- }
+ await lock
+ .release()
+ .catch((err) => logger.warn(err, `OIDC issuer key rotation lock release failed [orgId=${orgId}]`));
}
};
@@ -108,8 +102,7 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
let keys = await $listKeys(orgId);
if (getKeyRotationPlan(keys).keysToCreate) {
- // A busy lock means another request is already rotating and the current key is still valid, so only an
- // org with no key to sign with waits for it
+ // Only an org with no signing key waits; otherwise another request is rotating and the current key still works
keys = (await $rotateKeys(orgId, !getSigningKey(keys))) ?? keys;
}
@@ -145,14 +138,8 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
exp: iat + TOKEN_TTL_SECONDS,
jti: crypto.nativeCrypto.randomUUID()
},
- sign: async (data) => {
- const { signature } = await sign({
- data,
- signingAlgorithm: SigningAlgorithm.RSASSA_PKCS1_V1_5_SHA_256,
- isDigest: false
- });
- return signature;
- }
+ sign: async (data) =>
+ (await sign({ data, signingAlgorithm: SigningAlgorithm.RSASSA_PKCS1_V1_5_SHA_256, isDigest: false })).signature
});
};
@@ -171,8 +158,8 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
};
};
- // Cached so an anonymous caller cannot make every request decrypt keys. A stale set is harmless, because a key
- // is published a full signing period before it signs and was already out of use when it is deleted.
+ // Cached so anonymous requests do not each decrypt every key. A stale set is safe: keys are published a period
+ // before they sign
const getJwks = async (orgId: string): Promise<TJwks> => {
const cacheKey = KeyStorePrefixes.OidcIssuerJwks(orgId);
const cached = await keyStore.getItem(cacheKey);
@@ -186,8 +173,7 @@ export const oidcIssuerServiceFactory = ({ kmsDAL, kmsService, keyStore }: TOidc
.getPublicKey({ kmsId: id })
.then(publicKeyToJwk)
.catch((err) => {
- // A rotation can delete the oldest key after it was listed. That key stopped signing a full
- // period ago, so it is dropped rather than failing the whole set.
+ // A concurrent rotation can delete the oldest key, which no longer signs
if (err instanceof NotFoundError) return null;
throw err;
})