Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): close review gaps in JWT key hardening
Alfredo Lopez0ae6a82dd931
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9c880649c..681d569f4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 2e64e8220..e82aab44f 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/bannedDevSigningKeys.ts b/control-api/src/bannedDevSigningKeys.tsindex 7e5cc27f5..dea533970 100644--- a/control-api/src/bannedDevSigningKeys.ts+++ b/control-api/src/bannedDevSigningKeys.ts@@ -42,7 +42,8 @@ export function isBannedSigningKeyPem(fingerprints: ReadonlySet<string> = BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS): boolean {try {- return fingerprints.has(spkiDerFingerprint(createPublicKey(privateKeyPem)))+ const signingKey = createPrivateKey(privateKeyPem)+ return fingerprints.has(spkiDerFingerprint(createPublicKey(signingKey)))} catch {return false}@@ -55,6 +56,12 @@ export function isBannedSigningKeyPem(* itself is never included in the message.*/export function validateRsaPrivateKeyPem(privateKeyPem: string, envName: string): string {+ const envelopes = privateKeyPem.match(/-----BEGIN [A-Z0-9 ]*KEY-----/g) ?? []+ if (envelopes.length !== 1 || !/-----BEGIN (?:RSA )?PRIVATE KEY-----/.test(envelopes[0])) {+ throw new Error(+ `${envName} must contain exactly one PEM private key; concatenated key bundles are rejected.`+ )+ }let key: KeyObjecttry {key = createPrivateKey(privateKeyPem)@@ -122,11 +129,14 @@ export function assertNoBannedJwtKeys()}if (input.rpcPublicKeyEnvSet) {- const derived = createPublicKey(input.rpcPrivateKey)- .export({ type: 'spki', format: 'pem' })- .toString()- .trim()- if (derived !== input.rpcPublicKey.trim()) {+ let suppliedDer: Buffer+ try {+ suppliedDer = createPublicKey(input.rpcPublicKey).export({ type: 'spki', format: 'der' })+ } catch {+ throw new Error('CONTROL_API_RPC_JWT_PUBLIC_KEY must be a valid PEM-encoded public key')+ }+ const derivedDer = createPublicKey(input.rpcPrivateKey).export({ type: 'spki', format: 'der' })+ if (!derivedDer.equals(suppliedDer)) {throw new Error('CONTROL_API_RPC_JWT_PUBLIC_KEY must correspond to CONTROL_API_RPC_JWT_PRIVATE_KEY')diff --git a/control-api/src/config.ts b/control-api/src/config.tsindex 96745fcd1..96da371da 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -1434,18 +1434,16 @@ if (config.registryAuthEnabled) {}// Security check: reject historically committed dev JWT keys in any signing or-// verifying slot. Runs on every non-dev startup, not only production, because-// from-source deployments may leave NODE_ENV unset.-if (!CLERUM_DEV_MODE_ENABLED) {- assertNoBannedJwtKeys({- rpcPrivateKey: config.rpcJwtPrivateKey,- sessionPrivateKey: config.sessionJwtPrivateKey,- adminPrivateKey: config.adminJwtPrivateKey,- voucherPrivateKey: config.registryVoucherPrivateKey || undefined,- rpcPublicKey: config.rpcJwtPublicKey,- rpcPublicKeyEnvSet: Boolean(process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY),- })-}+// verifying slot on every startup. Generated dev keys are fresh, so explicit+// dev mode changes nothing for legitimate local use.+assertNoBannedJwtKeys({+ rpcPrivateKey: config.rpcJwtPrivateKey,+ sessionPrivateKey: config.sessionJwtPrivateKey,+ adminPrivateKey: config.adminJwtPrivateKey,+ voucherPrivateKey: config.registryVoucherPrivateKey || undefined,+ rpcPublicKey: config.rpcJwtPublicKey,+ rpcPublicKeyEnvSet: Boolean(process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY),+})if (process.env.NODE_ENV === 'production') {// NOTE: the old voucher-key fallback WARN (dedicated key unset → sign with thediff --git a/control-api/src/devSigningKeys.ts b/control-api/src/devSigningKeys.tsindex a8b234c67..3b8d75924 100644--- a/control-api/src/devSigningKeys.ts+++ b/control-api/src/devSigningKeys.ts@@ -1,5 +1,13 @@-import { createPrivateKey, generateKeyPairSync } from 'node:crypto'-import { type Stats, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { createPrivateKey, generateKeyPairSync, randomBytes } from 'node:crypto'+import {+ type Stats,+ linkSync,+ lstatSync,+ mkdirSync,+ readFileSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs'import { dirname, join } from 'node:path'import { validateRsaPrivateKeyPem } from './bannedDevSigningKeys.js'@@ -110,22 +118,33 @@ export function loadOrGenerateDevJwtPrivateKey(storeDir: string = DEFAULT_STORE_DIR): string {const filePath = join(storeDir, `${slot}.pem`)+ // Validate the store boundary on every path, including pure reuse of an+ // already-persisted key.+ ensureStoreDir(storeDir)const existing = readPersistedKey(filePath, slot)if (existing) {warnOnce()return existing}- ensureStoreDir(storeDir)const { privateKey } = generateKeyPairSync('rsa', {modulusLength: 2048,privateKeyEncoding: { type: 'pkcs8', format: 'pem' },publicKeyEncoding: { type: 'spki', format: 'pem' },})+ createPrivateKey(privateKey) // sanity: the generated key must re-parse+ // Publish atomically: write a complete 0600 temp file, then hard-link it+ // under the final name. link(2) fails with EEXIST when another process won,+ // and readers can only ever observe a fully written key.+ const tempPath = `${filePath}.tmp-${process.pid.toString(36)}-${randomBytes(6).toString('hex')}`try {- writeFileSync(filePath, privateKey, { flag: 'wx', mode: 0o600 })+ writeFileSync(tempPath, privateKey, { mode: 0o600 })+ assertOwnedRegularFile(tempPath)+ linkSync(tempPath, filePath)+ unlinkSync(tempPath)} catch (err) {if ((err as NodeJS.ErrnoException).code === 'EEXIST') {- // Another local process created the key first; adopt it.+ removeIfPresent(tempPath)+ // Another local process published a complete key first; adopt it.const winner = readPersistedKey(filePath, slot)if (winner) {warnOnce()@@ -135,7 +154,6 @@ export function loadOrGenerateDevJwtPrivateKey(throw err}assertOwnedRegularFile(filePath)- createPrivateKey(privateKey) // sanity: the generated key must re-parsewarnOnce()return privateKey.trim()}@@ -148,3 +166,11 @@ function warnOnce(): void {'and stored under control-api/.dev-keys; they are never valid for production deployments.')}++function removeIfPresent(path: string): void {+ try {+ unlinkSync(path)+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err+ }+}diff --git a/control-api/test/bannedDevSigningKeys.test.ts b/control-api/test/bannedDevSigningKeys.test.tsindex e4460ff2b..fe8fc4a35 100644--- a/control-api/test/bannedDevSigningKeys.test.ts+++ b/control-api/test/bannedDevSigningKeys.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import { generateKeyPairSync } from 'node:crypto'+import { createPublicKey } from 'node:crypto'import {BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS as DEFAULT_BANNED_FINGERPRINTS,assertNoBannedJwtKeys as assertGuard,@@ -58,7 +59,9 @@ describe('bannedDevSigningKeys', () => {privateKeyEncoding: { type: 'pkcs8', format: 'pem' },publicKeyEncoding: { type: 'spki', format: 'pem' },})- expect(() => validateSigningPem(ec.publicKey, 'TEST_ENV')).toThrow(/must be a PEM-encoded/)+ expect(() => validateSigningPem(ec.publicKey, 'TEST_ENV')).toThrow(+ /must contain exactly one PEM private key/+ )expect(() => validateSigningPem(ec.privateKey, 'TEST_ENV')).toThrow(/must be an RSA key/)})@@ -128,4 +131,51 @@ describe('bannedDevSigningKeys', () => {)).not.toThrow()})++ it('rejects concatenated key bundles instead of fingerprinting a decoy half', () => {+ const target = makeFresh()+ const decoy = makeFresh()+ const fingerprints = new Set([publicKeyFingerprint(target.public)])+ for (const combined of [+ `${decoy.public}\n${target.signing}`,+ `${target.signing}\n${decoy.public}`,+ ]) {+ expect(() => validateSigningPem(combined, 'TEST_ENV')).toThrow(+ /must contain exactly one PEM private key/+ )+ expect(() =>+ assertGuard(+ {+ rpcPrivateKey: combined,+ sessionPrivateKey: makeFresh().signing,+ adminPrivateKey: makeFresh().signing,+ rpcPublicKey: makeFresh().public,+ rpcPublicKeyEnvSet: false,+ },+ fingerprints+ )+ ).toThrow(/historically committed dev JWT key/)+ }+ })++ it('accepts equivalent verifier encodings and rejects different keys by identity', () => {+ const fresh = makeFresh()+ const fingerprints = new Set(['0'.repeat(64)])+ const pkcs1 = createPublicKey(fresh.public).export({ type: 'pkcs1', format: 'pem' }).toString()+ const crlf = fresh.public.trim().replace(/\n/g, '\r\n')+ for (const equivalent of [pkcs1, crlf]) {+ expect(() =>+ assertGuard(+ {+ rpcPrivateKey: fresh.signing,+ sessionPrivateKey: makeFresh().signing,+ adminPrivateKey: makeFresh().signing,+ rpcPublicKey: equivalent,+ rpcPublicKeyEnvSet: true,+ },+ fingerprints+ )+ ).not.toThrow()+ }+ })})diff --git a/control-api/test/config.jwtHardening.test.ts b/control-api/test/config.jwtHardening.test.tsindex 123db20f1..03173f654 100644--- a/control-api/test/config.jwtHardening.test.ts+++ b/control-api/test/config.jwtHardening.test.ts@@ -147,4 +147,12 @@ describe('config JWT hardening', () => {await import('../src/config.js')expect(existsSync(defaultDevSigningKeyStoreDir())).toBe(false)})++ it('rejects a historical verifier key even in explicit dev mode', async () => {+ process.env.CLERUM_DEV_MODE = 'true'+ process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY = HISTORICAL.rpc+ await expect(() => import('../src/config.js')).rejects.toThrow(+ /effective RPC JWT verifier public key/+ )+ })})diff --git a/control-api/test/config.prod.test.ts b/control-api/test/config.prod.test.tsindex 45dc0e991..183b48321 100644--- a/control-api/test/config.prod.test.ts+++ b/control-api/test/config.prod.test.ts@@ -11,14 +11,13 @@ function generateNonDevPem(): string {/*** Populate every CONTROL_API env var that the prod path requires so that- // Non-dev RPC/session/admin JWT keys; the banned-key guard fingerprints the- // full public key, so ordinary RSA-2048 material is fine.- * `src/config.ts`.+ * config evaluation reaches the key guards rather than throwing earlier on a+ * missing required env. Mirrors `requiredOrDevDefault` callsites in*/function applyProdEnv(env: Record<string, string | undefined>): void {env.NODE_ENV = 'production'- // Non-dev RPC/session/admin JWT keys — the existing prod guard rejects the- // hardcoded dev fingerprints.+ // Non-dev RPC/session/admin JWT keys; the banned-key guard fingerprints the+ // full public key, so ordinary RSA-2048 material is fine.env.CONTROL_API_RPC_JWT_PRIVATE_KEY = generateNonDevPem()env.CONTROL_API_SESSION_JWT_PRIVATE_KEY = generateNonDevPem()env.CONTROL_API_ADMIN_JWT_PRIVATE_KEY = generateNonDevPem()diff --git a/control-api/test/devSigningKeys.test.ts b/control-api/test/devSigningKeys.test.tsindex 4f990236c..005ede69b 100644--- a/control-api/test/devSigningKeys.test.ts+++ b/control-api/test/devSigningKeys.test.ts@@ -179,4 +179,24 @@ describe('devSigningKeys persistence contract', () => {warn.mockRestore()}})++ it('rejects a store directory with loose permissions on reuse', () => {+ const store = tempStore()+ loadOrGenerateDevJwtPrivateKey('rpc', store)+ chmodSync(store, 0o755)+ expect(() => loadOrGenerateDevJwtPrivateKey('rpc', store)).toThrow(+ /Dev JWT key store directory has group\/other permissions/+ )+ })++ it('rejects a symlinked store directory even when reusing a key', () => {+ const realStore = tempStore()+ const linkStore = `${tempStore()}-dirlink`+ tempDirs.push(linkStore)+ loadOrGenerateDevJwtPrivateKey('session', realStore)+ symlinkSync(realStore, linkStore)+ expect(() => loadOrGenerateDevJwtPrivateKey('session', linkStore)).toThrow(+ /Dev JWT key store path is not a directory/+ )+ })})