Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(auth): support JWKS key rotation (#21431)

YuTengjing87d91f405f7d
diff --git a/packages/trpc/src/utils/__tests__/internalJwt.test.ts b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
index bfcb5ef08da..1601997356d 100644
--- a/packages/trpc/src/utils/__tests__/internalJwt.test.ts
+++ b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
@@ -60,10 +60,12 @@ const buildSignJWTChain = () => {
};
const SignJWTMock = vi.fn();
+const createLocalJWKSetMock = vi.fn().mockReturnValue('mock-key-set');
const importJWKMock = vi.fn().mockResolvedValue('mock-crypto-key');
vi.mock('jose', () => ({
SignJWT: SignJWTMock,
+ createLocalJWKSet: (...args: unknown[]) => createLocalJWKSetMock(...args),
importJWK: (...args: unknown[]) => importJWKMock(...args),
jwtVerify: vi.fn(),
}));
diff --git a/packages/trpc/src/utils/internalJwt.rotation.test.ts b/packages/trpc/src/utils/internalJwt.rotation.test.ts
new file mode 100644
index 00000000000..436b891a547
--- /dev/null
+++ b/packages/trpc/src/utils/internalJwt.rotation.test.ts
@@ -0,0 +1,122 @@
+import { generateKeyPairSync } from 'node:crypto';
+
+import { calculateJwkThumbprint, decodeProtectedHeader, SignJWT } from 'jose';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+const { authEnvMock } = vi.hoisted(() => ({
+ authEnvMock: {
+ INTERNAL_JWT_EXPIRATION: '30s',
+ JWKS_KEY: '',
+ },
+}));
+
+vi.mock('@/envs/auth', () => ({ authEnv: authEnvMock }));
+
+const createRsaKey = (kid: string) => {
+ const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
+
+ return {
+ kid,
+ privateJwk: {
+ ...privateKey.export({ format: 'jwk' }),
+ alg: 'RS256',
+ kid,
+ use: 'sig',
+ },
+ privateKey,
+ publicJwk: {
+ ...publicKey.export({ format: 'jwk' }),
+ alg: 'RS256',
+ kid,
+ use: 'sig',
+ },
+ };
+};
+
+describe('internal JWT key rotation', () => {
+ const keys = {
+ new: createRsaKey('new-key'),
+ old: createRsaKey('old-key'),
+ };
+
+ beforeAll(() => {
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+ });
+
+ const signToken = (key: (typeof keys)[keyof typeof keys], kid: string | null = key.kid) =>
+ new SignJWT({ purpose: 'lobe-internal-call' })
+ .setProtectedHeader(kid === null ? { alg: 'RS256' } : { alg: 'RS256', kid })
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(key.privateKey);
+
+ const signHeteroToken = (key: (typeof keys)[keyof typeof keys], kid: string | null = key.kid) =>
+ new SignJWT({
+ capabilities: ['hetero:finish'],
+ operation_id: 'operation-1',
+ purpose: 'hetero-operation',
+ })
+ .setProtectedHeader(kid === null ? { alg: 'RS256' } : { alg: 'RS256', kid })
+ .setIssuer('urn:lobehub:internal')
+ .setAudience('urn:lobehub:hetero-operation')
+ .setSubject('user-1')
+ .setJti('jwt-1')
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(key.privateKey);
+
+ it.each(['old', 'new'] as const)('verifies a token signed with the %s key', async (name) => {
+ const { validateInternalJWT } = await import('./internalJwt');
+
+ await expect(validateInternalJWT(await signToken(keys[name]))).resolves.toBe(true);
+ });
+
+ it.each(['old', 'new'] as const)(
+ 'verifies a hetero operation token signed with the %s key',
+ async (name) => {
+ const { validateHeteroOperationJWT } = await import('./internalJwt');
+
+ await expect(
+ validateHeteroOperationJWT(await signHeteroToken(keys[name])),
+ ).resolves.toMatchObject({
+ operation_id: 'operation-1',
+ sub: 'user-1',
+ });
+ },
+ );
+
+ it('uses the first RS256 private key for signing', async () => {
+ const { signInternalJWT } = await import('./internalJwt');
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+ expect(decodeProtectedHeader(await signInternalJWT()).kid).toBe('old-key');
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.new.privateJwk, keys.old.privateJwk] });
+ expect(decodeProtectedHeader(await signInternalJWT()).kid).toBe('new-key');
+ });
+
+ it('derives a stable kid for a legacy key that omits one', async () => {
+ const { signInternalJWT, validateInternalJWT } = await import('./internalJwt');
+ const { kid: _kid, ...legacyPrivateJwk } = keys.old.privateJwk;
+ const expectedKid = await calculateJwkThumbprint(legacyPrivateJwk);
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [legacyPrivateJwk] });
+ const token = await signInternalJWT();
+
+ expect(decodeProtectedHeader(token).kid).toBe(expectedKid);
+ await expect(validateInternalJWT(token)).resolves.toBe(true);
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+ });
+
+ it('verifies in-flight tokens without kid after a second key is added', async () => {
+ const { validateHeteroOperationJWT, validateInternalJWT } = await import('./internalJwt');
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+
+ await expect(validateInternalJWT(await signToken(keys.old, null))).resolves.toBe(true);
+ await expect(
+ validateHeteroOperationJWT(await signHeteroToken(keys.old, null)),
+ ).resolves.toMatchObject({ operation_id: 'operation-1', sub: 'user-1' });
+ });
+});
diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index 9d2c603601c..af19546b93c 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -1,7 +1,15 @@
import { randomUUID } from 'node:crypto';
import debug from 'debug';
-import { importJWK, jwtVerify, SignJWT } from 'jose';
+import type { JSONWebKeySet, JWK, JWK_RSA_Public, JWTVerifyOptions } from 'jose';
+import {
+ calculateJwkThumbprint,
+ createLocalJWKSet,
+ decodeProtectedHeader,
+ importJWK,
+ jwtVerify,
+ SignJWT,
+} from 'jose';
import { authEnv } from '@/envs/auth';
@@ -38,58 +46,82 @@ export interface HeteroOperationJwtClaims {
/**
* Get RSA key pair from JWKS_KEY environment variable
*/
-const getJwksKey = () => {
+const isRsaSigningKey = (key: JWK): key is JWK_RSA_Public =>
+ key.alg === 'RS256' &&
+ key.kty === 'RSA' &&
+ typeof key.e === 'string' &&
+ typeof key.n === 'string';
+
+const getKeyId = (key: JWK_RSA_Public) => key.kid ?? calculateJwkThumbprint(key);
+
+const toPublicRsaKey = async (key: JWK_RSA_Public): Promise<JWK_RSA_Public> => ({
+ alg: 'RS256',
+ e: key.e,
+ kid: await getKeyId(key),
+ kty: 'RSA',
+ n: key.n,
+ ...(key.use ? { use: key.use } : {}),
+});
+
+const getJwksKeys = () => {
const jwksString = authEnv.JWKS_KEY;
if (!jwksString) {
throw new Error('JWKS_KEY environment variable is not set');
}
- const jwks = JSON.parse(jwksString);
- const rsaKey = jwks.keys.find((key: any) => key.alg === 'RS256' && key.kty === 'RSA');
+ const jwks = JSON.parse(jwksString) as JSONWebKeySet;
+ const rsaKeys = jwks.keys.filter(isRsaSigningKey);
- if (!rsaKey) {
+ if (rsaKeys.length === 0) {
throw new Error('No RS256 RSA key found in JWKS');
}
- return rsaKey;
+ return rsaKeys;
};
/**
* Get RSA private key for signing
*/
const getSigningKey = async () => {
- const rsaKey = getJwksKey();
+ const rsaKey = getJwksKeys()[0];
return {
key: await importJWK(rsaKey, 'RS256'),
- kid: rsaKey.kid as string,
+ kid: await getKeyId(rsaKey),
};
};
/**
* Get RSA public key for verification
*/
-const getVerificationKey = async () => {
- const privateRsaKey = getJwksKey();
-
- // Create a "clean" JWK object containing only public key components
- // The essential fields for RSA public key are: kty, n, e
- const publicKeyJwk = {
- alg: privateRsaKey.alg,
- e: privateRsaKey.e,
- kid: privateRsaKey.kid,
- kty: privateRsaKey.kty,
- n: privateRsaKey.n,
- use: privateRsaKey.use,
- };
+const isSignatureVerificationError = (error: unknown) =>
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
- // Remove any undefined fields to keep the object clean
- Object.keys(publicKeyJwk).forEach(
- (key) => (publicKeyJwk as any)[key] === undefined && delete (publicKeyJwk as any)[key],
- );
+const verifyJwt = async (token: string, options: JWTVerifyOptions) => {
+ const publicKeys = await Promise.all(getJwksKeys().map(toPublicRsaKey));
+
+ if (decodeProtectedHeader(token).kid) {
+ return jwtVerify(token, createLocalJWKSet({ keys: publicKeys }), options);
+ }
- return await importJWK(publicKeyJwk, 'RS256');
+ // Tokens issued before this rotation support landed did not include `kid`.
+ // Try each retained key only for those in-flight tokens; newly issued tokens
+ // keep the exact-key lookup above and avoid ambiguous JWKS selection.
+ let signatureError: unknown;
+ for (const publicKey of publicKeys) {
+ try {
+ return await jwtVerify(token, await importJWK(publicKey, 'RS256'), options);
+ } catch (error) {
+ if (!isSignatureVerificationError(error)) throw error;
+ signatureError = error;
+ }
+ }
+
+ throw signatureError ?? new Error('No RSA key available for JWT verification');
};
/**
@@ -213,8 +245,7 @@ export const validateHeteroOperationJWT = async (
token: string,
): Promise<HeteroOperationJwtClaims | null> => {
try {
- const publicKey = await getVerificationKey();
- const { payload } = await jwtVerify(token, publicKey, {
+ const { payload } = await verifyJwt(token, {
algorithms: ['RS256'],
audience: HETERO_OPERATION_JWT_AUDIENCE,
issuer: HETERO_OPERATION_JWT_ISSUER,
@@ -304,9 +335,7 @@ export const validateInternalJWT = async (token: string): Promise<boolean> => {
try {
log('Validating internal JWT token');
- const publicKey = await getVerificationKey();
-
- const { payload } = await jwtVerify(token, publicKey, {
+ const { payload } = await verifyJwt(token, {
algorithms: ['RS256'],
});
diff --git a/scripts/_shared/checkGatewayConfig.js b/scripts/_shared/checkGatewayConfig.js
index 4648b9fb419..94c9bea6493 100644
--- a/scripts/_shared/checkGatewayConfig.js
+++ b/scripts/_shared/checkGatewayConfig.js
@@ -6,6 +6,9 @@
* IMPORTANT: Keep this file as CommonJS (.js) for compatibility with startServer.js
*/
+// eslint-disable-next-line @typescript-eslint/no-require-imports -- startServer.js loads this file through CommonJS.
+const { createHash } = require('node:crypto');
+
const UPGRADE_DOC_URL =
'https://lobehub.com/docs/self-hosting/platform/docker-compose#upgrading-an-existing-deployment';
@@ -16,29 +19,66 @@ const UPGRADE_DOC_URL =
const PUBLIC_EXAMPLE_JWKS_KID = '6823046760c5d460';
/** JWK members that only a private RSA key carries. */
-const PRIVATE_JWK_FIELDS = ['d', 'p', 'q', 'dp', 'dq', 'qi'];
+const PRIVATE_JWK_FIELDS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth'];
const isUnset = (value) => !value || value.startsWith('YOUR_');
-/** First key of a JWKS JSON string, `null` for valid JSON without keys, `undefined` if unparsable. */
-const readFirstJwk = (raw) => {
+/** Keys of a JWKS JSON string, `null` for invalid JWKS shape, `undefined` if unparsable. */
+const readJwks = (raw) => {
try {
- const key = JSON.parse(raw)?.keys?.[0];
- return key && typeof key === 'object' ? key : null;
+ const keys = JSON.parse(raw)?.keys;
+ return Array.isArray(keys) && keys.every((key) => key && typeof key === 'object') ? keys : null;
} catch {
return undefined;
}
};
+/** Match the kid that oidc-provider assigns to legacy keys that omit one. */
+const withDerivedKid = (key) => ({
+ ...key,
+ kid:
+ key.kid ??
+ createHash('sha256')
+ .update(JSON.stringify({ e: key.e, kty: 'RSA', n: key.n }))
+ .digest('base64url'),
+});
+
+const getRsaSigningKeys = (keys) =>
+ keys?.filter((key) => key.alg === 'RS256' && key.kty === 'RSA').map(withDerivedKid) || [];
+
+const hasAmbiguousKeyIds = (keys) => {
+ if (keys.length < 2) return false;
+ const keyIds = keys.map((key) => key.kid);
+ return (
+ keyIds.some((kid) => typeof kid !== 'string' || kid.length === 0) ||
+ new Set(keyIds).size !== keyIds.length
+ );
+};
+
+const publicKeySetCoversPrivateKeys = (privateKeys, publicKeys) => {
+ const publicByKid = new Map(publicKeys.map((key) => [key.kid, key]));
+ return privateKeys.every((privateKey) => {
+ const publicKey = publicByKid.get(privateKey.kid);
+ return (
+ publicKey &&
+ publicKey.kty === privateKey.kty &&
+ publicKey.alg === privateKey.alg &&
+ publicKey.n === privateKey.n &&
+ publicKey.e === privateKey.e
+ );
+ });
+};
+
/**
* @param {NodeJS.ProcessEnv} [env]
* @returns {Array<{ name: string; vars: string[]; message: string }>}
*/
function collectGatewayConfigIssues(env = process.env) {
const issues = [];
- const privateJwk = isUnset(env.JWKS_KEY) ? undefined : readFirstJwk(env.JWKS_KEY);
+ const privateJwks = isUnset(env.JWKS_KEY) ? undefined : readJwks(env.JWKS_KEY);
+ const privateRsaKeys = getRsaSigningKeys(privateJwks);
- if (privateJwk?.kid === PUBLIC_EXAMPLE_JWKS_KID) {
+ if (privateRsaKeys.some((key) => key.kid === PUBLIC_EXAMPLE_JWKS_KID)) {
issues.push({
message:
'JWKS_KEY is the example key that was published in .env.example. Anyone can forge tokens this server and its gateway accept. Generate a new key and replace it in .env.',
@@ -54,11 +94,14 @@ function collectGatewayConfigIssues(env = process.env) {
if (isUnset(env.AGENT_GATEWAY_URL)) missing.push('AGENT_GATEWAY_URL');
if (isUnset(env.AGENT_GATEWAY_SERVICE_TOKEN)) missing.push('GATEWAY_SERVICE_TOKEN');
if (isUnset(env.JWKS_KEY)) missing.push('JWKS_KEY');
- else if (privateJwk === undefined) missing.push('JWKS_KEY (not valid JWKS JSON)');
+ else if (!privateJwks || privateRsaKeys.length === 0)
+ missing.push('JWKS_KEY (not valid JWKS JSON)');
- const publicJwk = isUnset(env.JWKS_PUBLIC_KEY) ? undefined : readFirstJwk(env.JWKS_PUBLIC_KEY);
+ const publicJwks = isUnset(env.JWKS_PUBLIC_KEY) ? undefined : readJwks(env.JWKS_PUBLIC_KEY);
+ const publicRsaKeys = getRsaSigningKeys(publicJwks);
if (isUnset(env.JWKS_PUBLIC_KEY)) missing.push('JWKS_PUBLIC_KEY');
- else if (publicJwk === undefined) missing.push('JWKS_PUBLIC_KEY (not valid JWKS JSON)');
+ else if (!publicJwks || publicRsaKeys.length === 0)
+ missing.push('JWKS_PUBLIC_KEY (not valid JWKS JSON)');
if (missing.length > 0) {
issues.push({
@@ -69,7 +112,7 @@ function collectGatewayConfigIssues(env = process.env) {
});
}
- if (publicJwk && PRIVATE_JWK_FIELDS.some((field) => field in publicJwk)) {
+ if (publicJwks?.some((key) => PRIVATE_JWK_FIELDS.some((field) => field in key))) {
issues.push({
message:
'JWKS_PUBLIC_KEY is passed to the gateway container, but it includes the private key. Anyone who can read the gateway environment could forge tokens. Replace it with the public half of JWKS_KEY.',
@@ -78,10 +121,27 @@ function collectGatewayConfigIssues(env = process.env) {
});
}
- if (privateJwk?.n && publicJwk?.n && privateJwk.n !== publicJwk.n) {
+ const ambiguousVars = [];
+ if (hasAmbiguousKeyIds(privateRsaKeys)) ambiguousVars.push('JWKS_KEY');
+ if (hasAmbiguousKeyIds(publicRsaKeys)) ambiguousVars.push('JWKS_PUBLIC_KEY');
+ if (ambiguousVars.length > 0) {
+ issues.push({
+ message:
+ 'JWKS key rotation requires every RS256 RSA key to have a unique kid so verifiers can select exactly one key.',
+ name: 'JWKS key ids are ambiguous',
+ vars: ambiguousVars,
+ });
+ }
+
+ if (
+ privateRsaKeys.length > 0 &&
+ publicRsaKeys.length > 0 &&
+ ambiguousVars.length === 0 &&
+ !publicKeySetCoversPrivateKeys(privateRsaKeys, publicRsaKeys)
+ ) {
issues.push({
message:
- 'JWKS_PUBLIC_KEY is not the public half of JWKS_KEY, so the gateway rejects every browser session and agent runs fall back to the browser. Derive it again from JWKS_KEY.',
+ 'JWKS_PUBLIC_KEY does not contain every signing key in JWKS_KEY, so the gateway may reject newly signed browser sessions. Publish the complete public set before enabling a new signing key.',
name: 'JWKS_PUBLIC_KEY does not match JWKS_KEY',
vars: ['JWKS_PUBLIC_KEY'],
});
diff --git a/scripts/_shared/checkGatewayConfig.test.ts b/scripts/_shared/checkGatewayConfig.test.ts
index d5c7b50a33a..6533e46547c 100644
--- a/scripts/_shared/checkGatewayConfig.test.ts
+++ b/scripts/_shared/checkGatewayConfig.test.ts
@@ -6,15 +6,23 @@ import {
PUBLIC_EXAMPLE_JWKS_KID,
} from './checkGatewayConfig.js';
-const jwks = (kid: string, fields: Record<string, string> = {}) =>
- JSON.stringify({ keys: [{ alg: 'RS256', e: 'AQAB', kid, kty: 'RSA', n: 'modulus', ...fields }] });
+const rsaKey = (kid: string | undefined, fields: Record<string, unknown> = {}) => ({
+ alg: 'RS256',
+ e: 'AQAB',
+ kid,
+ kty: 'RSA',
+ n: `modulus-${kid}`,
+ ...fields,
+});
+
+const jwks = (...keys: ReturnType<typeof rsaKey>[]) => JSON.stringify({ keys });
const configured = {
AGENT_GATEWAY_SERVICE_TOKEN: 'token',
AGENT_GATEWAY_URL: 'http://localhost:8787',
ENABLE_AGENT_GATEWAY: '1',
- JWKS_KEY: jwks('fresh-key', { d: 'private-exponent' }),
- JWKS_PUBLIC_KEY: jwks('fresh-key'),
+ JWKS_KEY: jwks(rsaKey('fresh-key', { d: 'private-exponent' })),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('fresh-key')),
};
describe('collectGatewayConfigIssues', () => {
@@ -23,7 +31,7 @@ describe('collectGatewayConfigIssues', () => {
});
it('ignores gateway settings when Gateway Mode is not enabled', () => {
- expect(collectGatewayConfigIssues({ JWKS_KEY: jwks('fresh-key') })).toEqual([]);
+ expect(collectGatewayConfigIssues({ JWKS_KEY: jwks(rsaKey('fresh-key')) })).toEqual([]);
});
it('lists every missing variable for an upgrade that kept the old .env', () => {
@@ -59,7 +67,7 @@ describe('collectGatewayConfigIssues', () => {
});
it('flags the public example JWKS_KEY even when Gateway Mode is off', () => {
- const issues = collectGatewayConfigIssues({ JWKS_KEY: jwks(PUBLIC_EXAMPLE_JWKS_KID) });
+ const issues = collectGatewayConfigIssues({ JWKS_KEY: jwks(rsaKey(PUBLIC_EXAMPLE_JWKS_KID)) });
expect(issues.map((issue) => issue.name)).toEqual(['Public example JWKS_KEY']);
});
@@ -76,11 +84,100 @@ describe('collectGatewayConfigIssues', () => {
it('flags a JWKS_PUBLIC_KEY derived from a different key', () => {
const issues = collectGatewayConfigIssues({
...configured,
- JWKS_PUBLIC_KEY: jwks('fresh-key', { n: 'another-modulus' }),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('fresh-key', { n: 'another-modulus' })),
});
expect(issues.map((issue) => issue.name)).toEqual(['JWKS_PUBLIC_KEY does not match JWKS_KEY']);
});
+
+ it('accepts the same rotating key set in a different order', () => {
+ const oldPrivate = rsaKey('old-key', { d: 'old-private' });
+ const newPrivate = rsaKey('new-key', { d: 'new-private' });
+
+ expect(
+ collectGatewayConfigIssues({
+ ...configured,
+ JWKS_KEY: jwks(oldPrivate, newPrivate),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('new-key'), rsaKey('old-key')),
+ }),
+ ).toEqual([]);
+ });
+
+ it('accepts a public-key superset during verifier-first rotation', () => {
+ expect(
+ collectGatewayConfigIssues({
+ ...configured,
+ JWKS_KEY: jwks(rsaKey('old-key', { d: 'old-private' })),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('old-key'), rsaKey('new-key')),
+ }),
+ ).toEqual([]);
+ });
+
+ it('accepts matching legacy keys that omit kid', () => {
+ expect(
+ collectGatewayConfigIssues({
+ ...configured,
+ JWKS_KEY: jwks(rsaKey(undefined, { d: 'old-private' })),
+ JWKS_PUBLIC_KEY: jwks(rsaKey(undefined)),
+ }),
+ ).toEqual([]);
+ });
+
+ it('flags a private field on the second public key', () => {
+ const issues = collectGatewayConfigIssues({
+ ...configured,
+ JWKS_KEY: jwks(
+ rsaKey('old-key', { d: 'old-private' }),
+ rsaKey('new-key', { d: 'new-private' }),
+ ),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('old-key'), rsaKey('new-key', { d: 'new-private' })),
+ });
+
+ expect(issues.map((issue) => issue.name)).toContain('JWKS_PUBLIC_KEY contains the private key');
+ });
+
+ it('flags the multi-prime RSA private field on a public key', () => {
+ const issues = collectGatewayConfigIssues({
+ ...configured,
+ JWKS_PUBLIC_KEY: jwks(
+ rsaKey('fresh-key', {
+ oth: [{ d: 'private-other-d', r: 'private-other-r', t: 'private-other-t' }],
+ }),
+ ),
+ });
+
+ expect(issues.map((issue) => issue.name)).toContain('JWKS_PUBLIC_KEY contains the private key');
+ });
+
+ it('flags a public key set that omits a rotating key', () => {
+ const issues = collectGatewayConfigIssues({
+ ...configured,
+ JWKS_KEY: jwks(
+ rsaKey('old-key', { d: 'old-private' }),
+ rsaKey('new-key', { d: 'new-private' }),
+ ),
+ JWKS_PUBLIC_KEY: jwks(rsaKey('old-key')),
+ });
+
+ expect(issues.map((issue) => issue.name)).toContain('JWKS_PUBLIC_KEY does not match JWKS_KEY');
+ });
+
+ it('flags the public example key when it is the second private key', () => {
+ const issues = collectGatewayConfigIssues({
+ JWKS_KEY: jwks(rsaKey('fresh-key'), rsaKey(PUBLIC_EXAMPLE_JWKS_KID)),
+ });
+
+ expect(issues.map((issue) => issue.name)).toEqual(['Public example JWKS_KEY']);
+ });
+
+ it.each([
+ ['JWKS_KEY', jwks(rsaKey('duplicate'), rsaKey('duplicate'))],
+ ['JWKS_PUBLIC_KEY', jwks(rsaKey(''), rsaKey('new-key'))],
+ ])('flags ambiguous key ids in %s', (variable, value) => {
+ const issues = collectGatewayConfigIssues({ ...configured, [variable]: value });
+
+ expect(issues.map((issue) => issue.name)).toContain('JWKS key ids are ambiguous');
+ });
});
describe('checkGatewayConfig', () => {
diff --git a/src/libs/oidc-provider/jwt.rotation.test.ts b/src/libs/oidc-provider/jwt.rotation.test.ts
new file mode 100644
index 00000000000..cd4ff216c07
--- /dev/null
+++ b/src/libs/oidc-provider/jwt.rotation.test.ts
@@ -0,0 +1,116 @@
+import { generateKeyPairSync } from 'node:crypto';
+
+import { calculateJwkThumbprint, SignJWT } from 'jose';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+const { authEnvMock } = vi.hoisted(() => ({
+ authEnvMock: { JWKS_KEY: '' },
+}));
+
+vi.mock('@/envs/auth', () => ({ authEnv: authEnvMock }));
+
+const createRsaKey = (kid: string) => {
+ const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
+
+ return {
+ kid,
+ privateJwk: {
+ ...privateKey.export({ format: 'jwk' }),
+ alg: 'RS256',
+ kid,
+ use: 'sig',
+ },
+ privateKey,
+ publicJwk: {
+ ...publicKey.export({ format: 'jwk' }),
+ alg: 'RS256',
+ kid,
+ use: 'sig',
+ },
+ };
+};
+
+describe('OIDC JWT key rotation', () => {
+ const acceptanceId = '7f0c9a7e-0000-4000-8000-000000000001';
+ const keys = {
+ new: createRsaKey('new-key'),
+ old: createRsaKey('old-key'),
+ };
+
+ beforeAll(() => {
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+ });
+
+ const signToken = (key: (typeof keys)[keyof typeof keys], kid: string | null = key.kid) =>
+ new SignJWT({ client_id: 'lobehub-desktop' })
+ .setProtectedHeader(kid === null ? { alg: 'RS256' } : { alg: 'RS256', kid })
+ .setSubject('user-1')
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(key.privateKey);
+
+ const signAcceptanceReviewToken = (
+ key: (typeof keys)[keyof typeof keys],
+ kid: string | null = key.kid,
+ ) =>
+ new SignJWT({ client_id: 'lobehub-review' })
+ .setProtectedHeader(kid === null ? { alg: 'RS256' } : { alg: 'RS256', kid })
+ .setAudience(`urn:lobehub:acceptance:${acceptanceId}`)
+ .setSubject('user-1')
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(key.privateKey);
+
+ it.each(['old', 'new'] as const)('verifies a token signed with the %s key', async (name) => {
+ const { validateOIDCJWT } = await import('./jwt');
+
+ await expect(validateOIDCJWT(await signToken(keys[name]))).resolves.toMatchObject({
+ userId: 'user-1',
+ });
+ });
+
+ it.each(['old', 'new'] as const)(
+ 'verifies an acceptance review token signed with the %s key',
+ async (name) => {
+ const { verifyAcceptanceReviewJWT } = await import('./jwt');
+
+ await expect(
+ verifyAcceptanceReviewJWT(await signAcceptanceReviewToken(keys[name])),
+ ).resolves.toMatchObject({ acceptanceId, userId: 'user-1' });
+ },
+ );
+
+ it('rejects a token whose kid is not in the configured JWKS', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+
+ await expect(validateOIDCJWT(await signToken(keys.old, 'unknown-key'))).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ });
+
+ it('verifies the derived kid used by oidc-provider for a legacy key', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const { kid: _kid, ...legacyPrivateJwk } = keys.old.privateJwk;
+ const expectedKid = await calculateJwkThumbprint(legacyPrivateJwk);
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [legacyPrivateJwk] });
+ await expect(validateOIDCJWT(await signToken(keys.old, expectedKid))).resolves.toMatchObject({
+ userId: 'user-1',
+ });
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+ });
+
+ it('verifies in-flight tokens without kid after a second key is added', async () => {
+ const { validateOIDCJWT, verifyAcceptanceReviewJWT } = await import('./jwt');
+
+ authEnvMock.JWKS_KEY = JSON.stringify({ keys: [keys.old.privateJwk, keys.new.privateJwk] });
+
+ await expect(validateOIDCJWT(await signToken(keys.old, null))).resolves.toMatchObject({
+ userId: 'user-1',
+ });
+ await expect(
+ verifyAcceptanceReviewJWT(await signAcceptanceReviewToken(keys.old, null)),
+ ).resolves.toMatchObject({ acceptanceId, userId: 'user-1' });
+ });
+});
diff --git a/src/libs/oidc-provider/jwt.test.ts b/src/libs/oidc-provider/jwt.test.ts
index 89e0a1cd255..7b9d005cfde 100644
--- a/src/libs/oidc-provider/jwt.test.ts
+++ b/src/libs/oidc-provider/jwt.test.ts
@@ -19,9 +19,13 @@ vi.mock('@/envs/auth', () => ({
}));
const importJWKMock = vi.fn();
+const createLocalJWKSetMock = vi.fn();
+const decodeProtectedHeaderMock = vi.fn();
const jwtVerifyMock = vi.fn();
vi.mock('jose', () => ({
+ createLocalJWKSet: (...args: unknown[]) => createLocalJWKSetMock(...args),
+ decodeProtectedHeader: (...args: unknown[]) => decodeProtectedHeaderMock(...args),
importJWK: (...args: unknown[]) => importJWKMock(...args),
jwtVerify: (...args: unknown[]) => jwtVerifyMock(...args),
}));
@@ -29,6 +33,8 @@ vi.mock('jose', () => ({
describe('validateOIDCJWT', () => {
beforeEach(() => {
vi.clearAllMocks();
+ createLocalJWKSetMock.mockReturnValue('public-key-set');
+ decodeProtectedHeaderMock.mockReturnValue({ kid: 'test-key' });
importJWKMock.mockResolvedValue('public-key');
});
@@ -64,6 +70,8 @@ describe('acceptance review tokens', () => {
beforeEach(() => {
vi.clearAllMocks();
+ createLocalJWKSetMock.mockReturnValue('public-key-set');
+ decodeProtectedHeaderMock.mockReturnValue({ kid: 'test-key' });
importJWKMock.mockResolvedValue('public-key');
});
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index 964db7cdffe..4b25e7374e7 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -1,6 +1,8 @@
import { acceptanceIdFromReviewResource } from '@lobechat/const';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
+import type { JSONWebKeySet, JWK, JWK_RSA_Public } from 'jose';
+import { calculateJwkThumbprint } from 'jose';
import { authEnv } from '@/envs/auth';
@@ -51,7 +53,22 @@ export const getJWKS = (): object => {
}
};
-const getVerificationKey = async () => {
+const isRsaSigningKey = (key: JWK): key is JWK_RSA_Public =>
+ key.alg === 'RS256' &&
+ key.kty === 'RSA' &&
+ typeof key.e === 'string' &&
+ typeof key.n === 'string';
+
+const toPublicRsaKey = async (key: JWK_RSA_Public): Promise<JWK_RSA_Public> => ({
+ alg: 'RS256',
+ e: key.e,
+ kid: key.kid ?? (await calculateJwkThumbprint(key)),
+ kty: 'RSA',
+ n: key.n,
+ ...(key.use ? { use: key.use } : {}),
+});
+
+const getVerificationKeys = async () => {
try {
const jwksString = getJwksKeyString();
@@ -59,37 +76,24 @@ const getVerificationKey = async () => {
throw new Error('JWKS_KEY environment variable is not set');
}
- const jwks = JSON.parse(jwksString);
+ const jwks = JSON.parse(jwksString) as JSONWebKeySet;
if (!jwks.keys || !Array.isArray(jwks.keys) || jwks.keys.length === 0) {
throw new Error('Invalid JWKS format: missing or empty keys array');
}
- const privateRsaKey = jwks.keys.find((key: any) => key.alg === 'RS256' && key.kty === 'RSA');
- if (!privateRsaKey) {
+ const publicKeys = await Promise.all(jwks.keys.filter(isRsaSigningKey).map(toPublicRsaKey));
+ if (publicKeys.length === 0) {
throw new Error('No RSA key with RS256 algorithm found in JWKS');
}
- // Create a “clean” JWK object containing only public key components.
- // The key fields of an RSA public key are kty, n, e. Others like kid, alg, use are also public.
- const publicKeyJwk = {
- alg: privateRsaKey.alg,
- e: privateRsaKey.e,
- kid: privateRsaKey.kid,
- kty: privateRsaKey.kty,
- n: privateRsaKey.n,
- use: privateRsaKey.use,
- };
-
- // Remove any undefined fields to keep the object clean
- Object.keys(publicKeyJwk).forEach(
- (key) => (publicKeyJwk as any)[key] === undefined && delete (publicKeyJwk as any)[key],
- );
-
const { importJWK } = await import('jose');
- // Now, in any environment, `importJWK` will correctly identify this object as a public key.
- return await importJWK(publicKeyJwk, 'RS256');
+ // Validate configuration before token verification so a malformed JWK remains an
+ // infrastructure error (500) instead of being misreported as invalid user auth (401).
+ await Promise.all(publicKeys.map((key) => importJWK(key, 'RS256')));
+
+ return publicKeys;
} catch (error) {
log('Failed to get JWKS public key: %O', error);
throw new Error(`JWKS_KEY public key retrieval failed: ${(error as Error).message}`, {
@@ -98,6 +102,36 @@ const getVerificationKey = async () => {
}
};
+const isSignatureVerificationError = (error: unknown) =>
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
+
+const verifyJwt = async (token: string, publicKeys: JWK_RSA_Public[]) => {
+ const { createLocalJWKSet, decodeProtectedHeader, importJWK, jwtVerify } = await import('jose');
+ const options = { algorithms: ['RS256'] };
+
+ if (decodeProtectedHeader(token).kid) {
+ return jwtVerify(token, createLocalJWKSet({ keys: publicKeys }), options);
+ }
+
+ // Tokens issued before this rotation support landed did not include `kid`.
+ // Try each retained key only for those in-flight tokens; newly issued tokens
+ // keep the exact-key lookup above and avoid ambiguous JWKS selection.
+ let signatureError: unknown;
+ for (const publicKey of publicKeys) {
+ try {
+ return await jwtVerify(token, await importJWK(publicKey, 'RS256'), options);
+ } catch (error) {
+ if (!isSignatureVerificationError(error)) throw error;
+ signatureError = error;
+ }
+ }
+
+ throw signatureError ?? new Error('No RSA key available for JWT verification');
+};
+
/**
* Validate OIDC JWT Access Token
* @param token - JWT access token
@@ -111,13 +145,10 @@ export const validateOIDCJWT = async (token: string) => {
// plain Error so upstream middleware maps them to 500 and triggers ops
// alerts — treating them as 401 would incorrectly ask clients to re-auth
// while the real problem is server-side.
- const publicKey = await getVerificationKey();
+ const publicKeys = await getVerificationKeys();
try {
- const { jwtVerify } = await import('jose');
- const { payload } = await jwtVerify(token, publicKey, {
- algorithms: ['RS256'],
- });
+ const { payload } = await verifyJwt(token, publicKeys);
log('JWT validation successful, payload: %O', payload);
@@ -173,9 +204,8 @@ export const validateOIDCJWT = async (token: string) => {
};
export const verifyAcceptanceReviewJWT = async (token: string) => {
- const publicKey = await getVerificationKey();
- const { jwtVerify } = await import('jose');
- const { payload } = await jwtVerify(token, publicKey, { algorithms: ['RS256'] });
+ const publicKeys = await getVerificationKeys();
+ const { payload } = await verifyJwt(token, publicKeys);
const acceptanceId = acceptanceIdFromReviewResource(payload.aud);
if (!isAcceptanceReviewClient(payload.client_id as string) || !acceptanceId || !payload.sub)
throw new Error('Not an acceptance review token');