Skip to content

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

TypeScript

fix(verifiers): fail closed and ban historical dev JWT verifier keys

Alfredo Lopezd4a4be33285a
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 3a52cd988..de260ddcc 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"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 a552b0270..399bf509d 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"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 90e6ae896..7709291a1 100644
--- a/control-api/src/devSigningKeys.ts
+++ b/control-api/src/devSigningKeys.ts
@@ -1,9 +1,13 @@
import { createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto'
import {
type Stats,
+ closeSync,
+ constants,
+ fstatSync,
linkSync,
lstatSync,
mkdirSync,
+ openSync,
readFileSync,
unlinkSync,
writeFileSync,
@@ -28,20 +32,75 @@ export function defaultDevSigningKeyStoreDir(): string {
return DEFAULT_STORE_DIR
}
-function assertOwnedRegularFile(filePath: string): void {
- const stats = lstatSync(filePath, { throwIfNoEntry: false })
- if (!stats) throw new Error(`Dev JWT key store file is missing after creation: ${filePath}`)
- if (stats.isSymbolicLink() || !stats.isFile()) {
+type StoreFileVisibility = 'owner-only' | 'shared-read'
+
+function assertStoreFileStats(
+ filePath: string,
+ stats: Stats,
+ visibility: StoreFileVisibility
+): void {
+ if (!stats.isFile()) {
throw new Error(`Dev JWT key store path is not a regular file: ${filePath}`)
}
if (process.geteuid && stats.uid !== process.geteuid()) {
throw new Error(`Dev JWT key store file is not owned by the current user: ${filePath}`)
}
- if ((stats.mode & 0o077) !== 0) {
+ if (visibility === 'owner-only' && (stats.mode & 0o077) !== 0) {
throw new Error(
`Dev JWT key store file has group/other permissions; expected 0600: ${filePath}`
)
}
+ if (visibility === 'shared-read' && (stats.mode & 0o022) !== 0) {
+ throw new Error(`Dev JWT key store public file must not be group/other writable: ${filePath}`)
+ }
+}
+
+/**
+ * Opens an existing store file without following symlinks and validates the
+ * opened descriptor itself, eliminating check-then-read filesystem races.
+ * Returns undefined only for ENOENT; the caller owns and must close the fd.
+ */
+function openStoreFileNoFollow(
+ filePath: string,
+ visibility: StoreFileVisibility
+): number | undefined {
+ let fd: number | undefined
+ try {
+ fd = openSync(filePath, constants.O_RDONLY | constants.O_NOFOLLOW)
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code
+ if (code === 'ENOENT') return undefined
+ if (code === 'ELOOP') {
+ throw new Error(`Dev JWT key store path is a symbolic link: ${filePath}`)
+ }
+ throw err
+ }
+ try {
+ assertStoreFileStats(filePath, fstatSync(fd), visibility)
+ } catch (err) {
+ closeSync(fd)
+ throw err
+ }
+ return fd
+}
+
+function readStoreFileNoFollow(
+ filePath: string,
+ visibility: StoreFileVisibility
+): string | undefined {
+ const fd = openStoreFileNoFollow(filePath, visibility)
+ if (fd === undefined) return undefined
+ try {
+ return readFileSync(fd, 'utf8')
+ } finally {
+ closeSync(fd)
+ }
+}
+
+function assertOwnedRegularFile(filePath: string): void {
+ const fd = openStoreFileNoFollow(filePath, 'owner-only')
+ if (fd === undefined) throw new Error(`Dev JWT key store file is missing: ${filePath}`)
+ closeSync(fd)
}
function assertOwnedPrivateDirectory(dirPath: string, stats: Stats): void {
@@ -76,26 +135,14 @@ function ensureStoreDir(storeDir: string): void {
}
function readPersistedKey(filePath: string, slot: DevJwtSlot): string | undefined {
- const stats = lstatSync(filePath, { throwIfNoEntry: false })
- if (!stats) return undefined
- if (stats.isSymbolicLink() || !stats.isFile()) {
- throw new Error(`Dev JWT key store path is not a regular file: ${filePath}`)
- }
- if (process.geteuid && stats.uid !== process.geteuid()) {
- throw new Error(`Dev JWT key store file is not owned by the current user: ${filePath}`)
- }
- if ((stats.mode & 0o077) !== 0) {
- throw new Error(
- `Dev JWT key store file has group/other permissions; expected 0600: ${filePath}`
- )
- }
- let raw: string
+ let raw: string | undefined
try {
- raw = readFileSync(filePath, 'utf8')
+ raw = readStoreFileNoFollow(filePath, 'owner-only')
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined
throw err
}
+ if (raw === undefined) return undefined
try {
return validateRsaPrivateKeyPem(raw.trim(), `${slot} dev signing key`)
} catch (err) {
@@ -108,12 +155,7 @@ function readPersistedKey(filePath: string, slot: DevJwtSlot): string | undefine
let warnedOnce = false
function readStoredDerivedPublic(publicPath: string): string | undefined {
- const stats = lstatSync(publicPath, { throwIfNoEntry: false })
- if (!stats) return undefined
- if (stats.isSymbolicLink() || !stats.isFile()) {
- throw new Error(`Dev JWT key store public path is not a regular file: ${publicPath}`)
- }
- return readFileSync(publicPath, 'utf8').trim()
+ return readStoreFileNoFollow(publicPath, 'shared-read')?.trim()
}
/**
@@ -172,7 +214,6 @@ export function loadOrGenerateDevJwtPrivateKey(
if (existing) {
warnOnce()
ensureDerivedPublicKey(slot, storeDir, existing)
- warnOnce()
return existing
}
const { privateKey } = generateKeyPairSync('rsa', {
@@ -198,18 +239,15 @@ export function loadOrGenerateDevJwtPrivateKey(
if (winner) {
warnOnce()
ensureDerivedPublicKey(slot, storeDir, winner)
- warnOnce()
return winner
}
}
throw err
}
assertOwnedRegularFile(filePath)
- assertOwnedRegularFile(filePath)
ensureDerivedPublicKey(slot, storeDir, privateKey)
warnOnce()
return privateKey.trim()
- return privateKey.trim()
}
function warnOnce(): void {
diff --git a/control-api/test/bannedDevSigningKeys.test.ts b/control-api/test/bannedDevSigningKeys.test.ts
index fe8fc4a35..9254d000a 100644
--- a/control-api/test/bannedDevSigningKeys.test.ts
+++ b/control-api/test/bannedDevSigningKeys.test.ts
@@ -88,7 +88,6 @@ describe('bannedDevSigningKeys', () => {
it('rejects a banned verifier public key and mismatched overrides', () => {
const fresh = makeFresh()
- const offender = makeOffender()
expect(() =>
assertGuard(
{
diff --git a/control-api/test/devSigningKeys.test.ts b/control-api/test/devSigningKeys.test.ts
index c6d30aaf7..e5139d442 100644
--- a/control-api/test/devSigningKeys.test.ts
+++ b/control-api/test/devSigningKeys.test.ts
@@ -144,7 +144,7 @@ describe('devSigningKeys persistence contract', () => {
loadOrGenerateDevJwtPrivateKey('admin', realStore)
mkdirSync(linkStore, { mode: 0o700 })
symlinkSync(join(realStore, 'admin.pem'), join(linkStore, 'admin.pem'))
- expect(() => loadOrGenerateDevJwtPrivateKey('admin', linkStore)).toThrow(/not a regular file/)
+ expect(() => loadOrGenerateDevJwtPrivateKey('admin', linkStore)).toThrow(/symbolic link/)
})
it('reuses the same identity across real separate processes', async () => {
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index c47638178..8871fc8a4 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.86",
+ "version": "0.1.87",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.86",
+ "version": "0.1.87",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 01619c163..af99d812a 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.86",
+ "version": "0.1.87",
"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 8da3d6f0e..00eb53e84 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -1,3 +1,4 @@
+import { createHash, createPublicKey } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -90,16 +91,6 @@ function normalizePem(value: string): string {
return value.replace(/\\n/g, '\n').trim()
}
-const DEV_SESSION_JWT_PUBLIC_KEY = normalizePem(`-----BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwrZja9jS/r+e2YF1FqEQ
-NMLsnffebYzXrZOb7uPMKhXBoKjJh/taR9v3kX2srfVtoikcKKr0Sfa7MMSLnZWd
-ETmi7MvbeVD3HpsXpVejmw9D0zeYYSGZplLF/b6HY0Lz2XVM8WdJl3Dicyu+SZbZ
-xeHZtMCMTTjvmoI/IYmmO4N3Pgz/SGi7V3EiwoALODP4OWDvd/1xFUiMPslLPgZU
-EczQ5tIpAaD4e0om3gUNsyOKYc5igojm6ooVqI9T3TUGBVJ0uSZB7ntWxKQ39WyI
-aH+oqnwDGbDcDLQ/wTuBtcn4brWTDgW1xA73HVBSImGFvvHCWBiQBiI1nvovUP0u
-WQIDAQAB
------END PUBLIC KEY-----`)
-
const EXTERNAL_GFS_EDGE_AGGREGATE_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN'
const EXTERNAL_GFS_EDGE_CLIENT_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN'
const EXTERNAL_GFS_EDGE_TOKEN_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN'
@@ -148,31 +139,59 @@ function serviceRoot(): string {
return typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
}
+const HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS: ReadonlySet<string> = new Set([
+ '4292d721765a93b0275f9f4ceb0a4667517fae00b5face8faa270513d610bb27',
+ 'f7dc08c248bf2b7724dead80dd96f9a5eeb49cf9920ba6fb46cf457a788d503e',
+ '2d05f607d125e4bd3c157d5c6115bf63cb454c1e45cc5bcc8eed950771dcfd31',
+])
+
+function assertUsableJwtPublicKey(publicPem: string, envName: string): string {
+ let fingerprint: string
+ try {
+ const der = createPublicKey(publicPem).export({ type: 'spki', format: 'der' })
+ fingerprint = createHash('sha256').update(der).digest('hex')
+ } catch {
+ throw new Error(`${envName} must be a 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
+}
+
/**
- * In explicit dev mode, verify with the public half control-api publishes next
- * to its generated session signing key, so a monorepo dev boot keeps one
- * shared key identity across the signer and this verifier.
- * EVENFIRE_DEV_KEY_STORE can relocate the store; EXTERNAL_REST_API_JWT_PUBLIC_KEY
- * always takes precedence.
+ * Env var first; explicit dev mode loads the public half published next to the
+ * control-api signing key; every other mode fails closed. The resolved key is
+ * always fingerprint-checked so a historically committed public key is never
+ * accepted as a verifier.
*/
function resolveSessionJwtPublicKey(): string {
- const fromEnv = process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
- if (fromEnv) return fromEnv
+ const envName = 'EXTERNAL_REST_API_JWT_PUBLIC_KEY'
+ if (process.env.NODE_ENV === 'production' && process.env.CLERUM_DEV_MODE === 'true') {
+ throw new Error(
+ '[SECURITY] Startup rejected: CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production.'
+ )
+ }
+ 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 {
- return readFileSync(publicPath, 'utf8')
+ 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 EXTERNAL_REST_API_JWT_PUBLIC_KEY.'
+ `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
)
}
+ return assertUsableJwtPublicKey(fromStore, envName)
}
- return DEV_SESSION_JWT_PUBLIC_KEY
+ return required(envName)
}
+
export const config: Config = {
port: Number(process.env.EXTERNAL_REST_API_PORT || 8091),
jsonBodyLimit: process.env.EXTERNAL_REST_API_JSON_BODY_LIMIT || '150mb',
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index f1c578244..bf309424c 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.86',
- rpcProxyVersion: '0.1.112',
+ externalRestApiVersion: '0.1.87',
+ rpcProxyVersion: '0.1.113',
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 370c905d0..bc9a72e83 100644
--- a/external-rest-api/test/config.devKeyStore.test.ts
+++ b/external-rest-api/test/config.devKeyStore.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateKeyPairSync } from 'node:crypto'
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -56,4 +56,53 @@ describe('external-rest-api shared dev key identity', () => {
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/
+ )
+ })
})
diff --git a/external-rest-api/test/testJwtKey.setup.ts b/external-rest-api/test/testJwtKey.setup.ts
new file mode 100644
index 000000000..8711ed97f
--- /dev/null
+++ b/external-rest-api/test/testJwtKey.setup.ts
@@ -0,0 +1,18 @@
+import { generateKeyPairSync } from 'node:crypto'
+
+/**
+ * Shared test 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.
+ */
+function testPublicKey(): string {
+ return generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+}
+
+if (!process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY) {
+ process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = testPublicKey()
+}
diff --git a/external-rest-api/vitest.config.ts b/external-rest-api/vitest.config.ts
index bc7655069..15644fae2 100644
--- a/external-rest-api/vitest.config.ts
+++ b/external-rest-api/vitest.config.ts
@@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- setupFiles: ['../scripts/testing/bind-loopback-in-tests.mjs'],
+ 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/**'],
},
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 6e2967f85..c4fee10b4 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.112",
+ "version": "0.1.113",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.112",
+ "version": "0.1.113",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index ed2a02696..b0d3ec855 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.112",
+ "version": "0.1.113",
"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 c15d4d262..91b4cd14a 100644
--- a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
+++ b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateKeyPairSync } from 'node:crypto'
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -56,4 +56,47 @@ describe('rpc-proxy shared dev key identity', () => {
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/
+ )
+ })
})
diff --git a/rpc-proxy/src/config.ts b/rpc-proxy/src/config.ts
index 7931162ca..0e4a6f397 100644
--- a/rpc-proxy/src/config.ts
+++ b/rpc-proxy/src/config.ts
@@ -1,3 +1,4 @@
+import { createHash, createPublicKey } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -177,16 +178,6 @@ export function parseWakeMaxHoldMs(raw: string): number {
return MAX_REQUEST_HOLD_MS
}
-const DEV_RPC_JWT_PUBLIC_KEY = normalizePem(`-----BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArCIYGHehMPpGKePxaKQa
-rDX5yrzifU5i4fzpI3EtkKSU6s5ug7EkKxc2DdMekoqXe9vr7qKyVwiilUIusXLX
-iW7KPMJlD/Fd5Bo7Qxt69wYiL5I4K37eDgCN6D3LduHySEnkhdI0GDpB4LM2ASOx
-QkEabepekZTMQyExmCIn/dHJ15B+4A9tiiephYOQNr3GcnW9eDomMt6NJLypikbr
-xJO6O7Ar0G+raTbflth8EQzWnGF+WgQW4iiM3wsFhpaE0mUlEbMGDGTMAZy1KfxA
-RRu+QZm3Lo+5AiCaHkijDCglHsXLhqsYi2AdRiavD1Gk9LKP/ztKw7q/D6fYFzmO
-QwIDAQAB
------END PUBLIC KEY-----`)
-
function serviceRoot(): string {
// Works in every supported runtime: CommonJS (dist and ts-node) resolves
// __dirname to <service>/dist or <service>/src; Vitest's ESM transform falls
@@ -194,30 +185,59 @@ function serviceRoot(): string {
return typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
}
+const HISTORICAL_DEV_JWT_PUBLIC_FINGERPRINTS: ReadonlySet<string> = new Set([
+ '4292d721765a93b0275f9f4ceb0a4667517fae00b5face8faa270513d610bb27',
+ 'f7dc08c248bf2b7724dead80dd96f9a5eeb49cf9920ba6fb46cf457a788d503e',
+ '2d05f607d125e4bd3c157d5c6115bf63cb454c1e45cc5bcc8eed950771dcfd31',
+])
+
+function assertUsableJwtPublicKey(publicPem: string, envName: string): string {
+ let fingerprint: string
+ try {
+ const der = createPublicKey(publicPem).export({ type: 'spki', format: 'der' })
+ fingerprint = createHash('sha256').update(der).digest('hex')
+ } catch {
+ throw new Error(`${envName} must be a 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
+}
+
/**
- * In explicit dev mode, verify with the public half control-api publishes next
- * to its generated RPC signing key, so a monorepo dev boot keeps one shared
- * key identity across the signer and this verifier. EVENFIRE_DEV_KEY_STORE can
- * relocate the store; RPC_PROXY_JWT_PUBLIC_KEY always takes precedence.
+ * Env var first; explicit dev mode loads the public half published next to the
+ * control-api signing key; every other mode fails closed. The resolved key is
+ * always fingerprint-checked so a historically committed public key is never
+ * accepted as a verifier.
*/
function resolveRpcJwtPublicKey(): string {
- const fromEnv = process.env.RPC_PROXY_JWT_PUBLIC_KEY
- if (fromEnv) return fromEnv
+ const envName = 'RPC_PROXY_JWT_PUBLIC_KEY'
+ if (process.env.NODE_ENV === 'production' && process.env.CLERUM_DEV_MODE === 'true') {
+ throw new Error(
+ '[SECURITY] Startup rejected: CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production.'
+ )
+ }
+ 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 {
- return readFileSync(publicPath, 'utf8')
+ 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 RPC_PROXY_JWT_PUBLIC_KEY.'
+ `Start control-api once with CLERUM_DEV_MODE=true, or set ${envName}.`
)
}
+ return assertUsableJwtPublicKey(fromStore, envName)
}
- return DEV_RPC_JWT_PUBLIC_KEY
+ return required(envName)
}
+
export const config: Config = {
port: Number(process.env.RPC_PROXY_PORT || 8094),
corsOrigin: parseCorsOrigin(
diff --git a/rpc-proxy/src/testJwtKey.setup.ts b/rpc-proxy/src/testJwtKey.setup.ts
new file mode 100644
index 000000000..c7be87ddc
--- /dev/null
+++ b/rpc-proxy/src/testJwtKey.setup.ts
@@ -0,0 +1,18 @@
+import { generateKeyPairSync } from 'node:crypto'
+
+/**
+ * Shared test 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.
+ */
+function testPublicKey(): string {
+ return generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+}
+
+if (!process.env.RPC_PROXY_JWT_PUBLIC_KEY) {
+ process.env.RPC_PROXY_JWT_PUBLIC_KEY = testPublicKey()
+}
diff --git a/rpc-proxy/vitest.config.ts b/rpc-proxy/vitest.config.ts
index bc7655069..0e78da48f 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'],
+ setupFiles: ['../scripts/testing/bind-loopback-in-tests.mjs', 'src/testJwtKey.setup.ts'],
include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
exclude: ['dist/**', 'node_modules/**'],
},