Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(security): hash rollback proof cookie
Alfredo Lopez619723fac81c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 53fde9aec..73cd7fa1f 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.506",+ "version": "0.1.507","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.506",+ "version": "0.1.507","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 190e8d55c..7e2fe6f5d 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.506",+ "version": "0.1.507","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.tsindex 5de059fbb..bb415c79e 100644--- a/control-api/src/routes/admin/secrets.ts+++ b/control-api/src/routes/admin/secrets.ts@@ -24,7 +24,6 @@ import { toPublicDeleteSecretSummary, toPublicSecretSummary } from '../../servicimport { SecretPreconditions, SecretUpsertRequest } from '../../types.js'import {MCP_SECRET_DELETE_PROOF_TTL_SECONDS,- type McpSecretDeleteProofClaims,createMcpSecretDeleteProof,mcpSecretDeleteProofCookieName,verifyMcpSecretDeleteProof,@@ -816,12 +815,11 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {}const name = req.params.name.trim()const requestedPrecondition = requestSecretPreconditions(req.body)- let deletePrecondition: SecretPreconditions- let signedCreateProof: McpSecretDeleteProofClaims | null = null+ let deletePrecondition: SecretPreconditions | null = requestedPrecondition+ let signedCreateProof: { proof: string; sessionJti: string } | null = nullif (requestedPrecondition) {// Current clients send the identity returned by POST and retain the// established compare-and-delete contract.- deletePrecondition = requestedPrecondition} else {// Only the historical empty DELETE body can use the stateless rollback// proof minted during this browser session's successful create. Any@@ -833,21 +831,11 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {const sessionJti = (req as UiAuthedRequest).adminAuth?.jti ?? ''const proofCookieName = mcpSecretDeleteProofCookieName(name)const proofCookie = readCookie(req, proofCookieName)- const candidateProof = verifyMcpSecretDeleteProof(proofCookie)- signedCreateProof =- candidateProof?.name === name &&- candidateProof.namespace === config.mcpServersNamespace &&- candidateProof.sessionJti === sessionJti- ? candidateProof- : null- if (!signedCreateProof) {+ if (!sessionJti || !proofCookie) {res.status(428).json({ error: 'secret_identity_precondition_required' })return}- deletePrecondition = {- uid: signedCreateProof.uid,- resourceVersion: signedCreateProof.resourceVersion,- }+ signedCreateProof = { proof: proofCookie, sessionJti }}let existing: {metadata?: { labels?: Record<string, string>; uid?: string; resourceVersion?: string }@@ -870,6 +858,28 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })return}+ if (signedCreateProof) {+ const proofVerification = verifyMcpSecretDeleteProof(signedCreateProof.proof, {+ name,+ namespace: config.mcpServersNamespace,+ uid: currentPrecondition.uid!,+ resourceVersion: currentPrecondition.resourceVersion!,+ sessionJti: signedCreateProof.sessionJti,+ })+ if (proofVerification === 'identity-mismatch') {+ res.status(409).json({ error: 'secret_identity_changed', outcome: 'repair_required' })+ return+ }+ if (proofVerification !== 'valid') {+ res.status(428).json({ error: 'secret_identity_precondition_required' })+ return+ }+ deletePrecondition = currentPrecondition+ }+ if (!deletePrecondition) {+ res.status(428).json({ error: 'secret_identity_precondition_required' })+ return+ }if (currentPrecondition.uid !== deletePrecondition.uid ||currentPrecondition.resourceVersion !== deletePrecondition.resourceVersiondiff --git a/control-api/src/utils/auth/mcpSecretDeleteProof.ts b/control-api/src/utils/auth/mcpSecretDeleteProof.tsindex 7ce945ec7..72e0e249e 100644--- a/control-api/src/utils/auth/mcpSecretDeleteProof.ts+++ b/control-api/src/utils/auth/mcpSecretDeleteProof.ts@@ -1,6 +1,4 @@-import jwt from 'jsonwebtoken'-import { createPublicKey } from 'node:crypto'-import { config } from '../../config.js'+import { createHash, timingSafeEqual } from 'node:crypto'export const MCP_SECRET_DELETE_PROOF_TTL_SECONDS = 120@@ -12,88 +10,94 @@ export type McpSecretDeleteProofInput = {sessionJti: string}-export type McpSecretDeleteProofClaims = McpSecretDeleteProofInput & {- exp: number-}+export type McpSecretDeleteProofVerification = 'valid' | 'identity-mismatch' | nullconst COOKIE_NAME_PREFIX = 'mcp_secret_delete_proof_'-const PROOF_AUDIENCE = 'control-api:mcp-secret-delete'-const PROOF_ISSUER = 'control-api'-const PROOF_KIND = 'mcp-secret-delete-proof'-const sessionJwtPublicKey = createPublicKey(config.sessionJwtPrivateKey).export({- type: 'spki',- format: 'pem',-})+const PROOF_VERSION = 'v1'+const DIGEST_RE = /^[a-f0-9]{64}$/function isNonEmptyString(value: unknown): value is string {return typeof value === 'string' && value.trim().length > 0}+function digestParts(...parts: string[]): string {+ const hash = createHash('sha256')+ for (const part of parts) {+ hash.update(String(Buffer.byteLength(part, 'utf8')), 'utf8')+ hash.update(':', 'utf8')+ hash.update(part, 'utf8')+ hash.update('|', 'utf8')+ }+ return hash.digest('hex')+}++function identityDigest(input: Pick<McpSecretDeleteProofInput, 'uid' | 'resourceVersion'>): string {+ return digestParts(PROOF_VERSION, input.uid, input.resourceVersion)+}++function proofDigest(+ input: McpSecretDeleteProofInput,+ expiresAt: number,+ boundIdentityDigest: string+): string {+ return digestParts(+ PROOF_VERSION,+ input.sessionJti,+ input.name,+ input.namespace,+ boundIdentityDigest,+ String(expiresAt)+ )+}++function sameDigest(left: string, right: string): boolean {+ if (!DIGEST_RE.test(left) || !DIGEST_RE.test(right)) return false+ return timingSafeEqual(Buffer.from(left, 'hex'), Buffer.from(right, 'hex'))+}++function hasCompleteInput(input: McpSecretDeleteProofInput): boolean {+ return (+ isNonEmptyString(input.name) &&+ isNonEmptyString(input.namespace) &&+ isNonEmptyString(input.uid) &&+ isNonEmptyString(input.resourceVersion) &&+ isNonEmptyString(input.sessionJti)+ )+}+export function mcpSecretDeleteProofCookieName(name: string): string {return `${COOKIE_NAME_PREFIX}${Buffer.from(name, 'utf8').toString('base64url')}`}export function createMcpSecretDeleteProof(input: McpSecretDeleteProofInput): string {- if (- !isNonEmptyString(input.name) ||- !isNonEmptyString(input.namespace) ||- !isNonEmptyString(input.uid) ||- !isNonEmptyString(input.resourceVersion) ||- !isNonEmptyString(input.sessionJti)- ) {+ if (!hasCompleteInput(input)) {throw new Error('A complete admin session and Secret identity are required for rollback proof')}-- return jwt.sign(- {- tokenKind: PROOF_KIND,- name: input.name,- namespace: input.namespace,- uid: input.uid,- resourceVersion: input.resourceVersion,- sessionJti: input.sessionJti,- },- config.sessionJwtPrivateKey,- {- algorithm: 'RS256',- audience: PROOF_AUDIENCE,- issuer: PROOF_ISSUER,- expiresIn: MCP_SECRET_DELETE_PROOF_TTL_SECONDS,- }+ const expiresAt = Math.floor(Date.now() / 1000) + MCP_SECRET_DELETE_PROOF_TTL_SECONDS+ const boundIdentityDigest = identityDigest(input)+ return [expiresAt, boundIdentityDigest, proofDigest(input, expiresAt, boundIdentityDigest)].join(+ '.')}-export function verifyMcpSecretDeleteProof(proof: string): McpSecretDeleteProofClaims | null {- if (!proof) return null-- try {- const payload = jwt.verify(proof, sessionJwtPublicKey, {- algorithms: ['RS256'],- audience: PROOF_AUDIENCE,- issuer: PROOF_ISSUER,- })- if (- typeof payload === 'string' ||- payload.tokenKind !== PROOF_KIND ||- !isNonEmptyString(payload.name) ||- !isNonEmptyString(payload.namespace) ||- !isNonEmptyString(payload.uid) ||- !isNonEmptyString(payload.resourceVersion) ||- !isNonEmptyString(payload.sessionJti) ||- typeof payload.exp !== 'number' ||- !Number.isSafeInteger(payload.exp)- ) {- return null- }- return {- name: payload.name,- namespace: payload.namespace,- uid: payload.uid,- resourceVersion: payload.resourceVersion,- sessionJti: payload.sessionJti,- exp: payload.exp,- }- } catch {+export function verifyMcpSecretDeleteProof(+ proof: string,+ input: McpSecretDeleteProofInput+): McpSecretDeleteProofVerification {+ if (!proof || !hasCompleteInput(input)) return null+ const [encodedExpiry, boundIdentityDigest, suppliedProofDigest, ...rest] = proof.split('.')+ if (+ rest.length > 0 ||+ !/^\d+$/.test(encodedExpiry) ||+ !DIGEST_RE.test(boundIdentityDigest) ||+ !DIGEST_RE.test(suppliedProofDigest)+ ) {return null}+ const expiresAt = Number(encodedExpiry)+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Math.floor(Date.now() / 1000)) return null+ if (!sameDigest(boundIdentityDigest, identityDigest(input))) return 'identity-mismatch'+ return sameDigest(suppliedProofDigest, proofDigest(input, expiresAt, boundIdentityDigest))+ ? 'valid'+ : null}diff --git a/control-api/test/routes.mcpSecrets.test.ts b/control-api/test/routes.mcpSecrets.test.tsindex a6c752bd8..388ecd3e3 100644--- a/control-api/test/routes.mcpSecrets.test.ts+++ b/control-api/test/routes.mcpSecrets.test.ts@@ -1109,7 +1109,7 @@ describe('DELETE /admin/mcp-secrets/:name (identity and dependency guard)', () =await agent.delete('/admin/mcp-secrets/linear-credentials').expect(428)- expect(gateway.getSecret).not.toHaveBeenCalled()+ expect(gateway.getSecret).toHaveBeenCalledOnce()expect(gateway.deleteSecret).not.toHaveBeenCalled()})diff --git a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts b/control-api/test/utils.auth.mcpSecretDeleteProof.test.tsindex b509c9285..08febd754 100644--- a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts+++ b/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts@@ -15,25 +15,20 @@ const claims = {}describe('MCP Secret delete proof', () => {- it('binds exactly the Secret identity claims to the admin session', () => {+ it('binds exactly the Secret identity to the admin session', () => {const now = 1_700_000_000_000const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now)try {const proof = createMcpSecretDeleteProof(claims)- expect(verifyMcpSecretDeleteProof(proof)).toEqual({- ...claims,- exp: Math.floor(now / 1000) + MCP_SECRET_DELETE_PROOF_TTL_SECONDS,- })- expect(Object.keys(verifyMcpSecretDeleteProof(proof) ?? {}).sort()).toEqual([- 'exp',- 'name',- 'namespace',- 'resourceVersion',- 'sessionJti',- 'uid',- ])+ expect(verifyMcpSecretDeleteProof(proof, claims)).toBe('valid')+ expect(verifyMcpSecretDeleteProof(proof, { ...claims, uid: 'uid-replacement' })).toBe(+ 'identity-mismatch'+ )+ expect(+ verifyMcpSecretDeleteProof(proof, { ...claims, sessionJti: 'other-session-jti' })+ ).toBeNull()} finally {nowSpy.mockRestore()}@@ -48,10 +43,10 @@ describe('MCP Secret delete proof', () => {const tampered = proof.split('.')tampered[2] = `${tampered[2]}x`- expect(verifyMcpSecretDeleteProof(tampered.join('.'))).toBeNull()+ expect(verifyMcpSecretDeleteProof(tampered.join('.'), claims)).toBeNull()nowSpy.mockReturnValue(now + (MCP_SECRET_DELETE_PROOF_TTL_SECONDS + 1) * 1000)- expect(verifyMcpSecretDeleteProof(proof)).toBeNull()+ expect(verifyMcpSecretDeleteProof(proof, claims)).toBeNull()} finally {nowSpy.mockRestore()}