Skip to content

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

TypeScript

fix(security): satisfy CodeQL guards

Alfredo Lopez20ce44727efe
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 962120e38..53fde9aec 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.505",
+ "version": "0.1.506",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.505",
+ "version": "0.1.506",
"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.json
index d8374c01c..190e8d55c 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.505",
+ "version": "0.1.506",
"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.ts
index 254f960a6..5de059fbb 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 { ipKeyGenerator, rateLimit } from 'express-rate-limit'
import { createHash } from 'node:crypto'
import { PROVIDER_CREDENTIAL_SLOTS } from '@clerum/llm-providers'
import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '@clerum/workflow-runtime-core'
@@ -7,6 +8,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 type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import { rootLogger } from '../../observability/logger.js'
import {
@@ -28,7 +30,6 @@ import {
verifyMcpSecretDeleteProof,
} from '../../utils/auth/mcpSecretDeleteProof.js'
import {
- CONTROL_UI_ADMIN_SESSION_COOKIE,
clearHttpOnlySessionCookie,
readCookie,
setHttpOnlySessionCookie,
@@ -38,13 +39,25 @@ import { isLlmHostSecret } from './llmSecretIdentity.js'
const logger = rootLogger
+const mcpSecretDeleteEdgeRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: 60,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ keyGenerator: req => {
+ const sessionJti = (req as UiAuthedRequest).adminAuth?.jti
+ return sessionJti
+ ? `admin-session:${createHash('sha256').update(sessionJti).digest('hex')}`
+ : ipKeyGenerator(req.ip ?? '127.0.0.1')
+ },
+})
+
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'
+ const sessionJti = (req as UiAuthedRequest).adminAuth?.jti
+ const caller = sessionJti || req.ip || 'unknown-admin'
return `admin-mcp-secret-delete:${createHash('sha256').update(caller).digest('hex')}`
},
})
@@ -576,21 +589,19 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })
return
}
- const sessionToken = readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)
- if (sessionToken) {
+ const sessionJti = (req as UiAuthedRequest).adminAuth?.jti
+ if (sessionJti) {
setHttpOnlySessionCookie(
req,
res,
mcpSecretDeleteProofCookieName(secretReq.name),
- createMcpSecretDeleteProof(
- {
- name: secretReq.name,
- namespace: targetNs,
- uid: completeIdentity.uid,
- resourceVersion: completeIdentity.resourceVersion,
- },
- sessionToken
- ),
+ createMcpSecretDeleteProof({
+ name: secretReq.name,
+ namespace: targetNs,
+ uid: completeIdentity.uid,
+ resourceVersion: completeIdentity.resourceVersion,
+ sessionJti,
+ }),
MCP_SECRET_DELETE_PROOF_TTL_SECONDS
)
}
@@ -796,6 +807,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
router.delete(
'/admin/mcp-secrets/:name',
enforceNamespace(config.mcpServersNamespace),
+ mcpSecretDeleteEdgeRateLimit,
mcpSecretDeleteRateLimit,
asyncHandler(async (req, res) => {
if (isPlatformManagedSecretName(req.params.name)) {
@@ -818,12 +830,14 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
res.status(428).json({ error: 'secret_identity_precondition_required' })
return
}
- const sessionToken = readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)
+ const sessionJti = (req as UiAuthedRequest).adminAuth?.jti ?? ''
const proofCookieName = mcpSecretDeleteProofCookieName(name)
const proofCookie = readCookie(req, proofCookieName)
- const candidateProof = verifyMcpSecretDeleteProof(proofCookie, sessionToken)
+ const candidateProof = verifyMcpSecretDeleteProof(proofCookie)
signedCreateProof =
- candidateProof?.name === name && candidateProof.namespace === config.mcpServersNamespace
+ candidateProof?.name === name &&
+ candidateProof.namespace === config.mcpServersNamespace &&
+ candidateProof.sessionJti === sessionJti
? candidateProof
: null
if (!signedCreateProof) {
diff --git a/control-api/src/utils/auth/mcpSecretDeleteProof.ts b/control-api/src/utils/auth/mcpSecretDeleteProof.ts
index 338202492..7ce945ec7 100644
--- a/control-api/src/utils/auth/mcpSecretDeleteProof.ts
+++ b/control-api/src/utils/auth/mcpSecretDeleteProof.ts
@@ -1,4 +1,6 @@
-import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
+import jwt from 'jsonwebtoken'
+import { createPublicKey } from 'node:crypto'
+import { config } from '../../config.js'
export const MCP_SECRET_DELETE_PROOF_TTL_SECONDS = 120
@@ -7,122 +9,91 @@ export type McpSecretDeleteProofInput = {
namespace: string
uid: string
resourceVersion: string
+ sessionJti: string
}
export type McpSecretDeleteProofClaims = McpSecretDeleteProofInput & {
exp: number
}
-const CLAIM_KEYS = ['name', 'namespace', 'uid', 'resourceVersion', 'exp'] as const
const COOKIE_NAME_PREFIX = 'mcp_secret_delete_proof_'
-const PROOF_VERSION = 'v1'
-const PROOF_ALGORITHM = 'aes-256-gcm'
-const PROOF_IV_BYTES = 12
+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',
+})
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0
}
-function proofKey(sessionKey: string): Buffer {
- return createHash('sha256')
- .update('evenfire:mcp-secret-delete-proof:v1\0', 'utf8')
- .update(sessionKey, 'utf8')
- .digest()
+export function mcpSecretDeleteProofCookieName(name: string): string {
+ return `${COOKIE_NAME_PREFIX}${Buffer.from(name, 'utf8').toString('base64url')}`
}
-function parseClaims(plaintext: Buffer): McpSecretDeleteProofClaims | null {
- let raw: unknown
- try {
- raw = JSON.parse(plaintext.toString('utf8'))
- } catch {
- return null
- }
-
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
- const claims = raw as Record<string, unknown>
+export function createMcpSecretDeleteProof(input: McpSecretDeleteProofInput): string {
if (
- Object.keys(claims).length !== CLAIM_KEYS.length ||
- !CLAIM_KEYS.every(key => Object.prototype.hasOwnProperty.call(claims, key)) ||
- !isNonEmptyString(claims.name) ||
- !isNonEmptyString(claims.namespace) ||
- !isNonEmptyString(claims.uid) ||
- !isNonEmptyString(claims.resourceVersion) ||
- typeof claims.exp !== 'number' ||
- !Number.isSafeInteger(claims.exp)
+ !isNonEmptyString(input.name) ||
+ !isNonEmptyString(input.namespace) ||
+ !isNonEmptyString(input.uid) ||
+ !isNonEmptyString(input.resourceVersion) ||
+ !isNonEmptyString(input.sessionJti)
) {
- return null
- }
-
- return {
- name: claims.name,
- namespace: claims.namespace,
- uid: claims.uid,
- resourceVersion: claims.resourceVersion,
- exp: claims.exp,
- }
-}
-
-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
+ throw new Error('A complete admin session and Secret identity are required for rollback proof')
}
-}
-
-export function mcpSecretDeleteProofCookieName(name: string): string {
- return `${COOKIE_NAME_PREFIX}${Buffer.from(name, 'utf8').toString('base64url')}`
-}
-export function createMcpSecretDeleteProof(
- input: McpSecretDeleteProofInput,
- sessionKey: string
-): string {
- if (!sessionKey) throw new Error('Admin session is required to issue an MCP Secret delete proof')
-
- const claims: McpSecretDeleteProofClaims = {
- name: input.name,
- namespace: input.namespace,
- uid: input.uid,
- resourceVersion: input.resourceVersion,
- exp: Math.floor(Date.now() / 1000) + MCP_SECRET_DELETE_PROOF_TTL_SECONDS,
- }
- 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('.')
+ 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,
+ }
+ )
}
-export function verifyMcpSecretDeleteProof(
- proof: string,
- sessionKey: string
-): McpSecretDeleteProofClaims | null {
- if (!proof || !sessionKey) 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
+export function verifyMcpSecretDeleteProof(proof: string): McpSecretDeleteProofClaims | null {
+ if (!proof) return null
- let claims: McpSecretDeleteProofClaims | null
try {
- 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()]))
+ 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 {
return null
}
- if (!claims || claims.exp <= Math.floor(Date.now() / 1000)) return null
- return claims
}
diff --git a/control-api/test/routes.mcpSecrets.test.ts b/control-api/test/routes.mcpSecrets.test.ts
index ba1d1409a..a6c752bd8 100644
--- a/control-api/test/routes.mcpSecrets.test.ts
+++ b/control-api/test/routes.mcpSecrets.test.ts
@@ -7,6 +7,8 @@ import { checkAndIncrement } from '../src/services/rateLimiterService.js'
import { CONTROL_UI_ADMIN_SESSION_COOKIE } from '../src/utils/auth/sessionCookies.js'
import { MockGateway } from './mockGateway.js'
+const TEST_ADMIN_SESSION_JTI = 'test-admin-session-jti'
+
vi.mock('../src/services/rateLimiterService.js', () => ({
checkAndIncrement: vi.fn(async (_key: string, maxPerMinute: number) => ({
allowed: true,
@@ -108,6 +110,12 @@ function k8sError(statusCode: number, message: string): Error & { statusCode: nu
function makeApp(gateway: ReturnType<typeof createGateway>) {
const app = express()
app.use(express.json())
+ app.use((req, _res, next) => {
+ ;(req as express.Request & { adminAuth?: { jti: string } }).adminAuth = {
+ jti: TEST_ADMIN_SESSION_JTI,
+ }
+ next()
+ })
app.use(createAdminSecretsRouter(gateway as never))
// Error handler so gateway errors return 500 instead of crashing
app.use(
diff --git a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts b/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts
index 03158d88d..b509c9285 100644
--- a/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts
+++ b/control-api/test/utils.auth.mcpSecretDeleteProof.test.ts
@@ -6,12 +6,12 @@ import {
verifyMcpSecretDeleteProof,
} from '../src/utils/auth/mcpSecretDeleteProof.js'
-const adminSession = 'test-admin-session'
const claims = {
name: 'linear-credentials',
namespace: 'mcp-server',
uid: 'uid-linear-credentials',
resourceVersion: '1',
+ sessionJti: 'test-admin-session-jti',
}
describe('MCP Secret delete proof', () => {
@@ -20,17 +20,18 @@ describe('MCP Secret delete proof', () => {
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now)
try {
- const proof = createMcpSecretDeleteProof(claims, adminSession)
+ const proof = createMcpSecretDeleteProof(claims)
- expect(verifyMcpSecretDeleteProof(proof, adminSession)).toEqual({
+ expect(verifyMcpSecretDeleteProof(proof)).toEqual({
...claims,
exp: Math.floor(now / 1000) + MCP_SECRET_DELETE_PROOF_TTL_SECONDS,
})
- expect(Object.keys(verifyMcpSecretDeleteProof(proof, adminSession) ?? {}).sort()).toEqual([
+ expect(Object.keys(verifyMcpSecretDeleteProof(proof) ?? {}).sort()).toEqual([
'exp',
'name',
'namespace',
'resourceVersion',
+ 'sessionJti',
'uid',
])
} finally {
@@ -38,20 +39,19 @@ describe('MCP Secret delete proof', () => {
}
})
- it('rejects a proof when its session binding, signature, or expiry is invalid', () => {
+ it('rejects a proof when its signature or expiry is invalid', () => {
const now = 1_700_000_000_000
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now)
try {
- const proof = createMcpSecretDeleteProof(claims, adminSession)
+ const proof = createMcpSecretDeleteProof(claims)
const tampered = proof.split('.')
tampered[2] = `${tampered[2]}x`
- expect(verifyMcpSecretDeleteProof(proof, 'different-admin-session')).toBeNull()
- expect(verifyMcpSecretDeleteProof(tampered.join('.'), adminSession)).toBeNull()
+ expect(verifyMcpSecretDeleteProof(tampered.join('.'))).toBeNull()
nowSpy.mockReturnValue(now + (MCP_SECRET_DELETE_PROOF_TTL_SECONDS + 1) * 1000)
- expect(verifyMcpSecretDeleteProof(proof, adminSession)).toBeNull()
+ expect(verifyMcpSecretDeleteProof(proof)).toBeNull()
} finally {
nowSpy.mockRestore()
}