Skip to content

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

TypeScript

fix(control-api): forward K8s 4xx status without leaking raw error message

Diego Zacarias2cbaa7de8cef
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d052d9440..9bb4e2174 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.433",
+ "version": "0.1.434",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.433",
+ "version": "0.1.434",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index e2b561351..87c5b1e45 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.433",
+ "version": "0.1.434",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/app.ts b/control-api/src/app.ts
index c45a2c156..0ebff8744 100644
--- a/control-api/src/app.ts
+++ b/control-api/src/app.ts
@@ -1,6 +1,7 @@
-import express, { NextFunction, Request, Response } from 'express'
+import express from 'express'
import { config } from './config.js'
import type { DbClient } from './db.js'
+import { clerumErrorHandler } from './http/errorHandler.js'
import { K8sGateway } from './k8s.js'
import { type UiAuthedRequest, requireAuthForControlUI } from './middleware/controlUIAuth.js'
import { correlationIdMiddleware } from './middleware/correlationId.js'
@@ -9,7 +10,6 @@ import {
createTracingInFlightLimiter,
getTracingMaxInFlight,
} from './middleware/tracingSubmitterAuth.js'
-import { rootLogger } from './observability/logger.js'
import { createAdminAuthRouter } from './routes/admin/auth.js'
import { createAdminRouter } from './routes/admin/index.js'
import { createWorkflowsAdminRouter } from './routes/admin/workflows/index.js'
@@ -34,7 +34,6 @@ import { createMetricsRouter } from './routes/metrics.js'
import { createRecipeOauthRouter } from './routes/recipeOauth.js'
import { createRegistryRouter } from './routes/registry.js'
import { createRpcAccessRouter } from './routes/rpc-access/index.js'
-import { memberRegistrationErrorResponse } from './services/memberRegistrationErrors.js'
import { setAdministrativeOperationService } from './services/resourceService.js'
import { HccAdministrativeOutcomeBindingResolver } from './services/tracing/adminOperationBindingResolver.js'
import { runWithAdministrativeRequestContext } from './services/tracing/adminOperationContext.js'
@@ -61,14 +60,6 @@ import {
const TRACING_INTERNAL_PATH_PREFIX = '/api/v1/internal/tracing/'
const RPC_HOST_ACCESS_PATH = /^\/api\/v1\/rpc\/access\/users\/[^/]+\/mcp-hosts\/[^/]+\/?$/i
-// Only errors we construct with these codes are ever forwarded verbatim by the
-// global handler (see below). Keeps the blast radius tight: every other
-// status-less or non-allowlisted error still collapses to a 500.
-const FORWARDABLE_INTEGRATION_CODES = new Set([
- 'registry_unavailable',
- 'registry_integration_error',
-])
-
export function createApp(gateway: K8sGateway) {
const traceIngestDb: DbClient = meterTracingDbClient({
query: (text, params) => getTracingPools().traceIngestPool.query(text, params),
@@ -247,108 +238,7 @@ export function createApp(gateway: K8sGateway) {
res.status(404).json({ error: 'Not Found' })
})
- app.use((err: unknown, req: Request, res: Response, _next: NextFunction) => {
- // Use the request-scoped correlation id if middleware ran, otherwise
- // synthesize a short tag for legacy paths.
- const correlationId = req.correlationId ?? Math.random().toString(36).slice(2, 10)
- const log = req.log ?? rootLogger
-
- // Typed member-registration failures map to 503 (spec §8.6) — scoped
- // instanceof check; the generic 5xx-collapse below stays intact.
- const memberRegistration = memberRegistrationErrorResponse(err)
- if (memberRegistration) {
- log.warn(
- {
- event: memberRegistration.error,
- correlationId,
- err: err instanceof Error ? err.message : String(err),
- },
- 'member registration unavailable'
- )
- res.status(memberRegistration.status).json({ error: memberRegistration.error, correlationId })
- return
- }
-
- // Errors thrown by service-layer code may carry a `.status` field to
- // signal that the upstream response (e.g., registry 404) should be
- // forwarded to the API client rather than collapsed into a 500. Honor
- // 4xx values; 5xx still surface as Internal Server Error so backend
- // failures don't leak through as caller-visible errors.
- const errStatus =
- err instanceof Error && typeof (err as Error & { status?: unknown }).status === 'number'
- ? (err as Error & { status: number }).status
- : undefined
- const isClientError = errStatus !== undefined && errStatus >= 400 && errStatus < 500
-
- if (isClientError) {
- log.warn(
- {
- event: 'forwarded_client_error',
- correlationId,
- status: errStatus,
- err: err instanceof Error ? err.message : String(err),
- },
- 'forwarded client error from upstream'
- )
- res.status(errStatus as number).json({
- error: err instanceof Error ? err.message : 'Bad Request',
- correlationId,
- })
- return
- }
-
- // Allowlisted registry-integration errors carry a safe code + message we set
- // ourselves (RegistryUnavailableError → 503; the 401 remap → 502). Forward
- // them so the marketplace shows a clear message instead of a raw 500. The
- // message is safe because only our own constructors set these codes.
- const integrationCode = (err as { code?: unknown }).code
- const integrationStatus = (err as { status?: unknown }).status
- if (
- typeof integrationStatus === 'number' &&
- (integrationStatus === 502 || integrationStatus === 503) &&
- typeof integrationCode === 'string' &&
- FORWARDABLE_INTEGRATION_CODES.has(integrationCode)
- ) {
- log.warn(
- {
- event: 'forwarded_registry_integration_error',
- correlationId,
- status: integrationStatus,
- code: integrationCode,
- err: err instanceof Error ? err.message : String(err),
- },
- 'forwarded registry integration error'
- )
- res.status(integrationStatus).json({
- error: integrationCode,
- message: err instanceof Error ? err.message : 'Registry integration error',
- correlationId,
- })
- return
- }
-
- log.error(
- {
- event: 'unhandled_error',
- correlationId,
- err: err instanceof Error ? err.message : String(err),
- stack: err instanceof Error ? err.stack : undefined,
- },
- 'unhandled error'
- )
- if (process.env.NODE_ENV !== 'production') {
- res.status(500).json({
- error: 'Internal Server Error',
- message: err instanceof Error ? err.message : 'Unknown error',
- correlationId,
- })
- } else {
- res.status(500).json({
- error: 'Internal Server Error',
- correlationId,
- })
- }
- })
+ app.use(clerumErrorHandler)
return app
}
diff --git a/control-api/src/http/errorHandler.ts b/control-api/src/http/errorHandler.ts
new file mode 100644
index 000000000..09716564a
--- /dev/null
+++ b/control-api/src/http/errorHandler.ts
@@ -0,0 +1,210 @@
+import type { NextFunction, Request, Response } from 'express'
+import { ApiException } from '@kubernetes/client-node'
+import { STATUS_CODES } from 'node:http'
+import { rootLogger } from '../observability/logger.js'
+import { memberRegistrationErrorResponse } from '../services/memberRegistrationErrors.js'
+
+// Only errors we construct with these codes are ever forwarded verbatim by the
+// global handler. Keeps the blast radius tight: every other status-less or
+// non-allowlisted error still collapses to a 500.
+export const FORWARDABLE_INTEGRATION_CODES = new Set([
+ 'registry_unavailable',
+ 'registry_integration_error',
+])
+
+/**
+ * Extract an HTTP status from an error the same way `extractK8sStatus`
+ * (resourceServiceHelpers) does, so a raw @kubernetes/client-node error — which
+ * carries its status on `.code` / `.statusCode` / `.response.*`, NOT a top-level
+ * `.status` — is forwarded with its real 4xx instead of collapsing to a 500.
+ *
+ * Precedence mirrors extractK8sStatus, with `.status` FIRST so the legacy
+ * service-layer path (errors that set `.status` deliberately) is preserved.
+ */
+function extractErrorStatus(err: unknown): number | undefined {
+ if (!err || typeof err !== 'object') return undefined
+ const maybe = err as {
+ status?: unknown
+ statusCode?: unknown
+ code?: unknown
+ response?: { statusCode?: unknown; status?: unknown }
+ }
+ if (typeof maybe.status === 'number') return maybe.status
+ if (typeof maybe.statusCode === 'number') return maybe.statusCode
+ if (typeof maybe.code === 'number') return maybe.code
+ if (maybe.response && typeof maybe.response.statusCode === 'number') {
+ return maybe.response.statusCode
+ }
+ if (maybe.response && typeof maybe.response.status === 'number') return maybe.response.status
+ return undefined
+}
+
+/**
+ * True when `err` is a raw @kubernetes/client-node ApiException, or an object
+ * carrying its leaking shape. ApiException stores the metav1.Status on `.body`
+ * and EVERY apiserver response header (Audit-Id, x-kubernetes-pf-*) on
+ * `.headers`, and its `.message` is built as
+ * `"HTTP-Code: …\nMessage: …\nBody: <JSON status>\nHeaders: <JSON headers>"`.
+ * Forwarding that message verbatim to the client leaks internals — hence the
+ * shape fallback, so a copy created against a duplicated module instance (where
+ * `instanceof` would miss) is still caught.
+ */
+function isK8sApiException(err: unknown): boolean {
+ if (err instanceof ApiException) return true
+ return (
+ err instanceof Error &&
+ 'body' in err &&
+ 'headers' in err &&
+ typeof (err as { headers?: unknown }).headers === 'object' &&
+ (err as { headers?: unknown }).headers !== null
+ )
+}
+
+/**
+ * Client-safe message for a forwarded 4xx.
+ *
+ * A raw K8s ApiException `.message` embeds the full metav1.Status body AND every
+ * apiserver response header — never forward it. Collapse K8s errors to the
+ * standard status text, surfacing at most the metav1.Status `body.message`
+ * (the apiserver's human explanation, e.g. `... already exists`), which is the
+ * same class of info the service layer already returns and carries no headers.
+ * Non-K8s Errors keep their own (author-controlled) message; non-Errors get
+ * 'Bad Request'.
+ */
+function clientErrorMessage(err: unknown, status: number): string {
+ const fallback = STATUS_CODES[status] ?? 'Bad Request'
+ if (isK8sApiException(err)) {
+ const body = (err as { body?: unknown }).body
+ if (body && typeof body === 'object') {
+ const bodyMessage = (body as { message?: unknown }).message
+ if (typeof bodyMessage === 'string' && bodyMessage.length > 0) return bodyMessage
+ } else if (typeof body === 'string' && body.length > 0) {
+ try {
+ const parsed = JSON.parse(body) as { message?: unknown }
+ if (typeof parsed.message === 'string' && parsed.message.length > 0) return parsed.message
+ } catch {
+ // body is not JSON — never forward the raw string, fall through to the
+ // generic status text.
+ }
+ }
+ return fallback
+ }
+ return err instanceof Error ? err.message : 'Bad Request'
+}
+
+/**
+ * Global Express error handler for control-api.
+ *
+ * Exported (rather than an inline closure in createApp) so it can be unit-tested
+ * in isolation. Behavior:
+ * - typed member-registration failures → their mapped status (spec §8.6);
+ * - any error carrying a 4xx status (via `.status` / `.statusCode` / `.code` /
+ * `.response.*`) is FORWARDED with a sanitized message — this is FIX-B: raw
+ * K8s 400/403/404/409/422 no longer collapse to 500;
+ * - allowlisted registry-integration 502/503 codes are forwarded verbatim;
+ * - everything else (5xx, status-less, non-Error throws) → 500, unchanged.
+ */
+export function clerumErrorHandler(
+ err: unknown,
+ req: Request,
+ res: Response,
+ _next: NextFunction
+): void {
+ // Use the request-scoped correlation id if middleware ran, otherwise
+ // synthesize a short tag for legacy paths.
+ const correlationId = req.correlationId ?? Math.random().toString(36).slice(2, 10)
+ const log = req.log ?? rootLogger
+
+ // Typed member-registration failures map to 503 (spec §8.6) — scoped
+ // instanceof check; the generic 5xx-collapse below stays intact.
+ const memberRegistration = memberRegistrationErrorResponse(err)
+ if (memberRegistration) {
+ log.warn(
+ {
+ event: memberRegistration.error,
+ correlationId,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'member registration unavailable'
+ )
+ res.status(memberRegistration.status).json({ error: memberRegistration.error, correlationId })
+ return
+ }
+
+ // Errors thrown by service-layer code (and raw K8s client errors) carry a
+ // status that signals the upstream response should be forwarded to the API
+ // client rather than collapsed into a 500. Honor 4xx values; 5xx still surface
+ // as Internal Server Error so backend failures don't leak through as
+ // caller-visible errors.
+ const errStatus = extractErrorStatus(err)
+ const isClientError = errStatus !== undefined && errStatus >= 400 && errStatus < 500
+
+ if (isClientError) {
+ log.warn(
+ {
+ event: 'forwarded_client_error',
+ correlationId,
+ status: errStatus,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'forwarded client error from upstream'
+ )
+ res.status(errStatus as number).json({
+ error: clientErrorMessage(err, errStatus as number),
+ correlationId,
+ })
+ return
+ }
+
+ // Allowlisted registry-integration errors carry a safe code + message we set
+ // ourselves (RegistryUnavailableError → 503; the 401 remap → 502). Forward
+ // them so the marketplace shows a clear message instead of a raw 500. The
+ // message is safe because only our own constructors set these codes.
+ const integrationCode = (err as { code?: unknown }).code
+ const integrationStatus = (err as { status?: unknown }).status
+ if (
+ typeof integrationStatus === 'number' &&
+ (integrationStatus === 502 || integrationStatus === 503) &&
+ typeof integrationCode === 'string' &&
+ FORWARDABLE_INTEGRATION_CODES.has(integrationCode)
+ ) {
+ log.warn(
+ {
+ event: 'forwarded_registry_integration_error',
+ correlationId,
+ status: integrationStatus,
+ code: integrationCode,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'forwarded registry integration error'
+ )
+ res.status(integrationStatus).json({
+ error: integrationCode,
+ message: err instanceof Error ? err.message : 'Registry integration error',
+ correlationId,
+ })
+ return
+ }
+
+ log.error(
+ {
+ event: 'unhandled_error',
+ correlationId,
+ err: err instanceof Error ? err.message : String(err),
+ stack: err instanceof Error ? err.stack : undefined,
+ },
+ 'unhandled error'
+ )
+ if (process.env.NODE_ENV !== 'production') {
+ res.status(500).json({
+ error: 'Internal Server Error',
+ message: err instanceof Error ? err.message : 'Unknown error',
+ correlationId,
+ })
+ } else {
+ res.status(500).json({
+ error: 'Internal Server Error',
+ correlationId,
+ })
+ }
+}
diff --git a/control-api/test/http.errorHandler.k8sStatus.test.ts b/control-api/test/http.errorHandler.k8sStatus.test.ts
new file mode 100644
index 000000000..7d2943ccc
--- /dev/null
+++ b/control-api/test/http.errorHandler.k8sStatus.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest'
+import express from 'express'
+import { ApiException } from '@kubernetes/client-node'
+import request from 'supertest'
+import { clerumErrorHandler } from '../src/http/errorHandler.js'
+
+/**
+ * UT-2a (FIX-B): the global error handler must forward a K8s error's real 4xx
+ * status instead of collapsing it to 500. Raw @kubernetes/client-node errors
+ * carry their status on `.code` / `.statusCode` / `.response.*`, NOT a top-level
+ * `.status` — the field the OLD inline handler read exclusively.
+ */
+
+/** Build a minimal Express app whose single route throws `err` (no auth). */
+function appThrowing(err: unknown) {
+ const app = express()
+ app.get('/boom', (_req, _res, next) => next(err))
+ app.use(clerumErrorHandler)
+ return app
+}
+
+describe('clerumErrorHandler — K8s status forwarding (UT-2a)', () => {
+ it('forwards {code:422} as 422 with a sanitized (non-leaking) body', async () => {
+ const res = await request(appThrowing({ code: 422, message: 'raw k8s internals' })).get('/boom')
+ expect(res.status).toBe(422)
+ // Plain (non-Error) objects must not leak their raw message.
+ expect(res.body.error).toBe('Bad Request')
+ })
+
+ it.each([
+ [{ code: 400 }, 400],
+ [{ code: 403 }, 403],
+ [{ code: 409 }, 409],
+ [{ statusCode: 422 }, 422],
+ [{ response: { statusCode: 422 } }, 422],
+ [{ response: { status: 404 } }, 404],
+ ])('forwards %o as %i', async (err, expected) => {
+ const res = await request(appThrowing(err)).get('/boom')
+ expect(res.status).toBe(expected)
+ })
+
+ it('preserves the legacy `.status` path (404)', async () => {
+ const res = await request(appThrowing({ status: 404, message: 'not found' })).get('/boom')
+ expect(res.status).toBe(404)
+ })
+
+ it('does NOT forward a 5xx code — {code:500} still collapses to 500', async () => {
+ const res = await request(appThrowing({ code: 500 })).get('/boom')
+ expect(res.status).toBe(500)
+ expect(res.body.error).toBe('Internal Server Error')
+ })
+
+ it('a status-less TypeError still collapses to 500 (no regression)', async () => {
+ const res = await request(appThrowing(new TypeError('kaboom'))).get('/boom')
+ expect(res.status).toBe(500)
+ expect(res.body.error).toBe('Internal Server Error')
+ })
+
+ /**
+ * S1 (security, info disclosure): a REAL @kubernetes/client-node ApiException
+ * — derived from its actual constructor (T1: fixture from the real producer,
+ * NOT a hand-built {code} object) — embeds the full metav1.Status body AND
+ * every apiserver response header (Audit-Id, x-kubernetes-pf-*) inside its
+ * `.message`. The 4xx branch must forward the real status but MUST NOT leak
+ * that message. Only the metav1.Status `body.message` may surface.
+ */
+ it('collapses a real K8s ApiException 4xx — forwards status, never leaks headers/raw message', async () => {
+ const body = {
+ kind: 'Status',
+ apiVersion: 'v1',
+ status: 'Failure',
+ message: 'hosts.clerum.io "product-agent" already exists',
+ reason: 'AlreadyExists',
+ code: 409,
+ }
+ const headers = {
+ 'audit-id': 'a1b2c3-secret-audit-uuid',
+ 'x-kubernetes-pf-flowschema-uid': 'internal-flowschema-uid',
+ 'content-type': 'application/json',
+ }
+ const err = new ApiException(409, 'Conflict', body, headers)
+
+ // Sanity: the real producer really does embed the leak in `.message`.
+ expect(err.message).toContain('Headers:')
+ expect(err.message).toContain('audit-id')
+
+ const res = await request(appThrowing(err)).get('/boom')
+ expect(res.status).toBe(409)
+
+ const serialized = JSON.stringify(res.body)
+ expect(serialized).not.toContain('Headers:')
+ expect(serialized).not.toContain('audit-id')
+ expect(serialized).not.toContain('x-kubernetes-pf')
+ expect(serialized).not.toContain(err.message)
+ // The safe metav1.Status body.message may surface as the client-facing text.
+ expect(res.body.error).toBe('hosts.clerum.io "product-agent" already exists')
+ })
+})
diff --git a/control-api/test/routes.resources.errorForwarding.test.ts b/control-api/test/routes.resources.errorForwarding.test.ts
new file mode 100644
index 000000000..afb5a4457
--- /dev/null
+++ b/control-api/test/routes.resources.errorForwarding.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * UT-2b (FIX-B wiring): a K8s 4xx raised by the gateway on a create with a VALID
+ * metadata.name must be forwarded by the wired-in global handler with its real
+ * status (here 409), NOT collapsed to 500. The valid name isolates the handler
+ * under test from the FIX-A1 name validator.
+ */
+
+const mockPoolQuery = vi.fn()
+const mockVerifyAdminToken = vi.fn()
+const mockIsAdminTokenRevoked = vi.fn()
+const mockFindAdminById = vi.fn()
+
+vi.mock('../src/db.js', () => ({
+ pool: {
+ query: (...args: unknown[]) => mockPoolQuery(...args),
+ },
+}))
+
+vi.mock('../src/utils/auth/adminAuthToken.js', () => ({
+ verifyAdminToken: (...args: unknown[]) => mockVerifyAdminToken(...args),
+}))
+
+vi.mock('../src/services/adminAuthService.js', () => ({
+ findAdminById: (...args: unknown[]) => mockFindAdminById(...args),
+ isAdminTokenRevoked: (...args: unknown[]) => mockIsAdminTokenRevoked(...args),
+}))
+
+const ADMIN_CLAIMS = {
+ sub: '00000000-0000-4000-8000-000000000001',
+ typ: 'user' as const,
+ role: 'admin' as const,
+ jti: 'admin-jti',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+}
+
+const ACTIVE_ADMIN = {
+ id: ADMIN_CLAIMS.sub,
+ username: 'admin',
+ email: '[email protected]',
+ passwordHash: 'hash',
+ sessionVersion: 0,
+ role: 'admin' as const,
+ status: 'active' as const,
+ failedAttempts: 0,
+ lockedUntil: null,
+}
+
+/** MockGateway whose Host create raises a raw K8s 409 (conflict on .code). */
+class ConflictingCreateGateway extends MockGateway {
+ override async createResource(
+ plural: Parameters<MockGateway['createResource']>[0],
+ body: Parameters<MockGateway['createResource']>[1],
+ namespace?: string
+ ): Promise<unknown> {
+ if (plural === 'hosts') {
+ const err = new Error('hosts "product-agent" already exists') as Error & { code: number }
+ err.code = 409
+ throw err
+ }
+ return super.createResource(plural, body, namespace)
+ }
+}
+
+describe('routes/resources — K8s error forwarding (UT-2b)', () => {
+ beforeEach(() => {
+ mockPoolQuery.mockReset()
+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ mockVerifyAdminToken.mockReset()
+ mockVerifyAdminToken.mockReturnValue(ADMIN_CLAIMS)
+ mockIsAdminTokenRevoked.mockReset()
+ mockIsAdminTokenRevoked.mockResolvedValue(false)
+ mockFindAdminById.mockReset()
+ mockFindAdminById.mockResolvedValue(ACTIVE_ADMIN)
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('forwards a K8s 409 raised on Host create (valid name) as 409, not 500', async () => {
+ const app = createApp(new ConflictingCreateGateway('mcp-host') as never)
+ const res = await request(app)
+ .post('/api/v1/admin/hosts')
+ .set('Cookie', 'control_ui_admin_session=admin-token')
+ .send({ metadata: { name: 'product-agent' }, spec: { contextRef: 'c1' } })
+ expect(res.status).toBe(409)
+ })
+})