Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(auth): reconcile JWT key hardening review and verifier contracts

Alfredo Lopezae04ca5dbcfc
diff --git a/control-api/README.md b/control-api/README.md
index 75ce1e680..dbbc2d0d3 100644
--- a/control-api/README.md
+++ b/control-api/README.md
@@ -170,19 +170,40 @@ Auth settings:
- `CONTROL_API_SESSION_JWT_PRIVATE_KEY`: RSA private key used to sign external REST API session JWTs (`/external/auth/*`) with RS256.
-Local development: run with `CLERUM_DEV_MODE=true` and no signing-key env vars.
+For local development, leave the signing-key env vars unset and start
+`control-api` first, from the repository root:
+
+```bash
+CLERUM_DEV_MODE=true npm --prefix control-api run dev
+```
+
+Then start `rpc-proxy` and `external-rest-api` in separate terminals with the
+same `CLERUM_DEV_MODE=true` opt-in. This mode is rejected with
+`NODE_ENV=production`.
+
Control API generates one RSA-2048 key per slot under the gitignored
`control-api/.dev-keys/` directory (`0700` directory, `0600` signing files,
`0644` derived public files) on first use, reuses it across restarts, and
publishes each derived public half as `<slot>.public.pem`. When
`rpc-proxy` and `external-rest-api` also run with `CLERUM_DEV_MODE=true`, they
load `rpc.public.pem` and `session.public.pem` from that store, so a monorepo
-dev boot keeps one shared key identity. Set `EVENFIRE_DEV_KEY_STORE` to
-relocate the store, or set the explicit `RPC_PROXY_JWT_PUBLIC_KEY` /
-`EXTERNAL_REST_API_JWT_PUBLIC_KEY` env vars to override it. Outside dev mode
-the three env vars above are always required, and keys whose public halves
-were ever committed to this repository are rejected in every slot, including
-the RPC verifier public key.
+dev boot keeps one shared key identity. Leave `EVENFIRE_DEV_KEY_STORE` unset
+or blank for the default; a nonblank override must be an absolute path set
+consistently in all three services.
+
+An environment-supplied signing key takes precedence and does not update the
+store. If you set `CONTROL_API_RPC_JWT_PRIVATE_KEY` or
+`CONTROL_API_SESSION_JWT_PRIVATE_KEY`, explicitly configure its matching public
+key in `RPC_PROXY_JWT_PUBLIC_KEY` or `EXTERNAL_REST_API_JWT_PUBLIC_KEY`,
+respectively. A store left from an earlier run may contain a different key.
+After deleting or rotating stored keys, or switching to an environment-supplied
+key, reconfigure the affected verifiers as needed and restart them. Running
+verifiers do not silently refresh their key identity.
+
+Outside dev mode, `CONTROL_API_RPC_JWT_PRIVATE_KEY`,
+`CONTROL_API_SESSION_JWT_PRIVATE_KEY`, and `CONTROL_API_ADMIN_JWT_PRIVATE_KEY`
+are always required. Keys whose public halves were ever committed to this
+repository are rejected in every slot, including the RPC verifier public key.
- `CONTROL_API_RPC_JWT_PRIVATE_KEY`: RSA private key used to sign RPC access JWTs for `rpc-proxy` (RS256).
- `CONTROL_API_JWT_ISSUER`: expected `iss` for session token signing and verification.
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 255a7e696..7bc4125fe 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.686",
+ "version": "0.1.687",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.686",
+ "version": "0.1.687",
"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.json
index c80efb5a9..d2e83ca3a 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.686",
+ "version": "0.1.687",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/devSigningKeys.ts b/control-api/src/devSigningKeys.ts
index 7709291a1..6756589a9 100644
--- a/control-api/src/devSigningKeys.ts
+++ b/control-api/src/devSigningKeys.ts
@@ -12,7 +12,7 @@ import {
unlinkSync,
writeFileSync,
} from 'node:fs'
-import { dirname, join } from 'node:path'
+import { dirname, isAbsolute, join } from 'node:path'
import { validateRsaPrivateKeyPem } from './bannedDevSigningKeys.js'
export type DevJwtSlot = 'rpc' | 'session' | 'admin'
@@ -26,7 +26,8 @@ export type DevJwtSlot = 'rpc' | 'session' | 'admin'
* falls back to the service working directory used by every test/npm script.
*/
const SERVICE_ROOT = typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
-const DEFAULT_STORE_DIR = process.env.EVENFIRE_DEV_KEY_STORE ?? join(SERVICE_ROOT, '.dev-keys')
+const DEFAULT_STORE_DIR =
+ process.env.EVENFIRE_DEV_KEY_STORE?.trim() || join(SERVICE_ROOT, '.dev-keys')
export function defaultDevSigningKeyStoreDir(): string {
return DEFAULT_STORE_DIR
@@ -158,6 +159,15 @@ function readStoredDerivedPublic(publicPath: string): string | undefined {
return readStoreFileNoFollow(publicPath, 'shared-read')?.trim()
}
+function assertMatchingDerivedPublic(publicPath: string, existing: string, derived: string): void {
+ if (existing !== derived) {
+ throw new Error(
+ `Dev JWT key store public file does not match its signing material: ${publicPath}. ` +
+ 'Delete the store only if you accept losing local dev tokens.'
+ )
+ }
+}
+
/**
* Publish the verifying half derived from the signing material as
* `<slot>.public.pem` (0644 inside the 0700 store). Sibling dev verifiers read
@@ -173,12 +183,7 @@ function ensureDerivedPublicKey(slot: DevJwtSlot, storeDir: string, signingPem:
.trim()
const existing = readStoredDerivedPublic(publicPath)
if (existing !== undefined) {
- if (existing !== derived) {
- throw new Error(
- `Dev JWT key store public file does not match its signing material: ${publicPath}. ` +
- 'Delete the store only if you accept losing local dev tokens.'
- )
- }
+ assertMatchingDerivedPublic(publicPath, existing, derived)
return
}
const tempPath = `${publicPath}.tmp-${process.pid.toString(36)}-${randomBytes(6).toString('hex')}`
@@ -189,7 +194,12 @@ function ensureDerivedPublicKey(slot: DevJwtSlot, storeDir: string, signingPem:
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
removeIfPresent(tempPath)
- // Another process published first; its content is validated on the next read.
+ // Validate the winning opened file before returning a usable identity.
+ const winner = readStoredDerivedPublic(publicPath)
+ if (winner === undefined) {
+ throw new Error(`Dev JWT key store public file disappeared: ${publicPath}`)
+ }
+ assertMatchingDerivedPublic(publicPath, winner, derived)
return
}
throw err
@@ -206,14 +216,30 @@ export function loadOrGenerateDevJwtPrivateKey(
slot: DevJwtSlot,
storeDir: string = DEFAULT_STORE_DIR
): string {
+ if (!isAbsolute(storeDir)) {
+ throw new Error('EVENFIRE_DEV_KEY_STORE must be an absolute path when dev JWT keys are needed.')
+ }
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)
+ let existing = readPersistedKey(filePath, slot)
+ const publicPath = join(storeDir, `${slot}.public.pem`)
+ if (!existing && readStoredDerivedPublic(publicPath) !== undefined) {
+ // A concurrent first start may have completed between the two reads.
+ // Adopt its private key; never publish a new identity over an orphan public key.
+ existing = readPersistedKey(filePath, slot)
+ if (!existing) {
+ throw new Error(
+ `Dev JWT key store has a public file without its signing material: ${publicPath}. ` +
+ `Restore the matching signing key at ${filePath}, or remove ${publicPath} ` +
+ 'only if you accept invalidating local dev tokens.'
+ )
+ }
+ }
if (existing) {
- warnOnce()
ensureDerivedPublicKey(slot, storeDir, existing)
+ warnOnce(storeDir)
return existing
}
const { privateKey } = generateKeyPairSync('rsa', {
@@ -237,8 +263,8 @@ export function loadOrGenerateDevJwtPrivateKey(
// Another local process published a complete key first; adopt it.
const winner = readPersistedKey(filePath, slot)
if (winner) {
- warnOnce()
ensureDerivedPublicKey(slot, storeDir, winner)
+ warnOnce(storeDir)
return winner
}
}
@@ -246,16 +272,16 @@ export function loadOrGenerateDevJwtPrivateKey(
}
assertOwnedRegularFile(filePath)
ensureDerivedPublicKey(slot, storeDir, privateKey)
- warnOnce()
+ warnOnce(storeDir)
return privateKey.trim()
}
-function warnOnce(): void {
+function warnOnce(storeDir: string): void {
if (warnedOnce) return
warnedOnce = true
console.warn(
'[ControlAPI] Dev JWT signing keys are active (CLERUM_DEV_MODE). Keys are generated locally ' +
- 'and stored under control-api/.dev-keys; they are never valid for production deployments.'
+ `and stored under ${JSON.stringify(storeDir)}; they are never valid for production deployments.`
)
}
diff --git a/control-api/src/services/registryConnectionDb.ts b/control-api/src/services/registryConnectionDb.ts
index a1eabf20e..530d96123 100644
--- a/control-api/src/services/registryConnectionDb.ts
+++ b/control-api/src/services/registryConnectionDb.ts
@@ -14,7 +14,7 @@ import {
} from './registryIdentityCache.js'
/**
- * Thrown when no voucher signing key/kid is resolvable (route maps to 500
+ * Thrown when no accepted voucher signing key/kid is resolvable (route maps to 500
* registry_voucher_unavailable). Authoritative home is here so
* `resolveVoucherSigningMaterial` can throw it without importing
* registryVoucher.ts (which would cycle). registryVoucher.ts re-exports it so
@@ -211,10 +211,7 @@ export async function resolveVoucherSigningMaterial(): Promise<{
const row = await getRegistryConnection()
if (!row || !row.privateKeyPem || !row.keyId) throw new VoucherUnavailableError()
if (isBannedSigningKeyPem(row.privateKeyPem)) {
- throw new Error(
- '[SECURITY] registry_connection voucher signing key is a historically committed dev ' +
- 'JWT key; replace it through registry enrollment.'
- )
+ throw new VoucherUnavailableError()
}
return { signingKey: row.privateKeyPem, kid: row.keyId }
}
diff --git a/control-api/test/config.jwtHardening.test.ts b/control-api/test/config.jwtHardening.test.ts
index 03173f654..87ecdc2ee 100644
--- a/control-api/test/config.jwtHardening.test.ts
+++ b/control-api/test/config.jwtHardening.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPublicKey, generateKeyPairSync } from 'node:crypto'
-import { existsSync } from 'node:fs'
import { BANNED_DEV_JWT_PUBLIC_KEYS as HISTORICAL } from './fixtures/bannedDevJwtPublicKeys.js'
+import { applyProdEnv } from './fixtures/productionConfigEnv.js'
const ORIGINAL_ENV = { ...process.env }
const SLOT_ENV_NAMES = [
@@ -84,6 +84,7 @@ describe('config JWT hardening', () => {
})
it('rejects CLERUM_DEV_MODE=true together with NODE_ENV=production before generation', async () => {
+ for (const name of SLOT_ENV_NAMES) delete process.env[name]
process.env.NODE_ENV = 'production'
process.env.CLERUM_DEV_MODE = 'true'
await expect(() => import('../src/config.js')).rejects.toThrow(
@@ -124,6 +125,7 @@ describe('config JWT hardening', () => {
})
it('accepts fresh RSA-2048 keys whose bodies start with the historical prefixes', async () => {
+ applyProdEnv(process.env)
process.env.CONTROL_API_RPC_JWT_PRIVATE_KEY = signingMaterialWithBodyPrefix('MIIEvA')
process.env.CONTROL_API_SESSION_JWT_PRIVATE_KEY = signingMaterialWithBodyPrefix('MIIEvg')
process.env.CONTROL_API_ADMIN_JWT_PRIVATE_KEY = signingMaterialWithBodyPrefix('MIIEvQ')
@@ -143,9 +145,13 @@ describe('config JWT hardening', () => {
})
it('performs no dev-key store I/O when every slot is configured', async () => {
- const { defaultDevSigningKeyStoreDir } = await import('../src/devSigningKeys.js')
- await import('../src/config.js')
- expect(existsSync(defaultDevSigningKeyStoreDir())).toBe(false)
+ for (const devMode of [undefined, 'true']) {
+ vi.resetModules()
+ if (devMode) process.env.CLERUM_DEV_MODE = devMode
+ else delete process.env.CLERUM_DEV_MODE
+ await import('../src/config.js')
+ expect(devProviderMocks.load).not.toHaveBeenCalled()
+ }
})
it('rejects a historical verifier key even in explicit dev mode', async () => {
diff --git a/control-api/test/config.prod.test.ts b/control-api/test/config.prod.test.ts
index 183b48321..226012530 100644
--- a/control-api/test/config.prod.test.ts
+++ b/control-api/test/config.prod.test.ts
@@ -1,50 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { generateKeyPairSync, randomBytes } from 'node:crypto'
-
-function generateNonDevPem(): string {
- return generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).privateKey
-}
-
-/**
- * Populate every CONTROL_API env var that the prod path requires so that
- * 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 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()
- // Remaining `requiredOrDevDefault` callsites in src/config.ts. Defaults are
- // dev-only — production must set these explicitly.
- env.INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET = randomBytes(32).toString('hex')
- env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET = randomBytes(32).toString('hex')
- env.CONTROL_API_MEMBER_REGISTRATION_SERVICE_BASE_URL = 'https://registration.evenfire.ai/api/v1'
- env.CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET = randomBytes(32).toString('hex')
- env.CONTROL_API_MEMBER_REGISTRATION_HMAC_KID = 'clerum'
- env.CONTROL_API_MEMBER_REGISTRATION_TENANT_ID = 'clerum'
- env.CONTROL_API_JWT_ISSUER = 'control-api'
- env.CONTROL_API_JWT_AUDIENCE = 'profile-ui'
- env.CONTROL_API_RPC_JWT_ISSUER = 'control-api'
- env.CONTROL_API_RPC_JWT_AUDIENCE = 'rpc-proxy'
- env.CONTROL_API_GOOGLE_CLIENT_ID = 'prod-google-client-id'
- env.CONTROL_API_ADMIN_JWT_ISSUER = 'control-api'
- env.CONTROL_API_ADMIN_JWT_AUDIENCE = 'control-ui'
- env.CONTROL_API_ADMIN_BOOTSTRAP_USERNAME = 'admin'
- // bcrypt hash of 'prod-bootstrap-password' (any valid bcrypt-shaped string is fine here).
- env.CONTROL_API_ADMIN_BOOTSTRAP_PASSWORD_HASH =
- '$2b$12$4dm17x2DESCxETGi0MpNruC0KpCev5lbKwqgmUkVLxKsNUxoXXXXXX'
- env.CONTROL_API_OAUTH_STATE_HMAC_SECRET = randomBytes(32).toString('hex')
- env.CONTROL_API_OAUTH_ENCRYPTION_KEY = randomBytes(32).toString('hex')
- env.CONTROL_API_INTERNAL_SERVICE_TOKENS =
- 'external-rest-api=prod-external-rest-api-token,rpc-proxy=prod-rpc-proxy-token,webhook-proxy=prod-webhook-proxy-token'
-}
+import { createPublicKey } from 'node:crypto'
+import { applyProdEnv, generateNonDevPem } from './fixtures/productionConfigEnv.js'
describe('config: production voucher key guard', () => {
const origEnv = { ...process.env }
@@ -85,6 +41,29 @@ describe('config: production voucher key guard', () => {
await expect(import('../src/config.js')).resolves.toBeDefined()
})
+ it('checks the voucher signing slot against the banned fingerprints in production', async () => {
+ const voucherKey = generateNonDevPem()
+ const guard = await import('../src/bannedDevSigningKeys.js')
+ const voucherFingerprint = guard.publicKeyPemFingerprint(
+ createPublicKey(voucherKey).export({ type: 'spki', format: 'pem' }).toString()
+ )
+ // Inject a generated identity into the real guard's ban set; historical
+ // private material must never become a tracked test fixture.
+ const fingerprints = new Set([
+ ...guard.BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS,
+ voucherFingerprint,
+ ])
+ const assertNoBannedJwtKeys = guard.assertNoBannedJwtKeys
+ vi.spyOn(guard, 'assertNoBannedJwtKeys').mockImplementation(input =>
+ assertNoBannedJwtKeys(input, fingerprints)
+ )
+ process.env.CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY = voucherKey
+
+ await expect(() => import('../src/config.js')).rejects.toThrow(
+ /CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY resolves to a historically committed dev JWT key/
+ )
+ })
+
it('rejects default dev internal service tokens in production', async () => {
process.env.CONTROL_API_INTERNAL_SERVICE_TOKENS =
'external-rest-api=dev-external-rest-api-token'
diff --git a/control-api/test/devSigningKeys.test.ts b/control-api/test/devSigningKeys.test.ts
index ca74d4383..2eb5fe20b 100644
--- a/control-api/test/devSigningKeys.test.ts
+++ b/control-api/test/devSigningKeys.test.ts
@@ -1,6 +1,6 @@
-import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { spawn, spawnSync } from 'node:child_process'
-import { createPublicKey } from 'node:crypto'
+import { createHash, createPublicKey } from 'node:crypto'
import {
chmodSync,
closeSync,
@@ -9,6 +9,8 @@ import {
mkdtempSync,
openSync,
readFileSync,
+ readdirSync,
+ realpathSync,
rmSync,
statSync,
symlinkSync,
@@ -16,7 +18,7 @@ import {
} from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import {
defaultDevSigningKeyStoreDir,
loadOrGenerateDevJwtPrivateKey,
@@ -41,8 +43,8 @@ beforeAll(() => {
process.execPath,
[
tsc,
- 'src/devSigningKeys.ts',
- 'src/bannedDevSigningKeys.ts',
+ join(process.cwd(), 'src/devSigningKeys.ts'),
+ join(process.cwd(), 'src/bannedDevSigningKeys.ts'),
'--outDir',
compileDir,
'--module',
@@ -65,9 +67,20 @@ afterAll(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
-afterEach(() => {
- // Stores created inside tests are also in tempDirs; nothing persistent remains.
-})
+function runProviderScript(
+ script: string,
+ storeDir: string,
+ override?: string
+): { status: number | null; stdout: string; stderr: string } {
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ DEVKEY_MODULE: compiledModulePath,
+ DEVKEY_STORE: storeDir,
+ }
+ delete env.EVENFIRE_DEV_KEY_STORE
+ if (override !== undefined) env.EVENFIRE_DEV_KEY_STORE = override
+ return spawnSync(process.execPath, ['-e', script], { cwd: storeDir, env, encoding: 'utf8' })
+}
function runChild(slot: 'rpc' | 'session' | 'admin', storeDir: string): Promise<string> {
return new Promise((resolve, reject) => {
@@ -168,6 +181,37 @@ describe('devSigningKeys persistence contract', () => {
expect(defaultDevSigningKeyStoreDir().endsWith(join('control-api', '.dev-keys'))).toBe(true)
})
+ it.each(['', ' \t\n '])('treats a blank store override as unset (%j)', override => {
+ const result = runProviderScript(
+ `const provider = require(process.env.DEVKEY_MODULE)
+ console.log(JSON.stringify({ store: provider.defaultDevSigningKeyStoreDir() }))`,
+ tempStore(),
+ override
+ )
+ expect(result.status, result.stderr).toBe(0)
+ expect(JSON.parse(result.stdout).store).toBe(
+ join(dirname(dirname(realpathSync(compiledModulePath))), '.dev-keys')
+ )
+ })
+
+ it('rejects a relative override only when the store is used, before writing files', () => {
+ const store = tempStore()
+ const result = runProviderScript(
+ `const provider = require(process.env.DEVKEY_MODULE)
+ let error
+ try { provider.loadOrGenerateDevJwtPrivateKey('rpc') } catch (err) { error = err.message }
+ console.log(JSON.stringify({ store: provider.defaultDevSigningKeyStoreDir(), error }))`,
+ store,
+ 'relative-dev-keys'
+ )
+ expect(result.status, result.stderr).toBe(0)
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ store: 'relative-dev-keys',
+ error: expect.stringMatching(/EVENFIRE_DEV_KEY_STORE.*absolute/),
+ })
+ expect(readdirSync(store)).toEqual([])
+ })
+
it('warns once without emitting key material when dev keys activate', async () => {
const { vi } = await import('vitest')
vi.resetModules()
@@ -178,6 +222,7 @@ describe('devSigningKeys persistence contract', () => {
provider.loadOrGenerateDevJwtPrivateKey('rpc', store)
provider.loadOrGenerateDevJwtPrivateKey('session', store)
expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls.flat())).toContain(store)
expect(String(warn.mock.calls.flat())).not.toContain('BEGIN')
} finally {
warn.mockRestore()
@@ -242,4 +287,107 @@ describe('devSigningKeys persistence contract', () => {
/public file does not match its signing material/
)
})
+
+ it('rejects an orphan verifying half without publishing a new signing identity', () => {
+ const store = tempStore()
+ loadOrGenerateDevJwtPrivateKey('session', store)
+ const privatePath = join(store, 'session.pem')
+ const publicPath = join(store, 'session.public.pem')
+ const publicBefore = readFileSync(publicPath, 'utf8')
+ rmSync(privatePath)
+ expect(() => loadOrGenerateDevJwtPrivateKey('session', store)).toThrow(
+ /public file without its signing material/
+ )
+ expect(readdirSync(store)).toEqual(['session.public.pem'])
+ expect(readFileSync(publicPath, 'utf8')).toBe(publicBefore)
+ try {
+ loadOrGenerateDevJwtPrivateKey('session', store)
+ } catch (err) {
+ expect((err as Error).message).toContain(privatePath)
+ expect((err as Error).message).toContain(publicPath)
+ expect((err as Error).message).toContain('invalidating local dev tokens')
+ }
+ })
+
+ it('adopts a concurrent complete pair published after the initial missing-private read', () => {
+ const source = tempStore()
+ loadOrGenerateDevJwtPrivateKey('admin', source)
+ const store = tempStore()
+ const result = runProviderScript(
+ `const fs = require('node:fs')
+ const { join } = require('node:path')
+ const { createHash } = require('node:crypto')
+ const source = ${JSON.stringify(source)}
+ const privatePath = join(process.env.DEVKEY_STORE, 'admin.pem')
+ const publicPath = join(process.env.DEVKEY_STORE, 'admin.public.pem')
+ const originalOpen = fs.openSync
+ let firstPrivateRead = true
+ fs.openSync = function (path, ...args) {
+ if (path === privatePath && firstPrivateRead) {
+ firstPrivateRead = false
+ try { return originalOpen(path, ...args) } catch (err) {
+ if (err.code === 'ENOENT') {
+ fs.linkSync(join(source, 'admin.pem'), privatePath)
+ fs.linkSync(join(source, 'admin.public.pem'), publicPath)
+ }
+ throw err
+ }
+ }
+ return originalOpen(path, ...args)
+ }
+ const provider = require(process.env.DEVKEY_MODULE)
+ const resolved = provider.loadOrGenerateDevJwtPrivateKey('admin', process.env.DEVKEY_STORE)
+ console.log(JSON.stringify({ fingerprint: createHash('sha256').update(resolved).digest('hex') }))`,
+ store
+ )
+ expect(result.status, result.stderr).toBe(0)
+ expect(JSON.parse(result.stdout).fingerprint).toBe(
+ createHash('sha256')
+ .update(readFileSync(join(source, 'admin.pem'), 'utf8').trim())
+ .digest('hex')
+ )
+ })
+
+ it('validates the opened winning public file immediately after a publication race', () => {
+ const store = tempStore()
+ loadOrGenerateDevJwtPrivateKey('rpc', store)
+ const matchingPublic = join(store, 'matching-public.pem')
+ writeFileSync(matchingPublic, readFileSync(join(store, 'rpc.public.pem')), { mode: 0o644 })
+ rmSync(join(store, 'rpc.public.pem'))
+ const otherStore = tempStore()
+ loadOrGenerateDevJwtPrivateKey('rpc', otherStore)
+ const result = runProviderScript(
+ `const fs = require('node:fs')
+ const { join } = require('node:path')
+ const publicPath = join(process.env.DEVKEY_STORE, 'rpc.public.pem')
+ const originalLink = fs.linkSync
+ const originalOpen = fs.openSync
+ let raced = false
+ fs.linkSync = function (source, target) {
+ if (target === publicPath && !raced) {
+ raced = true
+ originalLink(${JSON.stringify(join(otherStore, 'rpc.public.pem'))}, publicPath)
+ }
+ return originalLink(source, target)
+ }
+ fs.openSync = function (path, ...args) {
+ const fd = originalOpen(path, ...args)
+ if (path === publicPath && raced) {
+ fs.unlinkSync(publicPath)
+ originalLink(${JSON.stringify(matchingPublic)}, publicPath)
+ }
+ return fd
+ }
+ const provider = require(process.env.DEVKEY_MODULE)
+ let error
+ try { provider.loadOrGenerateDevJwtPrivateKey('rpc', process.env.DEVKEY_STORE) }
+ catch (err) { error = err.message }
+ console.log(JSON.stringify({ error }))`,
+ store
+ )
+ expect(result.status, result.stderr).toBe(0)
+ expect(JSON.parse(result.stdout).error).toMatch(
+ /public file does not match its signing material/
+ )
+ })
})
diff --git a/control-api/test/fixtures/productionConfigEnv.ts b/control-api/test/fixtures/productionConfigEnv.ts
new file mode 100644
index 000000000..a24695c21
--- /dev/null
+++ b/control-api/test/fixtures/productionConfigEnv.ts
@@ -0,0 +1,40 @@
+import { generateKeyPairSync, randomBytes } from 'node:crypto'
+
+export function generateNonDevPem(): string {
+ return generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).privateKey
+}
+
+/** Complete production configuration so tests reach the JWT key guard. */
+export function applyProdEnv(env: Record<string, string | undefined>): void {
+ env.NODE_ENV = 'production'
+ delete env.CLERUM_DEV_MODE
+ delete env.CONTROL_API_RPC_JWT_PUBLIC_KEY
+ env.CONTROL_API_RPC_JWT_PRIVATE_KEY = generateNonDevPem()
+ env.CONTROL_API_SESSION_JWT_PRIVATE_KEY = generateNonDevPem()
+ env.CONTROL_API_ADMIN_JWT_PRIVATE_KEY = generateNonDevPem()
+ env.INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET = randomBytes(32).toString('hex')
+ env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET = randomBytes(32).toString('hex')
+ env.CONTROL_API_MEMBER_REGISTRATION_SERVICE_BASE_URL = 'https://registration.evenfire.ai/api/v1'
+ env.CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET = randomBytes(32).toString('hex')
+ env.CONTROL_API_MEMBER_REGISTRATION_HMAC_KID = 'clerum'
+ env.CONTROL_API_MEMBER_REGISTRATION_TENANT_ID = 'clerum'
+ env.CONTROL_API_JWT_ISSUER = 'control-api'
+ env.CONTROL_API_JWT_AUDIENCE = 'profile-ui'
+ env.CONTROL_API_RPC_JWT_ISSUER = 'control-api'
+ env.CONTROL_API_RPC_JWT_AUDIENCE = 'rpc-proxy'
+ env.CONTROL_API_GOOGLE_CLIENT_ID = 'prod-google-client-id'
+ env.CONTROL_API_ADMIN_JWT_ISSUER = 'control-api'
+ env.CONTROL_API_ADMIN_JWT_AUDIENCE = 'control-ui'
+ env.CONTROL_API_ADMIN_BOOTSTRAP_USERNAME = 'admin'
+ // These test-only values exercise shape/presence checks, not authentication.
+ env.CONTROL_API_ADMIN_BOOTSTRAP_PASSWORD_HASH =
+ '$2b$12$4dm17x2DESCxETGi0MpNruC0KpCev5lbKwqgmUkVLxKsNUxoXXXXXX'
+ env.CONTROL_API_OAUTH_STATE_HMAC_SECRET = randomBytes(32).toString('hex')
+ env.CONTROL_API_OAUTH_ENCRYPTION_KEY = randomBytes(32).toString('hex')
+ env.CONTROL_API_INTERNAL_SERVICE_TOKENS =
+ 'external-rest-api=prod-external-rest-api-token,rpc-proxy=prod-rpc-proxy-token,webhook-proxy=prod-webhook-proxy-token'
+}
diff --git a/control-api/test/services.registryVoucher.test.ts b/control-api/test/services.registryVoucher.test.ts
index 391e0446d..7bb964b72 100644
--- a/control-api/test/services.registryVoucher.test.ts
+++ b/control-api/test/services.registryVoucher.test.ts
@@ -2,6 +2,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import jwt from 'jsonwebtoken'
import { generateKeyPairSync } from 'node:crypto'
+import * as devKeyPolicy from '../src/bannedDevSigningKeys.js'
import { __resetRegistryConnectionCacheForTests } from '../src/services/registryConnectionDb.js'
import { VoucherUnavailableError, mintIdentityVoucher } from '../src/services/registryVoucher.js'
@@ -16,14 +17,6 @@ const { cfg } = vi.hoisted(() => ({
} as Record<string, unknown>,
}))
vi.mock('../src/config.js', () => ({ config: cfg }))
-const bannedCheck = vi.hoisted(() => ({ value: false }))
-vi.mock('../src/bannedDevSigningKeys.js', async importOriginal => {
- const original = await importOriginal<typeof import('../src/bannedDevSigningKeys.js')>()
- return {
- ...original,
- isBannedSigningKeyPem: vi.fn(() => bannedCheck.value),
- }
-})
// self-hosted branch queries the DB — not exercised in the managed tests below.
vi.mock('../src/db.js', () => ({
pool: { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }) },
@@ -97,12 +90,14 @@ describe('voucher v2 (self-hosted) persisted-key guard', () => {
const { deriveOAuthEncryptionKey, encryptOAuthSecret } =
await import('../src/oauth/encryption.js')
const { pool } = await import('../src/db.js')
- const { isBannedSigningKeyPem } = await import('../src/bannedDevSigningKeys.js')
const encryptionKeyHex = 'ab'.repeat(32)
- const persisted = keypair().privateKey
+ const pair = keypair()
+ const persisted = pair.privateKey
cfg.registryConnectionMode = 'self-hosted'
;(cfg as Record<string, unknown>).oauthEncryptionKey = encryptionKeyHex
- vi.mocked(isBannedSigningKeyPem).mockReturnValueOnce(true)
+ expect(devKeyPolicy.isBannedSigningKeyPem(persisted)).toBe(false)
+ const check = vi.spyOn(devKeyPolicy, 'isBannedSigningKeyPem')
+ const fingerprint = devKeyPolicy.publicKeyPemFingerprint(pair.publicKey)
vi.mocked(pool.query).mockResolvedValueOnce({
rows: [
{
@@ -123,6 +118,19 @@ describe('voucher v2 (self-hosted) persisted-key guard', () => {
},
],
})
- await expect(mintIdentityVoucher(admin)).rejects.toThrow(/historically committed dev/)
+ // Exercise the real crypto ban with generated material; no historical
+ // private key is stored in a fixture or bypassed by a mocked predicate.
+ const fingerprints = devKeyPolicy.BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS as Set<string>
+ fingerprints.add(fingerprint)
+ try {
+ const voucher = mintIdentityVoucher(admin)
+ await expect(voucher).rejects.toBeInstanceOf(VoucherUnavailableError)
+ await expect(voucher).rejects.toMatchObject({ message: 'registry_voucher_unavailable' })
+ expect(check.mock.calls.map(([pem]) => devKeyPolicy.publicKeyPemFingerprint(pem))).toEqual([
+ fingerprint,
+ ])
+ } finally {
+ fingerprints.delete(fingerprint)
+ }
})
})
diff --git a/external-rest-api/.env.example b/external-rest-api/.env.example
index ab5b6d856..88f0721cb 100644
--- a/external-rest-api/.env.example
+++ b/external-rest-api/.env.example
@@ -1,3 +1,10 @@
+# Local development only: start control-api with CLERUM_DEV_MODE=true first.
+# Export these values before starting; npm run dev does not load this file.
+# NODE_ENV=production rejects CLERUM_DEV_MODE=true and requires an explicit public key.
+CLERUM_DEV_MODE=true
+# Unset or blank uses control-api/.dev-keys in this checkout. A nonblank override
+# must be absolute and identical in control-api, rpc-proxy, and external-rest-api.
+EVENFIRE_DEV_KEY_STORE=
EXTERNAL_REST_API_PORT=8091
EXTERNAL_REST_API_CORS_ORIGIN=*
EXTERNAL_REST_API_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
@@ -7,7 +14,10 @@ EXTERNAL_REST_API_CONTROL_API_SERVICE_NAME=external-rest-api
EXTERNAL_REST_API_MEMBER_REGISTRATION_SERVICE_BASE_URL=http://member-registration-service.profiles.svc.cluster.local:8092/api/v1
EXTERNAL_REST_API_MEMBER_REGISTRATION_SERVICE_SERVICE_TOKEN=replace-with-external-rest-api-member-registration-service-token
EXTERNAL_REST_API_MEMBER_REGISTRATION_SERVICE_SERVICE_NAME=external-rest-api
-EXTERNAL_REST_API_JWT_PUBLIC_KEY=-----BEGIN PUBLIC KEY-----\nreplace-with-session-rs256-public-key\n-----END PUBLIC KEY-----
+# Blank uses session.public.pem from the store in explicit dev mode. If control-api
+# uses CONTROL_API_SESSION_JWT_PRIVATE_KEY, set its matching public key here instead.
+# Restart/reconfigure after changing keys; running verifiers do not refresh them.
+EXTERNAL_REST_API_JWT_PUBLIC_KEY=
EXTERNAL_REST_API_JWT_ISSUER=control-api
EXTERNAL_REST_API_JWT_AUDIENCE=profile-ui
EXTERNAL_REST_API_ENABLE_DEV_LOGIN=false
diff --git a/external-rest-api/Makefile b/external-rest-api/Makefile
index 8efa937c7..af16c4faa 100644
--- a/external-rest-api/Makefile
+++ b/external-rest-api/Makefile
@@ -11,7 +11,7 @@ build: install
npm run build
dev: install
- npm run dev
+ CLERUM_DEV_MODE=true npm run dev
docker-build:
docker build -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) .
diff --git a/external-rest-api/README.md b/external-rest-api/README.md
index 9b242751c..c8e42e221 100644
--- a/external-rest-api/README.md
+++ b/external-rest-api/README.md
@@ -95,12 +95,34 @@ Security guarantees:
## Local Run
+Use Node 24 or newer. Start `control-api` first with `CLERUM_DEV_MODE=true`
+so it creates the shared development signing keys, then start this service in
+a separate terminal:
+
```bash
cd external-rest-api
npm install
-npm run dev
+CLERUM_DEV_MODE=true npm run dev
```
+`make dev` also opts into this local mode. It is rejected with
+`NODE_ENV=production`. Without this opt-in, set
+`EXTERNAL_REST_API_JWT_PUBLIC_KEY` explicitly.
+
+The shared store defaults to `control-api/.dev-keys` in the same checkout.
+Leave `EVENFIRE_DEV_KEY_STORE` unset or blank to use that default; a nonblank
+override must be an absolute path set consistently in all three services.
+`control-api` persists generated keys across restarts, and this service reads
+`session.public.pem` at startup.
+
+If `CONTROL_API_SESSION_JWT_PRIVATE_KEY` is supplied through the environment,
+set `EXTERNAL_REST_API_JWT_PUBLIC_KEY` to its matching public key explicitly.
+The signer does not update the store for an environment-supplied key, so an
+older store may contain a different identity. After deleting or rotating stored
+keys, or switching to an environment-supplied key, reconfigure the verifier as
+needed and restart it. Running verifiers do not silently refresh their key
+identity.
+
## Kubernetes Deploy
```bash
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 8871fc8a4..9b5ee500c 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.87",
+ "version": "0.1.88",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.87",
+ "version": "0.1.88",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index af99d812a..6215a84d3 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.87",
+ "version": "0.1.88",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/config.ts b/external-rest-api/src/config.ts
index 00eb53e84..045f32921 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -1,6 +1,6 @@
import { createHash, createPublicKey } from 'node:crypto'
-import { readFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
+import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs'
+import { dirname, isAbsolute, join } from 'node:path'
type Config = {
port: number
@@ -88,7 +88,11 @@ function assertNotPlaceholder(label: string, value: string): void {
}
function normalizePem(value: string): string {
- return value.replace(/\\n/g, '\n').trim()
+ return value
+ .replace(/\\r\\n/g, '\n')
+ .replace(/\\n/g, '\n')
+ .replace(/\r\n?/g, '\n')
+ .trim()
}
const EXTERNAL_GFS_EDGE_AGGREGATE_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN'
@@ -146,17 +150,87 @@ const HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS: ReadonlySet<string> = new Set([
])
function assertUsableJwtPublicKey(publicPem: string, envName: string): string {
+ const normalized = normalizePem(publicPem)
let fingerprint: string
+ let canonicalPublicPem: string
try {
- const der = createPublicKey(publicPem).export({ type: 'spki', format: 'der' })
+ // OpenSSL accepts the first key in a bundle and ignores trailing material.
+ // Require one public PEM block before parsing so the validated and used key agree.
+ if (
+ !/^-----BEGIN (PUBLIC KEY|RSA PUBLIC KEY)-----\n[A-Za-z0-9+/=\s]+\n-----END \1-----$/.test(
+ normalized
+ )
+ ) {
+ throw new Error('Expected one public key')
+ }
+ const key = createPublicKey(normalized)
+ if (key.asymmetricKeyType !== 'rsa') throw new Error('Expected RSA')
+ const der = key.export({ type: 'spki', format: 'der' })
fingerprint = createHash('sha256').update(der).digest('hex')
+ canonicalPublicPem = key.export({ type: 'spki', format: 'pem' }).toString().trim()
} catch {
- throw new Error(`${envName} must be a PEM-encoded RSA public key`)
+ throw new Error(`${envName} must be a single PEM-encoded RSA public key`)
}
if (HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS.has(fingerprint)) {
throw new Error(`${envName} must not use a historically committed dev JWT key`)
}
- return publicPem
+ return canonicalPublicPem
+}
+
+function readDevJwtPublicKey(storeDir: string, fileName: string, envName: string): string {
+ const publicPath = join(storeDir, fileName)
+ const missingStore = () =>
+ new Error(
+ `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
+ `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
+ )
+ let directoryStats
+ try {
+ directoryStats = lstatSync(storeDir)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw missingStore()
+ throw err
+ }
+ if (!directoryStats.isDirectory() || directoryStats.isSymbolicLink()) {
+ throw new Error(`Dev JWT key store path is not a directory: ${storeDir}`)
+ }
+ if (process.geteuid && directoryStats.uid !== process.geteuid()) {
+ throw new Error(`Dev JWT key store directory is not owned by the current user: ${storeDir}`)
+ }
+ if ((directoryStats.mode & 0o077) !== 0) {
+ throw new Error(
+ `Dev JWT key store directory has group/other permissions; expected 0700: ${storeDir}`
+ )
+ }
+ let fd: number
+ try {
+ // NONBLOCK avoids hanging on a hostile FIFO; fstat rejects every special file.
+ fd = openSync(publicPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code
+ if (code === 'ENOENT') throw missingStore()
+ if (code === 'ELOOP')
+ throw new Error(`Dev JWT key store path is a symbolic link: ${publicPath}`)
+ throw err
+ }
+ try {
+ const fileStats = fstatSync(fd)
+ if (!fileStats.isFile()) {
+ throw new Error(`Dev JWT key store path is not a regular file: ${publicPath}`)
+ }
+ if (process.geteuid && fileStats.uid !== process.geteuid()) {
+ throw new Error(`Dev JWT key store file is not owned by the current user: ${publicPath}`)
+ }
+ if ((fileStats.mode & 0o022) !== 0) {
+ throw new Error(
+ `Dev JWT key store public file must not be group/other writable: ${publicPath}`
+ )
+ }
+ // Read the descriptor whose identity and permissions were checked above.
+ return readFileSync(fd, 'utf8')
+ } finally {
+ closeSync(fd)
+ }
}
/**
@@ -175,18 +249,12 @@ function resolveSessionJwtPublicKey(): string {
const fromEnv = process.env[envName]
if (fromEnv) return assertUsableJwtPublicKey(fromEnv, envName)
if (process.env.CLERUM_DEV_MODE === 'true') {
- const storeDir =
- process.env.EVENFIRE_DEV_KEY_STORE ?? join(serviceRoot(), '..', 'control-api', '.dev-keys')
- const publicPath = join(storeDir, 'session.public.pem')
- let fromStore: string
- try {
- fromStore = readFileSync(publicPath, 'utf8')
- } catch {
- throw new Error(
- `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
- `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
- )
+ const override = process.env.EVENFIRE_DEV_KEY_STORE?.trim()
+ if (override && !isAbsolute(override)) {
+ throw new Error('EVENFIRE_DEV_KEY_STORE must be an absolute path')
}
+ const storeDir = override || join(serviceRoot(), '..', 'control-api', '.dev-keys')
+ const fromStore = readDevJwtPublicKey(storeDir, 'session.public.pem', envName)
return assertUsableJwtPublicKey(fromStore, envName)
}
return required(envName)
@@ -216,7 +284,7 @@ export const config: Config = {
})(),
controlApiServiceName:
process.env.EXTERNAL_REST_API_CONTROL_API_SERVICE_NAME || 'external-rest-api',
- jwtPublicKey: normalizePem(resolveSessionJwtPublicKey()),
+ jwtPublicKey: resolveSessionJwtPublicKey(),
jwtIssuer: requiredOrDevDefault('EXTERNAL_REST_API_JWT_ISSUER', 'control-api'),
jwtAudience: requiredOrDevDefault('EXTERNAL_REST_API_JWT_AUDIENCE', 'profile-ui'),
profileSessionCookieTtlSeconds: positiveIntegerFromEnv(
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index bf309424c..30732d784 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,8 +8,8 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.10.0',
- externalRestApiVersion: '0.1.87',
- rpcProxyVersion: '0.1.113',
+ externalRestApiVersion: '0.1.88',
+ rpcProxyVersion: '0.1.114',
desktopVersion: '0.10.0',
minimumDesktopVersion: '0.1.252',
}
diff --git a/external-rest-api/test/config.devKeyStore.test.ts b/external-rest-api/test/config.devKeyStore.test.ts
index bc9a72e83..4b6759a59 100644
--- a/external-rest-api/test/config.devKeyStore.test.ts
+++ b/external-rest-api/test/config.devKeyStore.test.ts
@@ -1,108 +1,11 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { generateKeyPairSync } from 'node:crypto'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-
-const ORIGINAL_ENV = { ...process.env }
-let store: string
-
-function seedSharedSessionVerifyingHalf(): string {
- const verifying = generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).publicKey
- writeFileSync(join(store, 'session.public.pem'), verifying, { mode: 0o644 })
- return verifying
-}
-
-beforeEach(() => {
- vi.resetModules()
- process.env = { ...ORIGINAL_ENV }
- delete process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
- process.env.CLERUM_DEV_MODE = 'true'
- store = mkdtempSync(join(tmpdir(), 'evenfire-ext-dev-keys-'))
- process.env.EVENFIRE_DEV_KEY_STORE = store
-})
-
-afterEach(() => {
- process.env = ORIGINAL_ENV
- rmSync(store, { recursive: true, force: true })
- vi.resetModules()
-})
-
-describe('external-rest-api shared dev key identity', () => {
- it('loads exactly the verifying half published by control-api', async () => {
- const published = seedSharedSessionVerifyingHalf()
- const { config } = await import('../src/config.js')
- expect(config.jwtPublicKey).toBe(published.trim())
- })
-
- it('fails loud when the shared store has not been created', async () => {
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /requires the control-api dev key store/
- )
- })
-
- it('prefers an explicit verifier env var over the shared store', async () => {
- seedSharedSessionVerifyingHalf()
- const explicit = generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).publicKey
- process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = explicit
- const { config } = await import('../src/config.js')
- expect(config.jwtPublicKey).toBe(explicit.trim())
- })
-
- it('fails closed in production when the verifier env var is unset or blank', async () => {
- process.env.NODE_ENV = 'production'
- delete process.env.CLERUM_DEV_MODE
- process.env.EXTERNAL_REST_API_CORS_ORIGIN = 'http://localhost:3001'
- process.env.EXTERNAL_REST_API_GOOGLE_CLIENT_ID = 'test-client'
- process.env.EXTERNAL_REST_API_CONTROL_API_BASE_URL = 'http://localhost:8080'
- process.env.EXTERNAL_REST_API_CONTROL_API_SERVICE_TOKEN = 'test-token'
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /Missing required environment variable: EXTERNAL_REST_API_JWT_PUBLIC_KEY/
- )
- process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = ''
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /Missing required environment variable: EXTERNAL_REST_API_JWT_PUBLIC_KEY/
- )
- })
-
- it('fails closed outside dev mode when the verifier env var is unset', async () => {
- delete process.env.CLERUM_DEV_MODE
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /Missing required environment variable: EXTERNAL_REST_API_JWT_PUBLIC_KEY/
- )
- })
-
- it('rejects CLERUM_DEV_MODE=true together with production', async () => {
- process.env.NODE_ENV = 'production'
- process.env.EXTERNAL_REST_API_CORS_ORIGIN = 'http://localhost:3001'
- process.env.EXTERNAL_REST_API_GOOGLE_CLIENT_ID = 'test-client'
- process.env.EXTERNAL_REST_API_CONTROL_API_BASE_URL = 'http://localhost:8080'
- process.env.EXTERNAL_REST_API_CONTROL_API_SERVICE_TOKEN = 'test-token'
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production/
- )
- })
-
- it('rejects a historically committed verifier public key even when supplied explicitly', async () => {
- process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwrZja9jS/r+e2YF1FqEQ
-NMLsnffebYzXrZOb7uPMKhXBoKjJh/taR9v3kX2srfVtoikcKKr0Sfa7MMSLnZWd
-ETmi7MvbeVD3HpsXpVejmw9D0zeYYSGZplLF/b6HY0Lz2XVM8WdJl3Dicyu+SZbZ
-xeHZtMCMTTjvmoI/IYmmO4N3Pgz/SGi7V3EiwoALODP4OWDvd/1xFUiMPslLPgZU
-EczQ5tIpAaD4e0om3gUNsyOKYc5igojm6ooVqI9T3TUGBVJ0uSZB7ntWxKQ39WyI
-aH+oqnwDGbDcDLQ/wTuBtcn4brWTDgW1xA73HVBSImGFvvHCWBiQBiI1nvovUP0u
-WQIDAQAB
------END PUBLIC KEY-----`
- await expect(() => import('../src/config.js')).rejects.toThrow(
- /must not use a historically committed dev JWT key/
- )
- })
+import * as testApi from 'vitest'
+import { defineDevJwtVerifierContract } from '../../rpc-proxy/test/helpers/devJwtVerifierContract.js'
+
+defineDevJwtVerifierContract({
+ testApi,
+ service: 'external-rest-api',
+ slot: 'session',
+ envName: 'EXTERNAL_REST_API_JWT_PUBLIC_KEY',
+ configSource: new URL('../src/config.ts', import.meta.url),
+ loadConfig: () => import('../src/config.js'),
})
diff --git a/rpc-proxy/.env.example b/rpc-proxy/.env.example
index c8a968154..eba64ddeb 100644
--- a/rpc-proxy/.env.example
+++ b/rpc-proxy/.env.example
@@ -1,6 +1,16 @@
+# Local development only: start control-api with CLERUM_DEV_MODE=true first.
+# Export these values before starting; npm run dev does not load this file.
+# NODE_ENV=production rejects CLERUM_DEV_MODE=true and requires an explicit public key.
+CLERUM_DEV_MODE=true
+# Unset or blank uses control-api/.dev-keys in this checkout. A nonblank override
+# must be absolute and identical in control-api, rpc-proxy, and external-rest-api.
+EVENFIRE_DEV_KEY_STORE=
RPC_PROXY_PORT=8094
RPC_PROXY_CORS_ORIGIN=http://localhost:3000
-RPC_PROXY_JWT_PUBLIC_KEY=-----BEGIN PUBLIC KEY-----\nreplace-with-rs256-public-key\n-----END PUBLIC KEY-----
+# Blank uses rpc.public.pem from the store in explicit dev mode. If control-api
+# uses CONTROL_API_RPC_JWT_PRIVATE_KEY, set its matching public key here instead.
+# Restart/reconfigure after changing keys; running verifiers do not refresh them.
+RPC_PROXY_JWT_PUBLIC_KEY=
RPC_PROXY_JWT_ISSUER=control-api
RPC_PROXY_JWT_AUDIENCE=rpc-proxy
RPC_PROXY_CONTROL_API_BASE_URL=http://control-api.control-plane.svc.cluster.local:8090/api/v1
diff --git a/rpc-proxy/Makefile b/rpc-proxy/Makefile
index 287baa547..e8dbc722f 100644
--- a/rpc-proxy/Makefile
+++ b/rpc-proxy/Makefile
@@ -11,7 +11,7 @@ build: install
npm run build
dev: install
- npm run dev
+ CLERUM_DEV_MODE=true npm run dev
docker-build:
docker build -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) .
diff --git a/rpc-proxy/README.md b/rpc-proxy/README.md
index ef5bdddf7..2c5476af7 100644
--- a/rpc-proxy/README.md
+++ b/rpc-proxy/README.md
@@ -40,16 +40,17 @@ External-facing user-scoped JSON-RPC proxy for MCP servers and MCP hosts.
Host runtime routes in `rpc-proxy` are REST-oriented and scope-specific. The status stream is a read-only telemetry channel.
-| Endpoint | Method | Required Scope | Access Type | Transport |
-| --- | --- | --- | --- | --- |
-| `/api/v1/rpc/hosts/:hostRef/messages` | `POST` | `host:message:invoke` | Write | REST |
-| `/api/v1/rpc/hosts/:hostRef/activity` | `GET` | `host:activity:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/activity/stream` | `GET` | `host:activity:read` | Read-only | SSE |
-| `/api/v1/rpc/hosts/:hostRef/status` | `GET` | `host:status:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/health` | `GET` | `host:health:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/status/stream` | `GET` | `host:status:read` | Read-only | SSE |
+| Endpoint | Method | Required Scope | Access Type | Transport |
+| -------------------------------------------- | ------ | --------------------- | ----------- | --------- |
+| `/api/v1/rpc/hosts/:hostRef/messages` | `POST` | `host:message:invoke` | Write | REST |
+| `/api/v1/rpc/hosts/:hostRef/activity` | `GET` | `host:activity:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/activity/stream` | `GET` | `host:activity:read` | Read-only | SSE |
+| `/api/v1/rpc/hosts/:hostRef/status` | `GET` | `host:status:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/health` | `GET` | `host:health:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/status/stream` | `GET` | `host:status:read` | Read-only | SSE |
Notes:
+
- `status/stream` does not accept request bodies and must not be used for message submission.
- `activity/stream` is read-only telemetry and never accepts message submission payloads.
- `activity` and `activity/stream` never include chain-of-thought/internal reasoning text.
@@ -126,18 +127,40 @@ Critical variables:
- `RPC_PROXY_CONTROL_API_CACHE_TTL_MS`
Required in production:
+
- `RPC_PROXY_CONTROL_API_SERVICE_TOKEN`
`RPC_PROXY_JWT_PUBLIC_KEY` must match the public key for `CONTROL_API_RPC_JWT_PRIVATE_KEY`.
## Local Run
+Use Node 24 or newer. Start `control-api` first with `CLERUM_DEV_MODE=true`
+so it creates the shared development signing keys, then start this service in
+a separate terminal:
+
```bash
cd rpc-proxy
npm install
-npm run dev
+CLERUM_DEV_MODE=true npm run dev
```
+`make dev` also opts into this local mode. It is rejected with
+`NODE_ENV=production`. Without this opt-in, set `RPC_PROXY_JWT_PUBLIC_KEY`
+explicitly.
+
+The shared store defaults to `control-api/.dev-keys` in the same checkout.
+Leave `EVENFIRE_DEV_KEY_STORE` unset or blank to use that default; a nonblank
+override must be an absolute path set consistently in all three services.
+`control-api` persists generated keys across restarts, and this service reads
+`rpc.public.pem` at startup.
+
+If `CONTROL_API_RPC_JWT_PRIVATE_KEY` is supplied through the environment, set
+`RPC_PROXY_JWT_PUBLIC_KEY` to its matching public key explicitly. The signer
+does not update the store for an environment-supplied key, so an older store
+may contain a different identity. After deleting or rotating stored keys, or
+switching to an environment-supplied key, reconfigure the verifier as needed
+and restart it. Running verifiers do not silently refresh their key identity.
+
## Kubernetes Deploy (Hardened Defaults)
The `deploy/` manifests include:
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index c4fee10b4..92c4a09c0 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.113",
+ "version": "0.1.114",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.113",
+ "version": "0.1.114",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index b0d3ec855..1c954d2ce 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.113",
+ "version": "0.1.114",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
index 91b4cd14a..924a0f0d7 100644
--- a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
+++ b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
@@ -1,102 +1,11 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { generateKeyPairSync } from 'node:crypto'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-
-const ORIGINAL_ENV = { ...process.env }
-let store: string
-
-function seedSharedRpcVerifyingHalf(): string {
- const verifying = generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).publicKey
- writeFileSync(join(store, 'rpc.public.pem'), verifying, { mode: 0o644 })
- return verifying
-}
-
-beforeEach(() => {
- vi.resetModules()
- process.env = { ...ORIGINAL_ENV }
- delete process.env.RPC_PROXY_JWT_PUBLIC_KEY
- process.env.CLERUM_DEV_MODE = 'true'
- store = mkdtempSync(join(tmpdir(), 'evenfire-rpc-dev-keys-'))
- process.env.EVENFIRE_DEV_KEY_STORE = store
-})
-
-afterEach(() => {
- process.env = ORIGINAL_ENV
- rmSync(store, { recursive: true, force: true })
- vi.resetModules()
-})
-
-describe('rpc-proxy shared dev key identity', () => {
- it('loads exactly the verifying half published by control-api', async () => {
- const published = seedSharedRpcVerifyingHalf()
- const { config } = await import('../config.js')
- expect(config.jwtPublicKey).toBe(published.trim())
- })
-
- it('fails loud when the shared store has not been created', async () => {
- await expect(() => import('../config.js')).rejects.toThrow(
- /requires the control-api dev key store/
- )
- })
-
- it('prefers an explicit verifier env var over the shared store', async () => {
- seedSharedRpcVerifyingHalf()
- const explicit = generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).publicKey
- process.env.RPC_PROXY_JWT_PUBLIC_KEY = explicit
- const { config } = await import('../config.js')
- expect(config.jwtPublicKey).toBe(explicit.trim())
- })
-
- it('fails closed in production when the verifier env var is unset or blank', async () => {
- process.env.NODE_ENV = 'production'
- delete process.env.CLERUM_DEV_MODE
- process.env.RPC_PROXY_CORS_ORIGIN = 'http://localhost:3000'
- await expect(() => import('../config.js')).rejects.toThrow(
- /Missing required environment variable: RPC_PROXY_JWT_PUBLIC_KEY/
- )
- process.env.RPC_PROXY_JWT_PUBLIC_KEY = ''
- await expect(() => import('../config.js')).rejects.toThrow(
- /Missing required environment variable: RPC_PROXY_JWT_PUBLIC_KEY/
- )
- })
-
- it('fails closed outside dev mode when the verifier env var is unset', async () => {
- delete process.env.CLERUM_DEV_MODE
- await expect(() => import('../config.js')).rejects.toThrow(
- /Missing required environment variable: RPC_PROXY_JWT_PUBLIC_KEY/
- )
- })
-
- it('rejects CLERUM_DEV_MODE=true together with production', async () => {
- process.env.NODE_ENV = 'production'
- process.env.RPC_PROXY_CORS_ORIGIN = 'http://localhost:3000'
- await expect(() => import('../config.js')).rejects.toThrow(
- /CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production/
- )
- })
-
- it('rejects a historically committed verifier public key even when supplied explicitly', async () => {
- process.env.RPC_PROXY_JWT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArCIYGHehMPpGKePxaKQa
-rDX5yrzifU5i4fzpI3EtkKSU6s5ug7EkKxc2DdMekoqXe9vr7qKyVwiilUIusXLX
-iW7KPMJlD/Fd5Bo7Qxt69wYiL5I4K37eDgCN6D3LduHySEnkhdI0GDpB4LM2ASOx
-QkEabepekZTMQyExmCIn/dHJ15B+4A9tiiephYOQNr3GcnW9eDomMt6NJLypikbr
-xJO6O7Ar0G+raTbflth8EQzWnGF+WgQW4iiM3wsFhpaE0mUlEbMGDGTMAZy1KfxA
-RRu+QZm3Lo+5AiCaHkijDCglHsXLhqsYi2AdRiavD1Gk9LKP/ztKw7q/D6fYFzmO
-QwIDAQAB
------END PUBLIC KEY-----`
- await expect(() => import('../config.js')).rejects.toThrow(
- /must not use a historically committed dev JWT key/
- )
- })
+import * as testApi from 'vitest'
+import { defineDevJwtVerifierContract } from '../../test/helpers/devJwtVerifierContract.js'
+
+defineDevJwtVerifierContract({
+ testApi,
+ service: 'rpc-proxy',
+ slot: 'rpc',
+ envName: 'RPC_PROXY_JWT_PUBLIC_KEY',
+ configSource: new URL('../config.ts', import.meta.url),
+ loadConfig: () => import('../config.js'),
})
diff --git a/rpc-proxy/src/config.ts b/rpc-proxy/src/config.ts
index 0e4a6f397..785a10d0c 100644
--- a/rpc-proxy/src/config.ts
+++ b/rpc-proxy/src/config.ts
@@ -1,6 +1,6 @@
import { createHash, createPublicKey } from 'node:crypto'
-import { readFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
+import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs'
+import { dirname, isAbsolute, join } from 'node:path'
type Config = {
port: number
@@ -104,7 +104,11 @@ function assertNotPlaceholder(label: string, value: string): void {
}
function normalizePem(value: string): string {
- return value.replace(/\\n/g, '\n').trim()
+ return value
+ .replace(/\\r\\n/g, '\n')
+ .replace(/\\n/g, '\n')
+ .replace(/\r\n?/g, '\n')
+ .trim()
}
export function parseSandboxUiAllowedPorts(raw: string): ReadonlySet<number> {
@@ -192,17 +196,87 @@ const HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS: ReadonlySet<string> = new Set([
])
function assertUsableJwtPublicKey(publicPem: string, envName: string): string {
+ const normalized = normalizePem(publicPem)
let fingerprint: string
+ let canonicalPublicPem: string
try {
- const der = createPublicKey(publicPem).export({ type: 'spki', format: 'der' })
+ // OpenSSL accepts the first key in a bundle and ignores trailing material.
+ // Require one public PEM block before parsing so the validated and used key agree.
+ if (
+ !/^-----BEGIN (PUBLIC KEY|RSA PUBLIC KEY)-----\n[A-Za-z0-9+/=\s]+\n-----END \1-----$/.test(
+ normalized
+ )
+ ) {
+ throw new Error('Expected one public key')
+ }
+ const key = createPublicKey(normalized)
+ if (key.asymmetricKeyType !== 'rsa') throw new Error('Expected RSA')
+ const der = key.export({ type: 'spki', format: 'der' })
fingerprint = createHash('sha256').update(der).digest('hex')
+ canonicalPublicPem = key.export({ type: 'spki', format: 'pem' }).toString().trim()
} catch {
- throw new Error(`${envName} must be a PEM-encoded RSA public key`)
+ throw new Error(`${envName} must be a single PEM-encoded RSA public key`)
}
if (HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS.has(fingerprint)) {
throw new Error(`${envName} must not use a historically committed dev JWT key`)
}
- return publicPem
+ return canonicalPublicPem
+}
+
+function readDevJwtPublicKey(storeDir: string, fileName: string, envName: string): string {
+ const publicPath = join(storeDir, fileName)
+ const missingStore = () =>
+ new Error(
+ `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
+ `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
+ )
+ let directoryStats
+ try {
+ directoryStats = lstatSync(storeDir)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') throw missingStore()
+ throw err
+ }
+ if (!directoryStats.isDirectory() || directoryStats.isSymbolicLink()) {
+ throw new Error(`Dev JWT key store path is not a directory: ${storeDir}`)
+ }
+ if (process.geteuid && directoryStats.uid !== process.geteuid()) {
+ throw new Error(`Dev JWT key store directory is not owned by the current user: ${storeDir}`)
+ }
+ if ((directoryStats.mode & 0o077) !== 0) {
+ throw new Error(
+ `Dev JWT key store directory has group/other permissions; expected 0700: ${storeDir}`
+ )
+ }
+ let fd: number
+ try {
+ // NONBLOCK avoids hanging on a hostile FIFO; fstat rejects every special file.
+ fd = openSync(publicPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code
+ if (code === 'ENOENT') throw missingStore()
+ if (code === 'ELOOP')
+ throw new Error(`Dev JWT key store path is a symbolic link: ${publicPath}`)
+ throw err
+ }
+ try {
+ const fileStats = fstatSync(fd)
+ if (!fileStats.isFile()) {
+ throw new Error(`Dev JWT key store path is not a regular file: ${publicPath}`)
+ }
+ if (process.geteuid && fileStats.uid !== process.geteuid()) {
+ throw new Error(`Dev JWT key store file is not owned by the current user: ${publicPath}`)
+ }
+ if ((fileStats.mode & 0o022) !== 0) {
+ throw new Error(
+ `Dev JWT key store public file must not be group/other writable: ${publicPath}`
+ )
+ }
+ // Read the descriptor whose identity and permissions were checked above.
+ return readFileSync(fd, 'utf8')
+ } finally {
+ closeSync(fd)
+ }
}
/**
@@ -221,18 +295,12 @@ function resolveRpcJwtPublicKey(): string {
const fromEnv = process.env[envName]
if (fromEnv) return assertUsableJwtPublicKey(fromEnv, envName)
if (process.env.CLERUM_DEV_MODE === 'true') {
- const storeDir =
- process.env.EVENFIRE_DEV_KEY_STORE ?? join(serviceRoot(), '..', 'control-api', '.dev-keys')
- const publicPath = join(storeDir, 'rpc.public.pem')
- let fromStore: string
- try {
- fromStore = readFileSync(publicPath, 'utf8')
- } catch {
- throw new Error(
- `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
- `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
- )
+ const override = process.env.EVENFIRE_DEV_KEY_STORE?.trim()
+ if (override && !isAbsolute(override)) {
+ throw new Error('EVENFIRE_DEV_KEY_STORE must be an absolute path')
}
+ const storeDir = override || join(serviceRoot(), '..', 'control-api', '.dev-keys')
+ const fromStore = readDevJwtPublicKey(storeDir, 'rpc.public.pem', envName)
return assertUsableJwtPublicKey(fromStore, envName)
}
return required(envName)
@@ -243,7 +311,7 @@ export const config: Config = {
corsOrigin: parseCorsOrigin(
requiredOrDevDefault('RPC_PROXY_CORS_ORIGIN', 'http://localhost:3000')
),
- jwtPublicKey: normalizePem(resolveRpcJwtPublicKey()),
+ jwtPublicKey: resolveRpcJwtPublicKey(),
jwtIssuer: requiredOrDevDefault('RPC_PROXY_JWT_ISSUER', 'control-api'),
jwtAudience: requiredOrDevDefault('RPC_PROXY_JWT_AUDIENCE', 'rpc-proxy'),
upstreamTimeoutMs: parsePositiveIntMs(
diff --git a/rpc-proxy/test/helpers/devJwtVerifierContract.ts b/rpc-proxy/test/helpers/devJwtVerifierContract.ts
new file mode 100644
index 000000000..732285dcc
--- /dev/null
+++ b/rpc-proxy/test/helpers/devJwtVerifierContract.ts
@@ -0,0 +1,440 @@
+import { execFileSync } from 'node:child_process'
+import { createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto'
+import {
+ chmodSync,
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ rmdirSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import {
+ BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS,
+ publicKeyPemFingerprint,
+} from '../../../control-api/src/bannedDevSigningKeys.js'
+import { loadOrGenerateDevJwtPrivateKey } from '../../../control-api/src/devSigningKeys.js'
+import { BANNED_DEV_JWT_PUBLIC_KEYS } from '../../../control-api/test/fixtures/bannedDevJwtPublicKeys.js'
+
+type VerifierModule = {
+ config: { jwtPublicKey: string; jwtIssuer: string; jwtAudience: string }
+}
+
+type VerifierContract = {
+ testApi: Pick<
+ typeof import('vitest'),
+ 'afterEach' | 'beforeEach' | 'describe' | 'expect' | 'it' | 'vi'
+ >
+ service: 'rpc-proxy' | 'external-rest-api'
+ slot: 'rpc' | 'session'
+ envName: string
+ configSource: URL
+ loadConfig: () => Promise<VerifierModule>
+}
+
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
+const freshPublic = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ .publicKey.export({ type: 'spki', format: 'pem' })
+ .toString()
+ .trim()
+const encodings = {
+ spki: (pem: string) => pem,
+ escaped: (pem: string) => pem.replace(/\n/g, '\\n'),
+ crlf: (pem: string) => pem.replace(/\n/g, '\r\n'),
+ 'escaped-crlf': (pem: string) => pem.replace(/\n/g, '\\r\\n'),
+ pkcs1: (pem: string) => createPublicKey(pem).export({ type: 'pkcs1', format: 'pem' }).toString(),
+}
+
+/**
+ * Both standalone services share this test contract. Identity cases use the
+ * real producer; written public files only exercise encodings and filesystem
+ * rejection, where no signing identity is being claimed.
+ * Caller-supplied test APIs respect the services' distinct Vitest versions.
+ */
+export function defineDevJwtVerifierContract(contract: VerifierContract): void {
+ const { afterEach, beforeEach, describe, expect, it, vi } = contract.testApi
+ // CI installs only the selected service's dependencies. Resolve from its
+ // source module, even when this shared test helper belongs to the sibling.
+ const serviceRequire = createRequire(contract.configSource)
+ const jwt = serviceRequire('jsonwebtoken') as typeof import('jsonwebtoken')
+ const ts = serviceRequire('typescript') as typeof import('typescript')
+ const originalEnv = { ...process.env }
+ let layout: string
+ let store: string
+ const publicFile = `${contract.slot}.public.pem`
+
+ beforeEach(() => {
+ vi.resetModules()
+ process.env = { ...originalEnv, NODE_ENV: 'test', CLERUM_DEV_MODE: 'true' }
+ delete process.env[contract.envName]
+ // Node canonicalizes require.__dirname; macOS aliases /var to /private/var.
+ layout = realpathSync(mkdtempSync(join(tmpdir(), `evenfire-${contract.slot}-verifier-`)))
+ store = join(layout, 'store')
+ mkdirSync(store, { mode: 0o700 })
+ process.env.EVENFIRE_DEV_KEY_STORE = store
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ process.env = originalEnv
+ rmSync(layout, { recursive: true, force: true })
+ vi.resetModules()
+ })
+
+ function publishPublic(pem = freshPublic): void {
+ writeFileSync(join(store, publicFile), pem, { mode: 0o644 })
+ }
+
+ function useProductionEnvironment(): void {
+ process.env.NODE_ENV = 'production'
+ delete process.env.CLERUM_DEV_MODE
+ const prefix = contract.service === 'rpc-proxy' ? 'RPC_PROXY' : 'EXTERNAL_REST_API'
+ const values = [
+ ['CORS_ORIGIN', 'http://localhost:3001'],
+ ['JWT_ISSUER', 'control-api'],
+ ['JWT_AUDIENCE', contract.slot === 'rpc' ? 'rpc-proxy' : 'profile-ui'],
+ ['CONTROL_API_BASE_URL', 'http://localhost:8090'],
+ ['CONTROL_API_SERVICE_TOKEN', randomUUID()],
+ ['HCC_BASE_URL', 'http://localhost:8081'],
+ ['HOST_NAMESPACE', 'mcp-host'],
+ ['DESKTOP_COOKIE_SECRET', randomUUID()],
+ ['SANDBOX_UI_COOKIE_SECRET', randomUUID()],
+ ['OAUTH_CALLBACK_BASE_URL', 'http://localhost:8090'],
+ ['GOOGLE_CLIENT_ID', randomUUID()],
+ ['PUBLIC_BASE_URL', 'http://localhost:8091'],
+ ['DESKTOP_RPC_PROXY_BASE_URL', 'http://localhost:8094'],
+ ['DESKTOP_APP_NAME', 'Evenfire'],
+ ['DESKTOP_RELEASE_BASE_URL', 'http://localhost:8091/releases'],
+ ]
+ Object.assign(
+ process.env,
+ Object.fromEntries(values.map(([name, value]) => [`${prefix}_${name}`, value]))
+ )
+ }
+
+ function runIsolatedRuntime(runtime: 'src' | 'dist', override: string | undefined) {
+ const producerDir = join(layout, 'control-api', runtime)
+ const verifierDir = join(layout, contract.service, runtime)
+ mkdirSync(producerDir, { recursive: true })
+ mkdirSync(verifierDir, { recursive: true })
+ const producerSource = join(repoRoot, 'control-api/src/devSigningKeys.ts')
+ const producerPath = join(producerDir, `devSigningKeys.${runtime === 'src' ? 'ts' : 'js'}`)
+ const verifierPath = join(verifierDir, `config.${runtime === 'src' ? 'ts' : 'js'}`)
+ if (runtime === 'src') {
+ copyFileSync(producerSource, producerPath)
+ copyFileSync(contract.configSource, verifierPath)
+ } else {
+ for (const [source, destination] of [
+ [producerSource, producerPath],
+ [contract.configSource, verifierPath],
+ ] as const) {
+ writeFileSync(
+ destination,
+ ts.transpileModule(readFileSync(source, 'utf8'), {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ esModuleInterop: true,
+ },
+ }).outputText
+ )
+ }
+ }
+ // Retain the real validation dependency without duplicating its contents.
+ writeFileSync(
+ join(producerDir, 'bannedDevSigningKeys.js'),
+ `module.exports = require(${JSON.stringify(join(repoRoot, 'control-api/src/bannedDevSigningKeys.ts'))})`
+ )
+ const runner = `
+ const producer = require(${JSON.stringify(producerPath)});
+ const material = producer.loadOrGenerateDevJwtPrivateKey(${JSON.stringify(contract.slot)});
+ const { config } = require(${JSON.stringify(verifierPath)});
+ const jwt = require(${JSON.stringify(serviceRequire.resolve('jsonwebtoken'))});
+ const signedJwt = jwt.sign({ sub: 'isolated-dev-key-store' }, material, {
+ algorithm: 'RS256', issuer: config.jwtIssuer, audience: config.jwtAudience
+ });
+ const claims = jwt.verify(signedJwt, config.jwtPublicKey, {
+ algorithms: ['RS256'], issuer: config.jwtIssuer, audience: config.jwtAudience
+ });
+ process.stdout.write(JSON.stringify({
+ storeDir: producer.defaultDevSigningKeyStoreDir(), sub: claims.sub, audience: claims.aud
+ }));
+ `
+ const env = { ...process.env }
+ delete env[contract.envName]
+ if (override === undefined) delete env.EVENFIRE_DEV_KEY_STORE
+ else env.EVENFIRE_DEV_KEY_STORE = override
+ return JSON.parse(
+ execFileSync(process.execPath, ['--import', serviceRequire.resolve('tsx'), '-e', runner], {
+ cwd: join(layout, contract.service),
+ env,
+ encoding: 'utf8',
+ timeout: 15_000,
+ maxBuffer: 64 * 1024,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ ) as { storeDir: string; sub: string; audience: string }
+ }
+
+ describe(`${contract.service} dev JWT verifier contract`, () => {
+ it('verifies a real producer RS256 token from an explicit absolute store', async () => {
+ const material = loadOrGenerateDevJwtPrivateKey(contract.slot, store)
+ const { config } = await contract.loadConfig()
+ expect(publicKeyPemFingerprint(config.jwtPublicKey)).toBe(
+ publicKeyPemFingerprint(
+ createPublicKey(material).export({ type: 'spki', format: 'pem' }).toString()
+ )
+ )
+ const signedJwt = jwt.sign({ sub: 'dev-key-store-contract' }, material, {
+ algorithm: 'RS256',
+ issuer: config.jwtIssuer,
+ audience: config.jwtAudience,
+ })
+ expect(
+ jwt.verify(signedJwt, config.jwtPublicKey, {
+ algorithms: ['RS256'],
+ issuer: config.jwtIssuer,
+ audience: config.jwtAudience,
+ })
+ ).toMatchObject({ sub: 'dev-key-store-contract', aud: config.jwtAudience })
+ })
+ for (const runtime of ['src', 'dist'] as const) {
+ it.each([undefined, '', ' \t '])(
+ `${runtime} shares the default producer store when override is %j`,
+ override => {
+ const result = runIsolatedRuntime(runtime, override)
+ expect(result.storeDir).toBe(join(layout, 'control-api', '.dev-keys'))
+ expect(result.sub).toBe('isolated-dev-key-store')
+ expect(result.audience).toBe(contract.slot === 'rpc' ? 'rpc-proxy' : 'profile-ui')
+ }
+ )
+ it(`${runtime} shares an explicit absolute producer store`, () => {
+ const result = runIsolatedRuntime(runtime, store)
+ expect(result.storeDir).toBe(store)
+ expect(result.sub).toBe('isolated-dev-key-store')
+ })
+ }
+ it('matches the canonical signing-key fingerprint denylist', async () => {
+ // Keep standalone runtime guards private; compare their explicit local
+ // identities, then test every canonical public fixture behavior below.
+ const declaration = readFileSync(contract.configSource, 'utf8').match(
+ /const HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS[\s\S]*?new Set\(\[([\s\S]*?)\]\)/
+ )
+ expect(declaration).not.toBeNull()
+ const localFingerprints = [...declaration![1].matchAll(/'([a-f0-9]{64})'/g)].map(
+ match => match[1]
+ )
+ expect(localFingerprints.sort()).toEqual([...BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS].sort())
+ })
+
+ if (contract.service === 'external-rest-api') {
+ it('loads this contract with only the external service dependencies installed', () => {
+ const helperDir = join(layout, 'rpc-proxy/test/helpers')
+ const callerDir = join(layout, 'external-rest-api/src')
+ mkdirSync(helperDir, { recursive: true })
+ mkdirSync(callerDir, { recursive: true })
+ const helperPath = join(helperDir, 'devJwtVerifierContract.ts')
+ copyFileSync(fileURLToPath(import.meta.url), helperPath)
+ const callerPath = join(callerDir, 'config.ts')
+ writeFileSync(callerPath, '')
+ symlinkSync(
+ join(dirname(fileURLToPath(contract.configSource)), '../node_modules'),
+ join(layout, 'external-rest-api/node_modules'),
+ 'dir'
+ )
+ for (const relativePath of [
+ 'control-api/src/bannedDevSigningKeys.ts',
+ 'control-api/src/devSigningKeys.ts',
+ 'control-api/test/fixtures/bannedDevJwtPublicKeys.ts',
+ ]) {
+ const fixturePath = join(layout, relativePath)
+ mkdirSync(dirname(fixturePath), { recursive: true })
+ symlinkSync(join(repoRoot, relativePath), fixturePath)
+ }
+ expect(existsSync(join(layout, 'rpc-proxy/node_modules'))).toBe(false)
+ const runner = `
+ const { defineDevJwtVerifierContract } = require(${JSON.stringify(helperPath)});
+ const it = () => {}; it.each = () => () => {};
+ defineDevJwtVerifierContract({
+ service: 'external-rest-api', slot: 'session', envName: 'EXTERNAL_REST_API_JWT_PUBLIC_KEY',
+ configSource: new URL(${JSON.stringify(pathToFileURL(callerPath).href)}),
+ loadConfig: async () => { throw new Error('Registration must not load configuration'); },
+ testApi: { beforeEach() {}, afterEach() {}, describe(_name, run) { run(); }, it, vi: {} }
+ });
+ process.stdout.write('caller-dependencies-ok');
+ `
+ expect(
+ execFileSync(
+ process.execPath,
+ ['--import', serviceRequire.resolve('tsx'), '-e', runner],
+ {
+ cwd: join(layout, 'external-rest-api'),
+ env: process.env,
+ encoding: 'utf8',
+ timeout: 15_000,
+ maxBuffer: 64 * 1024,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+ )
+ ).toBe('caller-dependencies-ok')
+ })
+ }
+
+ for (const [encoding, encode] of Object.entries(encodings)) {
+ it(`accepts a fresh operator ${encoding} verifier in production outside dev mode`, async () => {
+ useProductionEnvironment()
+ process.env[contract.envName] = encode(freshPublic)
+ expect((await contract.loadConfig()).config.jwtPublicKey).toBe(freshPublic)
+ })
+ for (const [slot, bannedPublic] of Object.entries(BANNED_DEV_JWT_PUBLIC_KEYS)) {
+ it(`rejects the historical ${slot} verifier as ${encoding} in production`, async () => {
+ useProductionEnvironment()
+ process.env[contract.envName] = encode(bannedPublic)
+ await expect(contract.loadConfig).rejects.toThrow(/historically committed dev JWT key/)
+ })
+ }
+ }
+ it.each([undefined, ''])(
+ 'fails closed in production with a missing or blank verifier (%j)',
+ async value => {
+ useProductionEnvironment()
+ if (value === undefined) delete process.env[contract.envName]
+ else process.env[contract.envName] = value
+ await expect(contract.loadConfig).rejects.toThrow(
+ new RegExp(`Missing required environment variable: ${contract.envName}`)
+ )
+ }
+ )
+ it('rejects production dev mode even when an operator verifier is supplied', async () => {
+ useProductionEnvironment()
+ process.env.CLERUM_DEV_MODE = 'true'
+ process.env[contract.envName] = freshPublic
+ await expect(contract.loadConfig).rejects.toThrow(
+ /CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production/
+ )
+ })
+ for (const [encoding, encode] of Object.entries(encodings)) {
+ for (const source of ['env', 'store']) {
+ it(`accepts fresh RSA ${encoding} from ${source} and uses canonical SPKI`, async () => {
+ if (source === 'env') {
+ delete process.env.CLERUM_DEV_MODE
+ process.env[contract.envName] = encode(freshPublic)
+ } else publishPublic(encode(freshPublic))
+ expect((await contract.loadConfig()).config.jwtPublicKey).toBe(freshPublic)
+ })
+ for (const [slot, bannedPublic] of Object.entries(BANNED_DEV_JWT_PUBLIC_KEYS)) {
+ it(`rejects the historical ${slot} identity as ${encoding} from ${source}`, async () => {
+ if (source === 'env') {
+ delete process.env.CLERUM_DEV_MODE
+ process.env[contract.envName] = encode(bannedPublic)
+ } else publishPublic(encode(bannedPublic))
+ await expect(contract.loadConfig).rejects.toThrow(/historically committed dev JWT key/)
+ })
+ }
+ }
+ }
+ for (const source of ['env', 'store']) {
+ it(`rejects malformed public material from ${source}`, async () => {
+ if (source === 'env') process.env[contract.envName] = 'not a PEM key'
+ else publishPublic('not a PEM key')
+ await expect(contract.loadConfig).rejects.toThrow(/PEM-encoded RSA public key/)
+ })
+ it(`rejects a non-RSA public key from ${source}`, async () => {
+ const ecPublic = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
+ .publicKey.export({ type: 'spki', format: 'pem' })
+ .toString()
+ if (source === 'env') process.env[contract.envName] = ecPublic
+ else publishPublic(ecPublic)
+ await expect(contract.loadConfig).rejects.toThrow(/PEM-encoded RSA public key/)
+ })
+ for (const escaped of [false, true]) {
+ it(`rejects a ${escaped ? 'escaped' : 'literal'} multi-PEM bundle from ${source}`, async () => {
+ const bundle = `${freshPublic}\n${BANNED_DEV_JWT_PUBLIC_KEYS.admin}`
+ const value = escaped ? encodings.escaped(bundle) : bundle
+ if (source === 'env') process.env[contract.envName] = value
+ else publishPublic(value)
+ await expect(contract.loadConfig).rejects.toThrow(/single PEM-encoded RSA public key/)
+ })
+ }
+ }
+ it('prefers an explicit verifier over an unused relative store override', async () => {
+ process.env[contract.envName] = freshPublic
+ process.env.EVENFIRE_DEV_KEY_STORE = 'unused-relative-store'
+ expect((await contract.loadConfig()).config.jwtPublicKey).toBe(freshPublic)
+ })
+ it('rejects a relative store override before reading any key', async () => {
+ process.env.EVENFIRE_DEV_KEY_STORE = 'relative-store'
+ await expect(contract.loadConfig).rejects.toThrow(
+ /EVENFIRE_DEV_KEY_STORE must be an absolute path/
+ )
+ })
+ it('fails loud when the producer public file is missing', async () => {
+ await expect(contract.loadConfig).rejects.toThrow(/requires the control-api dev key store/)
+ })
+ it('rejects a symlinked store directory', async () => {
+ rmdirSync(store)
+ const target = join(layout, 'directory-target')
+ mkdirSync(target, { mode: 0o700 })
+ writeFileSync(join(target, publicFile), freshPublic, { mode: 0o644 })
+ symlinkSync(target, store)
+ await expect(contract.loadConfig).rejects.toThrow(/not a directory/)
+ })
+ it('rejects a store path that is a regular file', async () => {
+ rmdirSync(store)
+ writeFileSync(store, 'not a directory')
+ await expect(contract.loadConfig).rejects.toThrow(/not a directory/)
+ })
+ it('rejects a directory with group or other permissions', async () => {
+ publishPublic()
+ chmodSync(store, 0o755)
+ await expect(contract.loadConfig).rejects.toThrow(/directory has group\/other permissions/)
+ })
+ it('rejects a directory owned by another user', async () => {
+ publishPublic()
+ const uid = process.geteuid!()
+ vi.spyOn(process, 'geteuid').mockReturnValue(uid + 1)
+ await expect(contract.loadConfig).rejects.toThrow(
+ /directory is not owned by the current user/
+ )
+ })
+ it('rejects a symlinked public file', async () => {
+ const target = join(layout, 'public-target.pem')
+ writeFileSync(target, freshPublic, { mode: 0o644 })
+ symlinkSync(target, join(store, publicFile))
+ await expect(contract.loadConfig).rejects.toThrow(/symbolic link/)
+ })
+ it('rejects a public path that is not a regular file', async () => {
+ mkdirSync(join(store, publicFile))
+ await expect(contract.loadConfig).rejects.toThrow(/not a regular file/)
+ })
+ it('rejects group or other writable public files', async () => {
+ publishPublic()
+ chmodSync(join(store, publicFile), 0o666)
+ await expect(contract.loadConfig).rejects.toThrow(
+ /public file must not be group\/other writable/
+ )
+ })
+ it('rejects a public file owned by another user', async () => {
+ publishPublic()
+ const uid = process.geteuid!()
+ vi.spyOn(process, 'geteuid')
+ .mockReturnValueOnce(uid)
+ .mockReturnValue(uid + 1)
+ await expect(contract.loadConfig).rejects.toThrow(/file is not owned by the current user/)
+ })
+ it('fails closed outside dev mode when the verifier is missing', async () => {
+ delete process.env.CLERUM_DEV_MODE
+ await expect(contract.loadConfig).rejects.toThrow(
+ new RegExp(`Missing required environment variable: ${contract.envName}`)
+ )
+ })
+ })
+}
diff --git a/rpc-proxy/src/testJwtKey.setup.ts b/rpc-proxy/test/testJwtKey.setup.ts
similarity index 87%
rename from rpc-proxy/src/testJwtKey.setup.ts
rename to rpc-proxy/test/testJwtKey.setup.ts
index c7be87ddc..6e924e25a 100644
--- a/rpc-proxy/src/testJwtKey.setup.ts
+++ b/rpc-proxy/test/testJwtKey.setup.ts
@@ -1,7 +1,7 @@
import { generateKeyPairSync } from 'node:crypto'
/**
- * Shared test fixture: a real, randomly generated RSA public key so config
+ * Test-only fixture: a real, randomly generated RSA public key so config
* suites exercise the non-dev path without the removed historical default.
* Suites that verify missing-key behavior delete this variable explicitly.
*/
diff --git a/rpc-proxy/vitest.config.ts b/rpc-proxy/vitest.config.ts
index 0e78da48f..15644fae2 100644
--- a/rpc-proxy/vitest.config.ts
+++ b/rpc-proxy/vitest.config.ts
@@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- setupFiles: ['../scripts/testing/bind-loopback-in-tests.mjs', 'src/testJwtKey.setup.ts'],
+ setupFiles: ['../scripts/testing/bind-loopback-in-tests.mjs', 'test/testJwtKey.setup.ts'],
include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
exclude: ['dist/**', 'node_modules/**'],
},