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.

🔨 chore: support key vault secret rotation fallback (#14205)

YuTengjing9cdbc9349903
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.test.ts
new file mode 100644
index 00000000000..7b02898c78b
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.test.ts
@@ -0,0 +1,46 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { signLlmRelayLease, verifyLlmRelayLease } from './protocol';
+
+describe('LLM relay lease rotation', () => {
+ const originalActive = process.env.KEY_VAULTS_SECRET;
+ const originalFallback = process.env.KEY_VAULTS_FALLBACK_SECRET;
+
+ beforeEach(() => {
+ process.env.KEY_VAULTS_SECRET = 'old-secret';
+ delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ });
+
+ afterEach(() => {
+ if (originalActive === undefined) delete process.env.KEY_VAULTS_SECRET;
+ else process.env.KEY_VAULTS_SECRET = originalActive;
+ if (originalFallback === undefined) delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ else process.env.KEY_VAULTS_FALLBACK_SECRET = originalFallback;
+ });
+
+ it('accepts an unexpired lease signed by the fallback secret', () => {
+ const now = Date.now();
+ const token = signLlmRelayLease({ callId: 'call-1', exp: now + 60_000, userId: 'user-1' });
+
+ process.env.KEY_VAULTS_SECRET = 'new-secret';
+ process.env.KEY_VAULTS_FALLBACK_SECRET = 'old-secret';
+
+ expect(verifyLlmRelayLease(token, 'call-1', now)).toEqual({
+ callId: 'call-1',
+ exp: now + 60_000,
+ userId: 'user-1',
+ });
+ });
+
+ it('signs new leases only with the active secret', () => {
+ const now = Date.now();
+ process.env.KEY_VAULTS_FALLBACK_SECRET = 'fallback-secret';
+ const token = signLlmRelayLease({ callId: 'call-2', exp: now + 60_000, userId: 'user-2' });
+
+ process.env.KEY_VAULTS_SECRET = 'fallback-secret';
+ delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+
+ expect(verifyLlmRelayLease(token, 'call-2', now)).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts
index 3d9e8721e41..2d5b75c9b59 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts
@@ -115,8 +115,14 @@ const getLeaseSecret = () => {
return secret;
};
-const sign = (body: string) =>
- createHmac('sha256', getLeaseSecret()).update(`llm-relay-lease:${body}`).digest('base64url');
+const sign = (body: string, secret = getLeaseSecret()) =>
+ createHmac('sha256', secret).update(`llm-relay-lease:${body}`).digest('base64url');
+
+const getLeaseVerificationSecrets = () => {
+ const active = getLeaseSecret();
+ const fallback = process.env.KEY_VAULTS_FALLBACK_SECRET;
+ return fallback?.trim() && fallback !== active ? [active, fallback] : [active];
+};
export const signLlmRelayLease = (claims: LeaseClaims) => {
const body = Buffer.from(JSON.stringify(claims)).toString('base64url');
@@ -133,9 +139,12 @@ export const verifyLlmRelayLease = (
const [body, signature] = token.split('.');
if (!body || !signature) return;
- const expected = Buffer.from(sign(body));
const actual = Buffer.from(signature);
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
+ const isAuthentic = getLeaseVerificationSecrets().some((secret) => {
+ const expected = Buffer.from(sign(body, secret));
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
+ });
+ if (!isAuthentic) return;
try {
const claims = JSON.parse(Buffer.from(body, 'base64url').toString()) as LeaseClaims;
diff --git a/apps/server/src/modules/KeyVaultsEncrypt/index.test.ts b/apps/server/src/modules/KeyVaultsEncrypt/index.test.ts
index e7619234be1..a1644f66bf5 100644
--- a/apps/server/src/modules/KeyVaultsEncrypt/index.test.ts
+++ b/apps/server/src/modules/KeyVaultsEncrypt/index.test.ts
@@ -1,22 +1,28 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { KeyVaultsGateKeeper } from './index';
+import { isKeyVaultsSecretBearerToken, KeyVaultsGateKeeper } from './index';
describe('KeyVaultsGateKeeper', () => {
let gateKeeper: KeyVaultsGateKeeper;
+ let originalFallbackSecret: string | undefined;
let originalSecret: string | undefined;
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(async () => {
+ originalFallbackSecret = process.env.KEY_VAULTS_FALLBACK_SECRET;
originalSecret = process.env.KEY_VAULTS_SECRET;
+ delete process.env.KEY_VAULTS_FALLBACK_SECRET;
process.env.KEY_VAULTS_SECRET = 'Q10pwdq00KXUu9R+c8A8p4PSlIRWi7KwgUophBtkHVk=';
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
});
afterEach(() => {
- process.env.KEY_VAULTS_SECRET = originalSecret;
+ if (originalFallbackSecret === undefined) delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ else process.env.KEY_VAULTS_FALLBACK_SECRET = originalFallbackSecret;
+ if (originalSecret === undefined) delete process.env.KEY_VAULTS_SECRET;
+ else process.env.KEY_VAULTS_SECRET = originalSecret;
consoleErrorSpy.mockRestore();
});
@@ -29,6 +35,49 @@ describe('KeyVaultsGateKeeper', () => {
expect(decryptionResult.wasAuthentic).toBe(true);
});
+ it('decrypts fallback ciphertext while new writes use the active secret', async () => {
+ const fallbackGateKeeper = gateKeeper;
+ process.env.KEY_VAULTS_FALLBACK_SECRET = process.env.KEY_VAULTS_SECRET;
+ process.env.KEY_VAULTS_SECRET = 'ofQiJCXLF8mYemwfMWLOHoHimlPu91YmLfU7YZ4lreQ=';
+ const rotatingGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+
+ const fallbackCiphertext = await fallbackGateKeeper.encrypt('fallback-data');
+ await expect(rotatingGateKeeper.decrypt(fallbackCiphertext)).resolves.toEqual({
+ plaintext: 'fallback-data',
+ wasAuthentic: true,
+ });
+
+ const activeCiphertext = await rotatingGateKeeper.encrypt('active-data');
+ await expect(fallbackGateKeeper.decrypt(activeCiphertext)).resolves.toEqual({
+ plaintext: '',
+ wasAuthentic: false,
+ });
+ });
+
+ it('rejects an invalid fallback secret before processing ciphertext', async () => {
+ process.env.KEY_VAULTS_FALLBACK_SECRET = Buffer.from('short').toString('base64');
+
+ await expect(KeyVaultsGateKeeper.initWithEnvKey()).rejects.toThrow(
+ '`KEY_VAULTS_FALLBACK_SECRET` must be 16, 24, or 32 bytes',
+ );
+ });
+
+ it('rejects fallback bearer tokens when the active secret is missing', () => {
+ const fallbackSecret = process.env.KEY_VAULTS_SECRET!;
+ process.env.KEY_VAULTS_FALLBACK_SECRET = fallbackSecret;
+ delete process.env.KEY_VAULTS_SECRET;
+
+ expect(isKeyVaultsSecretBearerToken(`Bearer ${fallbackSecret}`)).toBe(false);
+ });
+
+ it('rejects fallback bearer tokens when the active secret is blank', () => {
+ const fallbackSecret = process.env.KEY_VAULTS_SECRET!;
+ process.env.KEY_VAULTS_FALLBACK_SECRET = fallbackSecret;
+ process.env.KEY_VAULTS_SECRET = ' ';
+
+ expect(isKeyVaultsSecretBearerToken(`Bearer ${fallbackSecret}`)).toBe(false);
+ });
+
it('should return empty plaintext and false authenticity for invalid encrypted data', async () => {
const invalidEncryptedData = 'invalid:encrypted:data';
const decryptionResult = await gateKeeper.decrypt(invalidEncryptedData);
diff --git a/apps/server/src/modules/KeyVaultsEncrypt/index.ts b/apps/server/src/modules/KeyVaultsEncrypt/index.ts
index 19ae7dcada1..2506a1e2d52 100644
--- a/apps/server/src/modules/KeyVaultsEncrypt/index.ts
+++ b/apps/server/src/modules/KeyVaultsEncrypt/index.ts
@@ -6,39 +6,65 @@ interface DecryptionResult {
wasAuthentic: boolean;
}
+const importAesKey = async (secret: string, envName: string) => {
+ const rawKey = Buffer.from(secret, 'base64');
+
+ // AES-GCM supports 128, 192, and 256 bit keys.
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/AesKeyGenParams#length
+ if (![16, 24, 32].includes(rawKey.length)) {
+ throw new Error(
+ `\`${envName}\` must be 16, 24, or 32 bytes (128, 192, or 256 bits) when base64 decoded, got ${rawKey.length} bytes. ` +
+ 'Please run `openssl rand -base64 32` to create a valid key.',
+ );
+ }
+
+ return crypto.subtle.importKey('raw', rawKey, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
+};
+
+export const getKeyVaultsSecrets = () => {
+ const { KEY_VAULTS_FALLBACK_SECRET, KEY_VAULTS_SECRET } = getServerDBConfig();
+ const active = KEY_VAULTS_SECRET?.trim() ? KEY_VAULTS_SECRET : undefined;
+ const fallback =
+ active && KEY_VAULTS_FALLBACK_SECRET?.trim() ? KEY_VAULTS_FALLBACK_SECRET : undefined;
+
+ return {
+ active,
+ fallback: fallback === active ? undefined : fallback,
+ };
+};
+
+export const isKeyVaultsSecretBearerToken = (authorization: string | null) => {
+ const { active, fallback } = getKeyVaultsSecrets();
+ if (!active) return false;
+
+ return [active, fallback].some(
+ (secret) => secret !== undefined && authorization === `Bearer ${secret}`,
+ );
+};
+
export class KeyVaultsGateKeeper {
- private aesKey: CryptoKey;
+ private activeAesKey: CryptoKey;
+ private fallbackAesKey?: CryptoKey;
- constructor(aesKey: CryptoKey) {
- this.aesKey = aesKey;
+ constructor(activeAesKey: CryptoKey, fallbackAesKey?: CryptoKey) {
+ this.activeAesKey = activeAesKey;
+ this.fallbackAesKey = fallbackAesKey;
}
static initWithEnvKey = async () => {
- const { KEY_VAULTS_SECRET } = getServerDBConfig();
- if (!KEY_VAULTS_SECRET)
+ const { active, fallback } = getKeyVaultsSecrets();
+ if (!active)
throw new Error(` \`KEY_VAULTS_SECRET\` is not set, please set it in your environment variables.
If you don't have it, please run \`openssl rand -base64 32\` to create one.
`);
- const rawKey = Buffer.from(KEY_VAULTS_SECRET, 'base64');
+ const activeAesKey = await importAesKey(active, 'KEY_VAULTS_SECRET');
+ const fallbackAesKey = fallback
+ ? await importAesKey(fallback, 'KEY_VAULTS_FALLBACK_SECRET')
+ : undefined;
- // Validate key length - AES-GCM supports 128, 192, and 256 bit keys (16, 24, or 32 bytes)
- // See: https://developer.mozilla.org/en-US/docs/Web/API/AesKeyGenParams#length
- if (![16, 24, 32].includes(rawKey.length)) {
- throw new Error(
- `\`KEY_VAULTS_SECRET\` must be 16, 24, or 32 bytes (128, 192, or 256 bits) when base64 decoded, got ${rawKey.length} bytes. ` +
- 'Please run `openssl rand -base64 32` to create a valid key.',
- );
- }
- const aesKey = await crypto.subtle.importKey(
- 'raw',
- rawKey,
- { length: 256, name: 'AES-GCM' },
- false,
- ['encrypt', 'decrypt'],
- );
- return new KeyVaultsGateKeeper(aesKey);
+ return new KeyVaultsGateKeeper(activeAesKey, fallbackAesKey);
};
/**
@@ -53,7 +79,7 @@ If you don't have it, please run \`openssl rand -base64 32\` to create one.
iv,
name: 'AES-GCM',
},
- this.aesKey,
+ this.activeAesKey,
encodedKeyVault,
);
@@ -64,8 +90,7 @@ If you don't have it, please run \`openssl rand -base64 32\` to create one.
return `${Buffer.from(iv).toString('hex')}:${authTag.toString('hex')}:${encrypted.toString('hex')}`;
};
- // Assuming key and encrypted data are obtained from external sources
- decrypt = async (encryptedData: string): Promise<DecryptionResult> => {
+ private decryptWithKey = async (encryptedData: string, aesKey: CryptoKey) => {
const parts = encryptedData.split(':');
if (parts.length !== 3) {
throw new Error('Invalid encrypted data format');
@@ -78,22 +103,43 @@ If you don't have it, please run \`openssl rand -base64 32\` to create one.
// Combine encrypted data and authentication tag
const combined = Buffer.concat([encrypted, authTag]);
+ const decryptedBuffer = await crypto.subtle.decrypt(
+ {
+ iv,
+ name: 'AES-GCM',
+ },
+ aesKey,
+ combined,
+ );
+
+ return new TextDecoder().decode(decryptedBuffer);
+ };
+
+ // Assuming key and encrypted data are obtained from external sources
+ decrypt = async (encryptedData: string): Promise<DecryptionResult> => {
+ if (encryptedData.split(':').length !== 3) {
+ throw new Error('Invalid encrypted data format');
+ }
+
try {
- const decryptedBuffer = await crypto.subtle.decrypt(
- {
- iv,
- name: 'AES-GCM',
- },
- this.aesKey,
- combined,
- );
-
- const decrypted = new TextDecoder().decode(decryptedBuffer);
+ const plaintext = await this.decryptWithKey(encryptedData, this.activeAesKey);
return {
- plaintext: decrypted,
+ plaintext,
wasAuthentic: true,
};
} catch {
+ if (this.fallbackAesKey) {
+ try {
+ const plaintext = await this.decryptWithKey(encryptedData, this.fallbackAesKey);
+ return {
+ plaintext,
+ wasAuthentic: true,
+ };
+ } catch {
+ // Return the existing unauthentic result after both configured keys fail.
+ }
+ }
+
return {
plaintext: '',
wasAuthentic: false,
diff --git a/apps/server/src/router-hono/agent/__tests__/index.test.ts b/apps/server/src/router-hono/agent/__tests__/index.test.ts
new file mode 100644
index 00000000000..e383d121580
--- /dev/null
+++ b/apps/server/src/router-hono/agent/__tests__/index.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import app from '../index';
+
+const { mockGatewayStart } = vi.hoisted(() => ({
+ mockGatewayStart: vi.fn((c: { json: (body: object) => Response }) =>
+ c.json({ status: 'started' }),
+ ),
+}));
+
+vi.mock('../handlers/gatewayStart', () => ({ gatewayStart: mockGatewayStart }));
+
+describe('agent gateway start authentication', () => {
+ const originalActiveSecret = process.env.KEY_VAULTS_SECRET;
+ const originalFallbackSecret = process.env.KEY_VAULTS_FALLBACK_SECRET;
+
+ afterEach(() => {
+ if (originalActiveSecret === undefined) delete process.env.KEY_VAULTS_SECRET;
+ else process.env.KEY_VAULTS_SECRET = originalActiveSecret;
+
+ if (originalFallbackSecret === undefined) delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ else process.env.KEY_VAULTS_FALLBACK_SECRET = originalFallbackSecret;
+
+ mockGatewayStart.mockClear();
+ });
+
+ it('rejects a fallback bearer token when the active secret is missing', async () => {
+ delete process.env.KEY_VAULTS_SECRET;
+ process.env.KEY_VAULTS_FALLBACK_SECRET = 'fallback-secret';
+
+ const response = await app.request('/api/agent/gateway/start', {
+ headers: { authorization: 'Bearer fallback-secret' },
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(503);
+ await expect(response.json()).resolves.toEqual({ error: 'Service not configured' });
+ expect(mockGatewayStart).not.toHaveBeenCalled();
+ });
+
+ it('rejects a fallback bearer token when the active secret is blank', async () => {
+ process.env.KEY_VAULTS_SECRET = ' ';
+ process.env.KEY_VAULTS_FALLBACK_SECRET = 'fallback-secret';
+
+ const response = await app.request('/api/agent/gateway/start', {
+ headers: { authorization: 'Bearer fallback-secret' },
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(503);
+ await expect(response.json()).resolves.toEqual({ error: 'Service not configured' });
+ expect(mockGatewayStart).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.ts
index 568e9d5b6ab..6cd89dca7b5 100644
--- a/apps/server/src/router-hono/agent/index.ts
+++ b/apps/server/src/router-hono/agent/index.ts
@@ -77,7 +77,12 @@ app.get(
// POST /api/agent/gateway/start — non-Vercel ensureRunning (Bearer KEY_VAULTS_SECRET)
app.post(
'/gateway/start',
- bearerSecretAuth(() => process.env.KEY_VAULTS_SECRET),
+ bearerSecretAuth(() => {
+ const activeSecret = process.env.KEY_VAULTS_SECRET;
+ return activeSecret?.trim()
+ ? [activeSecret, process.env.KEY_VAULTS_FALLBACK_SECRET]
+ : undefined;
+ }),
gatewayStart,
);
diff --git a/apps/server/src/router-hono/agent/middlewares/__tests__/bearerSecretAuth.test.ts b/apps/server/src/router-hono/agent/middlewares/__tests__/bearerSecretAuth.test.ts
index 25426ae4e48..ec2c93e939a 100644
--- a/apps/server/src/router-hono/agent/middlewares/__tests__/bearerSecretAuth.test.ts
+++ b/apps/server/src/router-hono/agent/middlewares/__tests__/bearerSecretAuth.test.ts
@@ -64,6 +64,26 @@ describe('bearerSecretAuth middleware', () => {
expect(next).toHaveBeenCalledTimes(1);
});
+ it('accepts any configured rotation secret', async () => {
+ const next = vi.fn().mockResolvedValue(undefined);
+ const middleware = bearerSecretAuth(() => ['active', 'fallback']);
+
+ await middleware(buildContext('Bearer fallback').ctx, next);
+
+ expect(next).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns 503 when a rotation secret list contains no configured value', async () => {
+ const next = vi.fn();
+ const response = await bearerSecretAuth(() => [undefined, ''])(
+ buildContext('Bearer anything').ctx,
+ next,
+ );
+
+ expect(response?.status).toBe(503);
+ expect(next).not.toHaveBeenCalled();
+ });
+
it('evaluates the secret getter on each request (no cache)', async () => {
const getSecret = vi.fn();
getSecret.mockReturnValueOnce(undefined).mockReturnValueOnce('s');
diff --git a/apps/server/src/router-hono/agent/middlewares/bearerSecretAuth.ts b/apps/server/src/router-hono/agent/middlewares/bearerSecretAuth.ts
index 1b31010f300..c4da8600365 100644
--- a/apps/server/src/router-hono/agent/middlewares/bearerSecretAuth.ts
+++ b/apps/server/src/router-hono/agent/middlewares/bearerSecretAuth.ts
@@ -14,16 +14,19 @@ const log = debug('lobe-server:agent:bearer-secret-auth');
* - Returns `401` on header mismatch.
*/
export const bearerSecretAuth =
- (getSecret: () => string | undefined): MiddlewareHandler =>
+ (getSecret: () => string | readonly (string | undefined)[] | undefined): MiddlewareHandler =>
async (c, next) => {
- const secret = getSecret();
- if (!secret) {
+ const configured = getSecret();
+ const secrets = (Array.isArray(configured) ? configured : [configured]).filter(
+ (secret): secret is string => !!secret?.trim(),
+ );
+ if (secrets.length === 0) {
log('Secret is not configured for %s', c.req.path);
return c.json({ error: 'Service not configured' }, 503);
}
const authHeader = c.req.header('authorization');
- if (authHeader !== `Bearer ${secret}`) {
+ if (!secrets.some((secret) => authHeader === `Bearer ${secret}`)) {
return c.json({ error: 'Unauthorized' }, 401);
}
diff --git a/packages/app-config/src/db.ts b/packages/app-config/src/db.ts
index 60616899b4c..2c418bec35c 100644
--- a/packages/app-config/src/db.ts
+++ b/packages/app-config/src/db.ts
@@ -9,6 +9,7 @@ export const getServerDBConfig = () => {
DATABASE_TEST_URL: process.env.DATABASE_TEST_URL,
DATABASE_URL: process.env.DATABASE_URL,
+ KEY_VAULTS_FALLBACK_SECRET: process.env.KEY_VAULTS_FALLBACK_SECRET,
KEY_VAULTS_SECRET: process.env.KEY_VAULTS_SECRET,
REMOVE_GLOBAL_FILE: process.env.DISABLE_REMOVE_GLOBAL_FILE !== '0',
@@ -23,6 +24,7 @@ export const getServerDBConfig = () => {
DATABASE_TEST_URL: z.string().optional(),
DATABASE_URL: z.string().optional(),
+ KEY_VAULTS_FALLBACK_SECRET: z.string().optional(),
KEY_VAULTS_SECRET: z.string().optional(),
REMOVE_GLOBAL_FILE: z.boolean().optional(),
diff --git a/packages/database/src/models/__tests__/apiKey.test.ts b/packages/database/src/models/__tests__/apiKey.test.ts
index 22cd65eb184..3baaf03afc9 100644
--- a/packages/database/src/models/__tests__/apiKey.test.ts
+++ b/packages/database/src/models/__tests__/apiKey.test.ts
@@ -3,7 +3,7 @@ import { API_KEY_PREFIX, validateApiKeyFormat } from '@lobechat/utils/apiKey';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { hashApiKey } from '@/utils/server/apiKeyHash';
+import { hashApiKey, hashApiKeyWithSecret } from '@/utils/server/apiKeyHash';
import { getTestDB } from '../../core/getTestDB';
import { apiKeys, users, workspaces } from '../../schemas';
@@ -16,10 +16,13 @@ const userId = 'api-key-model-test-user-id';
const validKeyVaultsSecret = 'ofQiJCXLF8mYemwfMWLOHoHimlPu91YmLfU7YZ4lreQ=';
let apiKeyModel: ApiKeyModel;
+let originalFallbackSecret: string | undefined;
let originalKeyVaultsSecret: string | undefined;
beforeEach(async () => {
+ originalFallbackSecret = process.env.KEY_VAULTS_FALLBACK_SECRET;
originalKeyVaultsSecret = process.env.KEY_VAULTS_SECRET;
+ delete process.env.KEY_VAULTS_FALLBACK_SECRET;
process.env.KEY_VAULTS_SECRET = validKeyVaultsSecret;
apiKeyModel = new ApiKeyModel(serverDB, userId);
await serverDB.delete(users);
@@ -29,7 +32,10 @@ beforeEach(async () => {
afterEach(async () => {
await serverDB.delete(users).where(eq(users.id, userId));
await serverDB.delete(apiKeys).where(eq(apiKeys.userId, userId));
- process.env.KEY_VAULTS_SECRET = originalKeyVaultsSecret;
+ if (originalFallbackSecret === undefined) delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ else process.env.KEY_VAULTS_FALLBACK_SECRET = originalFallbackSecret;
+ if (originalKeyVaultsSecret === undefined) delete process.env.KEY_VAULTS_SECRET;
+ else process.env.KEY_VAULTS_SECRET = originalKeyVaultsSecret;
});
describe('ApiKeyModel', () => {
@@ -279,6 +285,26 @@ describe('ApiKeyModel', () => {
expect(found?.name).toBe('Test Key');
});
+ it('finds a key hashed with the rotation fallback in static and scoped lookups', async () => {
+ const validKey = `${API_KEY_PREFIX}1234567890abcdef`;
+ const fallbackSecret = 'fallback-hash-secret';
+ process.env.KEY_VAULTS_FALLBACK_SECRET = fallbackSecret;
+ await serverDB.insert(apiKeys).values({
+ enabled: true,
+ key: validKey,
+ keyHash: hashApiKeyWithSecret(validKey, fallbackSecret),
+ name: 'Fallback Key',
+ userId,
+ });
+
+ await expect(ApiKeyModel.findByKey(serverDB, validKey)).resolves.toMatchObject({
+ name: 'Fallback Key',
+ });
+ await expect(apiKeyModel.findByKey(validKey)).resolves.toMatchObject({
+ name: 'Fallback Key',
+ });
+ });
+
it('should return null for invalid key format', async () => {
const found = await apiKeyModel.findByKey('invalid-key-format');
diff --git a/packages/database/src/models/apiKey.ts b/packages/database/src/models/apiKey.ts
index 7c333aa85ee..2e2437df5a7 100644
--- a/packages/database/src/models/apiKey.ts
+++ b/packages/database/src/models/apiKey.ts
@@ -1,6 +1,6 @@
import { generateApiKey, isApiKeyExpired, validateApiKeyFormat } from '@lobechat/utils/apiKey';
-import { hashApiKey } from '@lobechat/utils/server';
-import { and, desc, eq, getTableColumns } from 'drizzle-orm';
+import { getApiKeyHashes, hashApiKey } from '@lobechat/utils/server';
+import { and, desc, eq, getTableColumns, inArray } from 'drizzle-orm';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
@@ -14,9 +14,13 @@ export class ApiKeyModel {
if (!validateApiKeyFormat(key)) {
return null;
}
- const keyHash = hashApiKey(key);
+ const keyHashes = getApiKeyHashes(key);
- const [row] = await db.select().from(apiKeys).where(eq(apiKeys.keyHash, keyHash)).limit(1);
+ const [row] = await db
+ .select()
+ .from(apiKeys)
+ .where(inArray(apiKeys.keyHash, keyHashes))
+ .limit(1);
return row;
};
@@ -169,11 +173,11 @@ export class ApiKeyModel {
findByKey = async (key: string) => {
if (!validateApiKeyFormat(key)) return null;
- const keyHash = hashApiKey(key);
+ const keyHashes = getApiKeyHashes(key);
const [row] = await this.db
.select()
.from(apiKeys)
- .where(and(eq(apiKeys.keyHash, keyHash), this.manageable()))
+ .where(and(inArray(apiKeys.keyHash, keyHashes), this.manageable()))
.limit(1);
return row;
};
diff --git a/packages/utils/src/server/apiKeyHash.test.ts b/packages/utils/src/server/apiKeyHash.test.ts
new file mode 100644
index 00000000000..7a0c0284468
--- /dev/null
+++ b/packages/utils/src/server/apiKeyHash.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getApiKeyHashes, hashApiKey, hashApiKeyWithSecret } from './apiKeyHash';
+
+const activeSecret = 'active-secret';
+const fallbackSecret = 'fallback-secret';
+
+describe('API key hashing during secret rotation', () => {
+ const originalActive = process.env.KEY_VAULTS_SECRET;
+ const originalFallback = process.env.KEY_VAULTS_FALLBACK_SECRET;
+
+ beforeEach(() => {
+ process.env.KEY_VAULTS_SECRET = activeSecret;
+ delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ });
+
+ afterEach(() => {
+ if (originalActive === undefined) delete process.env.KEY_VAULTS_SECRET;
+ else process.env.KEY_VAULTS_SECRET = originalActive;
+ if (originalFallback === undefined) delete process.env.KEY_VAULTS_FALLBACK_SECRET;
+ else process.env.KEY_VAULTS_FALLBACK_SECRET = originalFallback;
+ });
+
+ it('returns only the active hash when no fallback is configured', () => {
+ expect(getApiKeyHashes('lobe-test')).toEqual([hashApiKey('lobe-test')]);
+ });
+
+ it('returns active then fallback hashes without duplicates', () => {
+ process.env.KEY_VAULTS_FALLBACK_SECRET = fallbackSecret;
+
+ expect(getApiKeyHashes('lobe-test')).toEqual([
+ hashApiKeyWithSecret('lobe-test', activeSecret),
+ hashApiKeyWithSecret('lobe-test', fallbackSecret),
+ ]);
+
+ process.env.KEY_VAULTS_FALLBACK_SECRET = activeSecret;
+ expect(getApiKeyHashes('lobe-test')).toHaveLength(1);
+ });
+});
diff --git a/packages/utils/src/server/apiKeyHash.ts b/packages/utils/src/server/apiKeyHash.ts
index 1db6631de33..e3b8335b217 100644
--- a/packages/utils/src/server/apiKeyHash.ts
+++ b/packages/utils/src/server/apiKeyHash.ts
@@ -2,6 +2,11 @@ import { createHmac } from 'node:crypto';
const getApiKeyHashSecret = () => process.env.KEY_VAULTS_SECRET;
+const getApiKeyHashFallbackSecret = () => process.env.KEY_VAULTS_FALLBACK_SECRET;
+
+export const hashApiKeyWithSecret = (apiKey: string, secret: string): string =>
+ createHmac('sha256', secret).update(apiKey).digest('hex');
+
export const hashApiKey = (apiKey: string): string => {
const secret = getApiKeyHashSecret();
@@ -9,5 +14,20 @@ export const hashApiKey = (apiKey: string): string => {
throw new Error('`KEY_VAULTS_SECRET` is required for API key hash calculation.');
}
- return createHmac('sha256', secret).update(apiKey).digest('hex');
+ return hashApiKeyWithSecret(apiKey, secret);
+};
+
+export const getApiKeyHashes = (apiKey: string): string[] => {
+ const activeSecret = getApiKeyHashSecret();
+ if (!activeSecret) {
+ throw new Error('`KEY_VAULTS_SECRET` is required for API key hash calculation.');
+ }
+
+ const fallbackSecret = getApiKeyHashFallbackSecret();
+ const secrets =
+ fallbackSecret?.trim() && fallbackSecret !== activeSecret
+ ? [activeSecret, fallbackSecret]
+ : [activeSecret];
+
+ return secrets.map((secret) => hashApiKeyWithSecret(apiKey, secret));
};
diff --git a/src/app/(backend)/webapi/create-image/comfyui/route.ts b/src/app/(backend)/webapi/create-image/comfyui/route.ts
index 1fc5ff8703b..115f6fc332f 100644
--- a/src/app/(backend)/webapi/create-image/comfyui/route.ts
+++ b/src/app/(backend)/webapi/create-image/comfyui/route.ts
@@ -1,14 +1,12 @@
import { NextResponse } from 'next/server';
import { checkAuth } from '@/app/(backend)/middleware/auth';
-import { getServerDBConfig } from '@/config/db';
import { createCallerFactory } from '@/libs/trpc/lambda';
+import { isKeyVaultsSecretBearerToken } from '@/server/modules/KeyVaultsEncrypt';
import { lambdaRouter } from '@/server/routers/lambda';
export const maxDuration = 300;
-const serverDBEnv = getServerDBConfig();
-
// Custom handler that supports both regular auth and internal service auth
const handler = async (req: Request, { jwtPayload }: { jwtPayload?: any }) => {
try {
@@ -78,16 +76,11 @@ const handler = async (req: Request, { jwtPayload }: { jwtPayload?: any }) => {
};
export const POST = async (req: Request) => {
- // Check for internal service authentication (only if KEY_VAULTS_SECRET is set)
- if (serverDBEnv.KEY_VAULTS_SECRET) {
- const authorization = req.headers.get('Authorization');
+ const authorization = req.headers.get('Authorization');
- // If request has internal service token, bypass regular auth
- if (authorization === `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`) {
- // Internal service call from ComfyUI provider
- // Pass a system user ID for internal service calls
- return handler(req, { jwtPayload: { userId: 'INTERNAL_SERVICE' } });
- }
+ // If request has either rotation secret, bypass regular auth for internal service calls.
+ if (isKeyVaultsSecretBearerToken(authorization)) {
+ return handler(req, { jwtPayload: { userId: 'INTERNAL_SERVICE' } });
}
// Otherwise use regular checkAuth
diff --git a/src/libs/oidc-provider/cookies.test.ts b/src/libs/oidc-provider/cookies.test.ts
new file mode 100644
index 00000000000..2607a204eb8
--- /dev/null
+++ b/src/libs/oidc-provider/cookies.test.ts
@@ -0,0 +1,20 @@
+// @vitest-environment node
+import Keygrip from 'keygrip';
+import { describe, expect, it, vi } from 'vitest';
+
+import { getOIDCCookieKeys, verifyOIDCCookieSignature } from './cookies';
+
+vi.mock('@/config/db', () => ({
+ serverDBEnv: {
+ KEY_VAULTS_FALLBACK_SECRET: 'fallback-cookie-key',
+ KEY_VAULTS_SECRET: 'active-cookie-key',
+ },
+}));
+
+describe('OIDC cookie key rotation', () => {
+ it('signs with the active key and verifies signatures from the fallback key', () => {
+ expect(getOIDCCookieKeys()).toEqual(['active-cookie-key', 'fallback-cookie-key']);
+ const signature = new Keygrip(['fallback-cookie-key']).sign('_session=session-1');
+ expect(verifyOIDCCookieSignature('_session', 'session-1', signature)).toBe(true);
+ });
+});
diff --git a/src/libs/oidc-provider/cookies.ts b/src/libs/oidc-provider/cookies.ts
index 18af68ee123..cdf8468fe35 100644
--- a/src/libs/oidc-provider/cookies.ts
+++ b/src/libs/oidc-provider/cookies.ts
@@ -15,7 +15,8 @@ export const getOIDCCookieKeys = () => {
if (!key) {
throw new Error('KEY_VAULTS_SECRET is required for OIDC Provider cookie signing');
}
- return [key];
+ const fallbackKey = serverDBEnv.KEY_VAULTS_FALLBACK_SECRET;
+ return fallbackKey?.trim() && fallbackKey !== key ? [key, fallbackKey] : [key];
};
/**