Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(security): close CodeQL findings
Alfredo Lopezcc2ca85a154d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex b73f8aa11..962120e38 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.504",+ "version": "0.1.505","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.504",+ "version": "0.1.505","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 9adeb7ea7..d8374c01c 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.504",+ "version": "0.1.505","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 58c5f274a..254f960a6 100644--- a/control-api/src/routes/admin/secrets.ts+++ b/control-api/src/routes/admin/secrets.ts@@ -1,4 +1,5 @@import { Router } from 'express'+import { createHash } from 'node:crypto'import { PROVIDER_CREDENTIAL_SLOTS } from '@clerum/llm-providers'import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '@clerum/workflow-runtime-core'import { config } from '../../config.js'@@ -6,6 +7,7 @@ import { asyncHandler } from '../../http/asyncHandler.js'import { enforceNamespace } from '../../http/namespaceAudit.js'import { isValidDNSSubdomain } from '../../http/rfc1123.js'import { K8sGateway, extractHttpStatus } from '../../k8s.js'+import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { rootLogger } from '../../observability/logger.js'import {OWNER_RECIPE_LABEL_KEY,@@ -36,6 +38,17 @@ import { isLlmHostSecret } from './llmSecretIdentity.js'const logger = rootLogger+const mcpSecretDeleteRateLimit = rateLimitMiddleware({+ bucketType: 'admin_mcp_secret_delete',+ maxPerMinute: 30,+ getBucketKey: req => {+ const session = readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)+ const authorization = req.header('authorization') ?? ''+ const caller = session || authorization || req.ip || 'unknown-admin'+ return `admin-mcp-secret-delete:${createHash('sha256').update(caller).digest('hex')}`+ },+})+// The bedrock credential-slot keys and the vertex service-account key, derived// from the shared provider package (never hardcoded here) so the write-side// gate cannot drift from the UI's client-side gate (spec R4.5.3).@@ -85,14 +98,6 @@ function requestSecretPreconditions(raw: unknown): SecretPreconditions | null {return { uid: body.uid, resourceVersion: body.resourceVersion }}-function hasRequestedSecretIdentity(raw: unknown): boolean {- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false- return (- Object.prototype.hasOwnProperty.call(raw, 'uid') ||- Object.prototype.hasOwnProperty.call(raw, 'resourceVersion')- )-}-function isLegacyMcpSecretDeleteBody(raw: unknown): boolean {return (raw === undefined ||@@ -791,6 +796,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {router.delete('/admin/mcp-secrets/:name',enforceNamespace(config.mcpServersNamespace),+ mcpSecretDeleteRateLimit,asyncHandler(async (req, res) => {if (isPlatformManagedSecretName(req.params.name)) {res.status(400).json({ error: PLATFORM_MANAGED_SECRET_ERROR })@@ -798,10 +804,6 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {}const name = req.params.name.trim()const requestedPrecondition = requestSecretPreconditions(req.body)- if (hasRequestedSecretIdentity(req.body) && !requestedPrecondition) {- res.status(428).json({ error: 'secret_identity_precondition_required' })- return- }let deletePrecondition: SecretPreconditionslet signedCreateProof: McpSecretDeleteProofClaims | null = nullif (requestedPrecondition) {@@ -819,8 +821,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {const sessionToken = readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)const proofCookieName = mcpSecretDeleteProofCookieName(name)const proofCookie = readCookie(req, proofCookieName)- const candidateProof =- sessionToken && proofCookie ? verifyMcpSecretDeleteProof(proofCookie, sessionToken) : null+ const candidateProof = verifyMcpSecretDeleteProof(proofCookie, sessionToken)signedCreateProof =candidateProof?.name === name && candidateProof.namespace === config.mcpServersNamespace? candidateProofdiff --git a/control-api/src/utils/auth/mcpSecretDeleteProof.ts b/control-api/src/utils/auth/mcpSecretDeleteProof.tsindex 16bbf8deb..338202492 100644--- a/control-api/src/utils/auth/mcpSecretDeleteProof.ts+++ b/control-api/src/utils/auth/mcpSecretDeleteProof.ts@@ -1,4 +1,4 @@-import { createHmac, timingSafeEqual } from 'node:crypto'+import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'export const MCP_SECRET_DELETE_PROOF_TTL_SECONDS = 120@@ -15,27 +15,25 @@ export type McpSecretDeleteProofClaims = McpSecretDeleteProofInput & {const CLAIM_KEYS = ['name', 'namespace', 'uid', 'resourceVersion', 'exp'] as constconst COOKIE_NAME_PREFIX = 'mcp_secret_delete_proof_'+const PROOF_VERSION = 'v1'+const PROOF_ALGORITHM = 'aes-256-gcm'+const PROOF_IV_BYTES = 12function isNonEmptyString(value: unknown): value is string {return typeof value === 'string' && value.trim().length > 0}-function encodeClaims(claims: McpSecretDeleteProofClaims): string {- return Buffer.from(JSON.stringify(claims), 'utf8').toString('base64url')+function proofKey(sessionKey: string): Buffer {+ return createHash('sha256')+ .update('evenfire:mcp-secret-delete-proof:v1\0', 'utf8')+ .update(sessionKey, 'utf8')+ .digest()}-function sign(encodedClaims: string, sessionKey: string): Buffer {- return createHmac('sha256', sessionKey).update(encodedClaims, 'utf8').digest()-}--function parseClaims(encodedClaims: string): McpSecretDeleteProofClaims | null {- if (!/^[A-Za-z0-9_-]+$/.test(encodedClaims)) return null-+function parseClaims(plaintext: Buffer): McpSecretDeleteProofClaims | null {let raw: unknowntry {- const decoded = Buffer.from(encodedClaims, 'base64url')- if (decoded.toString('base64url') !== encodedClaims) return null- raw = JSON.parse(decoded.toString('utf8'))+ raw = JSON.parse(plaintext.toString('utf8'))} catch {return null}@@ -64,6 +62,16 @@ function parseClaims(encodedClaims: string): McpSecretDeleteProofClaims | null {}}+function decodeCanonicalBase64Url(value: string): Buffer | null {+ if (!/^[A-Za-z0-9_-]+$/.test(value)) return null+ try {+ const decoded = Buffer.from(value, 'base64url')+ return decoded.toString('base64url') === value ? decoded : null+ } catch {+ return null+ }+}+export function mcpSecretDeleteProofCookieName(name: string): string {return `${COOKIE_NAME_PREFIX}${Buffer.from(name, 'utf8').toString('base64url')}`}@@ -81,8 +89,16 @@ export function createMcpSecretDeleteProof(resourceVersion: input.resourceVersion,exp: Math.floor(Date.now() / 1000) + MCP_SECRET_DELETE_PROOF_TTL_SECONDS,}- const encodedClaims = encodeClaims(claims)- return `${encodedClaims}.${sign(encodedClaims, sessionKey).toString('base64url')}`+ const iv = randomBytes(PROOF_IV_BYTES)+ const cipher = createCipheriv(PROOF_ALGORITHM, proofKey(sessionKey), iv)+ cipher.setAAD(Buffer.from(PROOF_VERSION, 'utf8'))+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(claims), 'utf8'), cipher.final()])+ return [+ PROOF_VERSION,+ iv.toString('base64url'),+ ciphertext.toString('base64url'),+ cipher.getAuthTag().toString('base64url'),+ ].join('.')}export function verifyMcpSecretDeleteProof(@@ -91,34 +107,22 @@ export function verifyMcpSecretDeleteProof(): McpSecretDeleteProofClaims | null {if (!proof || !sessionKey) return null- const [encodedClaims, encodedSignature, ...rest] = proof.split('.')- if (- !encodedClaims ||- !encodedSignature ||- rest.length > 0 ||- !/^[A-Za-z0-9_-]+$/.test(encodedSignature)- ) {- return null- }+ const [version, encodedIv, encodedCiphertext, encodedAuthTag, ...rest] = proof.split('.')+ if (version !== PROOF_VERSION || rest.length > 0) return null+ const iv = decodeCanonicalBase64Url(encodedIv)+ const ciphertext = decodeCanonicalBase64Url(encodedCiphertext)+ const authTag = decodeCanonicalBase64Url(encodedAuthTag)+ if (!iv || iv.length !== PROOF_IV_BYTES || !ciphertext || !authTag) return null- const claims = parseClaims(encodedClaims)- if (!claims) return null-- let suppliedSignature: Buffer+ let claims: McpSecretDeleteProofClaims | nulltry {- suppliedSignature = Buffer.from(encodedSignature, 'base64url')+ const decipher = createDecipheriv(PROOF_ALGORITHM, proofKey(sessionKey), iv)+ decipher.setAAD(Buffer.from(PROOF_VERSION, 'utf8'))+ decipher.setAuthTag(authTag)+ claims = parseClaims(Buffer.concat([decipher.update(ciphertext), decipher.final()]))} catch {return null}- const expectedSignature = sign(encodedClaims, sessionKey)- if (- suppliedSignature.length !== expectedSignature.length ||- suppliedSignature.toString('base64url') !== encodedSignature ||- !timingSafeEqual(suppliedSignature, expectedSignature)- ) {- return null- }-- if (claims.exp <= Math.floor(Date.now() / 1000)) return null+ if (!claims || claims.exp <= Math.floor(Date.now() / 1000)) return nullreturn claims}diff --git a/control-api/test/mockGateway.ts b/control-api/test/mockGateway.tsindex 8313e9748..761243898 100644--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@ -690,7 +690,6 @@ export class MockGateway {throw err}this.assertPrecondition(req.name, existing, precondition)- const effectiveAnnotations = resolveSecretAnnotationsForReplace(existing.annotations, undefined)assertMutablePreservedSecretType(existing.type ?? 'Opaque')const updated = {...existing,diff --git a/control-api/test/routes.mcpSecrets.test.ts b/control-api/test/routes.mcpSecrets.test.tsindex e138503a6..ba1d1409a 100644--- a/control-api/test/routes.mcpSecrets.test.ts+++ b/control-api/test/routes.mcpSecrets.test.ts@@ -3,9 +3,21 @@ import express from 'express'import request from 'supertest'import { rootLogger } from '../src/observability/logger.js'import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'+import { checkAndIncrement } from '../src/services/rateLimiterService.js'import { CONTROL_UI_ADMIN_SESSION_COOKIE } from '../src/utils/auth/sessionCookies.js'import { MockGateway } from './mockGateway.js'+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn(async (_key: string, maxPerMinute: number) => ({+ allowed: true,+ remaining: maxPerMinute - 1,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ backendAvailable: true,+ })),+}))+/** The write shape the admin routes hand to the gateway. */type SecretWrite = {name: string@@ -850,6 +862,26 @@ describe('PUT /admin/mcp-secrets/:name (credential rotation, issue #223)', () =>})describe('DELETE /admin/mcp-secrets/:name (identity and dependency guard)', () => {+ it('rate-limits delete attempts before reading or mutating a Secret', async () => {+ vi.mocked(checkAndIncrement).mockResolvedValueOnce({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 31,+ backendAvailable: true,+ })+ const gateway = createGateway()++ await request(makeApp(gateway))+ .delete('/admin/mcp-secrets/linear-credentials')+ .send({ uid: 'uid-linear-credentials', resourceVersion: '1' })+ .expect(429)++ expect(gateway.getSecret).not.toHaveBeenCalled()+ expect(gateway.deleteSecret).not.toHaveBeenCalled()+ })+it('requires both server-issued identity values when a client supplies either one', async () => {const gateway = createGateway()const app = makeApp(gateway)diff --git a/control-api/test/routes.registryInstall.test.ts b/control-api/test/routes.registryInstall.test.tsindex 9289f654c..1758fea73 100644--- a/control-api/test/routes.registryInstall.test.ts+++ b/control-api/test/routes.registryInstall.test.ts@@ -587,7 +587,7 @@ describe('POST /admin/registry/install', () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })- const { app, gw } = makeInstallApp()+ const { app } = makeInstallApp()const res = await request(app).post('/admin/registry/install')@@ -1215,7 +1215,6 @@ describe('POST /admin/registry/install', () => {const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')const deleteResourceSpy = vi.spyOn(gw, 'deleteResource')const getResourceSpy = vi.spyOn(gw, 'getResource')- const getSecretSpy = vi.spyOn(gw, 'getSecret')const updateResourceSpy = vi.spyOn(gw, 'updateResource')let contextWriteFailed = falsediff --git a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts b/control-api/test/utils.auth.mcpSecretDeleteProof.test.tsindex 6a546bb77..03158d88d 100644--- a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts+++ b/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts@@ -44,10 +44,11 @@ describe('MCP Secret delete proof', () => {try {const proof = createMcpSecretDeleteProof(claims, adminSession)- const [payload, signature] = proof.split('.')+ const tampered = proof.split('.')+ tampered[2] = `${tampered[2]}x`expect(verifyMcpSecretDeleteProof(proof, 'different-admin-session')).toBeNull()- expect(verifyMcpSecretDeleteProof(`${payload}.${signature}x`, adminSession)).toBeNull()+ expect(verifyMcpSecretDeleteProof(tampered.join('.'), adminSession)).toBeNull()nowSpy.mockReturnValue(now + (MCP_SECRET_DELETE_PROOF_TTL_SECONDS + 1) * 1000)expect(verifyMcpSecretDeleteProof(proof, adminSession)).toBeNull()