Skip to content

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

TypeScript

fix(auth): centralize JWT identity and close regression seams

Alfredo Lopez0d44636abe0e
diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml
index c0e860060..114baefd9 100644
--- a/.github/workflows/build-publish.yml
+++ b/.github/workflows/build-publish.yml
@@ -124,6 +124,7 @@ jobs:
- 'packages/workflow-runtime-core/**'
- 'packages/workflow-recipe-capability-policy/**'
- 'packages/image-policy/**'
+ - 'packages/jwt-key-policy/**'
- 'packages/display-field/**'
- 'packages/llm-provider-attempt-contract/**'
- 'packages/grok-provider-attempt-contract/**'
@@ -135,6 +136,7 @@ jobs:
- 'packages/gfs-interaction-policy/**'
external-rest-api:
- 'external-rest-api/**'
+ - 'packages/jwt-key-policy/**'
host-context-controller:
- 'host-context-controller/**'
- 'packages/workflow-recipe-capability-policy/**'
@@ -159,6 +161,7 @@ jobs:
- 'packages/frontend-components/**'
rpc-proxy:
- 'rpc-proxy/**'
+ - 'packages/jwt-key-policy/**'
workflow-recipes:
- 'workflow-recipes/**'
- 'packages/workflow-runtime-core/**'
@@ -268,6 +271,7 @@ jobs:
changed: ${{ needs.detect.outputs.control-ui }}
- image: external-rest-api
path: external-rest-api
+ rooted: true
changed: ${{ needs.detect.outputs.external-rest-api }}
- image: host-context-controller
path: host-context-controller
@@ -307,6 +311,7 @@ jobs:
changed: ${{ needs.detect.outputs.profile-ui }}
- image: rpc-proxy
path: rpc-proxy
+ rooted: true
changed: ${{ needs.detect.outputs.rpc-proxy }}
- image: workflow-recipes
path: workflow-recipes
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 886372784..9c1dc2048 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -69,6 +69,7 @@ jobs:
- packages/workflow-runtime-core
- packages/workflow-sdk
- packages/network-policy-core
+ - packages/jwt-key-policy
- packages/llm-provider-attempt-contract
- packages/llm-providers
- packages/grok-provider-attempt-contract
@@ -122,6 +123,11 @@ jobs:
working-directory: ${{ matrix.service }}
run: npm run build
+ - name: Typecheck JWT policy consumer contracts
+ if: matrix.service == 'control-api' || matrix.service == 'rpc-proxy' || matrix.service == 'external-rest-api'
+ working-directory: ${{ matrix.service }}
+ run: npm run typecheck:jwt-contract
+
- name: Install Playwright Chromium
if: matrix.service == 'desktop-app'
working-directory: desktop-app
@@ -217,7 +223,7 @@ jobs:
# no tsconfig and no typescript dependency), so `npx tsc` there would fetch
# the unrelated `tsc` package from the registry instead of typechecking.
- name: Typecheck (tsc --noEmit)
- if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/gfs-interaction-policy' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/llm-provider-attempt-contract' && matrix.service != 'packages/grok-provider-attempt-contract' && matrix.service != 'packages/llm-providers' && matrix.service != 'packages/codex-catalog-projection'
+ if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/gfs-interaction-policy' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/jwt-key-policy' && matrix.service != 'packages/llm-provider-attempt-contract' && matrix.service != 'packages/grok-provider-attempt-contract' && matrix.service != 'packages/llm-providers' && matrix.service != 'packages/codex-catalog-projection'
working-directory: ${{ matrix.service }}
run: npx tsc --noEmit
diff --git a/Makefile b/Makefile
index 644c872bc..8311725aa 100644
--- a/Makefile
+++ b/Makefile
@@ -82,6 +82,7 @@ TEST_SERVICES := \
packages/workflow-runtime-core \
packages/workflow-sdk \
packages/network-policy-core \
+ packages/jwt-key-policy \
packages/codex-catalog-projection \
packages/llm-provider-attempt-contract \
packages/llm-providers \
diff --git a/control-api/Dockerfile b/control-api/Dockerfile
index 55a70e52d..e433412d9 100644
--- a/control-api/Dockerfile
+++ b/control-api/Dockerfile
@@ -1,6 +1,8 @@
FROM node:24-alpine AS builder
WORKDIR /app
+# Prebuilt policy and POSIX store: copy only the production exports and types.
+COPY packages/jwt-key-policy/package.json packages/jwt-key-policy/index.cjs packages/jwt-key-policy/index.d.ts packages/jwt-key-policy/dev-store.cjs packages/jwt-key-policy/dev-store.d.ts ./packages/jwt-key-policy/
COPY packages/workflow-recipe-capability-policy ./packages/workflow-recipe-capability-policy
COPY packages/image-policy ./packages/image-policy
# Shared prebuilt data-only providers package (no build step). Copied before
diff --git a/control-api/Dockerfile.dockerignore b/control-api/Dockerfile.dockerignore
index d2a770244..b70ffa9ce 100644
--- a/control-api/Dockerfile.dockerignore
+++ b/control-api/Dockerfile.dockerignore
@@ -1,5 +1,11 @@
**
!packages/
+!packages/jwt-key-policy/
+!packages/jwt-key-policy/package.json
+!packages/jwt-key-policy/index.cjs
+!packages/jwt-key-policy/index.d.ts
+!packages/jwt-key-policy/dev-store.cjs
+!packages/jwt-key-policy/dev-store.d.ts
!packages/workflow-recipe-capability-policy/
!packages/workflow-recipe-capability-policy/**
!packages/image-policy/
diff --git a/control-api/README.md b/control-api/README.md
index dbbc2d0d3..6ed517766 100644
--- a/control-api/README.md
+++ b/control-api/README.md
@@ -205,6 +205,38 @@ Outside dev mode, `CONTROL_API_RPC_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.
+All three services use `@clerum/jwt-key-policy` to select one complete PEM
+object and canonicalize its identity before signing or verification. Signing
+inputs accept unencrypted RSA PKCS#8/PKCS#1 private keys. Verifier environment
+variables accept RSA SPKI/PKCS#1 public keys and X509 public-key carriers;
+private PEMs remain accepted there for legacy compatibility, but configuring
+only the public half is recommended. X509 is a key carrier here: CA trust,
+hostname and certificate expiry are not validated. A public store file must
+never contain private material. Bundles, encrypted private keys, non-RSA keys
+and historically committed identities are rejected.
+
+RSA keys must have at least 2048 bits for every RS256 signing and verification
+role, including registry vouchers and proof-of-possession. This deliberately
+rejects weak verifier keys previously accepted; see
+[RFC 7518 section 3.3](https://www.rfc-editor.org/rfc/rfc7518.html#section-3.3).
+Material and descriptor reads are limited to 64 KiB. Invalid explicit input
+fails instead of generating a replacement or changing its source.
+
+The local store requires POSIX no-follow, nonblocking and exclusive-file
+guarantees. Keep its ancestors trusted and run cooperating services with the
+same effective UID; users or containers with another UID should configure
+their keys explicitly. The store does not defend against hostile ancestors or
+processes with the same UID. On a platform without these guarantees, configure
+all signing and verifying keys through the environment; explicit keys do not
+access the store. Stored-key corruption, or a rejected persisted registry key,
+requires explicit operator repair or re-enrollment. Startup never rotates,
+rewrites or deletes those identities automatically.
+
+Build the service image from the repository root with
+`docker build -f control-api/Dockerfile .`. Its context and runtime contain
+only the shared policy's production files and declarations, not its tests or
+local key data.
+
- `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.
- `CONTROL_API_JWT_AUDIENCE`: expected `aud` for session token signing and verification.
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index f0f315c32..d819ebf63 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,16 +1,17 @@
{
"name": "clerum-control-api",
- "version": "0.1.688",
+ "version": "0.1.689",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.688",
+ "version": "0.1.689",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
"@clerum/image-policy": "file:../packages/image-policy",
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
@@ -59,6 +60,14 @@
"version": "0.1.0",
"license": "MIT"
},
+ "../packages/jwt-key-policy": {
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ }
+ },
"../packages/llm-provider-attempt-contract": {
"name": "@clerum/llm-provider-attempt-contract",
"version": "0.1.0",
@@ -102,6 +111,10 @@
"resolved": "../packages/image-policy",
"link": true
},
+ "node_modules/@clerum/jwt-key-policy": {
+ "resolved": "../packages/jwt-key-policy",
+ "link": true
+ },
"node_modules/@clerum/llm-provider-attempt-contract": {
"resolved": "../packages/llm-provider-attempt-contract",
"link": true
diff --git a/control-api/package.json b/control-api/package.json
index bf10b20e9..d3ad9b7fc 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.688",
+ "version": "0.1.689",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
@@ -13,12 +13,14 @@
"start:trace-maintenance": "node dist/traceMaintenance.js",
"dev": "ts-node src/main.ts",
"test": "vitest run --no-file-parallelism",
- "test:run": "vitest run --no-file-parallelism"
+ "test:run": "vitest run --no-file-parallelism",
+ "typecheck:jwt-contract": "tsc -p tsconfig.jwt-contract-tests.json --noEmit && tsc -p tsconfig.jwt-package-types.json --noEmit"
},
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
"@clerum/image-policy": "file:../packages/image-policy",
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-api/src/bannedDevSigningKeys.ts b/control-api/src/bannedDevSigningKeys.ts
index dea533970..9b1e51506 100644
--- a/control-api/src/bannedDevSigningKeys.ts
+++ b/control-api/src/bannedDevSigningKeys.ts
@@ -1,97 +1,36 @@
-import { type KeyObject, createHash, createPrivateKey, createPublicKey } from 'node:crypto'
+import {
+ HISTORICAL_PUBLIC_KEY_FINGERPRINTS,
+ isBannedPublicKeyPem,
+ isBannedSigningKeyPem,
+ parseSigningMaterial,
+ parseVerifierMaterial,
+ publicKeyPemFingerprint,
+} from '@clerum/jwt-key-policy'
-/**
- * SHA-256 fingerprints over the public SPKI DER halves of the three RSA keys
- * that were once committed to this repository as dev JWT signing defaults.
- * The private keys were removed; these fingerprints permanently ban them from
- * every signing and verifying slot. Fingerprints of public keys are not
- * secrets and carry no signing material.
- */
-export const BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS: ReadonlySet<string> = new Set([
- // Committed dev RPC JWT key (removed from src/config.ts).
- '4292d721765a93b0275f9f4ceb0a4667517fae00b5face8faa270513d610bb27',
- // Committed dev session JWT key (removed from src/config.ts).
- 'f7dc08c248bf2b7724dead80dd96f9a5eeb49cf9920ba6fb46cf457a788d503e',
- // Committed dev admin JWT key (removed from src/config.ts).
- '2d05f607d125e4bd3c157d5c6115bf63cb454c1e45cc5bcc8eed950771dcfd31',
-])
+export { isBannedPublicKeyPem, isBannedSigningKeyPem, publicKeyPemFingerprint }
-function spkiDerFingerprint(key: KeyObject | string): string {
- const keyObject = typeof key === 'string' ? createPublicKey(key) : key
- const der = keyObject.export({ type: 'spki', format: 'der' })
- return createHash('sha256').update(der).digest('hex')
-}
-
-export function publicKeyPemFingerprint(publicKeyPem: string): string {
- return spkiDerFingerprint(publicKeyPem)
-}
-
-export function isBannedPublicKeyPem(
- publicKeyPem: string,
- fingerprints: ReadonlySet<string> = BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS
-): boolean {
- try {
- return fingerprints.has(publicKeyPemFingerprint(publicKeyPem))
- } catch {
- return false
- }
-}
-
-export function isBannedSigningKeyPem(
- privateKeyPem: string,
- fingerprints: ReadonlySet<string> = BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS
-): boolean {
- try {
- const signingKey = createPrivateKey(privateKeyPem)
- return fingerprints.has(spkiDerFingerprint(createPublicKey(signingKey)))
- } catch {
- return false
- }
-}
+// Preserve the legacy ReadonlySet API without exposing a mutable policy Set.
+export const BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS: ReadonlySet<string> = Object.freeze({
+ size: HISTORICAL_PUBLIC_KEY_FINGERPRINTS.length,
+ has: (value: string) => HISTORICAL_PUBLIC_KEY_FINGERPRINTS.includes(value),
+ entries: () =>
+ HISTORICAL_PUBLIC_KEY_FINGERPRINTS.map(value => [value, value] as [string, string]).values(),
+ keys: () => HISTORICAL_PUBLIC_KEY_FINGERPRINTS.values(),
+ values: () => HISTORICAL_PUBLIC_KEY_FINGERPRINTS.values(),
+ [Symbol.iterator]: () => HISTORICAL_PUBLIC_KEY_FINGERPRINTS.values(),
+ forEach(
+ callback: (value: string, key: string, set: ReadonlySet<string>) => void,
+ thisArg?: unknown
+ ) {
+ for (const value of HISTORICAL_PUBLIC_KEY_FINGERPRINTS) {
+ callback.call(thisArg, value, value, BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS)
+ }
+ },
+})
-/**
- * Strict validation for configured signing keys: must parse as a PEM private
- * key, be RSA, and have at least a 2048-bit modulus so RS256 is safe to use.
- * Parse failures produce an error naming the environment variable; the PEM
- * itself is never included in the message.
- */
+/** Compatibility entry point; policy and canonical identity belong to the package. */
export function validateRsaPrivateKeyPem(privateKeyPem: string, envName: string): string {
- const envelopes = privateKeyPem.match(/-----BEGIN [A-Z0-9 ]*KEY-----/g) ?? []
- if (envelopes.length !== 1 || !/-----BEGIN (?:RSA )?PRIVATE KEY-----/.test(envelopes[0])) {
- throw new Error(
- `${envName} must contain exactly one PEM private key; concatenated key bundles are rejected.`
- )
- }
- let key: KeyObject
- try {
- key = createPrivateKey(privateKeyPem)
- } catch {
- throw new Error(
- `${envName} must be a PEM-encoded RSA private key (PKCS#8 or PKCS#1); parsing failed. ` +
- 'Public-key PEMs, truncated bodies, and escaped line breaks are rejected.'
- )
- }
- if (key.asymmetricKeyType !== 'rsa') {
- throw new Error(
- `${envName} must be an RSA key for RS256 signing (got '${key.asymmetricKeyType}')`
- )
- }
- const jwk = key.export({ format: 'jwk' }) as { n?: string }
- if (typeof jwk.n !== 'string') {
- throw new Error(`${envName} could not be inspected as a JWK; refusing to use it for RS256`)
- }
- const modulusBytes = Buffer.from(jwk.n, 'base64url')
- let firstNonZero = 0
- while (firstNonZero < modulusBytes.length && modulusBytes[firstNonZero] === 0) firstNonZero++
- const modulusBits =
- modulusBytes.length === firstNonZero
- ? 0
- : (modulusBytes.length - firstNonZero - 1) * 8 +
- Math.ceil(Math.log2(modulusBytes[firstNonZero] + 1))
- if (modulusBits < 2048) {
- throw new Error(`${envName} RSA modulus must be at least 2048 bits (got ${modulusBits})`)
- }
- return privateKeyPem
+ return parseSigningMaterial(privateKeyPem, envName).privatePem
}
export function assertNoBannedJwtKeys(
@@ -103,43 +42,27 @@ export function assertNoBannedJwtKeys(
rpcPublicKey: string
rpcPublicKeyEnvSet: boolean
},
- fingerprints: ReadonlySet<string> = BANNED_DEV_JWT_PUBLIC_KEY_FINGERPRINTS
+ fingerprints?: Iterable<string>
): void {
- const slots: Array<[envName: string, pem: string]> = [
- ['CONTROL_API_RPC_JWT_PRIVATE_KEY', input.rpcPrivateKey],
- ['CONTROL_API_SESSION_JWT_PRIVATE_KEY', input.sessionPrivateKey],
- ['CONTROL_API_ADMIN_JWT_PRIVATE_KEY', input.adminPrivateKey],
- ]
+ const options = { fingerprints }
+ const rpc = parseSigningMaterial(input.rpcPrivateKey, 'CONTROL_API_RPC_JWT_PRIVATE_KEY', options)
+ parseSigningMaterial(input.sessionPrivateKey, 'CONTROL_API_SESSION_JWT_PRIVATE_KEY', options)
+ parseSigningMaterial(input.adminPrivateKey, 'CONTROL_API_ADMIN_JWT_PRIVATE_KEY', options)
if (input.voucherPrivateKey) {
- slots.push(['CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY', input.voucherPrivateKey])
- }
- for (const [envName, pem] of slots) {
- if (isBannedSigningKeyPem(pem, fingerprints)) {
- throw new Error(
- `[SECURITY] Startup rejected: ${envName} resolves to a historically committed dev JWT key. ` +
- 'Replace it with a deployment-specific RSA key.'
- )
- }
+ parseSigningMaterial(
+ input.voucherPrivateKey,
+ 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY',
+ options
+ )
}
- if (isBannedPublicKeyPem(input.rpcPublicKey, fingerprints)) {
+ const verifier = parseVerifierMaterial(
+ input.rpcPublicKey,
+ 'effective RPC JWT verifier public key (CONTROL_API_RPC_JWT_PUBLIC_KEY)',
+ options
+ )
+ if (input.rpcPublicKeyEnvSet && verifier.fingerprint !== rpc.fingerprint) {
throw new Error(
- '[SECURITY] Startup rejected: the effective RPC JWT verifier public key is a historically ' +
- 'committed dev JWT key. Set CONTROL_API_RPC_JWT_PUBLIC_KEY to the public half of the ' +
- 'configured private key.'
+ 'CONTROL_API_RPC_JWT_PUBLIC_KEY must correspond to CONTROL_API_RPC_JWT_PRIVATE_KEY'
)
}
- if (input.rpcPublicKeyEnvSet) {
- let suppliedDer: Buffer
- try {
- suppliedDer = createPublicKey(input.rpcPublicKey).export({ type: 'spki', format: 'der' })
- } catch {
- throw new Error('CONTROL_API_RPC_JWT_PUBLIC_KEY must be a valid PEM-encoded public key')
- }
- const derivedDer = createPublicKey(input.rpcPrivateKey).export({ type: 'spki', format: 'der' })
- if (!derivedDer.equals(suppliedDer)) {
- throw new Error(
- 'CONTROL_API_RPC_JWT_PUBLIC_KEY must correspond to CONTROL_API_RPC_JWT_PRIVATE_KEY'
- )
- }
- }
}
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 96da371da..aa3638efc 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -1,8 +1,13 @@
import { createPublicKey } from 'node:crypto'
import { DEFAULT_ALLOWED_PLUGIN_IMAGE_PREFIXES } from '@clerum/image-policy'
-import { assertNoBannedJwtKeys, validateRsaPrivateKeyPem } from './bannedDevSigningKeys.js'
-import { type DevJwtSlot, loadOrGenerateDevJwtPrivateKey } from './devSigningKeys.js'
+import {
+ type SigningMaterial,
+ parseSigningMaterial,
+ parseVerifierMaterial,
+} from '@clerum/jwt-key-policy'
+import { type DevJwtSlot, loadOrCreateDevJwtSigningMaterial } from './devSigningKeys.js'
import { REACTIVE_REFRESH_BUFFER_MS } from './oauth/tokenHelper.js'
+import { rootLogger } from './observability/logger.js'
type Config = {
port: number
@@ -53,8 +58,8 @@ type Config = {
adminJwtTtlSeconds: number
/**
* Optional RS256 private key used exclusively to sign registry identity
- * vouchers (POST /api/v1/registry/identity-voucher). When unset, falls back
- * to adminJwtPrivateKey.
+ * vouchers (POST /api/v1/registry/identity-voucher). Managed mode requires
+ * this dedicated material; self-hosted mode resolves its enrolled identity.
*
* Rationale: a captured admin session JWT (aud=control-ui, 1h TTL) signed by
* the SAME key as a voucher (aud=registry-api, 60s TTL) becomes a usable
@@ -502,10 +507,6 @@ const EXTERNAL_GFS_OPERATION_RL_PER_MIN_CEILING = 180
// 100 requests per second from one source on one public admin route.
const ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN_CEILING = 6_000
-function normalizePem(value: string): string {
- return value.replace(/\\n/g, '\n').trim()
-}
-
function parseRegistryConnectionMode(): 'managed' | 'self-hosted' {
const raw = process.env.REGISTRY_CONNECTION_MODE
if (raw === undefined || raw === '') return 'managed' // default; requiredness enforced in the guard below
@@ -540,12 +541,13 @@ const externalRateLimitConfig = (() => {
operation.value <= session.value && session.value < clientIp.value
if (!followsRecommendedTopology) {
- console.warn(
- '[ControlAPI] External rate-limit configuration crosses the recommended operation <= session < clientIp topology; preserving exact configured values',
+ rootLogger.warn(
{
+ event: 'external_rate_limit_topology_advisory',
resolved: { operation, session, clientIp },
recommendedTopology: 'operation <= session < clientIp',
- }
+ },
+ 'External rate limits cross the recommended topology; preserving configured values'
)
}
@@ -577,24 +579,52 @@ const JWT_SIGNING_KEY_ENV_NAMES: Record<DevJwtSlot, string> = {
admin: 'CONTROL_API_ADMIN_JWT_PRIVATE_KEY',
}
-function resolveControlApiJwtPrivateKey(slot: DevJwtSlot): string {
- const envName = JWT_SIGNING_KEY_ENV_NAMES[slot]
- const fromEnv = process.env[envName]
- if (fromEnv) return validateRsaPrivateKeyPem(normalizePem(fromEnv), envName)
- if (CLERUM_DEV_MODE_ENABLED) return loadOrGenerateDevJwtPrivateKey(slot)
- return required(envName)
-}
-
function publicKeyFromPrivateKey(privateKey: string): string {
return createPublicKey(privateKey).export({ type: 'spki', format: 'pem' }).toString()
}
const DEV_ADMIN_PASSWORD_HASH = '$2b$12$9QdfGGp5KYg8osGa1n0.DuwQiB1RopCWIDJhmsuK4ygjTmIT8pvgy'
-const RPC_JWT_PRIVATE_KEY = resolveControlApiJwtPrivateKey('rpc')
-const RPC_JWT_PUBLIC_KEY = normalizePem(
- process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY || publicKeyFromPrivateKey(RPC_JWT_PRIVATE_KEY)
-)
+// Validate every explicit input before dev-store access. A malformed configured
+// slot must not cause another slot to generate a new local identity.
+const explicitJwtSigningMaterial: Partial<Record<DevJwtSlot, SigningMaterial>> = {}
+for (const slot of ['rpc', 'session', 'admin'] as const) {
+ const envName = JWT_SIGNING_KEY_ENV_NAMES[slot]
+ const raw = process.env[envName]
+ if (raw) explicitJwtSigningMaterial[slot] = parseSigningMaterial(raw, envName)
+}
+const voucherRaw = process.env.CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY
+const voucherMaterial = voucherRaw
+ ? parseSigningMaterial(voucherRaw, 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY')
+ : undefined
+const rpcVerifierRaw = process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY
+const explicitRpcVerifier = rpcVerifierRaw
+ ? parseVerifierMaterial(
+ rpcVerifierRaw,
+ 'effective RPC JWT verifier public key (CONTROL_API_RPC_JWT_PUBLIC_KEY)'
+ )
+ : undefined
+
+function assertRpcIdentity(signing: SigningMaterial): void {
+ if (explicitRpcVerifier && explicitRpcVerifier.fingerprint !== signing.fingerprint) {
+ throw new Error(
+ 'CONTROL_API_RPC_JWT_PUBLIC_KEY must correspond to CONTROL_API_RPC_JWT_PRIVATE_KEY'
+ )
+ }
+}
+if (explicitJwtSigningMaterial.rpc) assertRpcIdentity(explicitJwtSigningMaterial.rpc)
+if (!CLERUM_DEV_MODE_ENABLED) {
+ for (const slot of ['rpc', 'session', 'admin'] as const) {
+ if (!explicitJwtSigningMaterial[slot]) required(JWT_SIGNING_KEY_ENV_NAMES[slot])
+ }
+}
+const jwtSigningMaterial = Object.fromEntries(
+ (['rpc', 'session', 'admin'] as const).map(slot => [
+ slot,
+ explicitJwtSigningMaterial[slot] ?? loadOrCreateDevJwtSigningMaterial(slot),
+ ])
+) as Record<DevJwtSlot, SigningMaterial>
+assertRpcIdentity(jwtSigningMaterial.rpc)
const memberRegistrationMode: 'remote' | 'hosted' = (() => {
const raw = (process.env.CONTROL_API_MEMBER_REGISTRATION_MODE || 'remote').trim()
@@ -627,8 +657,9 @@ if (memberRegistrationMode === 'hosted') {
)
}
if (memberRegistrationEnvPresent('CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET')) {
- console.warn(
- '[ControlAPI] CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET is set but IGNORED in hosted member-registration mode (deploy-injected legacy value; credentials are self-enrolled and stored in Postgres)'
+ rootLogger.warn(
+ { event: 'hosted_member_registration_env_secret_ignored' },
+ 'Hosted member-registration uses its enrolled credentials'
)
}
}
@@ -755,11 +786,11 @@ export const config: Config = {
),
controlUiBaseUrl: process.env.CONTROL_API_CONTROL_UI_BASE_URL || 'http://127.0.0.1:3000',
controlUiAppName: process.env.CONTROL_API_CONTROL_UI_APP_NAME || 'Evenfire',
- sessionJwtPrivateKey: resolveControlApiJwtPrivateKey('session'),
+ sessionJwtPrivateKey: jwtSigningMaterial.session.privatePem,
jwtIssuer: requiredOrDevDefault('CONTROL_API_JWT_ISSUER', 'control-api'),
jwtAudience: requiredOrDevDefault('CONTROL_API_JWT_AUDIENCE', 'profile-ui'),
- rpcJwtPrivateKey: RPC_JWT_PRIVATE_KEY,
- rpcJwtPublicKey: RPC_JWT_PUBLIC_KEY,
+ rpcJwtPrivateKey: jwtSigningMaterial.rpc.privatePem,
+ rpcJwtPublicKey: explicitRpcVerifier?.publicPem ?? jwtSigningMaterial.rpc.publicPem,
rpcJwtIssuer: requiredOrDevDefault('CONTROL_API_RPC_JWT_ISSUER', 'control-api'),
rpcJwtAudience: requiredOrDevDefault('CONTROL_API_RPC_JWT_AUDIENCE', 'rpc-proxy'),
rpcTokenTtlSeconds: Number(process.env.CONTROL_API_RPC_TOKEN_TTL_SECONDS || 300),
@@ -767,15 +798,12 @@ export const config: Config = {
hostSecretLabelValue: process.env.CONTROL_API_HOST_SECRET_LABEL_VALUE || 'true',
policyAuthAudience: process.env.CONTROL_API_POLICY_AUTH_AUDIENCE || 'control-api',
googleClientId: requiredOrDevDefault('CONTROL_API_GOOGLE_CLIENT_ID', 'dev-google-client-id'),
- adminJwtPrivateKey: resolveControlApiJwtPrivateKey('admin'),
+ adminJwtPrivateKey: jwtSigningMaterial.admin.privatePem,
adminJwtIssuer: requiredOrDevDefault('CONTROL_API_ADMIN_JWT_ISSUER', 'control-api'),
adminJwtAudience: requiredOrDevDefault('CONTROL_API_ADMIN_JWT_AUDIENCE', 'control-ui'),
adminJwtTtlSeconds: Number(process.env.CONTROL_API_ADMIN_JWT_TTL_SECONDS || 60 * 60),
- // Optional — empty string means "fall back to adminJwtPrivateKey" (see
- // registry.ts). Production should set this to a dedicated RS256 key.
- registryVoucherPrivateKey: normalizePem(
- process.env.CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY ?? ''
- ),
+ // No implicit admin identity substitution; managed mode requires this key.
+ registryVoucherPrivateKey: voucherMaterial?.privatePem ?? '',
registryVoucherKid: process.env.CONTROL_API_REGISTRY_VOUCHER_KID ?? '',
registryUrl: process.env.CLERUM_REGISTRY_URL ?? '',
registryClientId: process.env.CLERUM_REGISTRY_CLIENT_ID ?? '',
@@ -1403,7 +1431,10 @@ if (config.registryAuthEnabled) {
'REGISTRY_CONNECTION_MODE is required (managed|self-hosted) when CLERUM_REGISTRY_AUTH_ENABLED=true'
)
}
- console.log(`[ControlAPI] Registry connection mode: ${config.registryConnectionMode}`)
+ rootLogger.info(
+ { event: 'registry_connection_mode', mode: config.registryConnectionMode },
+ 'Registry connection mode'
+ )
if (config.registryConnectionMode === 'managed') {
// Managed machine creds live in env (unchanged).
@@ -1433,18 +1464,6 @@ if (config.registryAuthEnabled) {
// AFTER initDb (config.ts is sync and cannot query Postgres). See Task 8.
}
-// Security check: reject historically committed dev JWT keys in any signing or
-// verifying slot on every startup. Generated dev keys are fresh, so explicit
-// dev mode changes nothing for legitimate local use.
-assertNoBannedJwtKeys({
- rpcPrivateKey: config.rpcJwtPrivateKey,
- sessionPrivateKey: config.sessionJwtPrivateKey,
- adminPrivateKey: config.adminJwtPrivateKey,
- voucherPrivateKey: config.registryVoucherPrivateKey || undefined,
- rpcPublicKey: config.rpcJwtPublicKey,
- rpcPublicKeyEnvSet: Boolean(process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY),
-})
-
if (process.env.NODE_ENV === 'production') {
// NOTE: the old voucher-key fallback WARN (dedicated key unset → sign with the
// admin JWT key) is gone. Under voucher v2 a managed prod boot without the
diff --git a/control-api/src/devSigningKeys.ts b/control-api/src/devSigningKeys.ts
index 6756589a9..9e10fcb7e 100644
--- a/control-api/src/devSigningKeys.ts
+++ b/control-api/src/devSigningKeys.ts
@@ -1,294 +1,41 @@
-import { createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto'
+import { dirname } from 'node:path'
import {
- type Stats,
- closeSync,
- constants,
- fstatSync,
- linkSync,
- lstatSync,
- mkdirSync,
- openSync,
- readFileSync,
- unlinkSync,
- writeFileSync,
-} from 'node:fs'
-import { dirname, isAbsolute, join } from 'node:path'
-import { validateRsaPrivateKeyPem } from './bannedDevSigningKeys.js'
+ type DevJwtSlot,
+ type DevSigningMaterial,
+ loadOrCreateDevSigningMaterial,
+ resolveDevKeyStoreDir,
+} from '@clerum/jwt-key-policy/dev-store'
+import { rootLogger } from './observability/logger.js'
-export type DevJwtSlot = 'rpc' | 'session' | 'admin'
+export type { DevJwtSlot }
-/**
- * Local-only dev key store at <service>/.dev-keys, gitignored and never
- * touched when operators supply the three JWT key env vars or outside
- * CLERUM_DEV_MODE. Works in every supported runtime: CommonJS (dist and
- * ts-node) resolves __dirname to <service>/dist or <service>/src, so its
- * parent is the service root; Vitest's ESM transform has no __dirname and
- * falls back to the service working directory used by every test/npm script.
- */
+// In CJS this is <service>/src or <service>/dist; test transforms use the
+// service working directory. The package never infers a caller's service root.
const SERVICE_ROOT = typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
-const DEFAULT_STORE_DIR =
- process.env.EVENFIRE_DEV_KEY_STORE?.trim() || join(SERVICE_ROOT, '.dev-keys')
export function defaultDevSigningKeyStoreDir(): string {
- return DEFAULT_STORE_DIR
-}
-
-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 (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 {
- if (stats.isSymbolicLink() || !stats.isDirectory()) {
- throw new Error(`Dev JWT key store path is not a directory: ${dirPath}`)
- }
- if (process.geteuid && stats.uid !== process.geteuid()) {
- throw new Error(`Dev JWT key store directory is not owned by the current user: ${dirPath}`)
- }
- if ((stats.mode & 0o077) !== 0) {
- throw new Error(
- `Dev JWT key store directory has group/other permissions; expected 0700: ${dirPath}`
- )
- }
-}
-
-function ensureStoreDir(storeDir: string): void {
- const stats = lstatSync(storeDir, { throwIfNoEntry: false })
- if (stats) {
- assertOwnedPrivateDirectory(storeDir, stats)
- return
- }
- try {
- mkdirSync(storeDir, { mode: 0o700 })
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
- // Lost a creation race with another local process; revalidate the winner.
- }
- const dirStats = lstatSync(storeDir, { throwIfNoEntry: false })
- if (!dirStats) throw new Error(`Dev JWT key store directory disappeared: ${storeDir}`)
- assertOwnedPrivateDirectory(storeDir, dirStats)
-}
-
-function readPersistedKey(filePath: string, slot: DevJwtSlot): string | undefined {
- let raw: string | undefined
- try {
- 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) {
- throw new Error(
- `Dev JWT key store file is corrupt or not an RSA private key (delete it only if you accept losing dev tokens): ${filePath}: ${(err as Error).message}`
- )
- }
+ return resolveDevKeyStoreDir(SERVICE_ROOT, process.env.EVENFIRE_DEV_KEY_STORE)
}
let warnedOnce = false
-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
- * this file so the monorepo dev boot shares one key identity; it is never
- * written independently, and an existing copy that disagrees with the signing
- * material is a hard error.
- */
-function ensureDerivedPublicKey(slot: DevJwtSlot, storeDir: string, signingPem: string): void {
- const publicPath = join(storeDir, `${slot}.public.pem`)
- const derived = createPublicKey(signingPem)
- .export({ type: 'spki', format: 'pem' })
- .toString()
- .trim()
- const existing = readStoredDerivedPublic(publicPath)
- if (existing !== undefined) {
- assertMatchingDerivedPublic(publicPath, existing, derived)
- return
- }
- const tempPath = `${publicPath}.tmp-${process.pid.toString(36)}-${randomBytes(6).toString('hex')}`
- try {
- writeFileSync(tempPath, derived, { mode: 0o644 })
- linkSync(tempPath, publicPath)
- unlinkSync(tempPath)
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
- removeIfPresent(tempPath)
- // 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
- }
-}
-
-/**
- * Returns the dev private key for a slot, generating and persisting it with
- * exclusive creation on first use. Concurrent first starts converge on one
- * key per slot; existing files are never overwritten. The store directory is
- * only touched when a key is actually needed.
- */
-export function loadOrGenerateDevJwtPrivateKey(
+export function loadOrCreateDevJwtSigningMaterial(
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)
- 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) {
- ensureDerivedPublicKey(slot, storeDir, existing)
- warnOnce(storeDir)
- return existing
- }
- const { privateKey } = generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- })
- createPrivateKey(privateKey) // sanity: the generated key must re-parse
- // Publish atomically: write a complete 0600 temp file, then hard-link it
- // under the final name. link(2) fails with EEXIST when another process won,
- // and readers can only ever observe a fully written key.
- const tempPath = `${filePath}.tmp-${process.pid.toString(36)}-${randomBytes(6).toString('hex')}`
- try {
- writeFileSync(tempPath, privateKey, { mode: 0o600 })
- assertOwnedRegularFile(tempPath)
- linkSync(tempPath, filePath)
- unlinkSync(tempPath)
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
- removeIfPresent(tempPath)
- // Another local process published a complete key first; adopt it.
- const winner = readPersistedKey(filePath, slot)
- if (winner) {
- ensureDerivedPublicKey(slot, storeDir, winner)
- warnOnce(storeDir)
- return winner
- }
- }
- throw err
+ storeDir?: string
+): DevSigningMaterial {
+ const absoluteStore = storeDir === undefined ? defaultDevSigningKeyStoreDir() : storeDir
+ const material = loadOrCreateDevSigningMaterial(slot, absoluteStore)
+ if (!warnedOnce) {
+ warnedOnce = true
+ rootLogger.warn(
+ { event: 'dev_jwt_signing_keys_active', storeDir: absoluteStore },
+ 'Local dev JWT signing keys are active; never use this store for production'
+ )
}
- assertOwnedRegularFile(filePath)
- ensureDerivedPublicKey(slot, storeDir, privateKey)
- warnOnce(storeDir)
- return privateKey.trim()
+ return material
}
-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 ${JSON.stringify(storeDir)}; they are never valid for production deployments.`
- )
-}
-
-function removeIfPresent(path: string): void {
- try {
- unlinkSync(path)
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
- }
+/** Legacy consumer API, backed by the shared canonical store contract. */
+export function loadOrGenerateDevJwtPrivateKey(slot: DevJwtSlot, storeDir?: string): string {
+ return loadOrCreateDevJwtSigningMaterial(slot, storeDir).privatePem
}
diff --git a/control-api/src/routes/admin/registryConnect.ts b/control-api/src/routes/admin/registryConnect.ts
index 35811c028..aeef9f68a 100644
--- a/control-api/src/routes/admin/registryConnect.ts
+++ b/control-api/src/routes/admin/registryConnect.ts
@@ -13,7 +13,10 @@ import {
markConnected,
upsertPendingConnection,
} from '../../services/registryConnectionDb.js'
-import { signPop } from '../../services/registryPopSigner.js'
+import {
+ RegistrySigningMaterialUnavailableError,
+ signPop,
+} from '../../services/registryPopSigner.js'
/**
* The self-hosted connect flow (spec §6.1/§6.3). control-ui JWT auth; the
@@ -39,6 +42,26 @@ import { signPop } from '../../services/registryPopSigner.js'
/** Bound every registry hop (registryClient.ts convention). */
const REGISTRY_FETCH_TIMEOUT_MS = 10_000
+function respondToSigningMaterialFailure(
+ error: unknown,
+ res: Response,
+ operation: 'status' | 'registration' | 'claim' | 'recovery'
+): boolean {
+ if (!(error instanceof RegistrySigningMaterialUnavailableError)) return false
+ rootLogger.warn(
+ {
+ event: 'registry_pop_key_unavailable',
+ source: 'registry_pop',
+ slot: 'pop',
+ operation,
+ reason: error.reason,
+ },
+ 'Registry proof-of-possession signing material rejected'
+ )
+ res.status(409).json({ error: 'registry_signing_material_unavailable' })
+ return true
+}
+
export function createRegistryConnectRouter(): Router {
const router = Router()
const base = (): string => `${config.registryUrl}/api/v1/deployments`
@@ -54,7 +77,9 @@ export function createRegistryConnectRouter(): Router {
| { kind: 'error'; status: number }
// Single claim implementation shared by the manual paste route and the
- // auto-claim path. EXCEPTION-TOTAL: markConnected encrypts and writes to
+ // auto-claim path. Permanent signing policy failures propagate before the
+ // registry can consume a claim token. Later failures are values because
+ // markConnected encrypts and writes to
// Postgres AFTER the registry has already burned the one-time secret, so a
// throw here must be a value the caller can act on, never an unhandled 500.
async function redeemClaim(input: {
@@ -64,12 +89,12 @@ export function createRegistryConnectRouter(): Router {
adminId: string
claimToken: string
}): Promise<ClaimOutcome> {
+ const pop = signPop({
+ privateKeyPem: input.privateKeyPem,
+ sub: input.adminId,
+ kid: input.keyId,
+ })
try {
- const pop = signPop({
- privateKeyPem: input.privateKeyPem,
- sub: input.adminId,
- kid: input.keyId,
- })
const claimRes = await fetch(`${base()}/claim`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', DPoP: pop },
@@ -161,15 +186,16 @@ export function createRegistryConnectRouter(): Router {
// Poll the registry for the deployment's current lifecycle status. Best-effort:
// a poll failure degrades to the locally-known pending state so GET never 500s
// on a transient registry hiccup. Returns the parsed status/suspended/claimed
- // triple, or null on any failure.
+ // triple, or null on transport/response failure. A local signing-policy
+ // conflict is permanent and must reach the route before any registry call.
async function pollRegistryStatus(row: {
deploymentId: string
keyId: string
privateKeyPem: string
adminId: string
}): Promise<{ status: string | null; suspended: boolean; claimed: boolean } | null> {
+ const pop = signPop({ privateKeyPem: row.privateKeyPem, sub: row.adminId, kid: row.keyId })
try {
- const pop = signPop({ privateKeyPem: row.privateKeyPem, sub: row.adminId, kid: row.keyId })
const statusRes = await fetch(`${base()}/${row.deploymentId}/status`, {
method: 'GET',
headers: { DPoP: pop },
@@ -192,9 +218,9 @@ export function createRegistryConnectRouter(): Router {
suspended: parsed.suspended === true,
claimed: parsed.claimed === true,
}
- } catch (err) {
+ } catch {
rootLogger.warn(
- { event: 'registry_connect_status_poll_error', err: (err as Error).message },
+ { event: 'registry_connect_status_poll_error', reason: 'registry_transport_failure' },
'status poll threw; degrading to local pending'
)
return null
@@ -311,6 +337,7 @@ export function createRegistryConnectRouter(): Router {
authEnabled,
})
} catch (err) {
+ if (respondToSigningMaterialFailure(err, res, 'status')) return
next(err)
}
}
@@ -513,6 +540,7 @@ export function createRegistryConnectRouter(): Router {
.status(202)
.json({ state: 'connecting', deploymentId: reg.deployment_id, requestedOrgName })
} catch (err) {
+ if (respondToSigningMaterialFailure(err, res, 'registration')) return
next(err)
}
}
@@ -569,6 +597,7 @@ export function createRegistryConnectRouter(): Router {
return
}
} catch (err) {
+ if (respondToSigningMaterialFailure(err, res, 'claim')) return
next(err)
}
})
@@ -633,12 +662,12 @@ export function createRegistryConnectRouter(): Router {
'attempting auto-claim recovery'
)
let claimToken: string
+ const pop = signPop({
+ privateKeyPem: row.privateKeyPem,
+ sub: ctx.adminId,
+ kid: row.keyId,
+ })
try {
- const pop = signPop({
- privateKeyPem: row.privateKeyPem,
- sub: ctx.adminId,
- kid: row.keyId,
- })
const rotRes = await fetch(`${base()}/${row.deploymentId}/claim-token`, {
method: 'POST',
headers: { DPoP: pop },
@@ -709,6 +738,7 @@ export function createRegistryConnectRouter(): Router {
return
}
} catch (err) {
+ if (respondToSigningMaterialFailure(err, res, 'recovery')) return
next(err)
}
}
diff --git a/control-api/src/services/registryConnectionDb.ts b/control-api/src/services/registryConnectionDb.ts
index 530d96123..a3d126ca2 100644
--- a/control-api/src/services/registryConnectionDb.ts
+++ b/control-api/src/services/registryConnectionDb.ts
@@ -1,4 +1,4 @@
-import { isBannedSigningKeyPem } from '../bannedDevSigningKeys.js'
+import { JwtKeyMaterialError, parseSigningMaterial } from '@clerum/jwt-key-policy'
import { config } from '../config.js'
import { pool, withTransaction } from '../db.js'
import type { DbClient } from '../db.js'
@@ -7,6 +7,7 @@ import {
deriveOAuthEncryptionKey,
encryptOAuthSecret,
} from '../oauth/encryption.js'
+import { rootLogger } from '../observability/logger.js'
import {
invalidateRegistryIdentityCaches,
isRegistryIdentityCacheGenerationCurrent,
@@ -202,6 +203,30 @@ export async function deleteConnection(db: DbClient = pool): Promise<void> {
invalidateRegistryIdentityCaches()
}
+function usableVoucherSigningKey(
+ raw: string,
+ context: { source: 'registry_connection' | 'environment'; deploymentId?: string }
+): string {
+ try {
+ return parseSigningMaterial(raw, 'Registry voucher signing key').privatePem
+ } catch (error) {
+ if (!(error instanceof JwtKeyMaterialError)) throw error
+ rootLogger.warn(
+ {
+ event:
+ error.code === 'ERR_JWT_KEY_BANNED'
+ ? 'registry_voucher_key_banned'
+ : 'registry_voucher_key_invalid',
+ ...context,
+ slot: 'voucher',
+ reason: error.reason,
+ },
+ 'Registry voucher signing material rejected'
+ )
+ throw new VoucherUnavailableError()
+ }
+}
+
/** Mode-aware voucher signing material (spec §14.2). */
export async function resolveVoucherSigningMaterial(): Promise<{
signingKey: string
@@ -209,17 +234,25 @@ export async function resolveVoucherSigningMaterial(): Promise<{
}> {
if (config.registryConnectionMode === 'self-hosted') {
const row = await getRegistryConnection()
- if (!row || !row.privateKeyPem || !row.keyId) throw new VoucherUnavailableError()
- if (isBannedSigningKeyPem(row.privateKeyPem)) {
- throw new VoucherUnavailableError()
+ if (!row || !row.keyId) throw new VoucherUnavailableError()
+ return {
+ signingKey: usableVoucherSigningKey(row.privateKeyPem, {
+ source: 'registry_connection',
+ deploymentId: row.deploymentId,
+ }),
+ kid: row.keyId,
}
- return { signingKey: row.privateKeyPem, kid: row.keyId }
}
// managed
if (!config.registryVoucherPrivateKey || !config.registryVoucherKid) {
throw new VoucherUnavailableError()
}
- return { signingKey: config.registryVoucherPrivateKey, kid: config.registryVoucherKid }
+ return {
+ signingKey: usableVoucherSigningKey(config.registryVoucherPrivateKey, {
+ source: 'environment',
+ }),
+ kid: config.registryVoucherKid,
+ }
}
/** Mode-aware machine (client_credentials) creds (spec §8 registryClient). */
diff --git a/control-api/src/services/registryPopSigner.ts b/control-api/src/services/registryPopSigner.ts
index 1b29fb903..4ce51a9e7 100644
--- a/control-api/src/services/registryPopSigner.ts
+++ b/control-api/src/services/registryPopSigner.ts
@@ -1,6 +1,20 @@
// control-api/src/services/registryPopSigner.ts
import jwt from 'jsonwebtoken'
import { randomUUID } from 'node:crypto'
+import {
+ JwtKeyMaterialError,
+ type JwtKeyMaterialReason,
+ type SigningMaterial,
+ parseSigningMaterial,
+} from '@clerum/jwt-key-policy'
+
+/** Permanent local key failure; registry transport retries cannot repair it. */
+export class RegistrySigningMaterialUnavailableError extends Error {
+ constructor(readonly reason: JwtKeyMaterialReason) {
+ super('registry_signing_material_unavailable')
+ this.name = 'RegistrySigningMaterialUnavailableError'
+ }
+}
/**
* Self-signed proof-of-possession JWT (spec §4 / S1). Proves the caller holds a
@@ -15,7 +29,14 @@ export function signPop(input: {
kid?: string
ttlSeconds?: number
}): string {
- return jwt.sign({ sub: input.sub, jti: randomUUID() }, input.privateKeyPem, {
+ let material: SigningMaterial
+ try {
+ material = parseSigningMaterial(input.privateKeyPem, 'Registry proof-of-possession signing key')
+ } catch (error) {
+ if (!(error instanceof JwtKeyMaterialError)) throw error
+ throw new RegistrySigningMaterialUnavailableError(error.reason)
+ }
+ return jwt.sign({ sub: input.sub, jti: randomUUID() }, material.privatePem, {
algorithm: 'RS256',
audience: 'registry-api',
expiresIn: input.ttlSeconds ?? 120,
diff --git a/control-api/test/bannedDevSigningKeys.test.ts b/control-api/test/bannedDevSigningKeys.test.ts
index 9254d000a..bb59d233e 100644
--- a/control-api/test/bannedDevSigningKeys.test.ts
+++ b/control-api/test/bannedDevSigningKeys.test.ts
@@ -48,6 +48,14 @@ describe('bannedDevSigningKeys', () => {
expect(DEFAULT_BANNED_FINGERPRINTS.size).toBe(3)
})
+ it('exposes an immutable compatibility view rather than a mutable default Set', () => {
+ expect(Object.isFrozen(DEFAULT_BANNED_FINGERPRINTS)).toBe(true)
+ expect('add' in DEFAULT_BANNED_FINGERPRINTS).toBe(false)
+ expect('delete' in DEFAULT_BANNED_FINGERPRINTS).toBe(false)
+ expect('clear' in DEFAULT_BANNED_FINGERPRINTS).toBe(false)
+ expect([...DEFAULT_BANNED_FINGERPRINTS]).toHaveLength(3)
+ })
+
it('validates fresh RSA-2048 signing material', () => {
expect(() => validateSigningPem(makeFresh().signing, 'TEST_ENV')).not.toThrow()
})
@@ -60,9 +68,11 @@ describe('bannedDevSigningKeys', () => {
publicKeyEncoding: { type: 'spki', format: 'pem' },
})
expect(() => validateSigningPem(ec.publicKey, 'TEST_ENV')).toThrow(
- /must contain exactly one PEM private key/
+ expect.objectContaining({ code: 'ERR_JWT_KEY_INVALID', reason: 'wrong_key_role' })
+ )
+ expect(() => validateSigningPem(ec.privateKey, 'TEST_ENV')).toThrow(
+ expect.objectContaining({ code: 'ERR_JWT_KEY_INVALID', reason: 'non_rsa_key' })
)
- expect(() => validateSigningPem(ec.privateKey, 'TEST_ENV')).toThrow(/must be an RSA key/)
})
it('rejects a banned fingerprint in every signing slot', () => {
@@ -140,7 +150,7 @@ describe('bannedDevSigningKeys', () => {
`${target.signing}\n${decoy.public}`,
]) {
expect(() => validateSigningPem(combined, 'TEST_ENV')).toThrow(
- /must contain exactly one PEM private key/
+ expect.objectContaining({ code: 'ERR_JWT_KEY_INVALID', reason: 'multiple_pem_objects' })
)
expect(() =>
assertGuard(
@@ -153,7 +163,9 @@ describe('bannedDevSigningKeys', () => {
},
fingerprints
)
- ).toThrow(/historically committed dev JWT key/)
+ ).toThrow(
+ expect.objectContaining({ code: 'ERR_JWT_KEY_INVALID', reason: 'multiple_pem_objects' })
+ )
}
})
diff --git a/control-api/test/config.jwtHardening.test.ts b/control-api/test/config.jwtHardening.test.ts
index 87ecdc2ee..f5dd1778a 100644
--- a/control-api/test/config.jwtHardening.test.ts
+++ b/control-api/test/config.jwtHardening.test.ts
@@ -1,5 +1,10 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { createPublicKey, generateKeyPairSync } from 'node:crypto'
+import { type MockInstance, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createHash, createPublicKey, generateKeyPairSync, randomUUID } from 'node:crypto'
+import type { KeyObject } from 'node:crypto'
+import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { BANNED_DEV_JWT_PUBLIC_KEYS as HISTORICAL } from './fixtures/bannedDevJwtPublicKeys.js'
import { applyProdEnv } from './fixtures/productionConfigEnv.js'
@@ -10,21 +15,88 @@ const SLOT_ENV_NAMES = [
'CONTROL_API_ADMIN_JWT_PRIVATE_KEY',
] as const
-const devProviderMocks = vi.hoisted(() => ({
- load: vi.fn(
- (slot: 'rpc' | 'session' | 'admin') =>
- generateKeyPairSync('rsa', {
- modulusLength: 2048,
- privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
- publicKeyEncoding: { type: 'spki', format: 'pem' },
- }).privateKey
- ),
-}))
-
-vi.mock('../src/devSigningKeys.js', () => ({
- loadOrGenerateDevJwtPrivateKey: devProviderMocks.load,
- defaultDevSigningKeyStoreDir: () => '/nonexistent-dev-key-store',
-}))
+const fixtureApi = createRequire(import.meta.url)(
+ '../../packages/jwt-key-policy/test/crypto-fixtures.cjs'
+) as {
+ encodings: (material: string) => Record<string, string>
+ certificate: (material: KeyObject) => string
+}
+const rsaPair = generateKeyPairSync('rsa', { modulusLength: 2048 })
+const rsa4096Pair = generateKeyPairSync('rsa', { modulusLength: 4096 })
+const caseIdentity2048 = createHash('sha256')
+ .update(rsaPair.publicKey.export({ type: 'spki', format: 'der' }))
+ .digest('hex')
+const caseIdentity4096 = createHash('sha256')
+ .update(rsa4096Pair.publicKey.export({ type: 'spki', format: 'der' }))
+ .digest('hex')
+const signingCasePem = rsaPair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString().trim()
+const signingCasePublic = rsaPair.publicKey
+ .export({ type: 'spki', format: 'pem' })
+ .toString()
+ .trim()
+const signingCaseCertificate = fixtureApi.certificate(rsaPair.privateKey)
+const decoyCasePem = freshSigningMaterial()
+const otherCertificate = fixtureApi.certificate(
+ generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey
+)
+const signingCases = [
+ ...Object.entries(fixtureApi.encodings(signingCasePem)).map(([name, material]) => ({
+ name,
+ material,
+ reason: undefined,
+ })),
+ {
+ name: 'pkcs1',
+ material: rsaPair.privateKey.export({ type: 'pkcs1', format: 'pem' }).toString(),
+ reason: undefined,
+ },
+ {
+ name: 'rsa4096',
+ material: rsa4096Pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
+ reason: undefined,
+ },
+ {
+ name: 'rsa1024',
+ material: generateKeyPairSync('rsa', { modulusLength: 1024 })
+ .privateKey.export({ type: 'pkcs8', format: 'pem' })
+ .toString(),
+ reason: 'undersized_rsa_key',
+ },
+ {
+ name: 'encrypted',
+ material: rsaPair.privateKey
+ .export({ type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: randomUUID() })
+ .toString(),
+ reason: 'encrypted_private_key',
+ },
+ { name: 'malformed', material: 'malformed operator key material', reason: 'invalid_pem' },
+ { name: 'public', material: signingCasePublic, reason: 'wrong_key_role' },
+ {
+ name: 'ec',
+ material: generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
+ .privateKey.export({ type: 'pkcs8', format: 'pem' })
+ .toString(),
+ reason: 'non_rsa_key',
+ },
+ ...Object.entries({
+ privateThenPrivate: `${signingCasePem}\n${decoyCasePem}`,
+ publicThenPrivate: `${signingCasePublic}\n${signingCasePem}`,
+ privateThenPublic: `${signingCasePem}\n${signingCasePublic}`,
+ certificateThenPrivate: `${signingCaseCertificate}\n${signingCasePem}`,
+ privateThenCertificate: `${signingCasePem}\n${signingCaseCertificate}`,
+ certificateThenCertificate: `${signingCaseCertificate}\n${otherCertificate}`,
+ escapedCertificateThenPrivate: `${signingCaseCertificate}\n${signingCasePem}`.replace(
+ /\n/g,
+ '\\n'
+ ),
+ }).map(([name, material]) => ({ name, material, reason: 'multiple_pem_objects' })),
+]
+
+let providerLoad: MockInstance<
+ typeof import('../src/devSigningKeys.js').loadOrCreateDevJwtSigningMaterial
+>
+let fixtureRoot: string
+let fixtureStore: string
function freshSigningMaterial(): string {
return generateKeyPairSync('rsa', {
@@ -57,18 +129,24 @@ function resetEnv(): void {
delete process.env.NODE_ENV
delete process.env.CLERUM_DEV_MODE
delete process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY
+ delete process.env.CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY
}
-beforeEach(() => {
+beforeEach(async () => {
vi.resetModules()
- devProviderMocks.load.mockClear()
resetEnv()
+ fixtureRoot = mkdtempSync(join(tmpdir(), 'evenfire-config-jwt-'))
+ fixtureStore = join(fixtureRoot, '.dev-keys')
+ process.env.EVENFIRE_DEV_KEY_STORE = fixtureStore
+ const provider = await import('../src/devSigningKeys.js')
+ providerLoad = vi.spyOn(provider, 'loadOrCreateDevJwtSigningMaterial')
})
afterEach(() => {
resetEnv()
vi.restoreAllMocks()
vi.resetModules()
+ rmSync(fixtureRoot, { recursive: true, force: true })
})
describe('config JWT hardening', () => {
@@ -90,17 +168,29 @@ describe('config JWT hardening', () => {
await expect(() => import('../src/config.js')).rejects.toThrow(
/CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production/
)
- expect(devProviderMocks.load).not.toHaveBeenCalled()
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
})
it('uses the dev provider for unset slots in dev mode', async () => {
for (const name of SLOT_ENV_NAMES) delete process.env[name]
process.env.CLERUM_DEV_MODE = 'true'
const { config } = await import('../src/config.js')
- expect(devProviderMocks.load).toHaveBeenCalledTimes(3)
- expect(config.rpcJwtPrivateKey).toBeTruthy()
- expect(config.sessionJwtPrivateKey).toBeTruthy()
- expect(config.adminJwtPrivateKey).toBeTruthy()
+ expect(providerLoad).toHaveBeenCalledTimes(3)
+ expect(readdirSync(fixtureStore).sort()).toEqual([
+ 'admin.pem',
+ 'admin.public.pem',
+ 'rpc.pem',
+ 'rpc.public.pem',
+ 'session.pem',
+ 'session.public.pem',
+ ])
+ expect(
+ createPublicKey(config.rpcJwtPrivateKey)
+ .export({ type: 'spki', format: 'pem' })
+ .toString()
+ .trim() === config.rpcJwtPublicKey
+ ).toBe(true)
})
it('rejects a historical verifier public key even with a fresh signing key', async () => {
@@ -130,9 +220,9 @@ describe('config JWT hardening', () => {
process.env.CONTROL_API_SESSION_JWT_PRIVATE_KEY = signingMaterialWithBodyPrefix('MIIEvg')
process.env.CONTROL_API_ADMIN_JWT_PRIVATE_KEY = signingMaterialWithBodyPrefix('MIIEvQ')
const { config } = await import('../src/config.js')
- expect(config.rpcJwtPrivateKey).toContain('BEGIN')
- expect(config.sessionJwtPrivateKey).toContain('BEGIN')
- expect(config.adminJwtPrivateKey).toContain('BEGIN')
+ expect(config.rpcJwtPrivateKey.includes('BEGIN')).toBe(true)
+ expect(config.sessionJwtPrivateKey.includes('BEGIN')).toBe(true)
+ expect(config.adminJwtPrivateKey.includes('BEGIN')).toBe(true)
})
it('resolves with fully configured keys for non-production NODE_ENV values', async () => {
@@ -150,7 +240,8 @@ describe('config JWT hardening', () => {
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()
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
}
})
@@ -161,4 +252,127 @@ describe('config JWT hardening', () => {
/effective RPC JWT verifier public key/
)
})
+
+ for (const name of [
+ ...SLOT_ENV_NAMES,
+ 'CONTROL_API_RPC_JWT_PUBLIC_KEY',
+ 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY',
+ ]) {
+ it(`validates explicit ${name} before generating any missing dev slot`, async () => {
+ for (const slot of SLOT_ENV_NAMES) delete process.env[slot]
+ process.env.CLERUM_DEV_MODE = 'true'
+ process.env[name] = 'malformed operator material'
+ await expect(import('../src/config.js')).rejects.toMatchObject({
+ code: 'ERR_JWT_KEY_INVALID',
+ })
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
+ })
+ }
+
+ it('keeps fully configured identity independent of an unused relative store override', async () => {
+ process.env.CLERUM_DEV_MODE = 'true'
+ process.env.EVENFIRE_DEV_KEY_STORE = 'unused-relative-store'
+ const { config } = await import('../src/config.js')
+ expect(config.rpcJwtPublicKey.includes('PUBLIC KEY')).toBe(true)
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
+ })
+
+ for (const [slot, envName] of [
+ ['rpc', SLOT_ENV_NAMES[0]],
+ ['session', SLOT_ENV_NAMES[1]],
+ ['admin', SLOT_ENV_NAMES[2]],
+ ] as const) {
+ it(`rejects a generated denied ${slot} identity before its actual consumer signs`, async () => {
+ const policy = await import('@clerum/jwt-key-policy')
+ const offender = freshSigningMaterial()
+ const denied = policy.publicKeyPemFingerprint(
+ createPublicKey(offender).export({ type: 'spki', format: 'pem' }).toString()
+ )
+ const parse = policy.parseSigningMaterial
+ vi.spyOn(policy, 'parseSigningMaterial').mockImplementation((raw, source, options) =>
+ parse(raw, source, { ...options, fingerprints: [denied] })
+ )
+ process.env[envName] = offender
+ const loadConsumer =
+ slot === 'rpc'
+ ? () => import('../src/utils/auth/rpcAuthToken.js')
+ : slot === 'session'
+ ? () => import('../src/utils/auth/externalSessionAuthToken.js')
+ : () => import('../src/utils/auth/adminAuthToken.js')
+ await expect(loadConsumer()).rejects.toMatchObject({
+ code: 'ERR_JWT_KEY_BANNED',
+ reason: 'banned_identity',
+ })
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
+ })
+ }
+
+ it('signs and verifies through actual admin, session, and RPC consumers after canonicalization', async () => {
+ const material = freshSigningMaterial()
+ const escapedCr = material.replace(/\n/g, '\\r')
+ for (const name of SLOT_ENV_NAMES) process.env[name] = escapedCr
+ const admin = await import('../src/utils/auth/adminAuthToken.js')
+ const session = await import('../src/utils/auth/externalSessionAuthToken.js')
+ const rpc = await import('../src/utils/auth/rpcAuthToken.js')
+ expect(admin.verifyAdminToken(admin.signAdminToken('contract-admin'))?.sub).toBe(
+ 'contract-admin'
+ )
+ const sessionResult = session.verifyExternalSessionToken(
+ session.signExternalSessionToken({
+ userId: 'contract-user',
+ email: '[email protected]',
+ teamId: null,
+ role: 'member',
+ authGeneration: 1,
+ })
+ )
+ expect(sessionResult?.userId).toBe('contract-user')
+ expect(
+ rpc.verifyRpcAccessToken(
+ rpc.signRpcAccessToken({
+ sub: 'contract-rpc',
+ typ: 'user',
+ teamId: null,
+ accessScope: 'user',
+ scopes: ['host:health:read'],
+ hostRefs: ['contract-host'],
+ jti: 'contract-jti',
+ })
+ )?.sub
+ ).toBe('contract-rpc')
+ })
+
+ for (const [slot, envName, field] of [
+ ['rpc', SLOT_ENV_NAMES[0], 'rpcJwtPrivateKey'],
+ ['session', SLOT_ENV_NAMES[1], 'sessionJwtPrivateKey'],
+ ['admin', SLOT_ENV_NAMES[2], 'adminJwtPrivateKey'],
+ ['voucher', 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY', 'registryVoucherPrivateKey'],
+ ] as const) {
+ for (const testCase of signingCases) {
+ it(`${slot} applies the canonical signing policy to ${testCase.name}`, async () => {
+ process.env[envName] = testCase.material
+ if (testCase.reason) {
+ await expect(import('../src/config.js')).rejects.toMatchObject({
+ code: 'ERR_JWT_KEY_INVALID',
+ reason: testCase.reason,
+ source: envName,
+ })
+ } else {
+ const { config } = await import('../src/config.js')
+ const policy = await import('@clerum/jwt-key-policy')
+ const expected = testCase.name === 'rsa4096' ? caseIdentity4096 : caseIdentity2048
+ const actual = policy.publicKeyPemFingerprint(
+ createPublicKey(config[field]).export({ type: 'spki', format: 'pem' }).toString()
+ )
+ expect(actual).toBe(expected)
+ expect(config[field].startsWith('-----BEGIN PRIVATE KEY-----')).toBe(true)
+ }
+ expect(providerLoad).not.toHaveBeenCalled()
+ expect(existsSync(fixtureStore)).toBe(false)
+ })
+ }
+ }
})
diff --git a/control-api/test/config.prod.test.ts b/control-api/test/config.prod.test.ts
index 226012530..51b5c6fea 100644
--- a/control-api/test/config.prod.test.ts
+++ b/control-api/test/config.prod.test.ts
@@ -43,25 +43,23 @@ describe('config: production voucher key guard', () => {
it('checks the voucher signing slot against the banned fingerprints in production', async () => {
const voucherKey = generateNonDevPem()
- const guard = await import('../src/bannedDevSigningKeys.js')
+ const guard = await import('@clerum/jwt-key-policy')
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)
+ // Scope the additional denied identity to this real parsing decision.
+ // The package's immutable historical policy remains active.
+ const parseSigningMaterial = guard.parseSigningMaterial
+ vi.spyOn(guard, 'parseSigningMaterial').mockImplementation((raw, source, options) =>
+ parseSigningMaterial(raw, source, { ...options, fingerprints: [voucherFingerprint] })
)
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/
- )
+ await expect(() => import('../src/config.js')).rejects.toMatchObject({
+ code: 'ERR_JWT_KEY_BANNED',
+ reason: 'banned_identity',
+ source: 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY',
+ })
})
it('rejects default dev internal service tokens in production', async () => {
diff --git a/control-api/test/config.registryConnectionMode.test.ts b/control-api/test/config.registryConnectionMode.test.ts
index c6173a189..a84647e6a 100644
--- a/control-api/test/config.registryConnectionMode.test.ts
+++ b/control-api/test/config.registryConnectionMode.test.ts
@@ -22,7 +22,8 @@ beforeEach(() => {
delete process.env.REGISTRY_CONNECTION_MODE
})
afterEach(() => {
- process.env = ORIGINAL_ENV
+ process.env = { ...ORIGINAL_ENV }
+ vi.restoreAllMocks()
vi.resetModules()
})
@@ -63,10 +64,13 @@ describe('config: REGISTRY_CONNECTION_MODE discriminator', () => {
it('logs the resolved mode at import for an enabled registry', async () => {
enableManagedRegistryEnv()
process.env.REGISTRY_CONNECTION_MODE = 'managed'
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { rootLogger } = await import('../src/observability/logger.js')
+ const logSpy = vi.spyOn(rootLogger, 'info').mockImplementation(() => {})
await import('../src/config.js')
- const lines = logSpy.mock.calls.map(c => String(c[0]))
- expect(lines.some(l => /Registry connection mode: managed/.test(l))).toBe(true)
+ expect(logSpy).toHaveBeenCalledWith(
+ { event: 'registry_connection_mode', mode: 'managed' },
+ 'Registry connection mode'
+ )
})
})
diff --git a/control-api/test/devSigningKeys.test.ts b/control-api/test/devSigningKeys.test.ts
index 2eb5fe20b..374e430a8 100644
--- a/control-api/test/devSigningKeys.test.ts
+++ b/control-api/test/devSigningKeys.test.ts
@@ -4,6 +4,8 @@ import { createHash, createPublicKey } from 'node:crypto'
import {
chmodSync,
closeSync,
+ copyFileSync,
+ cpSync,
fstatSync,
mkdirSync,
mkdtempSync,
@@ -29,6 +31,12 @@ const require = createRequire(import.meta.url)
let compiledModulePath = ''
const tempDirs: string[] = []
+function publicIdentityFingerprint(material: string): string {
+ return createHash('sha256')
+ .update(createPublicKey(material).export({ type: 'spki', format: 'der' }))
+ .digest('hex')
+}
+
function tempStore(): string {
const dir = mkdtempSync(join(tmpdir(), 'evenfire-dev-keys-'))
tempDirs.push(dir)
@@ -46,21 +54,27 @@ beforeAll(() => {
join(process.cwd(), 'src/devSigningKeys.ts'),
join(process.cwd(), 'src/bannedDevSigningKeys.ts'),
'--outDir',
- compileDir,
+ join(compileDir, 'dist'),
+ '--rootDir',
+ join(process.cwd(), 'src'),
'--module',
- 'commonjs',
+ 'NodeNext',
'--target',
'es2022',
'--moduleResolution',
- 'node',
+ 'NodeNext',
'--skipLibCheck',
+ '--esModuleInterop',
],
{ cwd: process.cwd(), encoding: 'utf8' }
)
if (result.status !== 0) {
throw new Error(result.stderr || result.stdout || 'provider compilation failed')
}
- compiledModulePath = join(compileDir, 'devSigningKeys.js')
+ // This closure build exercises the actual wrapper in another process; full
+ // service/production-only layout validation is a separate build gate.
+ symlinkSync(join(process.cwd(), 'node_modules'), join(compileDir, 'node_modules'), 'dir')
+ compiledModulePath = join(compileDir, 'dist/devSigningKeys.js')
})
afterAll(() => {
@@ -79,7 +93,67 @@ function runProviderScript(
}
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' })
+ return spawnSync(process.execPath, ['-e', script], {
+ cwd: storeDir,
+ env,
+ encoding: 'utf8',
+ timeout: 15_000,
+ })
+}
+
+function runWrapperRuntime(runtime: 'src' | 'dist', override: string | undefined) {
+ const layout = realpathSync(tempStore())
+ const service = join(layout, 'control-api')
+ const moduleDir = join(service, runtime)
+ mkdirSync(moduleDir, { recursive: true })
+ symlinkSync(join(process.cwd(), 'node_modules'), join(service, 'node_modules'), 'dir')
+ if (runtime === 'src') {
+ for (const relative of [
+ 'devSigningKeys.ts',
+ 'observability/logger.ts',
+ 'utils/log/redact.ts',
+ ]) {
+ const destination = join(moduleDir, relative)
+ mkdirSync(dirname(destination), { recursive: true })
+ copyFileSync(join(process.cwd(), 'src', relative), destination)
+ }
+ } else {
+ cpSync(dirname(compiledModulePath), moduleDir, { recursive: true })
+ }
+ const modulePath = join(moduleDir, `devSigningKeys.${runtime === 'src' ? 'ts' : 'js'}`)
+ // Control API declares ts-node (not tsx). Its documented resolver maps the
+ // production .js import specifiers to these actual copied TypeScript files.
+ const sourceLoader =
+ runtime === 'src'
+ ? `require(${JSON.stringify(require.resolve('ts-node'))}).register({
+ project: ${JSON.stringify(join(process.cwd(), 'tsconfig.json'))}, experimentalResolver: true,
+ compilerOptions: { rootDir: ${JSON.stringify(service)} }
+ });`
+ : ''
+ const runner = `
+ ${sourceLoader}
+ const provider = require(${JSON.stringify(modulePath)});
+ const { createHash, createPublicKey } = require('node:crypto');
+ const material = provider.loadOrGenerateDevJwtPrivateKey('rpc');
+ process.stdout.write(JSON.stringify({ storeDir: provider.defaultDevSigningKeyStoreDir(),
+ fingerprint: createHash('sha256').update(createPublicKey(material).export({ type: 'spki', format: 'der' })).digest('hex') }));
+ `
+ const env: NodeJS.ProcessEnv = { ...process.env, LOG_LEVEL: 'silent' }
+ delete env.EVENFIRE_DEV_KEY_STORE
+ if (override !== undefined) env.EVENFIRE_DEV_KEY_STORE = override
+ const args = ['-e', runner]
+ const execute = () => {
+ const result = spawnSync(process.execPath, args, {
+ cwd: layout,
+ env,
+ encoding: 'utf8',
+ timeout: 15_000,
+ })
+ if (result.status !== 0)
+ throw new Error(`Wrapper runtime failed with process exit ${result.status}`)
+ return JSON.parse(result.stdout) as { storeDir: string; fingerprint: string }
+ }
+ return { first: execute(), second: execute(), serviceRoot: service }
}
function runChild(slot: 'rpc' | 'session' | 'admin', storeDir: string): Promise<string> {
@@ -89,12 +163,12 @@ function runChild(slot: 'rpc' | 'session' | 'admin', storeDir: string): Promise<
[
'-e',
`const provider = require(process.env.DEVKEY_MODULE)
- const { createHash } = require('node:crypto')
+ const { createHash, createPublicKey } = require('node:crypto')
const resolved = provider.loadOrGenerateDevJwtPrivateKey(
process.env.DEVKEY_SLOT,
process.env.DEVKEY_STORE
)
- console.log(JSON.stringify({ fingerprint: createHash('sha256').update(resolved).digest('hex') }))`,
+ console.log(JSON.stringify({ fingerprint: createHash('sha256').update(createPublicKey(resolved).export({ type: 'spki', format: 'der' })).digest('hex') }))`,
],
{
env: {
@@ -103,6 +177,7 @@ function runChild(slot: 'rpc' | 'session' | 'admin', storeDir: string): Promise<
DEVKEY_SLOT: slot,
DEVKEY_STORE: storeDir,
},
+ timeout: 15_000,
}
)
let stdout = ''
@@ -118,20 +193,37 @@ function runChild(slot: 'rpc' | 'session' | 'admin', storeDir: string): Promise<
}
describe('devSigningKeys persistence contract', () => {
+ for (const runtime of ['src', 'dist'] as const) {
+ for (const override of [undefined, '', ' \t ']) {
+ it(`${runtime} creates and preserves its default identity with ${JSON.stringify(override)} override from another cwd`, () => {
+ const result = runWrapperRuntime(runtime, override)
+ expect(result.first.storeDir).toBe(join(result.serviceRoot, '.dev-keys'))
+ expect(result.second.fingerprint).toBe(result.first.fingerprint)
+ })
+ }
+ it(`${runtime} creates and preserves identity in an absolute store from another cwd`, () => {
+ const store = realpathSync(tempStore())
+ const result = runWrapperRuntime(runtime, store)
+ expect(result.first.storeDir).toBe(store)
+ expect(result.second.fingerprint).toBe(result.first.fingerprint)
+ })
+ }
+
it('generates a 0600 file in a 0700 store and reuses it across calls', () => {
const store = tempStore()
const first = loadOrGenerateDevJwtPrivateKey('rpc', store)
const second = loadOrGenerateDevJwtPrivateKey('rpc', store)
- expect(second).toBe(first)
+ expect(second === first).toBe(true)
expect(statSync(join(store, 'rpc.pem')).mode & 0o777).toBe(0o600)
expect(statSync(store).mode & 0o777).toBe(0o700)
})
it('keeps slots independent', () => {
const store = tempStore()
- expect(loadOrGenerateDevJwtPrivateKey('rpc', store)).not.toBe(
- loadOrGenerateDevJwtPrivateKey('session', store)
- )
+ expect(
+ loadOrGenerateDevJwtPrivateKey('rpc', store) ===
+ loadOrGenerateDevJwtPrivateKey('session', store)
+ ).toBe(false)
})
it('fails loudly on corruption instead of regenerating', () => {
@@ -139,7 +231,9 @@ describe('devSigningKeys persistence contract', () => {
const file = join(store, 'rpc.pem')
loadOrGenerateDevJwtPrivateKey('rpc', store)
writeFileSync(file, 'corrupted store entry')
- expect(() => loadOrGenerateDevJwtPrivateKey('rpc', store)).toThrow(/corrupt or not an RSA/)
+ expect(() => loadOrGenerateDevJwtPrivateKey('rpc', store)).toThrow(
+ expect.objectContaining({ code: 'ERR_JWT_KEY_INVALID' })
+ )
expect(readFileSync(file, 'utf8')).toBe('corrupted store entry')
})
@@ -199,15 +293,14 @@ describe('devSigningKeys persistence contract', () => {
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 }))`,
+ try { provider.loadOrGenerateDevJwtPrivateKey('rpc') } catch (err) { error = { code: err.code, reason: err.reason } }
+ console.log(JSON.stringify({ 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/),
+ error: { code: 'ERR_JWT_DEV_STORE', reason: 'relative_store_path' },
})
expect(readdirSync(store)).toEqual([])
})
@@ -216,13 +309,17 @@ describe('devSigningKeys persistence contract', () => {
const { vi } = await import('vitest')
vi.resetModules()
const provider = await import('../src/devSigningKeys.js')
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { rootLogger } = await import('../src/observability/logger.js')
+ const warn = vi.spyOn(rootLogger, 'warn').mockImplementation(() => {})
try {
const store = tempStore()
provider.loadOrGenerateDevJwtPrivateKey('rpc', store)
provider.loadOrGenerateDevJwtPrivateKey('session', store)
expect(warn).toHaveBeenCalledTimes(1)
- expect(String(warn.mock.calls.flat())).toContain(store)
+ expect(warn.mock.calls[0]?.[0]).toMatchObject({
+ event: 'dev_jwt_signing_keys_active',
+ storeDir: store,
+ })
expect(String(warn.mock.calls.flat())).not.toContain('BEGIN')
} finally {
warn.mockRestore()
@@ -245,7 +342,7 @@ describe('devSigningKeys persistence contract', () => {
loadOrGenerateDevJwtPrivateKey('session', realStore)
symlinkSync(realStore, linkStore)
expect(() => loadOrGenerateDevJwtPrivateKey('session', linkStore)).toThrow(
- /Dev JWT key store path is not a directory/
+ expect.objectContaining({ code: 'ERR_JWT_DEV_STORE', reason: 'symbolic_link' })
)
})
@@ -303,9 +400,11 @@ describe('devSigningKeys persistence contract', () => {
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')
+ expect(err).toMatchObject({
+ code: 'ERR_JWT_DEV_STORE',
+ reason: 'orphan_public',
+ source: publicPath,
+ })
}
})
@@ -316,7 +415,7 @@ describe('devSigningKeys persistence contract', () => {
const result = runProviderScript(
`const fs = require('node:fs')
const { join } = require('node:path')
- const { createHash } = require('node:crypto')
+ const { createHash, createPublicKey } = 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')
@@ -337,14 +436,12 @@ describe('devSigningKeys persistence contract', () => {
}
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') }))`,
+ console.log(JSON.stringify({ fingerprint: createHash('sha256').update(createPublicKey(resolved).export({ type: 'spki', format: 'der' })).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')
+ publicIdentityFingerprint(readFileSync(join(source, 'admin.pem'), 'utf8'))
)
})
diff --git a/control-api/test/routes.registryConnect.keyPolicy.test.ts b/control-api/test/routes.registryConnect.keyPolicy.test.ts
new file mode 100644
index 000000000..3a22a50fd
--- /dev/null
+++ b/control-api/test/routes.registryConnect.keyPolicy.test.ts
@@ -0,0 +1,363 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import jwt from 'jsonwebtoken'
+import { generateKeyPairSync, randomBytes, randomUUID } from 'node:crypto'
+import request from 'supertest'
+import { publicKeyPemFingerprint } from '@clerum/jwt-key-policy'
+import { clerumErrorHandler } from '../src/http/errorHandler.js'
+import { rootLogger } from '../src/observability/logger.js'
+import { createRegistryConnectRouter } from '../src/routes/admin/registryConnect.js'
+import {
+ __resetRegistryConnectionCacheForTests,
+ upsertPendingConnection,
+} from '../src/services/registryConnectionDb.js'
+import { __resetRegistryIdentityCacheGenerationForTests } from '../src/services/registryIdentityCache.js'
+
+const { cfg, database, policy } = vi.hoisted(() => ({
+ cfg: {
+ registryConnectionMode: 'self-hosted',
+ registryUrl: 'https://registry.example.invalid',
+ oauthEncryptionKey: '',
+ } as Record<string, unknown>,
+ database: { query: vi.fn(), row: undefined as Record<string, unknown> | undefined },
+ policy: { denied: new Set<string>(), denyRegistration: false },
+}))
+vi.mock('../src/config.js', () => ({ config: cfg }))
+vi.mock('../src/db.js', () => ({
+ pool: { query: (sql: string, values?: unknown[]) => database.query(sql, values) },
+ withTransaction: async (run: (db: unknown) => Promise<unknown>) =>
+ run({ query: (sql: string, values?: unknown[]) => database.query(sql, values) }),
+}))
+vi.mock('@clerum/jwt-key-policy', async importOriginal => {
+ const actual = await importOriginal<typeof import('@clerum/jwt-key-policy')>()
+ return {
+ ...actual,
+ parseSigningMaterial: (
+ raw: string,
+ source: string,
+ options?: import('@clerum/jwt-key-policy').JwtFingerprintOptions
+ ) => {
+ const denied = [...policy.denied]
+ if (policy.denyRegistration) denied.push(actual.publicKeyPemFingerprint(raw))
+ return actual.parseSigningMaterial(raw, source, {
+ ...options,
+ fingerprints: [...(options?.fingerprints ?? []), ...denied],
+ })
+ },
+ }
+})
+// Auth/ratelimit/SQL transport are named HTTP preconditions and external
+// boundaries. The producer, encryption, key policy, PoP, routes and handler run.
+vi.mock('../src/middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (
+ req: express.Request,
+ _res: express.Response,
+ next: express.NextFunction
+ ) => {
+ ;(req as unknown as { adminAuth: { sub: string } }).adminAuth = { sub: 'admin-contract' }
+ next()
+ },
+}))
+vi.mock('../src/middleware/rateLimitMiddleware.js', () => ({
+ rateLimitMiddleware:
+ () => (_req: express.Request, _res: express.Response, next: express.NextFunction) =>
+ next(),
+}))
+vi.mock('../src/services/adminAuthService.js', () => ({
+ findAdminById: async () => ({ id: 'admin-contract', username: 'contract', status: 'active' }),
+}))
+
+function pair() {
+ return generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ })
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ database.row = undefined
+ cfg.registryUrl = 'https://registry.example.invalid'
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ policy.denied.clear()
+ policy.denyRegistration = false
+ database.query.mockImplementation(async (sql: string, values: unknown[] = []) => {
+ if (sql.includes('DELETE FROM registry_connection')) database.row = undefined
+ if (sql.includes('INSERT INTO registry_connection'))
+ database.row = {
+ deployment_id: values[0],
+ key_id: values[1],
+ public_key_pem: values[2],
+ private_key_encrypted: values[3],
+ requested_org_name: values[4],
+ contact_email: values[5],
+ status: values[6],
+ registry_url: values[7],
+ client_id: null,
+ client_secret_encrypted: null,
+ org_name: null,
+ }
+ const current = database.row
+ if (
+ sql.includes('UPDATE registry_connection') &&
+ current &&
+ current.deployment_id === values[3]
+ ) {
+ Object.assign(current, {
+ client_id: values[0],
+ client_secret_encrypted: values[1],
+ org_name: values[2],
+ status: 'connected',
+ })
+ }
+ return {
+ rows: sql.includes('SELECT deployment_id') && database.row ? [database.row] : [],
+ rowCount: 1,
+ }
+ })
+ vi.spyOn(rootLogger, 'warn')
+})
+afterEach(() => {
+ __resetRegistryConnectionCacheForTests()
+ __resetRegistryIdentityCacheGenerationForTests()
+ vi.restoreAllMocks()
+})
+
+async function persist(status: 'pending' | 'approved', invalid?: string) {
+ const material = pair()
+ await upsertPendingConnection({
+ deploymentId: 'deployment-contract',
+ keyId: 'key-contract',
+ publicKeyPem: material.publicKey,
+ privateKeyPem: invalid ?? material.privateKey,
+ requestedOrgName: 'contract-org',
+ contactEmail: '[email protected]',
+ registryUrl: 'https://registry.example.invalid',
+ status,
+ })
+ database.query.mockClear()
+ return material
+}
+function app() {
+ const application = express()
+ application.use(express.json())
+ application.use((req, _res, next) => {
+ ;(req as unknown as { log: typeof rootLogger }).log = rootLogger
+ ;(req as unknown as { correlationId: string }).correlationId = 'registry-policy-contract'
+ next()
+ })
+ application.use(createRegistryConnectRouter())
+ application.use(clerumErrorHandler)
+ return application
+}
+const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status })
+const mutationCount = () =>
+ database.query.mock.calls.filter(([sql]) => /DELETE|INSERT|UPDATE/.test(sql)).length
+
+// Opaque credentials are generated per boundary response, never literal fixtures.
+const claimEvidence = () => Object.fromEntries([['claim_token', randomUUID()]])
+const claimedCredentials = () =>
+ Object.fromEntries([
+ ['client_id', 'client-contract'],
+ ['client_secret', randomUUID()],
+ ['org', 'contract-org'],
+ ])
+
+function registryBoundary(publicKey: string) {
+ const effects = { burns: 0, rotations: 0, claims: [] as jwt.JwtPayload[] }
+ const outbound = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, options) => {
+ const url = String(input)
+ const pop = (options?.headers as Record<string, string> | undefined)?.DPoP
+ if (pop)
+ effects.claims.push(
+ jwt.verify(pop, publicKey, {
+ algorithms: ['RS256'],
+ audience: 'registry-api',
+ }) as jwt.JwtPayload
+ )
+ if (url.endsWith('/status'))
+ return response({ status: 'approved', claimed: false, suspended: false })
+ if (url.endsWith('/claim-token')) {
+ effects.rotations++
+ return response(claimEvidence())
+ }
+ if (url.endsWith('/claim')) {
+ effects.burns++
+ return response(claimedCredentials())
+ }
+ throw new Error('Unexpected registry boundary call')
+ })
+ return { outbound, effects }
+}
+
+describe('permanent persisted PoP policy conflicts', () => {
+ for (const kind of ['denied', 'malformed', 'mixed'] as const) {
+ it.each(['pending status', 'approved status', 'manual claim', 'recovery'])(
+ `${kind} key blocks %s before every registry/state effect`,
+ async operation => {
+ const invalid =
+ kind === 'malformed'
+ ? 'invalid signing material for a corruption fixture'
+ : kind === 'mixed'
+ ? pair().privateKey + pair().publicKey
+ : undefined
+ const material = await persist(
+ operation === 'approved status' || operation === 'recovery' ? 'approved' : 'pending',
+ invalid
+ )
+ if (kind === 'denied') policy.denied.add(publicKeyPemFingerprint(material.publicKey))
+ const before = JSON.stringify(database.row)
+ const { outbound, effects } = registryBoundary(material.publicKey)
+ const signing = vi.spyOn(jwt, 'sign')
+ const client = request(app())
+ const result = operation.endsWith('status')
+ ? await client.get('/admin/registry/connect').expect(409)
+ : await client
+ .post(
+ operation === 'recovery'
+ ? '/admin/registry/connect/recover'
+ : '/admin/registry/connect/claim'
+ )
+ .send(claimEvidence())
+ .expect(409)
+ expect(result.body.error).toBe('registry_signing_material_unavailable')
+ expect(outbound.mock.calls.length).toBe(0)
+ expect(signing.mock.calls.length).toBe(0)
+ expect(effects.burns).toBe(0)
+ expect(effects.rotations).toBe(0)
+ expect(mutationCount()).toBe(0)
+ expect(JSON.stringify(database.row) === before).toBe(true)
+ const events = vi
+ .mocked(rootLogger.warn)
+ .mock.calls.map(([fields]) => fields as Record<string, unknown>)
+ expect(events.some(fields => fields.event === 'registry_pop_key_unavailable')).toBe(true)
+ expect(JSON.stringify(events).includes('BEGIN')).toBe(false)
+ expect(JSON.stringify(events).includes(database.row!.private_key_encrypted as string)).toBe(
+ false
+ )
+ }
+ )
+ }
+})
+
+describe('fresh registry PoP contracts and transient separation', () => {
+ it('preserves real pending status and manual claim with the persisted kid/claims', async () => {
+ const material = await persist('pending')
+ const { effects } = registryBoundary(material.publicKey)
+ const result = await request(app()).get('/admin/registry/connect').expect(200)
+ expect(result.body.state).toBe('approved')
+ await request(app()).post('/admin/registry/connect/claim').send(claimEvidence()).expect(200)
+ expect(database.row!.status).toBe('connected')
+ expect(effects.burns).toBe(1)
+ expect(effects.claims.length).toBe(2)
+ expect(new Set(effects.claims.map(claims => claims.jti)).size).toBe(2)
+ for (const claims of effects.claims) {
+ expect(claims.sub).toBe('admin-contract')
+ expect(claims.iat).toBeUndefined()
+ expect(claims.exp! - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(120)
+ }
+ })
+
+ it('preserves real recovery rotation/claim and commits connected only after claim success', async () => {
+ const material = await persist('approved')
+ const { effects, outbound } = registryBoundary(material.publicKey)
+ const result = await request(app()).post('/admin/registry/connect/recover').expect(200)
+ expect(result.body.state).toBe('connected')
+ expect(effects.rotations).toBe(1)
+ expect(effects.burns).toBe(1)
+ expect(outbound.mock.calls.length).toBe(3)
+ expect(mutationCount()).toBe(1)
+ expect(database.row!.status).toBe('connected')
+ })
+
+ it('keeps actual transport failures as pending/connecting and does not mutate or burn', async () => {
+ await persist('pending')
+ const outbound = vi
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Fixture registry transport failure'))
+ const result = await request(app()).get('/admin/registry/connect').expect(200)
+ expect(result.body.state).toBe('pending')
+ expect(mutationCount()).toBe(0)
+ expect(outbound.mock.calls.length).toBe(1)
+ const manual = await request(app())
+ .post('/admin/registry/connect/claim')
+ .send(claimEvidence())
+ .expect(500)
+ expect(manual.body.error === 'registry_signing_material_unavailable').toBe(false)
+ expect(mutationCount()).toBe(0)
+ await persist('approved')
+ const recovery = await request(app()).post('/admin/registry/connect/recover').expect(202)
+ expect(recovery.body.state).toBe('connecting')
+ expect(mutationCount()).toBe(0)
+ })
+
+ it('rejects a denied new registration before outbound registration and local persistence', async () => {
+ policy.denyRegistration = true
+ const outbound = vi.spyOn(globalThis, 'fetch').mockResolvedValue(response({}, 201))
+ const signing = vi.spyOn(jwt, 'sign')
+ const result = await request(app())
+ .post('/admin/registry/connect/request')
+ .send({ requested_org_name: 'contract-org', contact_email: '[email protected]' })
+ .expect(409)
+ expect(result.body.error).toBe('registry_signing_material_unavailable')
+ expect(outbound.mock.calls.length).toBe(0)
+ expect(signing.mock.calls.length).toBe(0)
+ expect(mutationCount()).toBe(0)
+ expect(database.row === undefined).toBe(true)
+ })
+
+ it('keeps fresh registration no-kid PoP and auto-claim producer/connected behavior', async () => {
+ let registeringPublic = ''
+ let claimsConsumed = 0
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, options) => {
+ if (String(input).endsWith('/register')) {
+ const body = JSON.parse(options!.body as string) as {
+ public_key_pem: string
+ pop: string
+ deployment_info: { auto_claim: boolean }
+ }
+ registeringPublic = body.public_key_pem
+ const signed = jwt.decode(body.pop, { complete: true })!
+ expect(signed.header.kid).toBeUndefined()
+ expect(body.deployment_info.auto_claim).toBe(true)
+ expect(
+ (jwt.verify(body.pop, registeringPublic, { audience: 'registry-api' }) as jwt.JwtPayload)
+ .sub
+ ).toBe('admin-contract')
+ return response(
+ { ...claimEvidence(), deployment_id: 'deployment-contract', key_id: 'key-contract' },
+ 201
+ )
+ }
+ if (String(input).endsWith('/claim')) {
+ const pop = (options!.headers as Record<string, string>).DPoP
+ expect(jwt.decode(pop, { complete: true })!.header.kid).toBe('key-contract')
+ jwt.verify(pop, registeringPublic, { algorithms: ['RS256'], audience: 'registry-api' })
+ claimsConsumed++
+ return response(claimedCredentials())
+ }
+ throw new Error('Unexpected registry boundary call')
+ })
+ const result = await request(app())
+ .post('/admin/registry/connect/request')
+ .send({ requested_org_name: 'contract-org', contact_email: '[email protected]' })
+ .expect(200)
+ expect(result.body.state).toBe('connected')
+ expect(claimsConsumed).toBe(1)
+ expect(database.row!.status).toBe('connected')
+ expect(database.row!.requested_org_name).toBe('contract-org')
+ expect(database.row!.contact_email).toBe('[email protected]')
+ })
+
+ it('allows explicit DELETE cleanup with no URL even when the stored key is invalid', async () => {
+ await persist('approved', 'invalid signing material for a cleanup fixture')
+ cfg.registryUrl = ''
+ const outbound = vi.spyOn(globalThis, 'fetch')
+ const signing = vi.spyOn(jwt, 'sign')
+ await request(app()).delete('/admin/registry/connect').expect(204)
+ expect(database.row === undefined).toBe(true)
+ expect(mutationCount()).toBe(1)
+ expect(outbound.mock.calls.length).toBe(0)
+ expect(signing.mock.calls.length).toBe(0)
+ })
+})
diff --git a/control-api/test/services.registryConnectionDb.test.ts b/control-api/test/services.registryConnectionDb.test.ts
index c4847ecce..bad1180a8 100644
--- a/control-api/test/services.registryConnectionDb.test.ts
+++ b/control-api/test/services.registryConnectionDb.test.ts
@@ -1,6 +1,7 @@
// test/services.registryConnectionDb.test.ts
import { afterEach, describe, expect, it, vi } from 'vitest'
import { generateKeyPairSync, randomBytes } from 'node:crypto'
+import { publicKeyPemFingerprint } from '@clerum/jwt-key-policy'
import {
decryptOAuthSecret,
deriveOAuthEncryptionKey,
@@ -112,11 +113,12 @@ afterEach(() => {
describe('resolveVoucherSigningMaterial — managed', () => {
it('returns the env voucher key + kid', async () => {
- const { privateKey } = keypair()
+ const { privateKey, publicKey } = keypair()
cfg.registryVoucherPrivateKey = privateKey
cfg.registryVoucherKid = 'key-uuid-123'
const { signingKey, kid } = await resolveVoucherSigningMaterial()
- expect(signingKey).toBe(privateKey)
+ expect(signingKey === privateKey.trim()).toBe(true)
+ expect(publicKeyPemFingerprint(signingKey)).toBe(publicKeyPemFingerprint(publicKey))
expect(kid).toBe('key-uuid-123')
// managed never touches the DB
expect(dbQuery).not.toHaveBeenCalled()
@@ -137,17 +139,24 @@ describe('resolveVoucherSigningMaterial — managed', () => {
describe('resolveVoucherSigningMaterial — self-hosted', () => {
it('decrypts the private key from the DB row and uses row.key_id as kid', async () => {
- const { privateKey } = keypair()
+ const { privateKey, publicKey } = keypair()
const encKey = randomBytes(32).toString('hex')
cfg.registryConnectionMode = 'self-hosted'
cfg.oauthEncryptionKey = encKey
const enc = encryptOAuthSecret(deriveOAuthEncryptionKey(encKey), privateKey)
dbQuery.mockResolvedValueOnce({
- rows: [makeRawRow(encKey, { key_id: 'row-kid-9', private_key_encrypted: enc })],
+ rows: [
+ makeRawRow(encKey, {
+ key_id: 'row-kid-9',
+ public_key_pem: publicKey,
+ private_key_encrypted: enc,
+ }),
+ ],
rowCount: 1,
})
const { signingKey, kid } = await resolveVoucherSigningMaterial()
- expect(signingKey).toBe(privateKey)
+ expect(signingKey === privateKey.trim()).toBe(true)
+ expect(publicKeyPemFingerprint(signingKey)).toBe(publicKeyPemFingerprint(publicKey))
expect(kid).toBe('row-kid-9')
})
diff --git a/control-api/test/services.registryPopSigner.keyPolicy.test.ts b/control-api/test/services.registryPopSigner.keyPolicy.test.ts
new file mode 100644
index 000000000..3c0e5c416
--- /dev/null
+++ b/control-api/test/services.registryPopSigner.keyPolicy.test.ts
@@ -0,0 +1,102 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
+import { createPrivateKey, generateKeyPairSync } from 'node:crypto'
+import { publicKeyPemFingerprint } from '@clerum/jwt-key-policy'
+import { signPop } from '../src/services/registryPopSigner.js'
+
+const deniedIdentities = vi.hoisted(() => new Set<string>())
+vi.mock('@clerum/jwt-key-policy', async importOriginal => {
+ const actual = await importOriginal<typeof import('@clerum/jwt-key-policy')>()
+ return {
+ ...actual,
+ parseSigningMaterial: (
+ raw: string,
+ source: string,
+ options?: import('@clerum/jwt-key-policy').JwtFingerprintOptions
+ ) =>
+ actual.parseSigningMaterial(raw, source, {
+ ...options,
+ fingerprints: [...(options?.fingerprints ?? []), ...deniedIdentities],
+ }),
+ }
+})
+
+function pair() {
+ return generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ })
+}
+afterEach(() => {
+ deniedIdentities.clear()
+ vi.restoreAllMocks()
+})
+
+describe('registry PoP signing policy', () => {
+ it('canonicalizes an escaped-CR PKCS1 signer and preserves kid/audience/TTL/jti/noTimestamp', () => {
+ const material = pair()
+ const representation = createPrivateKey(material.privateKey)
+ .export({ type: 'pkcs1', format: 'pem' })
+ .toString()
+ .replace(/\n/g, '\\r')
+ const signedJwt = signPop({
+ privateKeyPem: representation,
+ sub: 'admin-contract',
+ kid: 'key-contract',
+ })
+ const header = jwt.decode(signedJwt, { complete: true })!.header
+ const claims = jwt.verify(signedJwt, material.publicKey, {
+ algorithms: ['RS256'],
+ audience: 'registry-api',
+ }) as jwt.JwtPayload
+ expect(header.kid).toBe('key-contract')
+ expect(claims.sub).toBe('admin-contract')
+ expect(typeof claims.jti).toBe('string')
+ expect(claims.iat).toBeUndefined()
+ expect(claims.exp! - Math.floor(Date.now() / 1000)).toBeGreaterThan(0)
+ expect(claims.exp! - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(120)
+ })
+
+ it('rejects a scoped denied identity before invoking the JWT signer', () => {
+ const material = pair()
+ deniedIdentities.add(publicKeyPemFingerprint(material.publicKey))
+ const signing = vi.spyOn(jwt, 'sign')
+ expect(() => signPop({ privateKeyPem: material.privateKey, sub: 'admin-contract' })).toThrow(
+ 'registry_signing_material_unavailable'
+ )
+ expect(signing.mock.calls.length).toBe(0)
+ })
+
+ it('classifies malformed key material as a permanent safe failure before signing', () => {
+ // Deliberately malformed input tests corruption rejection, not a key fixture.
+ const corrupted = 'invalid signing material for a corruption fixture'
+ const signing = vi.spyOn(jwt, 'sign')
+ let failure: unknown
+ try {
+ signPop({ privateKeyPem: corrupted, sub: 'admin-contract' })
+ } catch (error) {
+ failure = error
+ }
+ expect(failure).toMatchObject({
+ message: 'registry_signing_material_unavailable',
+ reason: 'invalid_pem',
+ })
+ expect(signing.mock.calls.length).toBe(0)
+ })
+
+ it('rejects mixed public/private objects rather than signing a selected private half', () => {
+ const material = pair()
+ const other = pair()
+ const signing = vi.spyOn(jwt, 'sign')
+ for (const mixed of [
+ material.privateKey + other.publicKey,
+ other.publicKey + material.privateKey,
+ ]) {
+ expect(() => signPop({ privateKeyPem: mixed, sub: 'admin-contract' })).toThrow(
+ 'registry_signing_material_unavailable'
+ )
+ }
+ expect(signing.mock.calls.length).toBe(0)
+ })
+})
diff --git a/control-api/test/services.registryVoucher.test.ts b/control-api/test/services.registryVoucher.test.ts
index 7bb964b72..d81d9e65e 100644
--- a/control-api/test/services.registryVoucher.test.ts
+++ b/control-api/test/services.registryVoucher.test.ts
@@ -1,12 +1,21 @@
-// control-api/test/services.registryVoucher.test.ts
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
import jwt from 'jsonwebtoken'
-import { generateKeyPairSync } from 'node:crypto'
-import * as devKeyPolicy from '../src/bannedDevSigningKeys.js'
-import { __resetRegistryConnectionCacheForTests } from '../src/services/registryConnectionDb.js'
+import { createPrivateKey, generateKeyPairSync, randomBytes } from 'node:crypto'
+import request from 'supertest'
+import { publicKeyPemFingerprint } from '@clerum/jwt-key-policy'
+import { clerumErrorHandler } from '../src/http/errorHandler.js'
+import { rootLogger } from '../src/observability/logger.js'
+import { createRegistryRouter } from '../src/routes/registry.js'
+import {
+ __resetRegistryConnectionCacheForTests,
+ resolveVoucherSigningMaterial,
+ upsertPendingConnection,
+} from '../src/services/registryConnectionDb.js'
+import { __resetRegistryIdentityCacheGenerationForTests } from '../src/services/registryIdentityCache.js'
import { VoucherUnavailableError, mintIdentityVoucher } from '../src/services/registryVoucher.js'
-const { cfg } = vi.hoisted(() => ({
+const { cfg, database, deniedIdentities } = vi.hoisted(() => ({
cfg: {
registryConnectionMode: 'managed',
registryVoucherPrivateKey: '',
@@ -15,11 +24,49 @@ const { cfg } = vi.hoisted(() => ({
registryClientId: '',
oauthEncryptionKey: '',
} as Record<string, unknown>,
+ database: { query: vi.fn(), row: undefined as Record<string, unknown> | undefined },
+ deniedIdentities: new Set<string>(),
}))
vi.mock('../src/config.js', () => ({ config: cfg }))
-// 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 }) },
+ pool: { query: (sql: string, values?: unknown[]) => database.query(sql, values) },
+ withTransaction: async (run: (db: unknown) => Promise<unknown>) =>
+ run({ query: (sql: string, values?: unknown[]) => database.query(sql, values) }),
+}))
+vi.mock('@clerum/jwt-key-policy', async importOriginal => {
+ const actual = await importOriginal<typeof import('@clerum/jwt-key-policy')>()
+ return {
+ ...actual,
+ parseSigningMaterial: (
+ raw: string,
+ source: string,
+ options?: import('@clerum/jwt-key-policy').JwtFingerprintOptions
+ ) =>
+ actual.parseSigningMaterial(raw, source, {
+ ...options,
+ fingerprints: [...(options?.fingerprints ?? []), ...deniedIdentities],
+ }),
+ }
+})
+// Authenticated admin and rate-limit persistence are HTTP preconditions. Policy,
+// SQL producer, encryption, voucher signer, router and global handler stay real.
+vi.mock('../src/middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (
+ req: express.Request,
+ _res: express.Response,
+ next: express.NextFunction
+ ) => {
+ ;(req as unknown as { adminAuth: { sub: string } }).adminAuth = { sub: 'admin-1' }
+ next()
+ },
+}))
+vi.mock('../src/middleware/rateLimitMiddleware.js', () => ({
+ rateLimitMiddleware:
+ () => (_req: express.Request, _res: express.Response, next: express.NextFunction) =>
+ next(),
+}))
+vi.mock('../src/services/adminAuthService.js', () => ({
+ findAdminById: async () => ({ id: 'admin-1', username: 'alice', status: 'active' }),
}))
function keypair() {
@@ -31,8 +78,39 @@ function keypair() {
}
const admin = { id: 'admin-1', username: 'alice' } as never
+beforeEach(() => {
+ vi.clearAllMocks()
+ database.row = undefined
+ database.query.mockImplementation(async (sql: string, values: unknown[] = []) => {
+ if (sql.includes('DELETE FROM registry_connection')) database.row = undefined
+ if (sql.includes('INSERT INTO registry_connection')) {
+ database.row = {
+ deployment_id: values[0],
+ key_id: values[1],
+ public_key_pem: values[2],
+ private_key_encrypted: values[3],
+ requested_org_name: values[4],
+ contact_email: values[5],
+ status: values[6],
+ registry_url: values[7],
+ client_id: null,
+ client_secret_encrypted: null,
+ org_name: null,
+ }
+ }
+ return {
+ rows: sql.includes('SELECT deployment_id') && database.row ? [database.row] : [],
+ rowCount: 1,
+ }
+ })
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ vi.spyOn(rootLogger, 'warn')
+ vi.spyOn(rootLogger, 'error')
+})
afterEach(() => {
__resetRegistryConnectionCacheForTests()
+ __resetRegistryIdentityCacheGenerationForTests()
+ deniedIdentities.clear()
cfg.registryConnectionMode = 'managed'
cfg.registryVoucherPrivateKey = ''
cfg.registryVoucherKid = ''
@@ -41,96 +119,164 @@ afterEach(() => {
vi.restoreAllMocks()
})
-describe('mintIdentityVoucher — voucher v2 (managed)', () => {
- it('emits a kid header and a payload of EXACTLY {iss,aud,sub,jti,exp}', async () => {
- const { publicKey, privateKey } = keypair()
- cfg.registryVoucherPrivateKey = privateKey
- cfg.registryVoucherKid = 'key-uuid-42'
- const token = await mintIdentityVoucher(admin)
+async function persist(pair = keypair(), stored = pair.privateKey) {
+ cfg.registryConnectionMode = 'self-hosted'
+ await upsertPendingConnection({
+ deploymentId: 'deployment-1',
+ keyId: 'key-uuid-42',
+ publicKeyPem: pair.publicKey,
+ privateKeyPem: stored,
+ requestedOrgName: 'contract-org',
+ contactEmail: '[email protected]',
+ registryUrl: 'https://registry.example.invalid',
+ status: 'approved',
+ })
+ return pair
+}
- const header = jwt.decode(token, { complete: true })!.header
- expect(header.alg).toBe('RS256')
- expect(header.kid).toBe('key-uuid-42')
+function app() {
+ const application = express()
+ application.use((req, _res, next) => {
+ ;(req as unknown as { log: typeof rootLogger }).log = rootLogger
+ ;(req as unknown as { correlationId: string }).correlationId = 'voucher-contract'
+ next()
+ })
+ application.use(createRegistryRouter())
+ application.use(clerumErrorHandler)
+ return application
+}
- const payload = jwt.verify(token, publicKey, {
+function reasonEvents() {
+ return vi.mocked(rootLogger.warn).mock.calls.map(([fields]) => fields as Record<string, unknown>)
+}
+
+describe('managed voucher v2', () => {
+ it('signs exactly the five voucher claims with the dedicated kid and 60-second TTL', async () => {
+ const pair = keypair()
+ cfg.registryVoucherPrivateKey = pair.privateKey
+ cfg.registryVoucherKid = 'key-uuid-42'
+ const signedJwt = await mintIdentityVoucher(admin)
+ const header = jwt.decode(signedJwt, { complete: true })!.header
+ const payload = jwt.verify(signedJwt, pair.publicKey, {
algorithms: ['RS256'],
issuer: 'control-api',
audience: 'registry-api',
}) as jwt.JwtPayload
+ expect(header.alg).toBe('RS256')
+ expect(header.kid).toBe('key-uuid-42')
expect(payload.sub).toBe('admin-1')
- expect(typeof payload.jti).toBe('string')
- expect(typeof payload.exp).toBe('number')
- // v2 drops these three:
- expect(payload.email).toBeUndefined()
- expect(payload.username).toBeUndefined()
- expect(payload.iat).toBeUndefined()
- // exactly the five keys
expect(Object.keys(payload).sort()).toEqual(['aud', 'exp', 'iss', 'jti', 'sub'])
- // TTL asserted against now (iat is gone)
- expect(payload.exp! - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(60)
expect(payload.exp! - Math.floor(Date.now() / 1000)).toBeGreaterThan(0)
+ expect(payload.exp! - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(60)
})
- it('does NOT fall back to adminJwtPrivateKey — throws when the dedicated key is unset', async () => {
- cfg.registryVoucherPrivateKey = ''
+ it('requires the dedicated key and kid even when an admin key exists', async () => {
+ cfg.adminJwtPrivateKey = keypair().privateKey
cfg.registryVoucherKid = 'key-uuid-42'
- cfg.adminJwtPrivateKey = keypair().privateKey // present, but must be ignored
await expect(mintIdentityVoucher(admin)).rejects.toBeInstanceOf(VoucherUnavailableError)
- })
-
- it('throws when the kid is unset', async () => {
cfg.registryVoucherPrivateKey = keypair().privateKey
cfg.registryVoucherKid = ''
await expect(mintIdentityVoucher(admin)).rejects.toBeInstanceOf(VoucherUnavailableError)
+ expect(database.query.mock.calls.length).toBe(0)
})
-})
-describe('voucher v2 (self-hosted) persisted-key guard', () => {
- it('rejects a persisted signing key flagged as historically committed', async () => {
- const { deriveOAuthEncryptionKey, encryptOAuthSecret } =
- await import('../src/oauth/encryption.js')
- const { pool } = await import('../src/db.js')
- const encryptionKeyHex = 'ab'.repeat(32)
+ it('canonicalizes a managed PKCS1/escaped-CR private representation', async () => {
const pair = keypair()
- const persisted = pair.privateKey
- cfg.registryConnectionMode = 'self-hosted'
- ;(cfg as Record<string, unknown>).oauthEncryptionKey = encryptionKeyHex
- expect(devKeyPolicy.isBannedSigningKeyPem(persisted)).toBe(false)
- const check = vi.spyOn(devKeyPolicy, 'isBannedSigningKeyPem')
- const fingerprint = devKeyPolicy.publicKeyPemFingerprint(pair.publicKey)
- vi.mocked(pool.query).mockResolvedValueOnce({
- rows: [
- {
- deployment_id: 'deployment-1',
- key_id: 'key-uuid-42',
- public_key_pem: '',
- private_key_encrypted: encryptOAuthSecret(
- deriveOAuthEncryptionKey(encryptionKeyHex),
- persisted
- ),
- client_id: '',
- client_secret_encrypted: null,
- org_name: null,
- requested_org_name: null,
- contact_email: null,
- status: 'connected',
- registry_url: '',
- },
- ],
- })
- // 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)
+ cfg.registryVoucherPrivateKey = createPrivateKey(pair.privateKey)
+ .export({ type: 'pkcs1', format: 'pem' })
+ .toString()
+ .replace(/\n/g, '\\r')
+ cfg.registryVoucherKid = 'key-uuid-42'
+ const resolved = await resolveVoucherSigningMaterial()
+ expect(resolved.signingKey === pair.privateKey.trim()).toBe(true)
+ const signedJwt = await mintIdentityVoucher(admin)
+ expect(
+ (jwt.verify(signedJwt, pair.publicKey, { audience: 'registry-api' }) as jwt.JwtPayload).sub
+ ).toBe('admin-1')
+ })
+})
+
+describe('persisted voucher key policy and actual HTTP composition', () => {
+ it('uses the real producer/encryption row and signs a fresh voucher through the HTTP route', async () => {
+ const pair = await persist()
+ for (const column of [
+ 'deployment_id',
+ 'key_id',
+ 'public_key_pem',
+ 'private_key_encrypted',
+ 'requested_org_name',
+ 'contact_email',
+ 'status',
+ ]) {
+ expect(
+ typeof database.row![column] === 'string' && (database.row![column] as string).length > 0
+ ).toBe(true)
}
+ expect(publicKeyPemFingerprint(database.row!.public_key_pem as string)).toBe(
+ publicKeyPemFingerprint(pair.publicKey)
+ )
+ expect((database.row!.private_key_encrypted as string).includes(pair.privateKey)).toBe(false)
+ const result = await request(app()).post('/registry/identity-voucher').expect(200)
+ expect(typeof result.body.voucher).toBe('string')
+ const payload = jwt.verify(result.body.voucher, pair.publicKey, {
+ algorithms: ['RS256'],
+ issuer: 'control-api',
+ audience: 'registry-api',
+ }) as jwt.JwtPayload
+ expect(payload.sub).toBe('admin-1')
+ expect(reasonEvents().length).toBe(0)
+ })
+
+ it('rejects a scoped denied persisted identity before signing and emits only safe reason metadata', async () => {
+ const pair = await persist()
+ deniedIdentities.add(publicKeyPemFingerprint(pair.publicKey))
+ const signing = vi.spyOn(jwt, 'sign')
+ const result = await request(app()).post('/registry/identity-voucher').expect(500)
+ expect(result.body.error).toBe('registry_voucher_unavailable')
+ expect(signing.mock.calls.length).toBe(0)
+ expect(reasonEvents().map(fields => fields.event)).toEqual(['registry_voucher_key_banned'])
+ expect(reasonEvents()[0]).toMatchObject({
+ source: 'registry_connection',
+ slot: 'voucher',
+ reason: 'banned_identity',
+ deploymentId: 'deployment-1',
+ })
+ const serialized = JSON.stringify(reasonEvents())
+ expect(serialized.includes(pair.privateKey)).toBe(false)
+ expect(serialized.includes(database.row!.private_key_encrypted as string)).toBe(false)
+ expect(serialized.includes('BEGIN')).toBe(false)
+ })
+
+ it('rejects malformed decrypted signing material with a distinct safe reason event', async () => {
+ await persist(keypair(), 'invalid signing material for a corruption fixture')
+ const signing = vi.spyOn(jwt, 'sign')
+ const result = await request(app()).post('/registry/identity-voucher').expect(500)
+ expect(result.body.error).toBe('registry_voucher_unavailable')
+ expect(signing.mock.calls.length).toBe(0)
+ expect(reasonEvents().map(fields => fields.event)).toEqual(['registry_voucher_key_invalid'])
+ expect(reasonEvents()[0].reason).toBe('invalid_pem')
+ })
+
+ it('keeps missing enrollment distinct from an invalid stored key', async () => {
+ cfg.registryConnectionMode = 'self-hosted'
+ const signing = vi.spyOn(jwt, 'sign')
+ const result = await request(app()).post('/registry/identity-voucher').expect(500)
+ expect(result.body.error).toBe('registry_voucher_unavailable')
+ expect(signing.mock.calls.length).toBe(0)
+ expect(reasonEvents().length).toBe(0)
+ })
+
+ it('preserves database and decryption failures instead of classifying them as missing enrollment', async () => {
+ cfg.registryConnectionMode = 'self-hosted'
+ const databaseFailure = new Error('database unavailable')
+ database.query.mockRejectedValueOnce(databaseFailure)
+ await expect(mintIdentityVoucher(admin)).rejects.toBe(databaseFailure)
+ const pair = await persist()
+ database.row!.private_key_encrypted = 'invalid-at-rest-envelope'
+ const failure = await mintIdentityVoucher(admin).catch(error => error)
+ expect(failure instanceof Error).toBe(true)
+ expect(failure instanceof VoucherUnavailableError).toBe(false)
+ expect(reasonEvents().length).toBe(0)
+ expect(typeof pair.publicKey).toBe('string')
})
})
diff --git a/control-api/tsconfig.jwt-contract-tests.json b/control-api/tsconfig.jwt-contract-tests.json
new file mode 100644
index 000000000..6f314f7be
--- /dev/null
+++ b/control-api/tsconfig.jwt-contract-tests.json
@@ -0,0 +1,26 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "..",
+ "noEmit": true,
+ "module": "ESNext",
+ "moduleResolution": "Bundler"
+ },
+ "include": [
+ "src/config.ts",
+ "src/bannedDevSigningKeys.ts",
+ "src/devSigningKeys.ts",
+ "src/middleware/correlationId.ts",
+ "test/config.jwtHardening.test.ts",
+ "test/config.prod.test.ts",
+ "test/config.registryConnectionMode.test.ts",
+ "test/bannedDevSigningKeys.test.ts",
+ "test/devSigningKeys.test.ts",
+ "test/services.registryConnectionDb.test.ts",
+ "test/services.registryVoucher.test.ts",
+ "test/services.registryPopSigner.keyPolicy.test.ts",
+ "test/routes.registryConnect.keyPolicy.test.ts",
+ "../scripts/testing/devJwtVerifierContract.ts"
+ ],
+ "exclude": []
+}
diff --git a/control-api/tsconfig.jwt-package-types.json b/control-api/tsconfig.jwt-package-types.json
new file mode 100644
index 000000000..798747bdb
--- /dev/null
+++ b/control-api/tsconfig.jwt-package-types.json
@@ -0,0 +1,17 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "..",
+ "noEmit": true,
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "types": ["node"],
+ "typeRoots": ["./node_modules/@types"]
+ },
+ "include": [
+ "../packages/jwt-key-policy/test/policy-types.cts",
+ "../packages/jwt-key-policy/test/policy-types.mts",
+ "../packages/jwt-key-policy/test/store-types.ts"
+ ],
+ "exclude": []
+}
diff --git a/deploy/images.json b/deploy/images.json
index 698d11973..6c7511325 100644
--- a/deploy/images.json
+++ b/deploy/images.json
@@ -23,6 +23,7 @@
"packages/workflow-runtime-core/**",
"packages/workflow-recipe-capability-policy/**",
"packages/image-policy/**",
+ "packages/jwt-key-policy/**",
"packages/display-field/**",
"packages/llm-provider-attempt-contract/**",
"packages/grok-provider-attempt-contract/**"
@@ -47,7 +48,8 @@
{
"name": "external-rest-api",
"path": "external-rest-api",
- "source_paths": ["external-rest-api/**"],
+ "rooted": true,
+ "source_paths": ["external-rest-api/**", "packages/jwt-key-policy/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -160,7 +162,8 @@
{
"name": "rpc-proxy",
"path": "rpc-proxy",
- "source_paths": ["rpc-proxy/**"],
+ "rooted": true,
+ "source_paths": ["rpc-proxy/**", "packages/jwt-key-policy/**"],
"published": true,
"deployed_to_minikube": true
},
diff --git a/external-rest-api/.env.example b/external-rest-api/.env.example
index 88f0721cb..4bce9faeb 100644
--- a/external-rest-api/.env.example
+++ b/external-rest-api/.env.example
@@ -17,6 +17,11 @@ EXTERNAL_REST_API_MEMBER_REGISTRATION_SERVICE_SERVICE_NAME=external-rest-api
# 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.
+# Explicit verifier keys require one RSA >=2048 PEM object (SPKI/PKCS#1 public
+# or X509 carrier); private PEM env input is legacy-compatible, not recommended.
+# Public store files never accept private material. Material/read limit: 64 KiB.
+# The store requires POSIX guarantees, trusted ancestors and the same effective
+# UID across services; otherwise supply the matching keys explicitly.
EXTERNAL_REST_API_JWT_PUBLIC_KEY=
EXTERNAL_REST_API_JWT_ISSUER=control-api
EXTERNAL_REST_API_JWT_AUDIENCE=profile-ui
diff --git a/external-rest-api/Dockerfile b/external-rest-api/Dockerfile
index 392708810..1cc43c85a 100644
--- a/external-rest-api/Dockerfile
+++ b/external-rest-api/Dockerfile
@@ -1,11 +1,13 @@
FROM node:24-alpine AS builder
WORKDIR /app
-COPY package*.json ./
+COPY packages/jwt-key-policy/package.json packages/jwt-key-policy/index.cjs packages/jwt-key-policy/index.d.ts packages/jwt-key-policy/dev-store.cjs packages/jwt-key-policy/dev-store.d.ts ./packages/jwt-key-policy/
+COPY external-rest-api/package*.json ./external-rest-api/
+WORKDIR /app/external-rest-api
RUN npm ci
-COPY tsconfig.json ./
-COPY src ./src
+COPY external-rest-api/tsconfig.json ./
+COPY external-rest-api/src ./src
RUN npm run build
RUN npm prune --production
@@ -16,10 +18,12 @@ WORKDIR /app
ENV NODE_ENV=production
ENV EXTERNAL_REST_API_PORT=8091
-COPY --from=builder --chown=app:app /app/package*.json ./
-COPY --from=builder --chown=app:app /app/dist ./dist
-COPY --from=builder --chown=app:app /app/node_modules ./node_modules
+COPY --from=builder --chown=app:app /app/packages/jwt-key-policy ./packages/jwt-key-policy
+COPY --from=builder --chown=app:app /app/external-rest-api/package*.json ./external-rest-api/
+COPY --from=builder --chown=app:app /app/external-rest-api/dist ./external-rest-api/dist
+COPY --from=builder --chown=app:app /app/external-rest-api/node_modules ./external-rest-api/node_modules
USER app
EXPOSE 8091
+WORKDIR /app/external-rest-api
CMD ["node", "dist/main.js"]
diff --git a/external-rest-api/Dockerfile.dockerignore b/external-rest-api/Dockerfile.dockerignore
new file mode 100644
index 000000000..accf9a1da
--- /dev/null
+++ b/external-rest-api/Dockerfile.dockerignore
@@ -0,0 +1,23 @@
+**
+!packages/
+!packages/jwt-key-policy/
+!packages/jwt-key-policy/package.json
+!packages/jwt-key-policy/index.cjs
+!packages/jwt-key-policy/index.d.ts
+!packages/jwt-key-policy/dev-store.cjs
+!packages/jwt-key-policy/dev-store.d.ts
+!external-rest-api/
+!external-rest-api/package.json
+!external-rest-api/package-lock.json
+!external-rest-api/tsconfig.json
+!external-rest-api/src/
+!external-rest-api/src/**
+**/node_modules/
+**/dist/
+**/.dev-keys/
+**/.env
+**/.env.*
+**/*.pem
+**/*.key
+**/*.log
+**/.local-notes/
diff --git a/external-rest-api/Makefile b/external-rest-api/Makefile
index af16c4faa..cac37acd8 100644
--- a/external-rest-api/Makefile
+++ b/external-rest-api/Makefile
@@ -14,7 +14,7 @@ dev: install
CLERUM_DEV_MODE=true npm run dev
docker-build:
- docker build -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) .
+ docker build -f Dockerfile -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) ..
docker-push: docker-build
docker push $(REGISTRY)/$(IMAGE_NAME):$(TAG)
diff --git a/external-rest-api/README.md b/external-rest-api/README.md
index c8e42e221..c32524031 100644
--- a/external-rest-api/README.md
+++ b/external-rest-api/README.md
@@ -123,6 +123,32 @@ 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.
+JWT material is checked by the shared `@clerum/jwt-key-policy`. Configure an
+RSA public key as SPKI or PKCS#1 PEM. An X509 certificate may carry the public
+identity, without CA, hostname or expiry validation. Private PEM environment
+values remain accepted for legacy compatibility and are converted to public
+SPKI; prefer supplying only the public half. Store public files reject private
+material. Exactly one complete PEM object is required; bundles, encrypted
+private material, non-RSA keys and historical committed identities fail.
+
+Every RS256 key must be RSA-2048 or stronger, including verifiers. This
+deliberately rejects previously accepted weak verifier keys under
+[RFC 7518 section 3.3](https://www.rfc-editor.org/rfc/rfc7518.html#section-3.3).
+The material/read limit is 64 KiB. Invalid explicit input never selects a
+different source or regenerates an identity.
+
+The dev store requires POSIX no-follow/nonblocking/exclusive-file guarantees,
+trusted ancestor directories and cooperating services with the same effective
+UID. It does not defend against hostile ancestors or same-UID processes.
+Use explicit signing/verifying environment keys for different users or
+unsupported platforms; this verifier then performs no store access. Corrupt
+or rejected keys require operator repair; they are not rotated automatically.
+
+`make docker-build` uses the repository root context. The equivalent command
+from that root is `docker build -f external-rest-api/Dockerfile .`. The image
+preserves the service/package layout and excludes package tests and local key
+data.
+
## Kubernetes Deploy
```bash
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 9b5ee500c..a4939707b 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,13 +1,14 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.88",
+ "version": "0.1.89",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.88",
+ "version": "0.1.89",
"dependencies": {
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
"express": "^4.21.2",
"express-rate-limit": "^8.5.1",
@@ -32,6 +33,18 @@
"node": ">=24"
}
},
+ "../packages/jwt-key-policy": {
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "node_modules/@clerum/jwt-key-policy": {
+ "resolved": "../packages/jwt-key-policy",
+ "link": true
+ },
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 6215a84d3..728f64ac4 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.88",
+ "version": "0.1.89",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
@@ -12,10 +12,12 @@
"dev": "tsx src/main.ts",
"test": "vitest run --no-file-parallelism",
"test:run": "vitest run --no-file-parallelism",
+ "typecheck:jwt-contract": "tsc -p tsconfig.jwt-contract-tests.json --noEmit",
"test:e2e": "npm --prefix ../tests/e2e run test:external-rest-api-e2e",
"test:e2e:watch": "npm --prefix ../tests/e2e run test:external-rest-api-e2e:watch"
},
"dependencies": {
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
"express": "^4.21.2",
"express-rate-limit": "^8.5.1",
diff --git a/external-rest-api/src/config.ts b/external-rest-api/src/config.ts
index 045f32921..d806f27f9 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -1,6 +1,13 @@
-import { createHash, createPublicKey } from 'node:crypto'
-import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs'
-import { dirname, isAbsolute, join } from 'node:path'
+import { dirname, join } from 'node:path'
+import { parseVerifierMaterial } from '@clerum/jwt-key-policy'
+import { readDevVerifierMaterial, resolveDevKeyStoreDir } from '@clerum/jwt-key-policy/dev-store'
+
+const DEV_MODE_ENABLED = process.env.CLERUM_DEV_MODE === 'true'
+if (process.env.NODE_ENV === 'production' && DEV_MODE_ENABLED) {
+ throw new Error(
+ '[SECURITY] Startup rejected: CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production.'
+ )
+}
type Config = {
port: number
@@ -87,14 +94,6 @@ function assertNotPlaceholder(label: string, value: string): void {
}
}
-function normalizePem(value: string): string {
- 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'
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'
@@ -143,96 +142,6 @@ 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 {
- const normalized = normalizePem(publicPem)
- let fingerprint: string
- let canonicalPublicPem: string
- try {
- // 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 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 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)
- }
-}
-
/**
* 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
@@ -241,21 +150,14 @@ function readDevJwtPublicKey(storeDir: string, fileName: string, envName: string
*/
function resolveSessionJwtPublicKey(): string {
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 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)
+ if (fromEnv) return parseVerifierMaterial(fromEnv, envName).publicPem
+ if (DEV_MODE_ENABLED) {
+ const storeDir = resolveDevKeyStoreDir(
+ join(serviceRoot(), '..', 'control-api'),
+ process.env.EVENFIRE_DEV_KEY_STORE
+ )
+ return readDevVerifierMaterial('session', storeDir).publicPem
}
return required(envName)
}
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 30732d784..44d79f630 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.88',
- rpcProxyVersion: '0.1.114',
+ externalRestApiVersion: '0.1.89',
+ rpcProxyVersion: '0.1.115',
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 4b6759a59..0fe5f1627 100644
--- a/external-rest-api/test/config.devKeyStore.test.ts
+++ b/external-rest-api/test/config.devKeyStore.test.ts
@@ -1,11 +1,19 @@
-import * as testApi from 'vitest'
-import { defineDevJwtVerifierContract } from '../../rpc-proxy/test/helpers/devJwtVerifierContract.js'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, it, vi } from 'vitest'
+import { createDevJwtVerifierContract } from '../../scripts/testing/devJwtVerifierContract.js'
-defineDevJwtVerifierContract({
- testApi,
+const contract = createDevJwtVerifierContract({
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'),
+ resetModules: () => vi.resetModules(),
+})
+
+beforeAll(contract.prepare, 60_000)
+beforeEach(contract.reset)
+afterEach(contract.cleanup)
+afterAll(contract.dispose)
+describe('external-rest-api dev JWT verifier contract', () => {
+ for (const testCase of contract.cases) it(testCase.name, testCase.run, 30_000)
})
diff --git a/external-rest-api/tsconfig.jwt-contract-tests.json b/external-rest-api/tsconfig.jwt-contract-tests.json
new file mode 100644
index 000000000..ab7162dbd
--- /dev/null
+++ b/external-rest-api/tsconfig.jwt-contract-tests.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "..",
+ "noEmit": true,
+ "module": "ESNext",
+ "moduleResolution": "Bundler"
+ },
+ "include": [
+ "src/config.ts",
+ "test/config.devKeyStore.test.ts",
+ "../scripts/testing/devJwtVerifierContract.ts"
+ ],
+ "exclude": []
+}
diff --git a/packages/jwt-key-policy/dev-store.cjs b/packages/jwt-key-policy/dev-store.cjs
new file mode 100644
index 000000000..2016311b2
--- /dev/null
+++ b/packages/jwt-key-policy/dev-store.cjs
@@ -0,0 +1,298 @@
+'use strict'
+
+const crypto = require('node:crypto')
+const fs = require('node:fs')
+const path = require('node:path')
+const {
+ MAX_PEM_MATERIAL_BYTES,
+ parseSigningMaterial,
+ parseVerifierMaterial,
+} = require('./index.cjs')
+
+const SLOTS = new Set(['rpc', 'session', 'admin'])
+const REASON_MESSAGES = Object.freeze({
+ invalid_slot: 'slot must be rpc, session, or admin',
+ relative_store_path: 'directory must be an absolute path',
+ unsupported_platform: 'requires POSIX effective-user and no-follow/nonblocking guarantees',
+ invalid_directory: 'path is not a directory',
+ symbolic_link: 'path is a symbolic link',
+ directory_owner_mismatch: 'directory is not owned by the current user',
+ insecure_directory: 'directory has group/other permissions; expected owner-only permissions',
+ not_regular_file: 'path is not a regular file',
+ file_owner_mismatch: 'file is not owned by the current user',
+ insecure_file: 'file has unsafe group/other permissions',
+ material_too_large: 'material exceeds the 64 KiB read limit',
+ missing_material: 'required material is missing',
+ orphan_public: 'has a public file without its signing material; operator recovery is required',
+ public_identity_mismatch: 'public file does not match its signing material; operator recovery is required',
+ temporary_collision: 'temporary path already exists; its contents were preserved',
+ incomplete_write: 'temporary file was not written completely',
+})
+
+class DevKeyStoreError extends Error {
+ constructor(source, reason) {
+ super(`Dev JWT key store ${REASON_MESSAGES[reason]}: ${source}`)
+ this.name = 'DevKeyStoreError'
+ this.code = 'ERR_JWT_DEV_STORE'
+ this.reason = reason
+ this.source = source
+ }
+}
+
+function fail(source, reason) {
+ throw new DevKeyStoreError(source, reason)
+}
+
+function absoluteStoreDirectory(storeDir) {
+ if (typeof storeDir !== 'string' || !path.isAbsolute(storeDir)) {
+ fail('EVENFIRE_DEV_KEY_STORE', 'relative_store_path')
+ }
+ // Lexical normalization preserves the final symlink for lstat. realpath
+ // would follow that symlink before the boundary could reject it.
+ return path.resolve(storeDir)
+}
+
+function resolveDevKeyStoreDir(serviceRoot, override) {
+ const supplied = typeof override === 'string' ? override.trim() : override
+ if (supplied !== undefined && typeof supplied !== 'string') {
+ fail('EVENFIRE_DEV_KEY_STORE', 'relative_store_path')
+ }
+ if (supplied) return absoluteStoreDirectory(supplied)
+ return path.join(absoluteStoreDirectory(serviceRoot), '.dev-keys')
+}
+
+function storePaths(slot, storeDir) {
+ // Validate the closed slot before constructing any filesystem path.
+ if (!SLOTS.has(slot)) fail('dev JWT slot', 'invalid_slot')
+ const directory = absoluteStoreDirectory(storeDir)
+ assertPosixStoreSupport(directory)
+ return {
+ directory,
+ privatePath: path.join(directory, `${slot}.pem`),
+ publicPath: path.join(directory, `${slot}.public.pem`),
+ }
+}
+
+function assertPosixStoreSupport(source) {
+ const requiredFlags = ['O_NOFOLLOW', 'O_NONBLOCK', 'O_CREAT', 'O_EXCL']
+ if (
+ process.platform === 'win32' ||
+ typeof process.geteuid !== 'function' ||
+ !requiredFlags.every(name => Number.isInteger(fs.constants[name]) && fs.constants[name] > 0)
+ ) {
+ fail(source, 'unsupported_platform')
+ }
+}
+
+function assertDirectoryStats(directory, stats) {
+ if (stats.isSymbolicLink()) fail(directory, 'symbolic_link')
+ if (!stats.isDirectory()) fail(directory, 'invalid_directory')
+ if (stats.uid !== process.geteuid()) fail(directory, 'directory_owner_mismatch')
+ if ((stats.mode & 0o077) !== 0) fail(directory, 'insecure_directory')
+}
+
+function readDirectoryStats(directory) {
+ return fs.lstatSync(directory, { throwIfNoEntry: false })
+}
+
+function ensureStoreDirectory(directory) {
+ let stats = readDirectoryStats(directory)
+ if (!stats) {
+ try {
+ fs.mkdirSync(directory, { mode: 0o700 })
+ } catch (error) {
+ if (error.code !== 'EEXIST') throw error
+ // A cooperating process created the directory; validate its result.
+ }
+ stats = readDirectoryStats(directory)
+ if (!stats) fail(directory, 'missing_material')
+ }
+ assertDirectoryStats(directory, stats)
+}
+
+function assertFileStats(filePath, stats, visibility) {
+ if (!stats.isFile()) fail(filePath, 'not_regular_file')
+ if (stats.uid !== process.geteuid()) fail(filePath, 'file_owner_mismatch')
+ const unsafeMask = visibility === 'private' ? 0o077 : 0o022
+ if ((stats.mode & unsafeMask) !== 0) fail(filePath, 'insecure_file')
+ if (stats.size > MAX_PEM_MATERIAL_BYTES) fail(filePath, 'material_too_large')
+}
+
+function closePreservingFailure(fd, primaryFailure) {
+ try {
+ fs.closeSync(fd)
+ } catch (error) {
+ if (!primaryFailure) throw error
+ }
+}
+
+function readStoreFile(filePath, visibility) {
+ let fd
+ try {
+ fd = fs.openSync(
+ filePath,
+ fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK
+ )
+ } catch (error) {
+ if (error.code === 'ENOENT') return undefined
+ if (error.code === 'ELOOP') fail(filePath, 'symbolic_link')
+ throw error
+ }
+ let primaryFailure
+ try {
+ assertFileStats(filePath, fs.fstatSync(fd), visibility)
+ // One bounded buffer also keeps repeated short reads from retaining a new
+ // allocation per chunk. The extra byte detects exact-limit file growth.
+ const buffer = Buffer.allocUnsafe(MAX_PEM_MATERIAL_BYTES + 1)
+ let bytes = 0
+ for (;;) {
+ const count = fs.readSync(fd, buffer, bytes, buffer.length - bytes, null)
+ if (count === 0) return buffer.subarray(0, bytes).toString('utf8')
+ bytes += count
+ if (bytes > MAX_PEM_MATERIAL_BYTES) fail(filePath, 'material_too_large')
+ }
+ } catch (error) {
+ primaryFailure = error
+ throw error
+ } finally {
+ closePreservingFailure(fd, primaryFailure)
+ }
+}
+
+function readSigningFile(privatePath) {
+ const raw = readStoreFile(privatePath, 'private')
+ return raw === undefined ? undefined : parseSigningMaterial(raw, privatePath)
+}
+
+function readPublicFile(publicPath) {
+ const raw = readStoreFile(publicPath, 'public')
+ return raw === undefined
+ ? undefined
+ : parseVerifierMaterial(raw, publicPath, { origin: 'store' })
+}
+
+/**
+ * Publish a complete owned candidate without replacing a final filename.
+ * Trusted ancestors and cooperating processes under the same euid are the
+ * filesystem boundary; path operations are not an adversarial openat sandbox.
+ * Atomic cooperation does not promise fsync/power-loss durability.
+ */
+function publishMaterial(finalPath, pem, visibility) {
+ const temporary = `${finalPath}.tmp-${process.pid.toString(36)}-${crypto.randomBytes(6).toString('hex')}`
+ const bytes = Buffer.from(pem, 'utf8')
+ const mode = visibility === 'private' ? 0o600 : 0o644
+ let fd
+ let ownsTemporary = false
+ let primaryFailure
+ try {
+ try {
+ fd = fs.openSync(
+ temporary,
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL |
+ fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK,
+ mode
+ )
+ ownsTemporary = true
+ } catch (error) {
+ // An existing candidate is not a final-publication winner. Never adopt,
+ // truncate or remove another operation's temporary file.
+ if (error.code === 'EEXIST' || error.code === 'ELOOP') {
+ fail(temporary, 'temporary_collision')
+ }
+ throw error
+ }
+ assertFileStats(temporary, fs.fstatSync(fd), visibility)
+ let written = 0
+ while (written < bytes.length) {
+ const count = fs.writeSync(fd, bytes, written, bytes.length - written, null)
+ if (count === 0) fail(temporary, 'incomplete_write')
+ written += count
+ }
+ const stats = fs.fstatSync(fd)
+ assertFileStats(temporary, stats, visibility)
+ if (stats.size !== bytes.length) fail(temporary, 'incomplete_write')
+ try {
+ fs.linkSync(temporary, finalPath)
+ return true
+ } catch (error) {
+ if (error.code === 'EEXIST') return false
+ throw error
+ }
+ } catch (error) {
+ primaryFailure = error
+ throw error
+ } finally {
+ let cleanupFailure
+ if (fd !== undefined) {
+ try { fs.closeSync(fd) } catch (error) { cleanupFailure = error }
+ }
+ if (ownsTemporary) {
+ try { fs.unlinkSync(temporary) } catch (error) {
+ if (error.code !== 'ENOENT' && !cleanupFailure) cleanupFailure = error
+ }
+ }
+ if (!primaryFailure && cleanupFailure) throw cleanupFailure
+ }
+}
+
+function assertPublicIdentity(publicPath, publicMaterial, signingMaterial) {
+ if (publicMaterial.fingerprint !== signingMaterial.fingerprint) {
+ fail(publicPath, 'public_identity_mismatch')
+ }
+}
+
+function ensurePublicMaterial(publicPath, signingMaterial) {
+ let verifying = readPublicFile(publicPath)
+ if (!verifying) {
+ publishMaterial(publicPath, signingMaterial.publicPem, 'public')
+ // Validate the actual opened winner, including successful own publication.
+ verifying = readPublicFile(publicPath)
+ if (!verifying) fail(publicPath, 'missing_material')
+ }
+ assertPublicIdentity(publicPath, verifying, signingMaterial)
+}
+
+function loadOrCreateDevSigningMaterial(slot, absoluteStore) {
+ const { directory, privatePath, publicPath } = storePaths(slot, absoluteStore)
+ ensureStoreDirectory(directory)
+ let signing = readSigningFile(privatePath)
+ if (!signing && readPublicFile(publicPath)) {
+ // A cooperating process may have published its complete pair between the
+ // first missing-private read and the public read. Re-read once, never mint
+ // a replacement identity over an orphan public file.
+ signing = readSigningFile(privatePath)
+ if (!signing) fail(publicPath, 'orphan_public')
+ }
+ if (!signing) {
+ const { privateKey } = crypto.generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ })
+ const candidate = parseSigningMaterial(privateKey, privatePath)
+ publishMaterial(privatePath, candidate.privatePem, 'private')
+ // Always consume the published inode. An EEXIST winner owns the identity,
+ // not this process's generated candidate.
+ signing = readSigningFile(privatePath)
+ if (!signing) fail(privatePath, 'missing_material')
+ }
+ ensurePublicMaterial(publicPath, signing)
+ return signing
+}
+
+function readDevVerifierMaterial(slot, absoluteStore) {
+ const { directory, publicPath } = storePaths(slot, absoluteStore)
+ const stats = readDirectoryStats(directory)
+ if (!stats) fail(directory, 'missing_material')
+ assertDirectoryStats(directory, stats)
+ const verifying = readPublicFile(publicPath)
+ if (!verifying) fail(publicPath, 'missing_material')
+ return verifying
+}
+
+module.exports = {
+ DevKeyStoreError,
+ resolveDevKeyStoreDir,
+ loadOrCreateDevSigningMaterial,
+ readDevVerifierMaterial,
+}
diff --git a/packages/jwt-key-policy/dev-store.d.ts b/packages/jwt-key-policy/dev-store.d.ts
new file mode 100644
index 000000000..3a769fc73
--- /dev/null
+++ b/packages/jwt-key-policy/dev-store.d.ts
@@ -0,0 +1,59 @@
+export type DevJwtSlot = 'rpc' | 'session' | 'admin'
+
+export interface DevSigningMaterial {
+ readonly privatePem: string
+ readonly publicPem: string
+ readonly fingerprint: string
+}
+
+export interface DevVerifierMaterial {
+ readonly publicPem: string
+ readonly fingerprint: string
+}
+
+export type DevKeyStoreReason =
+ | 'invalid_slot'
+ | 'relative_store_path'
+ | 'unsupported_platform'
+ | 'invalid_directory'
+ | 'symbolic_link'
+ | 'directory_owner_mismatch'
+ | 'insecure_directory'
+ | 'not_regular_file'
+ | 'file_owner_mismatch'
+ | 'insecure_file'
+ | 'material_too_large'
+ | 'missing_material'
+ | 'orphan_public'
+ | 'public_identity_mismatch'
+ | 'temporary_collision'
+ | 'incomplete_write'
+
+/** Safe boundary error. Native filesystem failures retain their errno/code. */
+export class DevKeyStoreError extends Error {
+ readonly code: 'ERR_JWT_DEV_STORE'
+ readonly reason: DevKeyStoreReason
+ readonly source: string
+ constructor(source: string, reason: DevKeyStoreReason)
+}
+
+/** Blank overrides select serviceRoot/.dev-keys; nonblank overrides must be absolute. */
+export function resolveDevKeyStoreDir(serviceRoot: string, override?: string): string
+
+/**
+ * Same-euid cooperating processes and trusted ancestors are required.
+ * No final identity is replaced or automatically repaired. Files are read
+ * through validated descriptors with a 64 KiB bound. Final-directory symlinks
+ * are rejected after lexical normalization; trusted ancestor symlinks remain
+ * allowed. Publication is atomic between processes, without an fsync promise.
+ */
+export function loadOrCreateDevSigningMaterial(
+ slot: DevJwtSlot,
+ absoluteStore: string
+): DevSigningMaterial
+
+/** Reads public material only; never creates a directory, key, or private-file read. */
+export function readDevVerifierMaterial(
+ slot: DevJwtSlot,
+ absoluteStore: string
+): DevVerifierMaterial
diff --git a/packages/jwt-key-policy/index.cjs b/packages/jwt-key-policy/index.cjs
new file mode 100644
index 000000000..cbc17254b
--- /dev/null
+++ b/packages/jwt-key-policy/index.cjs
@@ -0,0 +1,209 @@
+'use strict'
+
+const { createHash, createPrivateKey, createPublicKey } = require('node:crypto')
+
+// Public SPKI identities only. Never replace this policy through caller options.
+const HISTORICAL_PUBLIC_KEY_FINGERPRINTS = Object.freeze([
+ '4292d721765a93b0275f9f4ceb0a4667517fae00b5face8faa270513d610bb27',
+ 'f7dc08c248bf2b7724dead80dd96f9a5eeb49cf9920ba6fb46cf457a788d503e',
+ '2d05f607d125e4bd3c157d5c6115bf63cb454c1e45cc5bcc8eed950771dcfd31',
+])
+const MAX_PEM_MATERIAL_BYTES = 65536
+const PRIVATE_LABELS = new Set(['PRIVATE KEY', 'RSA PRIVATE KEY'])
+const PUBLIC_LABELS = new Set(['PUBLIC KEY', 'RSA PUBLIC KEY', 'CERTIFICATE'])
+const REASONS = Object.freeze({
+ invalid_type: 'must be a PEM string with valid policy options',
+ material_too_large: 'must not exceed 64 KiB of UTF-8 material',
+ invalid_pem: 'must contain one complete, valid PEM object',
+ multiple_pem_objects: 'must contain exactly one PEM object; mixed or concatenated objects are rejected',
+ unsupported_pem_type: 'contains an unsupported PEM object type',
+ encrypted_private_key: 'must not contain encrypted private material',
+ wrong_key_role: 'contains PEM material that is not permitted for this key role',
+ non_rsa_key: 'must be an RSA key for RS256; RSA-PSS and other key types are rejected',
+ undersized_rsa_key: 'RSA modulus must be at least 2048 bits',
+ banned_identity: 'must not use a historically committed dev JWT key or another denied identity',
+})
+
+function safeSource(source) {
+ // The API accepts a diagnostic label, not a value, URL, or crypto exception.
+ // Keep unsafe labels out of error messages as well as serialized metadata.
+ return typeof source === 'string' &&
+ /^[A-Za-z][A-Za-z0-9_.:/ ()-]{0,159}$/.test(source) &&
+ !/-----|(?:Bearer|Basic)\s/i.test(source)
+ ? source
+ : 'JWT key material'
+}
+
+class JwtKeyMaterialError extends Error {
+ constructor(source, reason) {
+ const safeReason = Object.hasOwn(REASONS, reason) ? reason : 'invalid_pem'
+ const label = safeSource(source)
+ super(`${label} ${REASONS[safeReason]}`)
+ this.name = 'JwtKeyMaterialError'
+ this.code = safeReason === 'banned_identity' ? 'ERR_JWT_KEY_BANNED' : 'ERR_JWT_KEY_INVALID'
+ this.reason = safeReason
+ this.source = label
+ }
+}
+
+function reject(source, reason) {
+ throw new JwtKeyMaterialError(source, reason)
+}
+
+function checkRaw(raw, source) {
+ if (typeof raw !== 'string') reject(source, 'invalid_type')
+ if (Buffer.byteLength(raw, 'utf8') > MAX_PEM_MATERIAL_BYTES) reject(source, 'material_too_large')
+}
+
+function normalizedValue(raw) {
+ return raw.replace(/\\r\\n|\\n|\\r/g, '\n').replace(/\r\n?/g, '\n').trim()
+}
+
+function normalizePem(raw) {
+ checkRaw(raw, 'JWT key material')
+ return normalizedValue(raw)
+}
+
+function onePemObject(raw, source) {
+ checkRaw(raw, source)
+ const normalized = normalizedValue(raw)
+ // Count every armor marker before parsing. OpenSSL otherwise selects a key
+ // from a bundle and can prefer a certificate/public key over its private half.
+ // Counting incomplete markers also prevents trailing truncated objects.
+ const begins = normalized.match(/-----BEGIN\b/gi) || []
+ const ends = normalized.match(/-----END\b/gi) || []
+ if (begins.length > 1 || ends.length > 1) reject(source, 'multiple_pem_objects')
+ if (begins.length !== 1 || ends.length !== 1) reject(source, 'invalid_pem')
+ const begin = /-----BEGIN ([^\r\n-]+)-----/.exec(normalized)
+ const end = /-----END ([^\r\n-]+)-----/.exec(normalized)
+ if (!begin || !end || begin[1] !== end[1] || end.index <= begin.index) reject(source, 'invalid_pem')
+ const label = begin[1]
+ const body = normalized.slice(begin.index + begin[0].length, end.index)
+ if (label === 'ENCRYPTED PRIVATE KEY' || /^(?:Proc-Type|DEK-Info):/mi.test(body)) {
+ reject(source, 'encrypted_private_key')
+ }
+ if (!PRIVATE_LABELS.has(label) && !PUBLIC_LABELS.has(label)) reject(source, 'unsupported_pem_type')
+ return { normalized, label }
+}
+
+function assertRsaStrength(key, source) {
+ if (key.asymmetricKeyType !== 'rsa') reject(source, 'non_rsa_key')
+ // Node >=24 exposes the actual parsed RSA modulus length for both key roles.
+ // RFC 7518 section 3.3 requires 2048 bits for RS256, including verification.
+ const bits = key.asymmetricKeyDetails && key.asymmetricKeyDetails.modulusLength
+ if (!Number.isInteger(bits) || bits < 2048) reject(source, 'undersized_rsa_key')
+}
+
+function parsedPrivate(raw, source) {
+ const object = onePemObject(raw, source)
+ if (!PRIVATE_LABELS.has(object.label)) reject(source, 'wrong_key_role')
+ let key
+ try {
+ key = createPrivateKey(object.normalized)
+ } catch {
+ reject(source, 'invalid_pem')
+ }
+ assertRsaStrength(key, source)
+ return key
+}
+
+function parsedPublic(raw, source, origin) {
+ const object = onePemObject(raw, source)
+ const carriesPrivate = PRIVATE_LABELS.has(object.label)
+ if (origin === 'store' && carriesPrivate) reject(source, 'wrong_key_role')
+ let key
+ try {
+ // Legacy explicit verifier envs accepted private PEMs. Retain that input
+ // contract, but export only its public identity and never retain raw PEM.
+ key = carriesPrivate
+ ? createPublicKey(createPrivateKey(object.normalized))
+ : createPublicKey(object.normalized)
+ } catch {
+ reject(source, 'invalid_pem')
+ }
+ assertRsaStrength(key, source)
+ return key
+}
+
+function fingerprint(key) {
+ return createHash('sha256').update(key.export({ type: 'spki', format: 'der' })).digest('hex')
+}
+
+function deniedIdentities(additional, source) {
+ let extra
+ try {
+ if (additional !== undefined && (additional === null || typeof additional[Symbol.iterator] !== 'function')) {
+ reject(source, 'invalid_type')
+ }
+ extra = additional === undefined ? [] : Array.from(additional)
+ } catch {
+ reject(source, 'invalid_type')
+ }
+ if (extra.some(value => typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))) {
+ reject(source, 'invalid_type')
+ }
+ return new Set([...HISTORICAL_PUBLIC_KEY_FINGERPRINTS, ...extra])
+}
+
+function checkOptions(options, source) {
+ if (options === null || (options !== undefined && typeof options !== 'object')) reject(source, 'invalid_type')
+}
+
+function assertAllowedIdentity(keyFingerprint, denied, source) {
+ if (denied.has(keyFingerprint)) reject(source, 'banned_identity')
+}
+
+function parseSigningMaterial(raw, source, options) {
+ checkOptions(options, source)
+ const denied = deniedIdentities(options && options.fingerprints, source)
+ const key = parsedPrivate(raw, source)
+ // Derive every output from this exact private KeyObject, never from raw text.
+ const publicKey = createPublicKey(key)
+ const keyFingerprint = fingerprint(publicKey)
+ assertAllowedIdentity(keyFingerprint, denied, source)
+ return {
+ privatePem: key.export({ type: 'pkcs8', format: 'pem' }).toString().trim(),
+ publicPem: publicKey.export({ type: 'spki', format: 'pem' }).toString().trim(),
+ fingerprint: keyFingerprint,
+ }
+}
+
+function parseVerifierMaterial(raw, source, options) {
+ checkOptions(options, source)
+ const origin = options && options.origin !== undefined ? options.origin : 'environment'
+ if (origin !== 'environment' && origin !== 'store') reject(source, 'invalid_type')
+ const denied = deniedIdentities(options && options.fingerprints, source)
+ const key = parsedPublic(raw, source, origin)
+ const keyFingerprint = fingerprint(key)
+ assertAllowedIdentity(keyFingerprint, denied, source)
+ return { publicPem: key.export({ type: 'spki', format: 'pem' }).toString().trim(), fingerprint: keyFingerprint }
+}
+
+function publicKeyPemFingerprint(pem) {
+ // Metadata must identify the historical public fixtures without accepting
+ // their authority. Only the parsers apply the unconditional historical ban.
+ return fingerprint(parsedPublic(pem, 'JWT public key fingerprint', 'environment'))
+}
+
+function isBannedSigningKeyPem(pem, additional) {
+ try {
+ const key = parsedPrivate(pem, 'JWT signing key identity')
+ return deniedIdentities(additional, 'JWT signing key identity').has(fingerprint(createPublicKey(key)))
+ } catch {
+ return false
+ }
+}
+
+function isBannedPublicKeyPem(pem, additional) {
+ try {
+ return deniedIdentities(additional, 'JWT public key identity').has(publicKeyPemFingerprint(pem))
+ } catch {
+ return false
+ }
+}
+
+module.exports = {
+ HISTORICAL_PUBLIC_KEY_FINGERPRINTS, MAX_PEM_MATERIAL_BYTES, JwtKeyMaterialError,
+ normalizePem, parseSigningMaterial, parseVerifierMaterial, publicKeyPemFingerprint,
+ isBannedSigningKeyPem, isBannedPublicKeyPem,
+}
diff --git a/packages/jwt-key-policy/index.d.ts b/packages/jwt-key-policy/index.d.ts
new file mode 100644
index 000000000..83914861c
--- /dev/null
+++ b/packages/jwt-key-policy/index.d.ts
@@ -0,0 +1,58 @@
+/** Immutable SHA-256 SPKI identities of historically committed signing keys. */
+export declare const HISTORICAL_PUBLIC_KEY_FINGERPRINTS: readonly string[]
+export declare const MAX_PEM_MATERIAL_BYTES: 65536
+
+export type JwtKeyMaterialReason =
+ | 'invalid_type'
+ | 'material_too_large'
+ | 'invalid_pem'
+ | 'multiple_pem_objects'
+ | 'unsupported_pem_type'
+ | 'encrypted_private_key'
+ | 'wrong_key_role'
+ | 'non_rsa_key'
+ | 'undersized_rsa_key'
+ | 'banned_identity'
+
+export declare class JwtKeyMaterialError extends Error {
+ readonly code: 'ERR_JWT_KEY_INVALID' | 'ERR_JWT_KEY_BANNED'
+ readonly reason: JwtKeyMaterialReason
+ /** Safe caller-supplied diagnostic label, never cryptographic material. */
+ readonly source: string
+ constructor(source: string, reason: JwtKeyMaterialReason)
+}
+
+export interface SigningMaterial {
+ privatePem: string
+ publicPem: string
+ fingerprint: string
+}
+export interface VerifierMaterial {
+ publicPem: string
+ fingerprint: string
+}
+export interface JwtFingerprintOptions {
+ /** Additional denied identities; the historical default cannot be disabled. */
+ fingerprints?: Iterable<string>
+}
+export interface JwtVerifierOptions extends JwtFingerprintOptions {
+ /** Environment inputs retain legacy private-key carriers; public stores forbid them. */
+ origin?: 'environment' | 'store'
+}
+
+/** Normalize literal and escaped LF/CRLF/CR within the 64 KiB material bound. */
+export declare function normalizePem(raw: string): string
+export declare function parseSigningMaterial(
+ raw: string,
+ source: string,
+ options?: JwtFingerprintOptions
+): SigningMaterial
+export declare function parseVerifierMaterial(
+ raw: string,
+ source: string,
+ options?: JwtVerifierOptions
+): VerifierMaterial
+/** Canonical identity metadata; this helper intentionally does not apply the denylist. */
+export declare function publicKeyPemFingerprint(pem: string): string
+export declare function isBannedSigningKeyPem(pem: string, fingerprints?: Iterable<string>): boolean
+export declare function isBannedPublicKeyPem(pem: string, fingerprints?: Iterable<string>): boolean
diff --git a/packages/jwt-key-policy/package-lock.json b/packages/jwt-key-policy/package-lock.json
new file mode 100644
index 000000000..9e724b659
--- /dev/null
+++ b/packages/jwt-key-policy/package-lock.json
@@ -0,0 +1,16 @@
+{
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ }
+ }
+ }
+}
diff --git a/packages/jwt-key-policy/package.json b/packages/jwt-key-policy/package.json
new file mode 100644
index 000000000..7d3937106
--- /dev/null
+++ b/packages/jwt-key-policy/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Canonical RSA JWT identity policy and local development key storage",
+ "main": "index.cjs",
+ "types": "index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "require": "./index.cjs",
+ "default": "./index.cjs"
+ },
+ "./dev-store": {
+ "types": "./dev-store.d.ts",
+ "require": "./dev-store.cjs",
+ "default": "./dev-store.cjs"
+ }
+ },
+ "engines": {
+ "node": ">=24"
+ },
+ "scripts": {
+ "build": "node --check index.cjs && node --check dev-store.cjs",
+ "test": "node --test test/*.test.cjs",
+ "test:crypto": "node --test test/policy-*.test.cjs test/crypto-*.test.cjs"
+ },
+ "license": "MIT"
+}
diff --git a/packages/jwt-key-policy/test/crypto-fixtures.cjs b/packages/jwt-key-policy/test/crypto-fixtures.cjs
new file mode 100644
index 000000000..824f3b60b
--- /dev/null
+++ b/packages/jwt-key-policy/test/crypto-fixtures.cjs
@@ -0,0 +1,95 @@
+'use strict'
+
+const { spawn, spawnSync } = require('node:child_process')
+const { generateKeyPairSync } = require('node:crypto')
+
+const PUBLIC_KEYS = Object.freeze({
+ rpc: `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArCIYGHehMPpGKePxaKQa
+rDX5yrzifU5i4fzpI3EtkKSU6s5ug7EkKxc2DdMekoqXe9vr7qKyVwiilUIusXLX
+iW7KPMJlD/Fd5Bo7Qxt69wYiL5I4K37eDgCN6D3LduHySEnkhdI0GDpB4LM2ASOx
+QkEabepekZTMQyExmCIn/dHJ15B+4A9tiiephYOQNr3GcnW9eDomMt6NJLypikbr
+xJO6O7Ar0G+raTbflth8EQzWnGF+WgQW4iiM3wsFhpaE0mUlEbMGDGTMAZy1KfxA
+RRu+QZm3Lo+5AiCaHkijDCglHsXLhqsYi2AdRiavD1Gk9LKP/ztKw7q/D6fYFzmO
+QwIDAQAB
+-----END PUBLIC KEY-----`,
+ session: `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwrZja9jS/r+e2YF1FqEQ
+NMLsnffebYzXrZOb7uPMKhXBoKjJh/taR9v3kX2srfVtoikcKKr0Sfa7MMSLnZWd
+ETmi7MvbeVD3HpsXpVejmw9D0zeYYSGZplLF/b6HY0Lz2XVM8WdJl3Dicyu+SZbZ
+xeHZtMCMTTjvmoI/IYmmO4N3Pgz/SGi7V3EiwoALODP4OWDvd/1xFUiMPslLPgZU
+EczQ5tIpAaD4e0om3gUNsyOKYc5igojm6ooVqI9T3TUGBVJ0uSZB7ntWxKQ39WyI
+aH+oqnwDGbDcDLQ/wTuBtcn4brWTDgW1xA73HVBSImGFvvHCWBiQBiI1nvovUP0u
+WQIDAQAB
+-----END PUBLIC KEY-----`,
+ admin: `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsrDvCYzx96OLO2qv37sb
+ZZvCuguzR+cWxwOYpx61AP+GL9lxV60FJJJKjtRhO/Ivm6koOzgVyln12BphipB0
+nJs9fdLzArpxeiuKaligrkL9c/2TwljmRpZagZzZKKAQR827b0WRz9qB63npbjMv
+/7L1GNxcMtLne2rTAYU3gez0I7phwKAYH/zY+T5iH2l0qpt/4Iy6t7pWOQ0qgrKe
+JPFe5qYWK3c8BWGnWJkhoLCNUCTnUa1yGaIHuRwKzwPH9b476rS72NGqGC4xRZXA
+einOdIz3PympLN0HyIjSsPBUlhewILwD5jQBC6DxYeXLQJY0UHWRLrOqQRkJsep6
+yQIDAQAB
+-----END PUBLIC KEY-----`,
+})
+
+function pem(key, type) {
+ return key.export({ type, format: 'pem' }).toString().trim()
+}
+
+let shared
+function fixtures() {
+ if (!shared) {
+ shared = Object.fromEntries([2048, 4096, 1024].map(bits => [bits, generateKeyPairSync('rsa', { modulusLength: bits })]))
+ shared.decoy = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ }
+ return shared
+}
+
+function encodings(value) {
+ return {
+ lf: value,
+ crlf: value.replace(/\n/g, '\r\n'),
+ cr: value.replace(/\n/g, '\r'),
+ escapedLf: value.replace(/\n/g, '\\n'),
+ escapedCrlf: value.replace(/\n/g, '\\r\\n'),
+ escapedCr: value.replace(/\n/g, '\\r'),
+ bom: '\ufeff' + value,
+ outsideWhitespace: '\t\n ' + value + ' \n\t',
+ beginWhitespace: value.replace(/^(-----BEGIN [^-]+-----)/, '$1 \t'),
+ endWhitespace: value.replace(/(-----END [^-]+-----)$/, '$1 \t'),
+ bodyWhitespace: value.split('\n').map(line => line.startsWith('-----') ? line : line + ' \t').join('\n'),
+ wrapped: 'Key material for the local contract fixture\n' + value + '\nEnd of contract fixture',
+ }
+}
+
+function certificate(key) {
+ const result = spawnSync('openssl', [
+ 'req', '-new', '-x509', '-key', '/dev/stdin', '-subj', '/CN=jwt-key-policy-contract',
+ '-days', '1', '-batch', '-quiet', '-config', '/dev/null',
+ ], { input: pem(key, 'pkcs8'), encoding: 'utf8', timeout: 10000, maxBuffer: 65536 })
+ if (result.status !== 0) throw new Error('Generated certificate fixture failed')
+ return result.stdout.trim()
+}
+
+function certificateWithPublic(publicPem) {
+ // A certificate is a configured public-key carrier, not a CA/trust assertion.
+ // All private bytes travel through an anonymous pipe and are never persisted.
+ return new Promise((resolve, reject) => {
+ const child = spawn('openssl', [
+ 'x509', '-new', '-force_pubkey', '/dev/stdin', '-signkey', '/dev/fd/3',
+ '-subj', '/CN=jwt-key-policy-public-contract', '-days', '1',
+ ], { stdio: ['pipe', 'pipe', 'ignore', 'pipe'], timeout: 10000 })
+ let output = ''
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', chunk => { output += chunk })
+ child.on('error', () => reject(new Error('Generated public certificate fixture failed')))
+ child.on('close', code => code === 0 ? resolve(output.trim()) : reject(new Error('Generated public certificate fixture failed')))
+ child.stdin.on('error', () => {})
+ child.stdio[3].on('error', () => {})
+ child.stdin.end(publicPem)
+ child.stdio[3].end(pem(fixtures()[2048].privateKey, 'pkcs8'))
+ })
+}
+
+module.exports = { PUBLIC_KEYS, pem, fixtures, encodings, certificate, certificateWithPublic }
diff --git a/packages/jwt-key-policy/test/crypto-identity.test.cjs b/packages/jwt-key-policy/test/crypto-identity.test.cjs
new file mode 100644
index 000000000..e71d36143
--- /dev/null
+++ b/packages/jwt-key-policy/test/crypto-identity.test.cjs
@@ -0,0 +1,148 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const { createPrivateKey, createPublicKey, sign, verify } = require('node:crypto')
+const { test } = require('node:test')
+const {
+ HISTORICAL_PUBLIC_KEY_FINGERPRINTS,
+ JwtKeyMaterialError,
+ parseSigningMaterial,
+ parseVerifierMaterial,
+ publicKeyPemFingerprint,
+ isBannedSigningKeyPem,
+ isBannedPublicKeyPem,
+} = require('../index.cjs')
+const { PUBLIC_KEYS, pem, fixtures, encodings, certificate, certificateWithPublic } = require('./crypto-fixtures.cjs')
+
+function rejected(action, reason, label) {
+ assert.throws(action, error => error instanceof JwtKeyMaterialError && error.reason === reason, label)
+}
+function provesSignature(material, expectedPublic, label) {
+ const payload = Buffer.from('JWT policy RSA identity proof')
+ const signature = sign('RSA-SHA256', payload, material.privatePem)
+ assert.equal(verify('RSA-SHA256', payload, material.publicPem, signature), true, label)
+ assert.equal(verify('RSA-SHA256', payload, expectedPublic, signature), true, label)
+ assert.equal(material.fingerprint, publicKeyPemFingerprint(expectedPublic), label)
+ // Compare private bytes only as a boolean; assertion failures cannot print them.
+ assert.ok(material.privatePem === pem(createPrivateKey(material.privatePem), 'pkcs8'), label)
+ assert.ok(material.publicPem === pem(createPublicKey(createPrivateKey(material.privatePem)), 'spki'), label)
+}
+
+for (const bits of [2048, 4096]) {
+ test(`RSA-${bits} PKCS8/PKCS1 signing variants preserve the actual identity`, () => {
+ const pair = fixtures()[bits]
+ const expectedPublic = pem(pair.publicKey, 'spki')
+ for (const type of ['pkcs8', 'pkcs1']) {
+ for (const [encoding, value] of Object.entries(encodings(pem(pair.privateKey, type)))) {
+ const label = `${bits}/${type}/${encoding}`
+ provesSignature(parseSigningMaterial(value, 'SIGNING_CONTRACT'), expectedPublic, label)
+ }
+ }
+ })
+ test(`RSA-${bits} verifier carriers and encodings canonicalize before consumption`, () => {
+ const pair = fixtures()[bits]
+ const expectedPublic = pem(pair.publicKey, 'spki')
+ const carriers = {
+ spki: expectedPublic, pkcs1Public: pem(pair.publicKey, 'pkcs1'), x509: certificate(pair.privateKey),
+ pkcs8Private: pem(pair.privateKey, 'pkcs8'), pkcs1Private: pem(pair.privateKey, 'pkcs1'),
+ }
+ const payload = Buffer.from('JWT policy verifier carrier proof')
+ const signature = sign('RSA-SHA256', payload, pair.privateKey)
+ for (const [carrier, raw] of Object.entries(carriers)) {
+ for (const [encoding, value] of Object.entries(encodings(raw))) {
+ for (const origin of ['environment', 'store']) {
+ const label = `${bits}/${carrier}/${encoding}/${origin}`
+ if (origin === 'store' && carrier.endsWith('Private')) {
+ rejected(() => parseVerifierMaterial(value, 'PUBLIC_STORE_CONTRACT', { origin }), 'wrong_key_role', label)
+ continue
+ }
+ const material = parseVerifierMaterial(value, 'VERIFIER_CONTRACT', { origin })
+ assert.ok(material.publicPem === expectedPublic, label)
+ assert.equal(material.fingerprint, publicKeyPemFingerprint(expectedPublic), label)
+ assert.equal(verify('RSA-SHA256', payload, material.publicPem, signature), true, label)
+ assert.equal(Object.hasOwn(material, 'privatePem'), false, label)
+ }
+ }
+ }
+ })
+}
+
+test('historical defaults have one immutable owner and metadata remains identifiable', () => {
+ assert.equal(Object.isFrozen(HISTORICAL_PUBLIC_KEY_FINGERPRINTS), true)
+ assert.equal(HISTORICAL_PUBLIC_KEY_FINGERPRINTS.length, 3)
+ assert.throws(() => HISTORICAL_PUBLIC_KEY_FINGERPRINTS.push('0'.repeat(64)), TypeError)
+ for (const publicPem of Object.values(PUBLIC_KEYS)) {
+ assert.equal(HISTORICAL_PUBLIC_KEY_FINGERPRINTS.includes(publicKeyPemFingerprint(publicPem)), true)
+ assert.equal(isBannedPublicKeyPem(publicPem), true)
+ }
+})
+
+test('all historical identities are rejected across public carriers, encodings and origins', async () => {
+ for (const [identity, publicPem] of Object.entries(PUBLIC_KEYS)) {
+ const carriers = {
+ spki: publicPem, pkcs1: pem(createPublicKey(publicPem), 'pkcs1'), x509: await certificateWithPublic(publicPem),
+ }
+ for (const [carrier, raw] of Object.entries(carriers)) {
+ for (const [encoding, value] of Object.entries(encodings(raw))) {
+ for (const origin of ['environment', 'store']) {
+ const label = `${identity}/${carrier}/${encoding}/${origin}`
+ rejected(() => parseVerifierMaterial(value, 'HISTORICAL_CONTRACT', { origin, fingerprints: [] }), 'banned_identity', label)
+ }
+ rejected(() => parseSigningMaterial(value, 'HISTORICAL_SIGNER_CONTRACT'), 'wrong_key_role', `${identity}/${carrier}/${encoding}`)
+ }
+ }
+ }
+})
+
+test('extra denied identities are scoped, additive and enforced for signers and every verifier origin', () => {
+ const pair = fixtures()[2048]
+ const signing = pem(pair.privateKey, 'pkcs8')
+ const publicPem = pem(pair.publicKey, 'spki')
+ const fingerprints = new Set([publicKeyPemFingerprint(publicPem)])
+ assert.equal(isBannedSigningKeyPem(signing), false)
+ assert.equal(isBannedSigningKeyPem(signing, fingerprints), true)
+ assert.equal(isBannedPublicKeyPem(publicPem, fingerprints), true)
+ for (const [encoding, value] of Object.entries(encodings(signing))) {
+ rejected(() => parseSigningMaterial(value, 'EXTRA_SIGNER_CONTRACT', { fingerprints }), 'banned_identity', encoding)
+ rejected(() => parseVerifierMaterial(value, 'EXTRA_ENV_CONTRACT', { fingerprints }), 'banned_identity', encoding)
+ }
+ for (const origin of ['environment', 'store']) {
+ rejected(() => parseVerifierMaterial(publicPem, 'EXTRA_PUBLIC_CONTRACT', { origin, fingerprints }), 'banned_identity', origin)
+ }
+ fingerprints.clear()
+ provesSignature(parseSigningMaterial(signing, 'FRESH_CONTRACT'), publicPem, 'scope does not mutate defaults')
+ for (const publicKey of Object.values(PUBLIC_KEYS)) {
+ rejected(() => parseVerifierMaterial(publicKey, 'DEFAULT_BAN_CONTRACT', { fingerprints }), 'banned_identity', 'empty overrides retain the default ban')
+ }
+})
+
+test('canonical signing output cannot select a second certificate or public identity', () => {
+ const pair = fixtures()[2048]
+ const decoy = fixtures().decoy
+ const signing = pem(pair.privateKey, 'pkcs8')
+ const otherPublic = pem(decoy.publicKey, 'spki')
+ const otherCertificate = certificate(decoy.privateKey)
+ for (const second of [otherPublic, otherCertificate, pem(decoy.privateKey, 'pkcs8')]) {
+ for (const raw of [signing + '\n' + second, second + '\n' + signing]) {
+ for (const value of [raw, raw.replace(/\n/g, '\\r\\n')]) {
+ rejected(() => parseSigningMaterial(value, 'MIXED_SIGNER_CONTRACT'), 'multiple_pem_objects', 'mixed signer')
+ for (const origin of ['environment', 'store']) {
+ rejected(() => parseVerifierMaterial(value, 'MIXED_VERIFIER_CONTRACT', { origin }), 'multiple_pem_objects', origin)
+ }
+ }
+ }
+ }
+ const canonical = parseSigningMaterial(signing, 'FRESH_SIGNER_CONTRACT')
+ const payload = Buffer.from('Distinct public identity proof')
+ const signature = sign('RSA-SHA256', payload, canonical.privatePem)
+ assert.equal(verify('RSA-SHA256', payload, otherPublic, signature), false)
+ provesSignature(canonical, pem(pair.publicKey, 'spki'), 'correct identity remains usable')
+})
+
+test('raw-before-normalized historical carrier substitution stays rejected', () => {
+ const signing = pem(fixtures()[2048].privateKey, 'pkcs8')
+ for (const publicPem of Object.values(PUBLIC_KEYS)) {
+ const raw = signing + '\n' + publicPem.replace(/\n/g, '\\n')
+ rejected(() => parseVerifierMaterial(raw, 'R1_VERIFIER_CONTRACT'), 'multiple_pem_objects', 'R1 preserved')
+ }
+})
diff --git a/packages/jwt-key-policy/test/crypto-package-load.test.cjs b/packages/jwt-key-policy/test/crypto-package-load.test.cjs
new file mode 100644
index 000000000..07530ba50
--- /dev/null
+++ b/packages/jwt-key-policy/test/crypto-package-load.test.cjs
@@ -0,0 +1,18 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const { test } = require('node:test')
+
+test('CommonJS and native ESM consumers load the public package contract', async () => {
+ const commonJs = require('@clerum/jwt-key-policy')
+ const nativeEsm = await import('@clerum/jwt-key-policy')
+ for (const name of [
+ 'normalizePem', 'parseSigningMaterial', 'parseVerifierMaterial',
+ 'publicKeyPemFingerprint', 'isBannedSigningKeyPem', 'isBannedPublicKeyPem', 'JwtKeyMaterialError',
+ ]) {
+ assert.equal(typeof commonJs[name], 'function', name)
+ assert.equal(nativeEsm[name] === commonJs[name], true, name)
+ }
+ assert.equal(nativeEsm.MAX_PEM_MATERIAL_BYTES, 65536)
+ assert.equal(nativeEsm.HISTORICAL_PUBLIC_KEY_FINGERPRINTS === commonJs.HISTORICAL_PUBLIC_KEY_FINGERPRINTS, true)
+})
diff --git a/packages/jwt-key-policy/test/policy-armor.test.cjs b/packages/jwt-key-policy/test/policy-armor.test.cjs
new file mode 100644
index 000000000..9df3c7e01
--- /dev/null
+++ b/packages/jwt-key-policy/test/policy-armor.test.cjs
@@ -0,0 +1,132 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const { generateKeyPairSync, randomUUID } = require('node:crypto')
+const { test } = require('node:test')
+const {
+ MAX_PEM_MATERIAL_BYTES, JwtKeyMaterialError, normalizePem,
+ parseSigningMaterial, parseVerifierMaterial,
+} = require('../index.cjs')
+const { fixtures, pem, encodings } = require('./crypto-fixtures.cjs')
+
+function rejected(action, reason) {
+ assert.throws(action, error => error instanceof JwtKeyMaterialError && error.code === 'ERR_JWT_KEY_INVALID' && error.reason === reason)
+}
+
+test('normalization accepts every supported raw and escaped newline representation', () => {
+ const publicPem = pem(fixtures()[2048].publicKey, 'spki')
+ for (const encoding of ['lf', 'crlf', 'cr', 'escapedLf', 'escapedCrlf', 'escapedCr', 'bom', 'outsideWhitespace']) {
+ assert.ok(normalizePem(encodings(publicPem)[encoding]) === publicPem, encoding)
+ }
+})
+
+test('complete single objects reject unmatched, truncated and unsupported armor', () => {
+ const publicPem = pem(fixtures()[2048].publicKey, 'spki')
+ for (const raw of [
+ publicPem.replace(/-----END [^-]+-----/, ''),
+ publicPem.replace('END PUBLIC KEY', 'END CERTIFICATE'),
+ publicPem.replace(/^-----BEGIN [^-]+-----/, ''),
+ publicPem.split('\n').reverse().join('\n'),
+ ]) rejected(() => parseVerifierMaterial(raw, 'ARMOR_CONTRACT'), 'invalid_pem')
+ for (const raw of [
+ publicPem + '\n-----BEGIN CERTIFICATE----',
+ '-----END CERTIFICATE----\n' + publicPem,
+ publicPem + '\n-----begin malformed armor',
+ ]) rejected(() => parseVerifierMaterial(raw, 'EXTRA_ARMOR_CONTRACT'), 'multiple_pem_objects')
+ // Invalid-body fixtures intentionally exercise armor/type rejection before crypto parsing.
+ for (const label of ['OPENSSH PRIVATE KEY', 'DSA PUBLIC KEY', 'UNKNOWN OBJECT']) {
+ const raw = `-----BEGIN ${label}-----\nAA==\n-----END ${label}-----`
+ rejected(() => parseVerifierMaterial(raw, 'UNSUPPORTED_ARMOR_CONTRACT'), 'unsupported_pem_type')
+ rejected(() => parseSigningMaterial(raw, 'UNSUPPORTED_SIGNER_CONTRACT'), 'unsupported_pem_type')
+ }
+ const invalidBody = publicPem.replace(/\n[\s\S]+\n-----END/, '\ninvalid-generated-body\n-----END')
+ rejected(() => parseVerifierMaterial(invalidBody, 'INVALID_BODY_CONTRACT'), 'invalid_pem')
+})
+
+test('public-only sources cannot supply signing keys and stores cannot accept private carriers', () => {
+ const pair = fixtures()[2048]
+ rejected(() => parseSigningMaterial(pem(pair.publicKey, 'spki'), 'WRONG_SIGNER_ROLE'), 'wrong_key_role')
+ for (const type of ['pkcs8', 'pkcs1']) {
+ const signing = pem(pair.privateKey, type)
+ rejected(() => parseVerifierMaterial(signing, 'WRONG_STORE_ROLE', { origin: 'store' }), 'wrong_key_role')
+ assert.equal(typeof parseVerifierMaterial(signing, 'LEGACY_ENV_ROLE').fingerprint, 'string')
+ }
+})
+
+test('every role rejects RSA below 2048 bits and non-RSA signing/verifying objects', () => {
+ const weak = fixtures()[1024]
+ rejected(() => parseSigningMaterial(pem(weak.privateKey, 'pkcs8'), 'WEAK_SIGNER'), 'undersized_rsa_key')
+ for (const origin of ['environment', 'store']) {
+ rejected(() => parseVerifierMaterial(pem(weak.publicKey, 'spki'), 'WEAK_VERIFIER', { origin }), 'undersized_rsa_key')
+ }
+ const alternatives = [
+ generateKeyPairSync('ec', { namedCurve: 'prime256v1' }),
+ generateKeyPairSync('ed25519'),
+ generateKeyPairSync('dsa', { modulusLength: 2048, divisorLength: 256 }),
+ generateKeyPairSync('rsa-pss', { modulusLength: 2048, hashAlgorithm: 'sha256', mgf1HashAlgorithm: 'sha256', saltLength: 32 }),
+ ]
+ for (const pair of alternatives) {
+ rejected(() => parseSigningMaterial(pem(pair.privateKey, 'pkcs8'), 'NON_RSA_SIGNER'), 'non_rsa_key')
+ for (const origin of ['environment', 'store']) {
+ rejected(() => parseVerifierMaterial(pem(pair.publicKey, 'spki'), 'NON_RSA_VERIFIER', { origin }), 'non_rsa_key')
+ }
+ }
+})
+
+test('encrypted private material is rejected without password handling or fallback', () => {
+ for (const type of ['pkcs8', 'pkcs1']) {
+ const options = Object.fromEntries([['type', type], ['format', 'pem'], ['cipher', 'aes-256-cbc'], ['passphrase', randomUUID()]])
+ const encrypted = fixtures()[2048].privateKey.export(options).toString()
+ rejected(() => parseSigningMaterial(encrypted, 'ENCRYPTED_SIGNER'), 'encrypted_private_key')
+ rejected(() => parseVerifierMaterial(encrypted, 'ENCRYPTED_ENV'), 'encrypted_private_key')
+ }
+})
+
+test('DER, JWK and OpenSSH representations cannot enter the PEM contract', () => {
+ const pair = fixtures()[2048]
+ const values = [
+ pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64'),
+ JSON.stringify(pair.publicKey.export({ format: 'jwk' })),
+ 'ssh-rsa ' + pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64'),
+ ]
+ for (const raw of values) {
+ rejected(() => parseSigningMaterial(raw, 'NON_PEM_SIGNER'), 'invalid_pem')
+ rejected(() => parseVerifierMaterial(raw, 'NON_PEM_VERIFIER'), 'invalid_pem')
+ }
+})
+
+test('the raw UTF8 bound is applied before parsing or escape normalization', () => {
+ assert.equal(MAX_PEM_MATERIAL_BYTES, 65536)
+ const publicPem = pem(fixtures()[2048].publicKey, 'spki')
+ const exact = 'x'.repeat(MAX_PEM_MATERIAL_BYTES - Buffer.byteLength(publicPem) - 1) + '\n' + publicPem
+ assert.equal(Buffer.byteLength(exact), MAX_PEM_MATERIAL_BYTES)
+ assert.equal(typeof parseVerifierMaterial(exact, 'EXACT_BOUND').fingerprint, 'string')
+ for (const raw of [exact + 'x', '\\r'.repeat(MAX_PEM_MATERIAL_BYTES / 2) + publicPem, 'é'.repeat(MAX_PEM_MATERIAL_BYTES / 2) + publicPem]) {
+ rejected(() => parseSigningMaterial(raw, 'OVERSIZED_SIGNER'), 'material_too_large')
+ rejected(() => parseVerifierMaterial(raw, 'OVERSIZED_VERIFIER'), 'material_too_large')
+ rejected(() => normalizePem(raw), 'material_too_large')
+ }
+})
+
+test('safe contextual failures contain neither input material nor native crypto errors', () => {
+ const signing = pem(fixtures()[2048].privateKey, 'pkcs8')
+ assert.throws(() => parseVerifierMaterial(signing, signing, { origin: 'store' }), error => {
+ assert.equal(error instanceof JwtKeyMaterialError, true)
+ assert.equal(error.code, 'ERR_JWT_KEY_INVALID')
+ assert.equal(error.source, 'JWT key material')
+ assert.equal(Object.hasOwn(error, 'cause'), false)
+ assert.equal(error.message.includes(signing.slice(0, 60)), false)
+ assert.equal(JSON.stringify(error).includes(signing.split('\n')[1]), false)
+ assert.equal(/OSSL|DECODER|asn1/i.test(error.message), false)
+ return true
+ })
+ assert.throws(() => parseVerifierMaterial('invalid', 'VERIFIER_SOURCE'), error =>
+ error instanceof JwtKeyMaterialError && error.message.includes('VERIFIER_SOURCE'))
+ rejected(() => parseVerifierMaterial('invalid', 'VERIFIER_SOURCE', { origin: 'unknown' }), 'invalid_type')
+ for (const raw of [undefined, null, Buffer.from('invalid'), 1]) {
+ rejected(() => parseSigningMaterial(raw, 'INVALID_TYPE'), 'invalid_type')
+ }
+ for (const fingerprints of [null, 1, {}, ['not-an-identity']]) {
+ rejected(() => parseSigningMaterial(signing, 'INVALID_POLICY_OPTIONS', { fingerprints }), 'invalid_type')
+ }
+})
diff --git a/packages/jwt-key-policy/test/policy-types.cts b/packages/jwt-key-policy/test/policy-types.cts
new file mode 100644
index 000000000..db98f7445
--- /dev/null
+++ b/packages/jwt-key-policy/test/policy-types.cts
@@ -0,0 +1,11 @@
+import policy = require('@clerum/jwt-key-policy')
+
+declare const configuredPem: string
+const material: policy.SigningMaterial = policy.parseSigningMaterial(configuredPem, 'CJS_TYPE_CONTRACT')
+const verifier: policy.VerifierMaterial = policy.parseVerifierMaterial(material.publicPem, 'CJS_TYPE_CONTRACT', {
+ origin: 'store', fingerprints: new Set<string>(),
+})
+const identity: string = policy.publicKeyPemFingerprint(verifier.publicPem)
+const failure: policy.JwtKeyMaterialError = new policy.JwtKeyMaterialError('CJS_TYPE_CONTRACT', 'invalid_pem')
+const maximum: 65536 = policy.MAX_PEM_MATERIAL_BYTES
+void [identity, failure, maximum]
diff --git a/packages/jwt-key-policy/test/policy-types.mts b/packages/jwt-key-policy/test/policy-types.mts
new file mode 100644
index 000000000..da391dfd3
--- /dev/null
+++ b/packages/jwt-key-policy/test/policy-types.mts
@@ -0,0 +1,43 @@
+import {
+ HISTORICAL_PUBLIC_KEY_FINGERPRINTS,
+ JwtKeyMaterialError,
+ MAX_PEM_MATERIAL_BYTES,
+ isBannedPublicKeyPem,
+ isBannedSigningKeyPem,
+ normalizePem,
+ parseSigningMaterial,
+ parseVerifierMaterial,
+ publicKeyPemFingerprint,
+ type JwtFingerprintOptions,
+ type JwtVerifierOptions,
+ type SigningMaterial,
+ type VerifierMaterial,
+} from '@clerum/jwt-key-policy'
+
+declare const configuredPem: string
+declare const sourceLabel: string
+const extraIdentities: Iterable<string> = new Set<string>()
+const signingOptions: JwtFingerprintOptions = { fingerprints: extraIdentities }
+const verifierOptions: JwtVerifierOptions = { origin: 'store', fingerprints: extraIdentities }
+const signing: SigningMaterial = parseSigningMaterial(configuredPem, sourceLabel, signingOptions)
+const verifier: VerifierMaterial = parseVerifierMaterial(configuredPem, sourceLabel, verifierOptions)
+const canonicalPrivate: string = signing.privatePem
+const canonicalPublic: string = verifier.publicPem
+const identity: string = publicKeyPemFingerprint(canonicalPublic)
+const normalized: string = normalizePem(configuredPem)
+const signingDenied: boolean = isBannedSigningKeyPem(canonicalPrivate, extraIdentities)
+const verifierDenied: boolean = isBannedPublicKeyPem(canonicalPublic, extraIdentities)
+const maximum: 65536 = MAX_PEM_MATERIAL_BYTES
+const failure = new JwtKeyMaterialError(sourceLabel, 'banned_identity')
+const failureCode: 'ERR_JWT_KEY_INVALID' | 'ERR_JWT_KEY_BANNED' = failure.code
+
+// @ts-expect-error The default policy is immutable to callers.
+HISTORICAL_PUBLIC_KEY_FINGERPRINTS.push(identity)
+// @ts-expect-error A public verifier result cannot expose private material.
+verifier.privatePem
+// @ts-expect-error Only the two defined origins are permitted.
+parseVerifierMaterial(configuredPem, sourceLabel, { origin: 'unknown' })
+// @ts-expect-error Error metadata is read-only to typed consumers.
+failure.code = 'ERR_JWT_KEY_INVALID'
+
+void [canonicalPrivate, canonicalPublic, identity, normalized, signingDenied, verifierDenied, maximum, failureCode]
diff --git a/packages/jwt-key-policy/test/store-fixtures.cjs b/packages/jwt-key-policy/test/store-fixtures.cjs
new file mode 100644
index 000000000..0f758b704
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-fixtures.cjs
@@ -0,0 +1,97 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const crypto = require('node:crypto')
+const fs = require('node:fs')
+const Module = require('node:module')
+const os = require('node:os')
+const path = require('node:path')
+
+function keyPair() {
+ return crypto.generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ })
+}
+
+function fixture(t) {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'evenfire-jwt-store-test-')))
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }))
+ const store = path.join(root, 'store')
+ fs.mkdirSync(store, { mode: 0o700 })
+ return { root, store }
+}
+
+function publishPair(directory, pair, slot = 'rpc') {
+ fs.writeFileSync(path.join(directory, `${slot}.pem`), pair.privateKey, { mode: 0o600 })
+ fs.writeFileSync(path.join(directory, `${slot}.public.pem`), pair.publicKey, { mode: 0o644 })
+}
+
+function digest(value) {
+ return crypto.createHash('sha256').update(value).digest('hex')
+}
+
+function snapshot(directory) {
+ return Object.fromEntries(fs.readdirSync(directory).sort().map(name => {
+ const file = path.join(directory, name)
+ const stats = fs.lstatSync(file)
+ return [name, {
+ mode: stats.mode & 0o7777,
+ type: stats.isFile() ? 'file' : stats.isSymbolicLink() ? 'symlink' : 'other',
+ hash: stats.isFile() ? digest(fs.readFileSync(file)) : null,
+ }]
+ }))
+}
+
+function expectReason(run, reason) {
+ assert.throws(run, error => error.reason === reason)
+}
+
+function withFsPatches(patches, run) {
+ const originals = {}
+ for (const [name, build] of Object.entries(patches)) {
+ originals[name] = fs[name]
+ fs[name] = build(originals[name])
+ }
+ try { return run() } finally {
+ for (const [name, original] of Object.entries(originals)) fs[name] = original
+ }
+}
+
+function storeWithPolicy(transform) {
+ // Execute the unchanged store with a locally scoped policy wrapper. The
+ // wrapper delegates to the real parser with generated fingerprint vectors;
+ // neither exported policy state nor production dependency seams are mutated.
+ const filename = require.resolve('../dev-store.cjs')
+ const loaded = new Module(filename, module)
+ loaded.filename = filename
+ loaded.paths = Module._nodeModulePaths(path.dirname(filename))
+ const ordinaryRequire = loaded.require.bind(loaded)
+ loaded.require = name => name === './index.cjs'
+ ? transform(require('../index.cjs'))
+ : ordinaryRequire(name)
+ loaded._compile(fs.readFileSync(filename, 'utf8'), filename)
+ return loaded.exports
+}
+
+function errno(code, label = 'injected local filesystem failure') {
+ return Object.assign(new Error(label), { code })
+}
+
+function temporaries(directory) {
+ return fs.readdirSync(directory).filter(name => name.includes('.tmp-'))
+}
+
+module.exports = {
+ digest,
+ errno,
+ expectReason,
+ fixture,
+ keyPair,
+ publishPair,
+ snapshot,
+ storeWithPolicy,
+ temporaries,
+ withFsPatches,
+}
diff --git a/packages/jwt-key-policy/test/store-io.test.cjs b/packages/jwt-key-policy/test/store-io.test.cjs
new file mode 100644
index 000000000..61633d98e
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-io.test.cjs
@@ -0,0 +1,209 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const fs = require('node:fs')
+const path = require('node:path')
+const { test } = require('node:test')
+const policy = require('../index.cjs')
+const storeApi = require('../dev-store.cjs')
+const { errno, expectReason, fixture, keyPair, publishPair, snapshot, withFsPatches } = require('./store-fixtures.cjs')
+const pair = keyPair()
+const fingerprint = policy.publicKeyPemFingerprint(pair.publicKey)
+const childFixture = path.join(__dirname, 'store-process-fixture.cjs')
+
+test('lexical directory spellings reject the same final symlink', t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const before = snapshot(store)
+ const link = path.join(root, 'directory-link')
+ fs.symlinkSync(store, link)
+ for (const suffix of ['', '/', '/.', '/./']) {
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', link + suffix), 'symbolic_link')
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', link + suffix), 'symbolic_link')
+ }
+ assert.equal(storeApi.loadOrCreateDevSigningMaterial('rpc', store + '/./').fingerprint, fingerprint)
+ assert.deepEqual(snapshot(store), before)
+})
+
+test('a trusted ancestor alias is allowed without following the final component', t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const alias = path.join(root, 'ancestor')
+ fs.symlinkSync(root, alias)
+ const directory = path.join(alias, 'store')
+ assert.equal(storeApi.loadOrCreateDevSigningMaterial('rpc', directory).fingerprint, fingerprint)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', directory).fingerprint, fingerprint)
+})
+
+test('directory ownership, type and permissions are validated', t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const regular = path.join(root, 'ordinary-file')
+ fs.writeFileSync(regular, 'synthetic directory fixture', { mode: 0o600 })
+ for (const operation of [storeApi.loadOrCreateDevSigningMaterial, storeApi.readDevVerifierMaterial]) {
+ expectReason(() => operation('rpc', regular), 'invalid_directory')
+ fs.chmodSync(store, 0o755)
+ expectReason(() => operation('rpc', store), 'insecure_directory')
+ fs.chmodSync(store, 0o700)
+ withFsPatches({ lstatSync: original => (...args) => {
+ const stats = original(...args)
+ return args[0] === store ? Object.assign(Object.create(stats), { uid: process.geteuid() + 1 }) : stats
+ } }, () => expectReason(() => operation('rpc', store), 'directory_owner_mismatch'))
+ }
+})
+
+test('stricter and owner-executable existing permissions retain compatibility', t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ for (const modes of [[0o500, 0o400, 0o444], [0o700, 0o700, 0o555], [0o1700, 0o600, 0o644]]) {
+ fs.chmodSync(path.join(store, 'rpc.pem'), modes[1])
+ fs.chmodSync(path.join(store, 'rpc.public.pem'), modes[2])
+ fs.chmodSync(store, modes[0])
+ try {
+ const before = snapshot(store)
+ assert.equal(storeApi.loadOrCreateDevSigningMaterial('rpc', store).fingerprint, fingerprint)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint)
+ assert.deepEqual(snapshot(store), before)
+ } finally { fs.chmodSync(store, 0o700) }
+ }
+})
+
+for (const [filename, mode] of [['rpc.pem', 0o644], ['rpc.public.pem', 0o664]]) {
+ test(`${filename} unsafe permissions fail without rewriting files`, t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ fs.chmodSync(path.join(store, filename), mode)
+ const before = snapshot(store)
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'insecure_file')
+ assert.deepEqual(snapshot(store), before)
+ })
+}
+
+for (const filename of ['rpc.pem', 'rpc.public.pem']) {
+ for (const shape of ['directory', 'symlink']) {
+ test(`${filename} rejects an unsuitable ${shape} fixture`, t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const target = path.join(store, filename)
+ fs.unlinkSync(target)
+ if (shape === 'directory') fs.mkdirSync(target, { mode: 0o700 })
+ else {
+ const source = path.join(root, 'other-owned-store')
+ fs.mkdirSync(source, { mode: 0o700 })
+ publishPair(source, pair)
+ fs.symlinkSync(path.join(source, filename), target)
+ }
+ const before = snapshot(store)
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), shape === 'directory' ? 'not_regular_file' : 'symbolic_link')
+ assert.deepEqual(snapshot(store), before)
+ })
+ }
+
+ test(`${filename} validates the owner of the opened descriptor`, t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const opened = new Map()
+ let checked = false
+ withFsPatches({
+ openSync: original => (file, ...args) => { const fd = original(file, ...args); opened.set(fd, file); return fd },
+ closeSync: original => fd => { opened.delete(fd); return original(fd) },
+ fstatSync: original => fd => {
+ const stats = original(fd)
+ if (opened.get(fd) === path.join(store, filename)) {
+ checked = true
+ return Object.assign(Object.create(stats), { uid: process.geteuid() + 1 })
+ }
+ return stats
+ },
+ }, () => expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'file_owner_mismatch'))
+ assert.equal(checked, true)
+ assert.equal(opened.size, 0)
+ })
+}
+
+test('unsupported POSIX effective-user guarantees fail before filesystem access', () => {
+ const original = process.geteuid
+ process.geteuid = undefined
+ try {
+ withFsPatches({ lstatSync: () => () => { throw new Error('unexpected filesystem access') } }, () => {
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', '/unused'), 'unsupported_platform')
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', '/unused'), 'unsupported_platform')
+ assert.equal(storeApi.resolveDevKeyStoreDir('/service'), '/service/.dev-keys')
+ })
+ } finally { process.geteuid = original }
+})
+
+for (const stage of ['fstatSync', 'readSync']) {
+ test(`${stage} errors close the descriptor and preserve the primary failure`, t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const primary = errno('EIO')
+ const held = new Set()
+ withFsPatches({
+ openSync: original => (...args) => { const fd = original(...args); held.add(fd); return fd },
+ closeSync: original => fd => { held.delete(fd); return original(fd) },
+ [stage]: () => () => { throw primary },
+ }, () => assert.throws(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), failure => failure === primary))
+ assert.equal(held.size, 0)
+ })
+}
+
+test('initial oversize and growth past the bound fail with closed descriptors', t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const file = path.join(store, 'rpc.public.pem')
+ fs.writeFileSync(file, 'x'.repeat(policy.MAX_PEM_MATERIAL_BYTES + 1))
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', store), 'material_too_large')
+ fs.writeFileSync(file, pair.publicKey)
+ const held = new Set()
+ let grew = false
+ withFsPatches({
+ openSync: original => (...args) => { const fd = original(...args); held.add(fd); return fd },
+ closeSync: original => fd => { held.delete(fd); return original(fd) },
+ readSync: original => (...args) => {
+ if (!grew) { grew = true; fs.appendFileSync(file, 'x'.repeat(policy.MAX_PEM_MATERIAL_BYTES)) }
+ return original(...args)
+ },
+ }, () => expectReason(() => storeApi.readDevVerifierMaterial('rpc', store), 'material_too_large'))
+ assert.equal(grew, true)
+ assert.equal(held.size, 0)
+})
+
+test('exact-bound valid material and short reads use a single bounded buffer', t => {
+ const { store } = fixture(t)
+ const file = path.join(store, 'rpc.public.pem')
+ const padding = policy.MAX_PEM_MATERIAL_BYTES - Buffer.byteLength(pair.publicKey)
+ fs.writeFileSync(file, pair.publicKey + ' '.repeat(padding), { mode: 0o644 })
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint)
+ fs.writeFileSync(file, pair.publicKey)
+ let allocated
+ let reads = 0
+ withFsPatches({ readSync: original => (fd, buffer, offset, length, position) => {
+ allocated ??= buffer
+ assert.equal(buffer === allocated, true)
+ assert.equal(buffer.length, policy.MAX_PEM_MATERIAL_BYTES + 1)
+ reads += 1
+ return original(fd, buffer, offset, Math.min(1, length), position)
+ } }, () => assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint))
+ assert.equal(reads > 1, true)
+})
+
+for (const [filename, operation] of [['rpc.pem', 'sign'], ['rpc.public.pem', 'sign'], ['rpc.public.pem', 'verify']]) {
+ test(`${operation} rejects a ${filename} FIFO within a finite child deadline`, t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const run = () => spawnSync(process.execPath, [childFixture, operation, store], { encoding: 'utf8', timeout: 2500, env: { PATH: process.env.PATH } })
+ const positive = run()
+ assert.equal(positive.status, 0)
+ assert.deepEqual(JSON.parse(positive.stdout), { outcome: 'accepted', fingerprint })
+ const file = path.join(store, filename)
+ fs.unlinkSync(file)
+ assert.equal(spawnSync('/usr/bin/mkfifo', ['-m', '600', file]).status, 0)
+ const negative = run()
+ assert.equal(negative.error?.code === 'ETIMEDOUT', false)
+ assert.equal(negative.status, 0)
+ assert.deepEqual(JSON.parse(negative.stdout), { outcome: 'rejected', reason: 'not_regular_file', code: 'ERR_JWT_DEV_STORE' })
+ assert.equal(fs.lstatSync(file).isFIFO(), true)
+ })
+}
diff --git a/packages/jwt-key-policy/test/store-process-fixture.cjs b/packages/jwt-key-policy/test/store-process-fixture.cjs
new file mode 100644
index 000000000..eca0210e4
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-process-fixture.cjs
@@ -0,0 +1,14 @@
+'use strict'
+
+const store = require('../dev-store.cjs')
+const action = process.argv[2] === 'verify'
+ ? store.readDevVerifierMaterial
+ : store.loadOrCreateDevSigningMaterial
+let evidence
+try {
+ const accepted = action('rpc', process.argv[3])
+ evidence = { outcome: 'accepted', fingerprint: accepted.fingerprint }
+} catch (failure) {
+ evidence = { outcome: 'rejected', reason: failure.reason, code: failure.code }
+}
+process.stdout.write(JSON.stringify(evidence))
diff --git a/packages/jwt-key-policy/test/store-publication.test.cjs b/packages/jwt-key-policy/test/store-publication.test.cjs
new file mode 100644
index 000000000..dbdd9bc56
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-publication.test.cjs
@@ -0,0 +1,339 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const { spawn } = require('node:child_process')
+const crypto = require('node:crypto')
+const fs = require('node:fs')
+const path = require('node:path')
+const { test } = require('node:test')
+const policy = require('../index.cjs')
+const storeApi = require('../dev-store.cjs')
+const { digest, errno, expectReason, fixture, keyPair, publishPair, snapshot, storeWithPolicy, temporaries, withFsPatches } = require('./store-fixtures.cjs')
+const pair = keyPair()
+const other = keyPair()
+const fingerprint = policy.publicKeyPemFingerprint(pair.publicKey)
+const childFixture = path.join(__dirname, 'store-process-fixture.cjs')
+
+function runChild(directory) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [childFixture, 'sign', directory], { env: { PATH: process.env.PATH }, stdio: ['ignore', 'pipe', 'pipe'] })
+ let stdout = ''
+ const deadline = setTimeout(() => child.kill('SIGTERM'), 8000)
+ child.stdout.on('data', chunk => { stdout += chunk })
+ child.stderr.resume()
+ child.once('error', failure => { clearTimeout(deadline); reject(failure) })
+ child.once('close', (status, signal) => {
+ clearTimeout(deadline)
+ if (status !== 0) reject(new Error(`owned fixture process failed: status=${status}, signal=${signal}`))
+ else {
+ try { resolve(JSON.parse(stdout)) } catch { reject(new Error('owned fixture process emitted invalid metadata')) }
+ }
+ })
+ })
+}
+
+test('two first processes and a restarted process converge on one complete identity', async t => {
+ const { root } = fixture(t)
+ const directory = path.join(root, 'first-start')
+ const [first, second] = await Promise.all([runChild(directory), runChild(directory)])
+ assert.equal(first.outcome, 'accepted')
+ assert.deepEqual(second, first)
+ const restart = await runChild(directory)
+ assert.deepEqual(restart, first)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', directory).fingerprint, first.fingerprint)
+ assert.deepEqual(temporaries(directory), [])
+})
+
+for (const [name, finalFile, mode] of [['signing', 'rpc.pem', 0o600], ['public', 'rpc.public.pem', 0o644]]) {
+ for (const collision of ['symlink', 'hardlink']) {
+ test(`${name} temporary ${collision} collision preserves the fixture and every final file`, t => {
+ const { root, store } = fixture(t)
+ if (name === 'public') {
+ publishPair(store, pair)
+ fs.unlinkSync(path.join(store, 'rpc.public.pem'))
+ }
+ const victim = path.join(root, 'unrelated-owned-fixture')
+ fs.writeFileSync(victim, 'synthetic preexisting bytes', { mode })
+ const nonce = Buffer.alloc(6, 0x19)
+ const candidate = `${path.join(store, finalFile)}.tmp-${process.pid.toString(36)}-${nonce.toString('hex')}`
+ if (collision === 'symlink') fs.symlinkSync(victim, candidate)
+ else fs.linkSync(victim, candidate)
+ const before = snapshot(store)
+ const victimBefore = digest(fs.readFileSync(victim))
+ const random = crypto.randomBytes
+ crypto.randomBytes = size => { assert.equal(size, nonce.length); return nonce }
+ try { expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'temporary_collision') }
+ finally { crypto.randomBytes = random }
+ assert.equal(digest(fs.readFileSync(victim)), victimBefore)
+ assert.deepEqual(snapshot(store), before)
+ assert.equal(fs.existsSync(path.join(store, finalFile)), false)
+ assert.equal(temporaries(store).length, 1)
+ })
+ }
+}
+
+test('other stale temporaries are preserved and are never adopted as identity', t => {
+ const { store } = fixture(t)
+ const stale = path.join(store, 'rpc.pem.tmp-old-operation')
+ fs.writeFileSync(stale, 'synthetic unrelated temporary bytes', { mode: 0o600 })
+ const before = digest(fs.readFileSync(stale))
+ const accepted = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, accepted.fingerprint)
+ assert.equal(digest(fs.readFileSync(stale)), before)
+ assert.deepEqual(temporaries(store), [path.basename(stale)])
+})
+
+for (const half of ['signing', 'public']) {
+ for (const stage of ['open', 'fstat', 'write', 'link']) {
+ test(`${half} publication ${stage} EIO preserves the prefix and cleans only its candidate`, t => {
+ const { store } = fixture(t)
+ if (half === 'public') {
+ publishPair(store, pair)
+ fs.unlinkSync(path.join(store, 'rpc.public.pem'))
+ }
+ const before = snapshot(store)
+ const primary = errno('EIO')
+ const held = new Map()
+ let hit = false
+ const isCandidate = file => typeof file === 'string' && file.includes('.tmp-')
+ withFsPatches({
+ openSync: original => (file, ...args) => {
+ if (stage === 'open' && isCandidate(file)) { hit = true; throw primary }
+ const fd = original(file, ...args)
+ held.set(fd, file)
+ return fd
+ },
+ closeSync: original => fd => { held.delete(fd); return original(fd) },
+ fstatSync: original => fd => {
+ if (stage === 'fstat' && isCandidate(held.get(fd))) { hit = true; throw primary }
+ return original(fd)
+ },
+ writeSync: original => (fd, ...args) => {
+ if (stage === 'write' && isCandidate(held.get(fd))) { hit = true; throw primary }
+ return original(fd, ...args)
+ },
+ linkSync: original => (from, to) => {
+ if (stage === 'link' && isCandidate(from)) { hit = true; throw primary }
+ return original(from, to)
+ },
+ }, () => assert.throws(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), failure => failure === primary))
+ assert.equal(hit, true)
+ assert.equal(held.size, 0)
+ assert.deepEqual(snapshot(store), before)
+ assert.deepEqual(temporaries(store), [])
+ })
+ }
+}
+
+test('zero-byte writes fail rather than spinning and discard the owned candidate', t => {
+ const { store } = fixture(t)
+ withFsPatches({ writeSync: () => () => 0 }, () => expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'incomplete_write'))
+ assert.deepEqual(fs.readdirSync(store), [])
+})
+
+test('short writes still publish complete material that passes the real reader', t => {
+ const { store } = fixture(t)
+ let writes = 0
+ withFsPatches({ writeSync: original => (fd, buffer, offset, length, position) => {
+ writes += 1
+ return original(fd, buffer, offset, Math.min(23, length), position)
+ } }, () => {
+ const accepted = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, accepted.fingerprint)
+ })
+ assert.equal(writes > 2, true)
+ assert.deepEqual(temporaries(store), [])
+})
+
+test('cleanup failures never replace the primary publication failure', t => {
+ const { store } = fixture(t)
+ const primary = errno('EIO')
+ const secondary = errno('EBUSY')
+ let closed = false
+ let unlinked = false
+ withFsPatches({
+ writeSync: () => () => { throw primary },
+ closeSync: original => fd => { original(fd); closed = true; throw secondary },
+ unlinkSync: original => file => { original(file); unlinked = true; throw secondary },
+ }, () => assert.throws(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), failure => failure === primary))
+ assert.equal(closed, true)
+ assert.equal(unlinked, true)
+ assert.deepEqual(fs.readdirSync(store), [])
+})
+
+test('a cleanup error after final publication fails without removing the final identity', t => {
+ const { store } = fixture(t)
+ const failure = errno('EIO')
+ withFsPatches({ unlinkSync: original => file => { original(file); throw failure } }, () => assert.throws(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), error => error === failure))
+ assert.deepEqual(fs.readdirSync(store), ['rpc.pem'])
+ const before = snapshot(store)['rpc.pem']
+ const accepted = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ assert.deepEqual(snapshot(store)['rpc.pem'], before)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, accepted.fingerprint)
+})
+
+test('a private publication winner owns the identity, not the losing generated candidate', t => {
+ const { root, store } = fixture(t)
+ const source = path.join(root, 'winner')
+ fs.mkdirSync(source, { mode: 0o700 })
+ publishPair(source, other)
+ let raced = false
+ withFsPatches({ linkSync: original => (from, to) => {
+ if (to === path.join(store, 'rpc.pem') && !raced) {
+ raced = true
+ original(path.join(source, 'rpc.pem'), to)
+ }
+ return original(from, to)
+ } }, () => {
+ const accepted = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ assert.equal(accepted.fingerprint, policy.publicKeyPemFingerprint(other.publicKey))
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, accepted.fingerprint)
+ })
+ assert.equal(raced, true)
+ assert.deepEqual(temporaries(store), [])
+})
+
+for (const shape of ['corrupt', 'unsafe', 'symlink', 'directory']) {
+ test(`a ${shape} signing winner fails without replacing it or publishing a public half`, t => {
+ const { root, store } = fixture(t)
+ const source = path.join(root, 'winner')
+ fs.mkdirSync(source, { mode: 0o700 })
+ publishPair(source, other)
+ const selected = path.join(source, 'rpc.pem')
+ if (shape === 'corrupt') fs.writeFileSync(selected, 'synthetic invalid signing fixture')
+ if (shape === 'unsafe') fs.chmodSync(selected, 0o644)
+ const before = snapshot(source)
+ const final = path.join(store, 'rpc.pem')
+ let raced = false
+ withFsPatches({ linkSync: original => (from, to) => {
+ if (to === final && !raced) {
+ raced = true
+ if (shape === 'symlink') fs.symlinkSync(selected, final)
+ else if (shape === 'directory') fs.mkdirSync(final, { mode: 0o700 })
+ else original(selected, final)
+ }
+ return original(from, to)
+ } }, () => expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), {
+ corrupt: 'invalid_pem', unsafe: 'insecure_file', symlink: 'symbolic_link', directory: 'not_regular_file',
+ }[shape]))
+ assert.equal(raced, true)
+ assert.equal(fs.existsSync(final), true)
+ assert.equal(fs.existsSync(path.join(store, 'rpc.public.pem')), false)
+ assert.deepEqual(snapshot(source), before)
+ assert.deepEqual(temporaries(store), [])
+ })
+}
+
+for (const half of ['signing', 'public']) {
+ test(`a generated-denied ${half} winner is rejected by the real policy`, t => {
+ const { root, store } = fixture(t)
+ const source = path.join(root, 'winner')
+ fs.mkdirSync(source, { mode: 0o700 })
+ publishPair(source, other)
+ if (half === 'public') {
+ publishPair(store, pair)
+ fs.unlinkSync(path.join(store, 'rpc.public.pem'))
+ }
+ const denied = policy.publicKeyPemFingerprint(other.publicKey)
+ const restricted = storeWithPolicy(real => ({ ...real,
+ parseSigningMaterial: (raw, label) => real.parseSigningMaterial(raw, label, { fingerprints: [denied] }),
+ parseVerifierMaterial: (raw, label, options) => real.parseVerifierMaterial(raw, label, { ...options, fingerprints: [denied] }),
+ }))
+ const leaf = half === 'signing' ? 'rpc.pem' : 'rpc.public.pem'
+ const final = path.join(store, leaf)
+ const selected = path.join(source, leaf)
+ const before = digest(fs.readFileSync(selected))
+ let raced = false
+ withFsPatches({ linkSync: original => (from, to) => {
+ if (to === final && !raced) { raced = true; original(selected, to) }
+ return original(from, to)
+ } }, () => expectReason(() => restricted.loadOrCreateDevSigningMaterial('rpc', store), 'banned_identity'))
+ assert.equal(raced, true)
+ assert.equal(digest(fs.readFileSync(final)), before)
+ assert.deepEqual(temporaries(store), [])
+ })
+}
+
+for (const winner of ['matching', 'mismatched', 'corrupt', 'unsafe']) {
+ test(`the ${winner} public publication winner is validated and preserved`, t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ fs.unlinkSync(path.join(store, 'rpc.public.pem'))
+ const selected = path.join(root, 'winner-public')
+ fs.writeFileSync(selected, winner === 'mismatched' ? other.publicKey : pair.publicKey, { mode: 0o644 })
+ if (winner === 'corrupt') fs.writeFileSync(selected, 'synthetic invalid winner bytes')
+ if (winner === 'unsafe') fs.chmodSync(selected, 0o666)
+ const before = digest(fs.readFileSync(selected))
+ let raced = false
+ withFsPatches({ linkSync: original => (from, to) => {
+ if (to === path.join(store, 'rpc.public.pem') && !raced) { raced = true; original(selected, to) }
+ return original(from, to)
+ } }, () => {
+ const run = () => storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ if (winner === 'matching') assert.equal(run().fingerprint, fingerprint)
+ else expectReason(run, { mismatched: 'public_identity_mismatch', corrupt: 'invalid_pem', unsafe: 'insecure_file' }[winner])
+ })
+ assert.equal(raced, true)
+ assert.equal(digest(fs.readFileSync(path.join(store, 'rpc.public.pem'))), before)
+ assert.deepEqual(temporaries(store), [])
+ })
+}
+
+for (const reason of ['file_owner_mismatch', 'not_regular_file', 'insecure_file']) {
+ test(`public winner descriptor metadata ${reason} cannot be bypassed by its valid path`, t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const final = path.join(store, 'rpc.public.pem')
+ fs.unlinkSync(final)
+ const selected = path.join(root, 'winner-public')
+ fs.writeFileSync(selected, pair.publicKey, { mode: 0o644 })
+ const opened = new Map()
+ let raced = false
+ let checked = false
+ withFsPatches({
+ linkSync: original => (from, to) => { if (to === final && !raced) { raced = true; original(selected, to) } return original(from, to) },
+ openSync: original => (file, ...args) => { const fd = original(file, ...args); opened.set(fd, file); return fd },
+ closeSync: original => fd => { opened.delete(fd); return original(fd) },
+ fstatSync: original => fd => {
+ const stats = original(fd)
+ if (raced && opened.get(fd) === final) {
+ checked = true
+ const changed = Object.create(stats)
+ if (reason === 'file_owner_mismatch') changed.uid = process.geteuid() + 1
+ if (reason === 'not_regular_file') changed.isFile = () => false
+ if (reason === 'insecure_file') changed.mode = stats.mode | 0o022
+ return changed
+ }
+ return stats
+ },
+ }, () => expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), reason))
+ assert.equal(raced, true)
+ assert.equal(checked, true)
+ assert.equal(opened.size, 0)
+ assert.equal(policy.publicKeyPemFingerprint(fs.readFileSync(final, 'utf8')), fingerprint)
+ assert.deepEqual(temporaries(store), [])
+ })
+}
+
+test('a public winner is validated through its descriptor even when its path is replaced', t => {
+ const { root, store } = fixture(t)
+ publishPair(store, pair)
+ const final = path.join(store, 'rpc.public.pem')
+ fs.unlinkSync(final)
+ const bad = path.join(root, 'different-public')
+ const good = path.join(root, 'matching-public')
+ fs.writeFileSync(bad, other.publicKey, { mode: 0o644 })
+ fs.writeFileSync(good, pair.publicKey, { mode: 0o644 })
+ let raced = false
+ let replaced = false
+ withFsPatches({
+ linkSync: original => (from, to) => { if (to === final && !raced) { raced = true; original(bad, to) } return original(from, to) },
+ openSync: original => (file, ...args) => {
+ const fd = original(file, ...args)
+ if (file === final && raced && !replaced) { replaced = true; fs.renameSync(good, final) }
+ return fd
+ },
+ }, () => expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'public_identity_mismatch'))
+ assert.equal(replaced, true)
+ assert.deepEqual(temporaries(store), [])
+})
diff --git a/packages/jwt-key-policy/test/store-state.test.cjs b/packages/jwt-key-policy/test/store-state.test.cjs
new file mode 100644
index 000000000..ef85755ad
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-state.test.cjs
@@ -0,0 +1,188 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const crypto = require('node:crypto')
+const fs = require('node:fs')
+const path = require('node:path')
+const { test } = require('node:test')
+const policy = require('../index.cjs')
+const storeApi = require('../dev-store.cjs')
+const { expectReason, fixture, keyPair, publishPair, snapshot, storeWithPolicy, temporaries, withFsPatches } = require('./store-fixtures.cjs')
+const { certificate, PUBLIC_KEYS } = require('./crypto-fixtures.cjs')
+const pair = keyPair()
+const anotherPair = keyPair()
+const fingerprint = policy.publicKeyPemFingerprint(pair.publicKey)
+
+test('store resolution is lexical, absolute and free of filesystem access', () => {
+ withFsPatches({ lstatSync: () => () => { throw new Error('unexpected directory access') }, mkdirSync: () => () => { throw new Error('unexpected creation') } }, () => {
+ for (const override of [undefined, '', ' \t\n ']) {
+ assert.equal(storeApi.resolveDevKeyStoreDir('/service-root', override), '/service-root/.dev-keys')
+ }
+ assert.equal(storeApi.resolveDevKeyStoreDir('/unused-root', ' /absolute/store/./ '), '/absolute/store')
+ expectReason(() => storeApi.resolveDevKeyStoreDir('/service-root', 'relative'), 'relative_store_path')
+ expectReason(() => storeApi.resolveDevKeyStoreDir('relative'), 'relative_store_path')
+ })
+})
+
+test('closed slots and relative paths fail before any filesystem operation', () => {
+ withFsPatches({ lstatSync: () => () => { throw new Error('unexpected filesystem access') } }, () => {
+ for (const slot of ['', '../rpc', 'voucher', undefined]) {
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial(slot, '/unused'), 'invalid_slot')
+ expectReason(() => storeApi.readDevVerifierMaterial(slot, '/unused'), 'invalid_slot')
+ }
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', 'relative'), 'relative_store_path')
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', 'relative'), 'relative_store_path')
+ })
+})
+
+test('missing directory and empty slot create a complete canonical pair', t => {
+ const { root } = fixture(t)
+ const directory = path.join(root, 'missing')
+ const material = storeApi.loadOrCreateDevSigningMaterial('rpc', directory)
+ assert.equal(fs.statSync(directory).mode & 0o777, 0o700)
+ assert.equal(fs.statSync(path.join(directory, 'rpc.pem')).mode & 0o777, 0o600)
+ assert.equal(fs.statSync(path.join(directory, 'rpc.public.pem')).mode & 0o777, 0o644)
+ assert.equal(policy.publicKeyPemFingerprint(material.privatePem), material.fingerprint)
+ assert.equal(policy.publicKeyPemFingerprint(material.publicPem), material.fingerprint)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', directory).fingerprint, material.fingerprint)
+ assert.deepEqual(temporaries(directory), [])
+})
+
+test('complete pairs and independent slots preserve their existing identities and bytes', t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const before = snapshot(store)
+ const first = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ const second = storeApi.loadOrCreateDevSigningMaterial('rpc', store)
+ assert.equal(first.fingerprint, fingerprint)
+ assert.equal(second.fingerprint, fingerprint)
+ assert.deepEqual(snapshot(store), before)
+ const session = storeApi.loadOrCreateDevSigningMaterial('session', store)
+ assert.notEqual(session.fingerprint, first.fingerprint)
+})
+
+test('private-only state publishes its public half without rewriting the private', t => {
+ const { store } = fixture(t)
+ fs.writeFileSync(path.join(store, 'rpc.pem'), pair.privateKey, { mode: 0o600 })
+ const before = snapshot(store)['rpc.pem']
+ assert.equal(storeApi.loadOrCreateDevSigningMaterial('rpc', store).fingerprint, fingerprint)
+ assert.deepEqual(snapshot(store)['rpc.pem'], before)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint)
+})
+
+test('equivalent PKCS1, CRLF and X509 public carriers are reused without rewriting either file', t => {
+ const { root } = fixture(t)
+ const forms = [
+ crypto.createPublicKey(pair.publicKey).export({ type: 'pkcs1', format: 'pem' }).toString(),
+ pair.publicKey.replace(/\n/g, '\r\n'),
+ certificate(crypto.createPrivateKey(pair.privateKey)),
+ ]
+ for (let index = 0; index < forms.length; index++) {
+ const directory = path.join(root, `encoding-${index}`)
+ fs.mkdirSync(directory, { mode: 0o700 })
+ publishPair(directory, { ...pair, publicKey: forms[index] })
+ const before = snapshot(directory)
+ const result = storeApi.loadOrCreateDevSigningMaterial('rpc', directory)
+ assert.equal(result.fingerprint, fingerprint)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', directory).fingerprint, fingerprint)
+ assert.deepEqual(snapshot(directory), before)
+ }
+})
+
+test('orphan public state fails without generating or altering an identity', t => {
+ const { store } = fixture(t)
+ fs.writeFileSync(path.join(store, 'rpc.public.pem'), pair.publicKey, { mode: 0o644 })
+ const before = snapshot(store)
+ const generate = crypto.generateKeyPairSync
+ crypto.generateKeyPairSync = () => { throw new Error('unexpected replacement generation') }
+ try { expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), 'orphan_public') }
+ finally { crypto.generateKeyPairSync = generate }
+ assert.deepEqual(snapshot(store), before)
+ assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint)
+})
+
+for (const state of ['corrupt', 'unsafe', 'historical']) {
+ test(`public-only ${state} material never creates a replacement signing identity`, t => {
+ const { store } = fixture(t)
+ const file = path.join(store, 'rpc.public.pem')
+ let value = pair.publicKey
+ if (state === 'corrupt') value = 'synthetic invalid public fixture'
+ if (state === 'historical') value = PUBLIC_KEYS.rpc
+ fs.writeFileSync(file, value, { mode: 0o644 })
+ if (state === 'unsafe') fs.chmodSync(file, 0o666)
+ const before = snapshot(store)
+ const generate = crypto.generateKeyPairSync
+ crypto.generateKeyPairSync = () => { throw new Error('unexpected replacement generation') }
+ try {
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), {
+ corrupt: 'invalid_pem', unsafe: 'insecure_file', historical: 'banned_identity',
+ }[state])
+ } finally { crypto.generateKeyPairSync = generate }
+ assert.deepEqual(snapshot(store), before)
+ })
+}
+
+test('a complete cooperating pair appearing after the missing-private read is adopted', t => {
+ const { store } = fixture(t)
+ const privatePath = path.join(store, 'rpc.pem')
+ let first = true
+ withFsPatches({ openSync: original => (file, ...args) => {
+ if (file === privatePath && first) {
+ first = false
+ try { return original(file, ...args) } catch (error) {
+ if (error.code === 'ENOENT') publishPair(store, pair)
+ throw error
+ }
+ }
+ return original(file, ...args)
+ } }, () => assert.equal(storeApi.loadOrCreateDevSigningMaterial('rpc', store).fingerprint, fingerprint))
+ assert.deepEqual(temporaries(store), [])
+})
+
+for (const [name, privateValue, publicValue, reason] of [
+ ['corrupt private with public', 'synthetic invalid private', pair.publicKey, 'invalid_pem'],
+ ['corrupt private without public', 'synthetic invalid private', undefined, 'invalid_pem'],
+ ['public in private slot', pair.publicKey, pair.publicKey, 'wrong_key_role'],
+ ['private in public slot', pair.privateKey, pair.privateKey, 'wrong_key_role'],
+ ['corrupt public with private', pair.privateKey, 'synthetic invalid public', 'invalid_pem'],
+ ['different public identity', pair.privateKey, anotherPair.publicKey, 'public_identity_mismatch'],
+]) {
+ test(`${name} fails with a specific reason and preserves all files`, t => {
+ const { store } = fixture(t)
+ fs.writeFileSync(path.join(store, 'rpc.pem'), privateValue, { mode: 0o600 })
+ if (publicValue !== undefined) fs.writeFileSync(path.join(store, 'rpc.public.pem'), publicValue, { mode: 0o644 })
+ const before = snapshot(store)
+ expectReason(() => storeApi.loadOrCreateDevSigningMaterial('rpc', store), reason)
+ assert.deepEqual(snapshot(store), before)
+ })
+}
+
+for (const half of ['private', 'public']) {
+ test(`a generated-denied ${half} identity fails through the real parser and preserves the pair`, t => {
+ const { store } = fixture(t)
+ publishPair(store, pair)
+ const before = snapshot(store)
+ const restricted = storeWithPolicy(real => ({ ...real,
+ ...(half === 'private'
+ ? { parseSigningMaterial: (raw, source) => real.parseSigningMaterial(raw, source, { fingerprints: [fingerprint] }) }
+ : { parseVerifierMaterial: (raw, source, options) => real.parseVerifierMaterial(raw, source, { ...options, fingerprints: [fingerprint] }) }),
+ }))
+ expectReason(() => restricted.loadOrCreateDevSigningMaterial('rpc', store), 'banned_identity')
+ assert.deepEqual(snapshot(store), before)
+ })
+}
+
+test('a verifier never creates missing material or opens private material', t => {
+ const { root, store } = fixture(t)
+ const missing = path.join(root, 'missing')
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', missing), 'missing_material')
+ assert.equal(fs.existsSync(missing), false)
+ expectReason(() => storeApi.readDevVerifierMaterial('rpc', store), 'missing_material')
+ assert.deepEqual(fs.readdirSync(store), [])
+ publishPair(store, pair)
+ fs.unlinkSync(path.join(store, 'rpc.pem'))
+ withFsPatches({ openSync: original => (file, ...args) => {
+ assert.equal(file.endsWith('rpc.pem'), false, 'verifier must not read the signing file')
+ return original(file, ...args)
+ } }, () => assert.equal(storeApi.readDevVerifierMaterial('rpc', store).fingerprint, fingerprint))
+})
diff --git a/packages/jwt-key-policy/test/store-types.ts b/packages/jwt-key-policy/test/store-types.ts
new file mode 100644
index 000000000..fa8f0f334
--- /dev/null
+++ b/packages/jwt-key-policy/test/store-types.ts
@@ -0,0 +1,30 @@
+// This file is checked with --noEmit; no store operation is executed.
+import {
+ DevKeyStoreError,
+ loadOrCreateDevSigningMaterial,
+ readDevVerifierMaterial,
+ resolveDevKeyStoreDir,
+ type DevJwtSlot,
+ type DevSigningMaterial,
+ type DevVerifierMaterial,
+} from '@clerum/jwt-key-policy/dev-store'
+
+const slot: DevJwtSlot = 'rpc'
+const directory: string = resolveDevKeyStoreDir('/compile-only-service', '')
+const signing: DevSigningMaterial = loadOrCreateDevSigningMaterial(slot, directory)
+const verifying: DevVerifierMaterial = readDevVerifierMaterial(slot, directory)
+const acceptedFingerprint: string = signing.fingerprint
+const acceptedPublic: string = verifying.publicPem
+const storeFailure = new DevKeyStoreError('compile-only-source', 'missing_material')
+const storeCode: 'ERR_JWT_DEV_STORE' = storeFailure.code
+
+// @ts-expect-error The closed slot cannot become a path supplied by a caller.
+loadOrCreateDevSigningMaterial('../rpc', directory)
+// @ts-expect-error Canonical material fields are readonly for consumers.
+signing.privatePem = ''
+// @ts-expect-error Canonical verifier identity is readonly for consumers.
+verifying.fingerprint = ''
+// @ts-expect-error Error reasons are a closed safe contract.
+new DevKeyStoreError('compile-only-source', 'unknown_reason')
+
+void [acceptedFingerprint, acceptedPublic, storeCode]
diff --git a/rpc-proxy/.env.example b/rpc-proxy/.env.example
index eba64ddeb..26c008cd8 100644
--- a/rpc-proxy/.env.example
+++ b/rpc-proxy/.env.example
@@ -10,6 +10,11 @@ RPC_PROXY_CORS_ORIGIN=http://localhost:3000
# 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.
+# Explicit verifier keys require one RSA >=2048 PEM object (SPKI/PKCS#1 public
+# or X509 carrier); private PEM env input is legacy-compatible, not recommended.
+# Public store files never accept private material. Material/read limit: 64 KiB.
+# The store requires POSIX guarantees, trusted ancestors and the same effective
+# UID across services; otherwise supply the matching keys explicitly.
RPC_PROXY_JWT_PUBLIC_KEY=
RPC_PROXY_JWT_ISSUER=control-api
RPC_PROXY_JWT_AUDIENCE=rpc-proxy
diff --git a/rpc-proxy/Dockerfile b/rpc-proxy/Dockerfile
index 3b95ec385..733f658f8 100644
--- a/rpc-proxy/Dockerfile
+++ b/rpc-proxy/Dockerfile
@@ -1,11 +1,13 @@
FROM node:24-alpine AS builder
WORKDIR /app
-COPY package*.json ./
+COPY packages/jwt-key-policy/package.json packages/jwt-key-policy/index.cjs packages/jwt-key-policy/index.d.ts packages/jwt-key-policy/dev-store.cjs packages/jwt-key-policy/dev-store.d.ts ./packages/jwt-key-policy/
+COPY rpc-proxy/package*.json ./rpc-proxy/
+WORKDIR /app/rpc-proxy
RUN npm ci
-COPY tsconfig.json ./
-COPY src ./src
+COPY rpc-proxy/tsconfig.json ./
+COPY rpc-proxy/src ./src
RUN npm run build
RUN npm prune --production
@@ -16,10 +18,12 @@ WORKDIR /app
ENV NODE_ENV=production
ENV RPC_PROXY_PORT=8094
-COPY --from=builder --chown=app:app /app/package*.json ./
-COPY --from=builder --chown=app:app /app/dist ./dist
-COPY --from=builder --chown=app:app /app/node_modules ./node_modules
+COPY --from=builder --chown=app:app /app/packages/jwt-key-policy ./packages/jwt-key-policy
+COPY --from=builder --chown=app:app /app/rpc-proxy/package*.json ./rpc-proxy/
+COPY --from=builder --chown=app:app /app/rpc-proxy/dist ./rpc-proxy/dist
+COPY --from=builder --chown=app:app /app/rpc-proxy/node_modules ./rpc-proxy/node_modules
USER app
EXPOSE 8094
+WORKDIR /app/rpc-proxy
CMD ["node", "dist/main.js"]
diff --git a/rpc-proxy/Dockerfile.dockerignore b/rpc-proxy/Dockerfile.dockerignore
new file mode 100644
index 000000000..9454d6323
--- /dev/null
+++ b/rpc-proxy/Dockerfile.dockerignore
@@ -0,0 +1,23 @@
+**
+!packages/
+!packages/jwt-key-policy/
+!packages/jwt-key-policy/package.json
+!packages/jwt-key-policy/index.cjs
+!packages/jwt-key-policy/index.d.ts
+!packages/jwt-key-policy/dev-store.cjs
+!packages/jwt-key-policy/dev-store.d.ts
+!rpc-proxy/
+!rpc-proxy/package.json
+!rpc-proxy/package-lock.json
+!rpc-proxy/tsconfig.json
+!rpc-proxy/src/
+!rpc-proxy/src/**
+**/node_modules/
+**/dist/
+**/.dev-keys/
+**/.env
+**/.env.*
+**/*.pem
+**/*.key
+**/*.log
+**/.local-notes/
diff --git a/rpc-proxy/Makefile b/rpc-proxy/Makefile
index e8dbc722f..bc44092eb 100644
--- a/rpc-proxy/Makefile
+++ b/rpc-proxy/Makefile
@@ -14,10 +14,10 @@ dev: install
CLERUM_DEV_MODE=true npm run dev
docker-build:
- docker build -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) .
+ docker build -f Dockerfile -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) ..
docker-push: docker-build
docker push $(REGISTRY)/$(IMAGE_NAME):$(TAG)
docker-push-cross:
- docker buildx build --platform linux/amd64 -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) --push .
+ docker buildx build --platform linux/amd64 -f Dockerfile -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) --push ..
diff --git a/rpc-proxy/README.md b/rpc-proxy/README.md
index 2c5476af7..46562ed72 100644
--- a/rpc-proxy/README.md
+++ b/rpc-proxy/README.md
@@ -161,6 +161,31 @@ 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.
+JWT material is checked by the shared `@clerum/jwt-key-policy`. Configure an
+RSA public key as SPKI or PKCS#1 PEM. An X509 certificate may carry the public
+identity, without CA, hostname or expiry validation. Private PEM environment
+values remain accepted for legacy compatibility and are converted to public
+SPKI; prefer supplying only the public half. Store public files reject private
+material. Exactly one complete PEM object is required; bundles, encrypted
+private material, non-RSA keys and historical committed identities fail.
+
+Every RS256 key must be RSA-2048 or stronger, including verifiers. This
+deliberately rejects previously accepted weak verifier keys under
+[RFC 7518 section 3.3](https://www.rfc-editor.org/rfc/rfc7518.html#section-3.3).
+The material/read limit is 64 KiB. Invalid explicit input never selects a
+different source or regenerates an identity.
+
+The dev store requires POSIX no-follow/nonblocking/exclusive-file guarantees,
+trusted ancestor directories and cooperating services with the same effective
+UID. It does not defend against hostile ancestors or same-UID processes.
+Use explicit signing/verifying environment keys for different users or
+unsupported platforms; this verifier then performs no store access. Corrupt
+or rejected keys require operator repair; they are not rotated automatically.
+
+`make docker-build` uses the repository root context. The equivalent command
+from that root is `docker build -f rpc-proxy/Dockerfile .`. The image preserves
+the service/package layout and excludes package tests and local key data.
+
## Kubernetes Deploy (Hardened Defaults)
The `deploy/` manifests include:
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 92c4a09c0..e992c19cc 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,13 +1,14 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.114",
+ "version": "0.1.115",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.114",
+ "version": "0.1.115",
"dependencies": {
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
"express": "^4.21.2",
"http-proxy": "^1.18.1",
@@ -29,6 +30,18 @@
"node": ">=24"
}
},
+ "../packages/jwt-key-policy": {
+ "name": "@clerum/jwt-key-policy",
+ "version": "0.1.0",
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "node_modules/@clerum/jwt-key-policy": {
+ "resolved": "../packages/jwt-key-policy",
+ "link": true
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 1c954d2ce..f3e1032f8 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.114",
+ "version": "0.1.115",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
@@ -10,12 +10,14 @@
"build": "tsc",
"test": "vitest run",
"test:watch": "vitest",
+ "typecheck:jwt-contract": "tsc -p tsconfig.jwt-contract-tests.json --noEmit",
"test:e2e": "npm --prefix ../tests/e2e run test:rpc-proxy-e2e",
"test:e2e:watch": "npm --prefix ../tests/e2e run test:rpc-proxy-e2e:watch",
"start": "node dist/main.js",
"dev": "tsx src/main.ts"
},
"dependencies": {
+ "@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
"express": "^4.21.2",
"http-proxy": "^1.18.1",
diff --git a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
index 924a0f0d7..f7f33b676 100644
--- a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
+++ b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
@@ -1,11 +1,19 @@
-import * as testApi from 'vitest'
-import { defineDevJwtVerifierContract } from '../../test/helpers/devJwtVerifierContract.js'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, it, vi } from 'vitest'
+import { createDevJwtVerifierContract } from '../../../scripts/testing/devJwtVerifierContract.js'
-defineDevJwtVerifierContract({
- testApi,
+const contract = createDevJwtVerifierContract({
service: 'rpc-proxy',
slot: 'rpc',
envName: 'RPC_PROXY_JWT_PUBLIC_KEY',
configSource: new URL('../config.ts', import.meta.url),
loadConfig: () => import('../config.js'),
+ resetModules: () => vi.resetModules(),
+})
+
+beforeAll(contract.prepare, 60_000)
+beforeEach(contract.reset)
+afterEach(contract.cleanup)
+afterAll(contract.dispose)
+describe('rpc-proxy dev JWT verifier contract', () => {
+ for (const testCase of contract.cases) it(testCase.name, testCase.run, 30_000)
})
diff --git a/rpc-proxy/src/config.ts b/rpc-proxy/src/config.ts
index 785a10d0c..7f1d1a0a0 100644
--- a/rpc-proxy/src/config.ts
+++ b/rpc-proxy/src/config.ts
@@ -1,6 +1,13 @@
-import { createHash, createPublicKey } from 'node:crypto'
-import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs'
-import { dirname, isAbsolute, join } from 'node:path'
+import { dirname, join } from 'node:path'
+import { parseVerifierMaterial } from '@clerum/jwt-key-policy'
+import { readDevVerifierMaterial, resolveDevKeyStoreDir } from '@clerum/jwt-key-policy/dev-store'
+
+const DEV_MODE_ENABLED = process.env.CLERUM_DEV_MODE === 'true'
+if (process.env.NODE_ENV === 'production' && DEV_MODE_ENABLED) {
+ throw new Error(
+ '[SECURITY] Startup rejected: CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production.'
+ )
+}
type Config = {
port: number
@@ -103,14 +110,6 @@ function assertNotPlaceholder(label: string, value: string): void {
}
}
-function normalizePem(value: string): string {
- return value
- .replace(/\\r\\n/g, '\n')
- .replace(/\\n/g, '\n')
- .replace(/\r\n?/g, '\n')
- .trim()
-}
-
export function parseSandboxUiAllowedPorts(raw: string): ReadonlySet<number> {
const ports = new Set<number>()
for (const token of raw.split(',')) {
@@ -189,96 +188,6 @@ 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 {
- const normalized = normalizePem(publicPem)
- let fingerprint: string
- let canonicalPublicPem: string
- try {
- // 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 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 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)
- }
-}
-
/**
* 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
@@ -287,21 +196,14 @@ function readDevJwtPublicKey(storeDir: string, fileName: string, envName: string
*/
function resolveRpcJwtPublicKey(): string {
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 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)
+ if (fromEnv) return parseVerifierMaterial(fromEnv, envName).publicPem
+ if (DEV_MODE_ENABLED) {
+ const storeDir = resolveDevKeyStoreDir(
+ join(serviceRoot(), '..', 'control-api'),
+ process.env.EVENFIRE_DEV_KEY_STORE
+ )
+ return readDevVerifierMaterial('rpc', storeDir).publicPem
}
return required(envName)
}
diff --git a/rpc-proxy/test/helpers/devJwtVerifierContract.ts b/rpc-proxy/test/helpers/devJwtVerifierContract.ts
deleted file mode 100644
index 732285dcc..000000000
--- a/rpc-proxy/test/helpers/devJwtVerifierContract.ts
+++ /dev/null
@@ -1,440 +0,0 @@
-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/tsconfig.jwt-contract-tests.json b/rpc-proxy/tsconfig.jwt-contract-tests.json
new file mode 100644
index 000000000..6bf634f47
--- /dev/null
+++ b/rpc-proxy/tsconfig.jwt-contract-tests.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "..",
+ "noEmit": true,
+ "module": "ESNext",
+ "moduleResolution": "Bundler"
+ },
+ "include": [
+ "src/config.ts",
+ "src/__tests__/config.devKeyStore.test.ts",
+ "../scripts/testing/devJwtVerifierContract.ts"
+ ],
+ "exclude": []
+}
diff --git a/scripts/minikube/build-images.sh b/scripts/minikube/build-images.sh
index 01cd87626..b9530c4b7 100755
--- a/scripts/minikube/build-images.sh
+++ b/scripts/minikube/build-images.sh
@@ -1208,12 +1208,14 @@ build_image "control-api" \
"${PROJECT_DIR}/control-api/Dockerfile"
build_image "external-rest-api" \
- "${PROJECT_DIR}/external-rest-api" \
- "clerum/external-rest-api:test"
+ "${PROJECT_DIR}" \
+ "clerum/external-rest-api:test" \
+ "${PROJECT_DIR}/external-rest-api/Dockerfile"
build_image "rpc-proxy" \
- "${PROJECT_DIR}/rpc-proxy" \
- "clerum/rpc-proxy:test"
+ "${PROJECT_DIR}" \
+ "clerum/rpc-proxy:test" \
+ "${PROJECT_DIR}/rpc-proxy/Dockerfile"
build_image "webhook-proxy" \
"${PROJECT_DIR}/webhook-proxy" \
diff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.sh
index 6d00f4196..ab1789b57 100755
--- a/scripts/minikube/pre-gate-incremental.sh
+++ b/scripts/minikube/pre-gate-incremental.sh
@@ -194,6 +194,13 @@ incremental_classify_path() {
channel-reader/*) incremental_add_target channel-reader channels channel-reader-chatllm ;;
mcp-proxy/*) incremental_add_target mcp-proxy mcp-server mcp-proxy ;;
control-ui/*) incremental_add_target control-ui control-plane control-ui ;;
+ packages/jwt-key-policy/*)
+ # All three images consume this one policy/store package. Package-only
+ # changes must rebuild each consumer, including GHCR shadow builds.
+ incremental_add_target control-api control-plane control-api
+ incremental_add_target external-rest-api profiles external-rest-api
+ incremental_add_target rpc-proxy rpc-proxy rpc-proxy
+ ;;
packages/gfs-interaction-policy/*)
# Control UI imports the GFS naming policy and mcp-host imports the
# FileReference v1 contract and byte classifier; both Dockerfiles COPY
diff --git a/scripts/minikube/pre-gate-marker.sh b/scripts/minikube/pre-gate-marker.sh
index 0d517c60a..d786327cd 100755
--- a/scripts/minikube/pre-gate-marker.sh
+++ b/scripts/minikube/pre-gate-marker.sh
@@ -12,14 +12,17 @@ pre_gate_marker_fingerprint_dir() {
return 0
fi
- # `.claude/` holds agent tool state (plan-state.json and the like) that is
- # rewritten outside any source change; hashing it invalidates a fresh marker.
+ # Agent state and generated dev credentials are not deployed inputs. Image
+ # contexts exclude .dev-keys, so local key creation/rotation must not stale
+ # the marker for an otherwise identical source and image acquisition.
local digest
if ! digest="$(
set -o pipefail
find "${project_dir}/${dir}" \
-type f \
! -path '*/.claude/*' \
+ ! -path '*/.dev-keys' \
+ ! -path '*/.dev-keys/*' \
! -path '*/node_modules/*' \
! -path '*/dist/*' \
! -path '*/.next/*' \
@@ -64,6 +67,7 @@ pre_gate_marker_cluster_fingerprint() {
host-context-controller \
packages/workflow-runtime-core \
packages/network-policy-core \
+ packages/jwt-key-policy \
workflow-recipes \
packages/workflow-sdk \
tests/e2e/fixtures/custom-workflow-coordinator \
diff --git a/scripts/precommit/bump-staged-package-versions.mjs b/scripts/precommit/bump-staged-package-versions.mjs
index b2d3793d9..d378f5a85 100644
--- a/scripts/precommit/bump-staged-package-versions.mjs
+++ b/scripts/precommit/bump-staged-package-versions.mjs
@@ -30,6 +30,11 @@ const MANIFEST_FIELD_BY_PACKAGE = {
}
const MANIFEST_COUNTER_PACKAGES = Object.keys(MANIFEST_FIELD_BY_PACKAGE)
+// Changes to these prebuilt runtime packages affect their declared consumers
+// even when no file inside a service was staged. Read dependency declarations
+// from the index so unstaged manifest edits cannot choose committed counters.
+const SHARED_RUNTIME_PACKAGE_ROOTS = ['packages/jwt-key-policy']
+
function exitWithError(message, status = 1) {
console.error(message)
process.exit(status)
@@ -67,6 +72,26 @@ function readJsonFromGit(ref, relativePath) {
return JSON.parse(result.stdout)
}
+function getAffectedPackageRootsForFile(file) {
+ const directRoot = getPackageRootForFile(file)
+ const sharedRoot = SHARED_RUNTIME_PACKAGE_ROOTS.find(
+ root => file === root || file.startsWith(`${root}/`)
+ )
+ if (!sharedRoot) return directRoot ? [directRoot] : []
+
+ const sharedPath = resolve(repoRoot, sharedRoot)
+ const consumers = sortedPackageRoots.filter(root => {
+ const manifest = readJsonFromGit('', `${root}/package.json`)
+ return Object.values(manifest?.dependencies ?? {}).some(
+ spec =>
+ typeof spec === 'string' &&
+ spec.startsWith('file:') &&
+ resolve(repoRoot, root, spec.slice(5)) === sharedPath
+ )
+ })
+ return [...(directRoot ? [directRoot] : []), ...consumers]
+}
+
function stageFile(relativePath) {
const addResult = spawnSync('git', ['add', '--', relativePath], {
cwd: repoRoot,
@@ -141,7 +166,7 @@ const affectedPackages = [
.map(file => file.trim())
.filter(Boolean)
.filter(file => !IGNORED_FILES.includes(file))
- .map(getPackageRootForFile)
+ .flatMap(getAffectedPackageRootsForFile)
.filter(Boolean)
),
]
diff --git a/scripts/release/validate-release-version-bumps.mjs b/scripts/release/validate-release-version-bumps.mjs
index 3be4197e4..0eb7e8c4a 100644
--- a/scripts/release/validate-release-version-bumps.mjs
+++ b/scripts/release/validate-release-version-bumps.mjs
@@ -8,14 +8,14 @@ const PROJECTS = [
{
name: 'external-rest-api',
packagePath: 'external-rest-api/package.json',
- codePrefixes: ['external-rest-api/src/', 'external-rest-api/test/'],
+ codePrefixes: ['external-rest-api/src/', 'external-rest-api/test/', 'packages/jwt-key-policy/'],
codeFiles: ['external-rest-api/tsconfig.json'],
ignoredFiles: ['external-rest-api/src/releaseManifest.ts'],
},
{
name: 'rpc-proxy',
packagePath: 'rpc-proxy/package.json',
- codePrefixes: ['rpc-proxy/src/', 'rpc-proxy/test/'],
+ codePrefixes: ['rpc-proxy/src/', 'rpc-proxy/test/', 'packages/jwt-key-policy/'],
codeFiles: ['rpc-proxy/tsconfig.json'],
},
]
diff --git a/scripts/testing/devJwtVerifierContract.ts b/scripts/testing/devJwtVerifierContract.ts
new file mode 100644
index 000000000..18720d95d
--- /dev/null
+++ b/scripts/testing/devJwtVerifierContract.ts
@@ -0,0 +1,416 @@
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { createPublicKey, type KeyObject, generateKeyPairSync, randomUUID } from 'node:crypto'
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, 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 } from 'node:url'
+import type * as Policy from '../../packages/jwt-key-policy/index.js'
+import type * as Store from '../../packages/jwt-key-policy/dev-store.js'
+
+type VerifierModule = { config: { jwtPublicKey: string; jwtIssuer: string; jwtAudience: string } }
+export type VerifierContractOptions = {
+ service: 'rpc-proxy' | 'external-rest-api'
+ slot: 'rpc' | 'session'
+ envName: string
+ configSource: URL
+ loadConfig: () => Promise<VerifierModule>
+ resetModules: () => void
+}
+export type VerifierContractCase = { name: string; run: () => void | Promise<void> }
+
+type CryptoFixtures = {
+ PUBLIC_KEYS: Readonly<Record<'rpc' | 'session' | 'admin', string>>
+ encodings: (pem: string) => Record<string, string>
+ certificate: (material: KeyObject) => string
+ certificateWithPublic: (publicPem: string) => Promise<string>
+}
+type RuntimeResult = {
+ storeDir: string
+ fingerprint?: string
+ signatureVerified?: boolean
+ storeOperations: number
+ code?: string
+ reason?: string
+ productionDevModeRejected?: boolean
+}
+
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
+
+/** Framework-neutral fixture/cases; each caller uses its own test API/types. */
+export function createDevJwtVerifierContract(options: VerifierContractOptions) {
+ const serviceRoot = dirname(dirname(fileURLToPath(options.configSource)))
+ const serviceRequire = createRequire(options.configSource)
+ const policy = serviceRequire('@clerum/jwt-key-policy') as typeof Policy
+ const storeApi = serviceRequire('@clerum/jwt-key-policy/dev-store') as typeof Store
+ const cryptoFixtures = serviceRequire(join(repoRoot, 'packages/jwt-key-policy/test/crypto-fixtures.cjs')) as CryptoFixtures
+ const pair = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ const freshPublic = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString().trim()
+ const signingPem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString().trim()
+ const cert = cryptoFixtures.certificate(pair.privateKey)
+ const encodings = cryptoFixtures.encodings(freshPublic)
+ const originalEnv = { ...process.env }
+ let artifactRoot: string | undefined
+ let layout: string | undefined
+ let store: string
+ const cases: VerifierContractCase[] = []
+ const add = (name: string, run: VerifierContractCase['run']) => cases.push({ name, run })
+ const publicPath = () => join(store, `${options.slot}.public.pem`)
+ const publish = (pem = freshPublic) => writeFileSync(publicPath(), pem, { mode: 0o644 })
+ const fingerprint = (pem: string) => policy.publicKeyPemFingerprint(pem)
+ const expectFailure = (code: string, reason?: string) => assert.rejects(options.loadConfig, error => {
+ const value = error as { code?: string; reason?: string }
+ assert.equal(value.code, code)
+ if (reason !== undefined) assert.equal(value.reason, reason)
+ return true
+ })
+
+ async function withEffectiveUid(values: readonly number[], run: () => Promise<void>): Promise<void> {
+ const effectiveUid = process.geteuid
+ assert.equal(typeof effectiveUid, 'function', 'Ownership cases require the documented POSIX store platform')
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'geteuid')
+ let call = 0
+ Object.defineProperty(process, 'geteuid', {
+ configurable: true, value: () => values[Math.min(call++, values.length - 1)],
+ })
+ try { await run() } finally {
+ if (descriptor) Object.defineProperty(process, 'geteuid', descriptor)
+ else delete process.geteuid
+ }
+ }
+
+ function productionEnvironment(): void {
+ process.env.NODE_ENV = 'production'
+ delete process.env.CLERUM_DEV_MODE
+ const prefix = options.service === 'rpc-proxy' ? 'RPC_PROXY' : 'EXTERNAL_REST_API'
+ const values = {
+ CORS_ORIGIN: 'http://localhost:3001', JWT_ISSUER: 'control-api',
+ JWT_AUDIENCE: options.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',
+ }
+ for (const [name, value] of Object.entries(values)) process.env[`${prefix}_${name}`] = value
+ }
+
+ // Compile the actual configuration and its TypeScript closure. Full-service
+ // builds and production image validation remain separate evidence lanes.
+ function prepare(): void {
+ artifactRoot = realpathSync(mkdtempSync(join(tmpdir(), `evenfire-${options.slot}-jwt-artifact-`)))
+ execFileSync(process.execPath, [
+ serviceRequire.resolve('typescript/bin/tsc'), fileURLToPath(options.configSource),
+ '--outDir', artifactRoot, '--rootDir', join(serviceRoot, 'src'),
+ '--module', 'NodeNext', '--moduleResolution', 'NodeNext', '--target', 'ES2022',
+ '--strict', '--skipLibCheck', '--esModuleInterop',
+ ], { cwd: serviceRoot, stdio: ['ignore', 'pipe', 'pipe'], timeout: 45_000, maxBuffer: 256 * 1024 })
+ }
+
+ function reset(): void {
+ options.resetModules()
+ process.env = { ...originalEnv, NODE_ENV: 'test', CLERUM_DEV_MODE: 'true' }
+ delete process.env[options.envName]
+ layout = realpathSync(mkdtempSync(join(tmpdir(), `evenfire-${options.slot}-verifier-`)))
+ store = join(layout, 'store')
+ mkdirSync(store, { mode: 0o700 })
+ process.env.EVENFIRE_DEV_KEY_STORE = store
+ }
+
+ function cleanup(): void {
+ process.env = { ...originalEnv }
+ if (layout) rmSync(layout, { recursive: true, force: true })
+ layout = undefined
+ options.resetModules()
+ }
+
+ function dispose(): void {
+ cleanup()
+ if (artifactRoot) rmSync(artifactRoot, { recursive: true, force: true })
+ artifactRoot = undefined
+ }
+
+ function runRuntime(runtime: 'src' | 'dist', override: string | undefined, configure?: {
+ supplied?: string; productionDev?: boolean; denied?: string; consumerOverride?: string
+ }): RuntimeResult {
+ assert.ok(layout && artifactRoot, 'Prepare the actual consumer artifacts before running a runtime case')
+ const moduleDir = join(layout, options.service, runtime)
+ const policyDir = join(layout, 'node_modules/@clerum/jwt-key-policy')
+ mkdirSync(join(layout, 'control-api'), { recursive: true })
+ mkdirSync(moduleDir, { recursive: true })
+ mkdirSync(policyDir, { recursive: true })
+ for (const name of ['package.json', 'index.cjs', 'index.d.ts', 'dev-store.cjs', 'dev-store.d.ts']) {
+ copyFileSync(join(repoRoot, 'packages/jwt-key-policy', name), join(policyDir, name))
+ }
+ const configPath = join(moduleDir, runtime === 'src' ? 'config.ts' : 'config.js')
+ copyFileSync(runtime === 'src' ? options.configSource : join(artifactRoot, 'config.js'), configPath)
+ const runner = `
+ const path = require('node:path');
+ const fs = require('node:fs');
+ const crypto = require('node:crypto');
+ let storeOperations = 0;
+ let storeDir = '';
+ for (const name of ['lstatSync', 'openSync', 'mkdirSync', 'readFileSync', 'writeFileSync', 'linkSync', 'unlinkSync']) {
+ const original = fs[name];
+ fs[name] = (...args) => {
+ if (storeDir && typeof args[0] === 'string' && path.resolve(args[0]).startsWith(storeDir)) storeOperations++;
+ return original(...args);
+ };
+ }
+ const policy = require(${JSON.stringify(join(policyDir, 'index.cjs'))});
+ const storeApi = require(${JSON.stringify(join(policyDir, 'dev-store.cjs'))});
+ storeDir = storeApi.resolveDevKeyStoreDir(${JSON.stringify(join(layout, 'control-api'))}, process.env.EVENFIRE_DEV_KEY_STORE);
+ const material = storeApi.loadOrCreateDevSigningMaterial(${JSON.stringify(options.slot)}, storeDir);
+ storeOperations = 0;
+ if (${JSON.stringify(configure?.consumerOverride ?? null)} !== null) process.env.EVENFIRE_DEV_KEY_STORE = ${JSON.stringify(configure?.consumerOverride ?? null)};
+ if (${JSON.stringify(configure?.denied ?? null)}) {
+ const parse = policy.parseVerifierMaterial;
+ policy.parseVerifierMaterial = (raw, source, options) => parse(raw, source, { ...options, fingerprints: [${JSON.stringify(configure?.denied ?? '')}] });
+ }
+ try {
+ const { config } = require(${JSON.stringify(configPath)});
+ const input = Buffer.from('actual-verifier-key-contract');
+ const signature = crypto.sign('RSA-SHA256', input, material.privatePem);
+ process.stdout.write(JSON.stringify({ storeDir, fingerprint: policy.publicKeyPemFingerprint(config.jwtPublicKey),
+ signatureVerified: crypto.verify('RSA-SHA256', input, config.jwtPublicKey, signature), storeOperations }));
+ } catch (error) {
+ process.stdout.write(JSON.stringify({ storeDir, storeOperations, code: error.code, reason: error.reason,
+ productionDevModeRejected: /CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production/.test(error.message) }));
+ }
+ `
+ const env = { ...process.env }
+ if (override === undefined) delete env.EVENFIRE_DEV_KEY_STORE
+ else env.EVENFIRE_DEV_KEY_STORE = override
+ delete env[options.envName]
+ if (configure?.supplied !== undefined) env[options.envName] = configure.supplied
+ if (configure?.productionDev) env.NODE_ENV = 'production'
+ const args = runtime === 'src' ? ['--import', serviceRequire.resolve('tsx'), '-e', runner] : ['-e', runner]
+ return JSON.parse(execFileSync(process.execPath, args, {
+ cwd: join(layout, options.service), env, encoding: 'utf8', timeout: 15_000,
+ maxBuffer: 64 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
+ })) as RuntimeResult
+ }
+
+ add('verifies the real producer public identity and distinguishes another identity', async () => {
+ const material = storeApi.loadOrCreateDevSigningMaterial(options.slot, store)
+ const { config } = await options.loadConfig()
+ assert.equal(fingerprint(config.jwtPublicKey), material.fingerprint)
+ assert.equal(fingerprint(config.jwtPublicKey) === fingerprint(freshPublic), false)
+ })
+ for (const runtime of ['src', 'dist'] as const) {
+ for (const override of [undefined, '', ' \t ']) {
+ add(`${runtime} shares the default store with ${JSON.stringify(override)} override and restarts`, () => {
+ const first = runRuntime(runtime, override)
+ const second = runRuntime(runtime, override)
+ assert.equal(first.storeDir, join(layout!, 'control-api', '.dev-keys'))
+ assert.equal(first.signatureVerified, true)
+ assert.equal(second.signatureVerified, true)
+ assert.equal(second.fingerprint, first.fingerprint)
+ })
+ }
+ add(`${runtime} shares an absolute producer store and restarts`, () => {
+ const first = runRuntime(runtime, store)
+ const second = runRuntime(runtime, store)
+ assert.equal(first.storeDir, store)
+ assert.equal(first.signatureVerified, true)
+ assert.equal(second.fingerprint, first.fingerprint)
+ })
+ }
+ for (const [name, encoded] of Object.entries(encodings)) {
+ for (const origin of ['environment', 'store'] as const) {
+ add(`accepts ${name} from ${origin} as canonical SPKI`, async () => {
+ if (origin === 'environment') process.env[options.envName] = encoded
+ else publish(encoded)
+ assert.equal((await options.loadConfig()).config.jwtPublicKey === freshPublic, true)
+ })
+ }
+ for (const [slot, publicPem] of Object.entries(cryptoFixtures.PUBLIC_KEYS)) {
+ add(`rejects historical ${slot} in ${name} in production`, async () => {
+ productionEnvironment()
+ process.env[options.envName] = cryptoFixtures.encodings(publicPem)[name]
+ await expectFailure('ERR_JWT_KEY_BANNED', 'banned_identity')
+ })
+ add(`rejects historical ${slot} in ${name} from the public store`, async () => {
+ publish(cryptoFixtures.encodings(publicPem)[name])
+ await expectFailure('ERR_JWT_KEY_BANNED', 'banned_identity')
+ })
+ }
+ }
+ const carriers = {
+ pkcs1: createPublicKey(freshPublic).export({ type: 'pkcs1', format: 'pem' }).toString(),
+ certificate: cert,
+ }
+ for (const [name, pem] of Object.entries(carriers)) {
+ for (const origin of ['environment', 'store'] as const) {
+ add(`accepts RSA ${name} from ${origin}`, async () => {
+ if (origin === 'environment') process.env[options.envName] = pem
+ else publish(pem)
+ assert.equal(fingerprint((await options.loadConfig()).config.jwtPublicKey), fingerprint(freshPublic))
+ })
+ }
+ for (const [slot, publicPem] of Object.entries(cryptoFixtures.PUBLIC_KEYS)) {
+ add(`rejects historical ${slot} as ${name}`, async () => {
+ process.env[options.envName] = name === 'certificate'
+ ? await cryptoFixtures.certificateWithPublic(publicPem)
+ : createPublicKey(publicPem).export({ type: 'pkcs1', format: 'pem' }).toString()
+ await expectFailure('ERR_JWT_KEY_BANNED', 'banned_identity')
+ })
+ add(`rejects historical ${slot} as ${name} from the public store`, async () => {
+ const material = name === 'certificate'
+ ? await cryptoFixtures.certificateWithPublic(publicPem)
+ : createPublicKey(publicPem).export({ type: 'pkcs1', format: 'pem' }).toString()
+ publish(material)
+ await expectFailure('ERR_JWT_KEY_BANNED', 'banned_identity')
+ })
+ }
+ }
+ for (const [name, pem] of Object.entries({
+ pkcs8: signingPem, pkcs1: pair.privateKey.export({ type: 'pkcs1', format: 'pem' }).toString(),
+ })) {
+ add(`accepts legacy ${name} environment input but exports public only`, async () => {
+ process.env[options.envName] = pem
+ const { config } = await options.loadConfig()
+ assert.equal(config.jwtPublicKey === freshPublic, true)
+ assert.equal(config.jwtPublicKey.includes('PRIVATE'), false)
+ })
+ add(`rejects private ${name} in a public store`, async () => {
+ publish(pem)
+ await expectFailure('ERR_JWT_KEY_INVALID', 'wrong_key_role')
+ })
+ }
+ add('accepts RSA-4096 and refuses RSA-1024 verification material', async () => {
+ for (const bits of [4096, 1024]) {
+ const publicPem = generateKeyPairSync('rsa', { modulusLength: bits }).publicKey.export({ type: 'spki', format: 'pem' }).toString()
+ options.resetModules()
+ process.env[options.envName] = publicPem
+ if (bits === 4096) assert.equal(fingerprint((await options.loadConfig()).config.jwtPublicKey), fingerprint(publicPem))
+ else await expectFailure('ERR_JWT_KEY_INVALID', 'undersized_rsa_key')
+ }
+ })
+ for (const origin of ['environment', 'store'] as const) {
+ for (const [name, value] of Object.entries({
+ malformed: 'not a PEM key',
+ ec: generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey.export({ type: 'spki', format: 'pem' }).toString(),
+ publicBundle: `${freshPublic}\n${cryptoFixtures.PUBLIC_KEYS.admin}`,
+ mixedBundle: `${cert}\n${signingPem}`,
+ reverseMixedBundle: `${signingPem}\n${cert}`,
+ certificateBundle: `${cert}\n${cert}`,
+ escapedBundle: `${freshPublic}\n${cert}`.replace(/\n/g, '\\n'),
+ })) {
+ add(`rejects ${name} from ${origin}`, async () => {
+ if (origin === 'environment') process.env[options.envName] = value
+ else publish(value)
+ await expectFailure('ERR_JWT_KEY_INVALID')
+ })
+ }
+ }
+ add('explicit material uses zero store I/O with an unused relative override', async () => {
+ process.env[options.envName] = freshPublic
+ process.env.EVENFIRE_DEV_KEY_STORE = 'unused-relative-store'
+ assert.equal(fingerprint((await options.loadConfig()).config.jwtPublicKey), fingerprint(freshPublic))
+ const result = runRuntime('dist', store, { supplied: freshPublic, consumerOverride: 'unused-relative-store' })
+ assert.equal(result.storeOperations, 0)
+ assert.equal(result.fingerprint, fingerprint(freshPublic))
+ })
+ add('malformed explicit input never falls back to a valid producer store', () => {
+ const rejected = runRuntime('dist', store, { supplied: 'malformed explicit input' })
+ assert.equal(rejected.code, 'ERR_JWT_KEY_INVALID')
+ assert.equal(rejected.storeOperations, 0)
+ const valid = runRuntime('dist', store)
+ assert.equal(valid.signatureVerified, true)
+ assert.equal(valid.storeOperations > 0, true)
+ })
+ add('generated denied identity fails at the actual emitted config boundary', () => {
+ const denied = runRuntime('dist', store, { supplied: freshPublic, denied: fingerprint(freshPublic) })
+ assert.equal(denied.code, 'ERR_JWT_KEY_BANNED')
+ assert.equal(denied.reason, 'banned_identity')
+ assert.equal(denied.storeOperations, 0)
+ assert.equal(runRuntime('dist', store).signatureVerified, true)
+ })
+ add('production dev mode rejects before store access with or without explicit material', () => {
+ productionEnvironment()
+ process.env.CLERUM_DEV_MODE = 'true'
+ for (const supplied of [undefined, freshPublic]) {
+ const result = runRuntime('dist', store, { supplied, productionDev: true })
+ assert.equal(result.productionDevModeRejected, true)
+ assert.equal(result.storeOperations, 0)
+ }
+ })
+ for (const devFlag of [undefined, '', 'false', 'TRUE', '1']) {
+ add(`fails closed when dev flag is ${JSON.stringify(devFlag)}`, async () => {
+ if (devFlag === undefined) delete process.env.CLERUM_DEV_MODE
+ else process.env.CLERUM_DEV_MODE = devFlag
+ await assert.rejects(options.loadConfig, new RegExp(`Missing required environment variable: ${options.envName}`))
+ })
+ }
+ for (const value of [undefined, '']) {
+ add(`fails closed in production with ${JSON.stringify(value)} material`, async () => {
+ productionEnvironment()
+ if (value === undefined) delete process.env[options.envName]
+ else process.env[options.envName] = value
+ await assert.rejects(options.loadConfig, new RegExp(`Missing required environment variable: ${options.envName}`))
+ })
+ }
+ add('rejects relative used store paths', async () => {
+ process.env.EVENFIRE_DEV_KEY_STORE = 'relative-store'
+ await expectFailure('ERR_JWT_DEV_STORE', 'relative_store_path')
+ })
+ add('requires existing producer material without generating it', async () => {
+ await expectFailure('ERR_JWT_DEV_STORE', 'missing_material')
+ })
+ for (const suffix of ['', '/', '/.']) {
+ add(`rejects final-directory symlinks with ${JSON.stringify(suffix)} suffix`, async () => {
+ rmdirSync(store)
+ const target = join(layout!, 'target')
+ mkdirSync(target, { mode: 0o700 })
+ writeFileSync(join(target, `${options.slot}.public.pem`), freshPublic, { mode: 0o644 })
+ symlinkSync(target, store)
+ process.env.EVENFIRE_DEV_KEY_STORE = store + suffix
+ await expectFailure('ERR_JWT_DEV_STORE', 'symbolic_link')
+ })
+ }
+ add('rejects writable public files and broad directory permissions', async () => {
+ publish()
+ chmodSync(publicPath(), 0o666)
+ await expectFailure('ERR_JWT_DEV_STORE', 'insecure_file')
+ chmodSync(publicPath(), 0o644)
+ chmodSync(store, 0o755)
+ options.resetModules()
+ await expectFailure('ERR_JWT_DEV_STORE', 'insecure_directory')
+ })
+ add('rejects public symlinks and non-regular public paths', async () => {
+ const target = join(layout!, 'public-target.pem')
+ writeFileSync(target, freshPublic, { mode: 0o644 })
+ symlinkSync(target, publicPath())
+ await expectFailure('ERR_JWT_DEV_STORE', 'symbolic_link')
+ rmSync(publicPath())
+ mkdirSync(publicPath())
+ options.resetModules()
+ await expectFailure('ERR_JWT_DEV_STORE', 'not_regular_file')
+ })
+
+ add('rejects a regular file where the producer directory must be', async () => {
+ rmdirSync(store)
+ writeFileSync(store, 'directory contract fixture')
+ await expectFailure('ERR_JWT_DEV_STORE', 'invalid_directory')
+ })
+ add('rejects foreign-owned directories after a same-owner positive control', async () => {
+ publish()
+ const getUid = process.geteuid
+ assert.ok(typeof getUid === 'function', 'Ownership cases require POSIX effective-user support')
+ const uid = getUid()
+ assert.equal(fingerprint((await options.loadConfig()).config.jwtPublicKey), fingerprint(freshPublic))
+ options.resetModules()
+ await withEffectiveUid([uid + 1], () => expectFailure('ERR_JWT_DEV_STORE', 'directory_owner_mismatch'))
+ })
+ add('rejects foreign-owned public files after validating the directory', async () => {
+ publish()
+ const getUid = process.geteuid
+ assert.ok(typeof getUid === 'function', 'Ownership cases require POSIX effective-user support')
+ const uid = getUid()
+ await withEffectiveUid([uid, uid + 1], () => expectFailure('ERR_JWT_DEV_STORE', 'file_owner_mismatch'))
+ })
+
+ return { cases, prepare, reset, cleanup, dispose }
+}
diff --git a/scripts/tests/test-dockerfile-local-packages.sh b/scripts/tests/test-dockerfile-local-packages.sh
index e6ac18d75..35eed65c1 100755
--- a/scripts/tests/test-dockerfile-local-packages.sh
+++ b/scripts/tests/test-dockerfile-local-packages.sh
@@ -180,6 +180,31 @@ assert_dockerignore_mutations_rejected() {
rm -rf -- "$fixture_dir"
}
+assert_jwt_policy_runtime_context() {
+ local service="$1" ignore="$REPO_ROOT/$1/Dockerfile.dockerignore"
+ local actual expected
+ expected="$(printf '%s\n' \
+ '!packages/jwt-key-policy/' \
+ '!packages/jwt-key-policy/package.json' \
+ '!packages/jwt-key-policy/index.cjs' \
+ '!packages/jwt-key-policy/index.d.ts' \
+ '!packages/jwt-key-policy/dev-store.cjs' \
+ '!packages/jwt-key-policy/dev-store.d.ts')"
+ actual="$(awk 'index($0, "!packages/jwt-key-policy/") == 1 { print }' "$ignore")"
+ if [[ "$actual" != "$expected" ]]; then
+ fail "$service context must allow only the policy runtime files and types"
+ fi
+ assert_copy_before_first_ci "$service/Dockerfile" jwt-key-policy
+ if ! grep -Fq '/app/packages' "$REPO_ROOT/$service/Dockerfile" || \
+ ! grep -Fq "WORKDIR /app/$service" "$REPO_ROOT/$service/Dockerfile"; then
+ fail "$service must preserve the runtime package/service file-link layout"
+ fi
+}
+
+for service in control-api rpc-proxy external-rest-api; do
+ assert_jwt_policy_runtime_context "$service"
+done
+
# Direct consumers. The first four are Node services; profile-ui and
# control-ui are Next.js consumers and therefore also require materialization.
assert_copy_before_every_ci control-api/Dockerfile \
diff --git a/scripts/tests/test-images-manifest.sh b/scripts/tests/test-images-manifest.sh
index 24830e5dc..01d931271 100755
--- a/scripts/tests/test-images-manifest.sh
+++ b/scripts/tests/test-images-manifest.sh
@@ -1399,6 +1399,51 @@ assert_e2e_only_images_are_unpublished_minikube_fixtures() {
fi
}
+assert_jwt_key_policy_change_rebuilds_all_consumers() {
+ local output rc
+ output="$(node -e '
+ import("'"$REPO_ROOT"'/scripts/release/images-manifest.mjs").then(async m => {
+ const fs = await import("node:fs")
+ const wf = fs.readFileSync("'"$REPO_ROOT"'/.github/workflows/build-publish.yml", "utf8")
+ const sourcePath = "packages/jwt-key-policy/**"
+ const expected = ["control-api", "external-rest-api", "rpc-proxy"]
+ const problems = []
+ const filtersMatch = wf.match(/filters: \|\n([\s\S]*?)\n\n {2}build-push:/)
+ if (!filtersMatch) throw new Error("paths-filter block is missing")
+ const filters = {}
+ let currentKey
+ for (const line of filtersMatch[1].split("\n")) {
+ if (!line.trim()) continue
+ const key = line.match(/^\s*([\w.-]+):\s*$/)
+ const value = line.match(/^\s*-\s*\x27([^\x27]+)\x27\s*$/)
+ if (key) { currentKey = key[1]; filters[currentKey] = [] }
+ else if (value && currentKey) filters[currentKey].push(value[1])
+ else throw new Error("unexpected paths-filter syntax")
+ }
+ const selectedFilters = Object.entries(filters)
+ .filter(([, paths]) => paths.includes(sourcePath)).map(([name]) => name).sort()
+ const selectedImages = m.IMAGES
+ .filter(image => image.source_paths?.includes(sourcePath)).map(image => image.name).sort()
+ if (selectedFilters.join(",") !== expected.join(",")) problems.push("JWT policy filter consumer set differs")
+ if (selectedImages.join(",") !== expected.join(",")) problems.push("JWT policy manifest consumer set differs")
+ for (const name of expected) {
+ const image = m.IMAGES.find(image => image.name === name)
+ if (!image?.rooted) problems.push(`${name} must use the root build context`)
+ const manifest = JSON.parse(fs.readFileSync(`'"$REPO_ROOT"'/${name}/package.json`, "utf8"))
+ if (manifest.dependencies?.["@clerum/jwt-key-policy"] !== "file:../packages/jwt-key-policy") {
+ problems.push(`${name} must declare its production policy dependency`)
+ }
+ }
+ console.log(problems.join("; "))
+ }).catch(error => { console.log(error.message); process.exit(1) })' 2>&1)"
+ rc=$?
+ if [ "$rc" -ne 0 ] || [ -n "$output" ]; then
+ fail "JWT policy consumer routing contract failed: $output"
+ else
+ pass "a JWT-policy-only change rebuilds all three rooted consumers"
+ fi
+}
+
assert_every_defined_case_is_invoked() {
local self defined invoked missing
self="$REPO_ROOT/scripts/tests/test-images-manifest.sh"
@@ -1427,6 +1472,7 @@ assert_display_field_change_rebuilds_both_consumers
assert_llm_provider_attempt_contract_change_rebuilds_consumers
assert_codex_catalog_projection_change_rebuilds_consumers
assert_gfs_interaction_policy_change_rebuilds_consumers
+assert_jwt_key_policy_change_rebuilds_all_consumers
assert_all_three_image_lists_agree
assert_the_verify_set_splits_on_published_not_on_mode
assert_the_default_ghcr_verify_set_omits_only_the_e2e_fixtures
diff --git a/scripts/tests/test-jwt-policy-version-consumers.sh b/scripts/tests/test-jwt-policy-version-consumers.sh
new file mode 100644
index 000000000..4e8a9a081
--- /dev/null
+++ b/scripts/tests/test-jwt-policy-version-consumers.sh
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+source "$REPO_ROOT/scripts/tests/lib/minikube-fixture-repo.sh"
+fixture_root="$(mktemp -d)"
+minikube_test_fixture_repo_init "$REPO_ROOT" "$fixture_root"
+fixture_repo="$MINIKUBE_TEST_PROJECT_DIR"
+cleanup() {
+ local status=$?
+ trap - EXIT
+ minikube_test_assert_host_unchanged || status=1
+ rm -rf -- "$fixture_root"
+ exit "$status"
+}
+trap cleanup EXIT
+
+mkdir -p "$fixture_repo/scripts/precommit" "$fixture_repo/scripts/prettier" \
+ "$fixture_repo/scripts/release" "$fixture_repo/packages/jwt-key-policy"
+cp "$REPO_ROOT/scripts/precommit/bump-staged-package-versions.mjs" "$fixture_repo/scripts/precommit/"
+cp "$REPO_ROOT/scripts/prettier/paths.mjs" "$fixture_repo/scripts/prettier/"
+cp "$REPO_ROOT/scripts/release/"{release-coordinates,update-desktop-release-manifest,validate-release-version-bumps}.mjs \
+ "$fixture_repo/scripts/release/"
+cp "$REPO_ROOT/packages/jwt-key-policy/package.json" "$fixture_repo/packages/jwt-key-policy/"
+for service in control-api rpc-proxy external-rest-api desktop-app; do
+ mkdir -p "$fixture_repo/$service"
+ cp "$REPO_ROOT/$service/package.json" "$fixture_repo/$service/"
+done
+mkdir -p "$fixture_repo/external-rest-api/src"
+cp "$REPO_ROOT/external-rest-api/src/releaseManifest.ts" "$fixture_repo/external-rest-api/src/"
+printf 'module.exports = { revision: 1 }\n' >"$fixture_repo/packages/jwt-key-policy/index.cjs"
+git -C "$fixture_repo" add .
+git -C "$fixture_repo" commit -qm baseline
+baseline="$(git -C "$fixture_repo" rev-parse HEAD)"
+printf 'module.exports = { revision: 2 }\n' >"$fixture_repo/packages/jwt-key-policy/index.cjs"
+git -C "$fixture_repo" add packages/jwt-key-policy/index.cjs
+
+(cd "$fixture_repo" && node scripts/precommit/bump-staged-package-versions.mjs >/dev/null)
+node --input-type=module - "$fixture_repo" "$baseline" <<'NODE'
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+const [root, baseline] = process.argv.slice(2)
+for (const service of ['control-api', 'rpc-proxy', 'external-rest-api']) {
+ const before = JSON.parse(execFileSync('git', ['-C', root, 'show', `${baseline}:${service}/package.json`], { encoding: 'utf8' }))
+ const after = JSON.parse(readFileSync(join(root, service, 'package.json'), 'utf8'))
+ const parts = before.version.split('.').map(Number)
+ parts[2]++
+ assert.equal(after.version, parts.join('.'), `${service} must bump for a shared runtime change`)
+}
+NODE
+git -C "$fixture_repo" commit -qm policy
+(cd "$fixture_repo" && node scripts/release/validate-release-version-bumps.mjs --previous "$baseline" --current HEAD)
+printf 'PASS: a package-only JWT policy change bumps all consumers and validates release counters\n'
diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.sh
index 352d67dff..623c0371e 100755
--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh
+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh
@@ -136,6 +136,26 @@ else
fail "gfs-interaction-policy maps to the wrong consumers: ${gfs_policy_targets:-<none>}"
fi
+jwt_policy_targets="$(
+ PROJECT_DIR="$PWD"
+ PROFILE=fake
+ KC="kubectl --context=fake"
+ FORCE_CLUSTER_SYNC=false
+ FORCE_RESTART=false
+ IMAGE_SOURCE=local
+ IMAGE_TAG=test
+ IMAGES_GENERATED_AT=test
+ log() { :; }
+ source "$INCREMENTAL_SCRIPT"
+ incremental_classify_path packages/jwt-key-policy/index.cjs
+ printf '%s\n' ${INCREMENTAL_TARGETS[@]+"${INCREMENTAL_TARGETS[@]}"}
+)"
+if [[ "$jwt_policy_targets" == $'control-api|control-plane|control-api\nexternal-rest-api|profiles|external-rest-api\nrpc-proxy|rpc-proxy|rpc-proxy' ]]; then
+ pass "a JWT policy change reshadows all three signing and verifying consumers"
+else
+ fail "JWT policy maps to the wrong consumers: ${jwt_policy_targets:-<none>}"
+fi
+
if contains 'incremental_plan' &&
contains 'incremental_build_images' &&
contains 'incremental_restart_targets' &&
@@ -300,6 +320,36 @@ else
fi
rm -rf "${agent_state_dir}"
+# Local credentials are excluded from image contexts and are not deployed
+# inputs. The package policy is a deployed input, including package-only edits.
+jwt_input_dir="$(mktemp -d)"
+mkdir -p "${jwt_input_dir}/control-api/src" "${jwt_input_dir}/rpc-proxy/src" \
+ "${jwt_input_dir}/external-rest-api/src" "${jwt_input_dir}/packages/jwt-key-policy"
+printf 'export const imageInput = 1\n' >"${jwt_input_dir}/control-api/src/index.ts"
+printf 'module.exports = { revision: 1 }\n' >"${jwt_input_dir}/packages/jwt-key-policy/index.cjs"
+jwt_input_fp() { (source "$MARKER_SCRIPT" && pre_gate_marker_cluster_fingerprint "${jwt_input_dir}"); }
+jwt_input_before="$(jwt_input_fp)"
+for service in control-api rpc-proxy external-rest-api; do
+ mkdir -p "${jwt_input_dir}/${service}/.dev-keys/nested"
+ # Non-key bytes prove input ownership; this fixture never signs or parses PEM.
+ printf 'local-only-generated-material\n' >"${jwt_input_dir}/${service}/.dev-keys/rpc.pem"
+ printf 'local-only-temporary\n' >"${jwt_input_dir}/${service}/.dev-keys/nested/stale.tmp"
+done
+jwt_input_after_store="$(jwt_input_fp)"
+printf 'module.exports = { revision: 2 }\n' >"${jwt_input_dir}/packages/jwt-key-policy/index.cjs"
+jwt_input_after_policy="$(jwt_input_fp)"
+if [[ "$jwt_input_before" =~ ^[0-9a-f]{40}$ && "$jwt_input_before" == "$jwt_input_after_store" ]]; then
+ pass "generated dev stores do not invalidate the deployed-source fingerprint"
+else
+ fail "generated dev stores changed the deployed-source fingerprint"
+fi
+if [[ "$jwt_input_after_policy" =~ ^[0-9a-f]{40}$ && "$jwt_input_after_store" != "$jwt_input_after_policy" ]]; then
+ pass "package-only JWT policy changes invalidate the deployed-source fingerprint"
+else
+ fail "deployed-source fingerprint ignores package-only JWT policy changes"
+fi
+rm -rf "${jwt_input_dir}"
+
control_api_migration_line="$(grep -nF 'run-control-api-db-migration.sh' "$SCRIPT" | head -n 1 | cut -d: -f1)"
runtime_roles_line="$(grep -nF 'provision-control-api-runtime-roles.sh' "$SCRIPT" | head -n 1 | cut -d: -f1)"
control_api_probe_restore_line="$(grep -nF ' restore_control_api' "$SCRIPT" | tail -n 1 | cut -d: -f1)"
diff --git a/scripts/tests/test-precommit-release-manifest-ignore.sh b/scripts/tests/test-precommit-release-manifest-ignore.sh
index 15687a2dd..12f7eced1 100755
--- a/scripts/tests/test-precommit-release-manifest-ignore.sh
+++ b/scripts/tests/test-precommit-release-manifest-ignore.sh
@@ -539,4 +539,10 @@ assert_a_self_concealing_manifest_edit_cannot_suppress_the_resync
assert_a_corrupted_committed_package_json_is_refused_not_crashed
assert_a_deletion_only_change_still_bumps_the_counter
+if bash "$REPO_ROOT/scripts/tests/test-jwt-policy-version-consumers.sh"; then
+ pass "shared JWT policy changes bump declared consumers through the normal hook"
+else
+ fail "shared JWT policy consumer version contract failed"
+fi
+
exit $FAIL