Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): route stale-warning catch through structured logging (R1-M5)
Diego Zacariasbb51c5ebe7e3
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 7099b0ab3..f3aa19e5b 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.450",+ "version": "0.1.451","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.450",+ "version": "0.1.451","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.jsonindex 4b01b56f5..6cb10e86a 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.450",+ "version": "0.1.451","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/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex b366a25aa..3ed3a97d8 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -4,6 +4,7 @@ import {PROVIDER_CREDENTIAL_SLOTS,isLlmProviderId,} from '@clerum/llm-providers'+import { rootLogger } from '../../observability/logger.js'import {getModelAllowlistState as getModelAllowlistStateDefault,isModelAllowed as isModelAllowedDefault,@@ -21,6 +22,8 @@ import {} from './modelAllowlistTolerance.js'import { STALE_MODEL_ASSIGNED, type StaleModelWarning } from './staleModelWarning.js'+const logger = rootLogger.child({ module: 'admin-host-spec-validation' })+// A Kubernetes Secret/ConfigMap data key: `[-._a-zA-Z0-9]`, max 253 chars.// A fallback `credentialSlot` names a key inside the chatllm-api-keys Secret, so// it must satisfy that format. We validate the FORMAT only — the key's existence@@ -400,10 +403,13 @@ async function maybeWarnStale(try {state = await getState(provider, model)} catch (err) {- console.warn(- `[Admin] stale-model warning lookup failed for "${provider}/${model}"; proceeding without a warning: ${- err instanceof Error ? err.message : String(err)- }`+ // Structured (Pino) logging JSON-escapes field values — CR/LF included — so a+ // request-derived provider/model cannot forge or split a log record. Do NOT+ // interpolate these into a line-oriented sink (console.*). Best-effort:+ // swallow and proceed without a warning; behavior is unchanged.+ logger.warn(+ { provider, model, err: err instanceof Error ? err.message : String(err) },+ 'stale-model warning lookup failed; proceeding without a warning')return}diff --git a/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts b/control-api/test/routes.resources.staleModelWarning.logInjection.test.tsnew file mode 100644index 000000000..188e78225--- /dev/null+++ b/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'+import { MockGateway } from './mockGateway.js'++// R1-M5 — log-record injection guard for the best-effort stale-warning catch+// (hostSpecValidation.ts `maybeWarnStale`). The `model` name is request-derived+// and validated with only `.trim()` (internal CR/LF survive). The old code+// interpolated it into a LINE-oriented sink (console.warn), so a `model` such as+// "gpt-4\nlevel=fatal msg=..." could forge/split a second log record. The fix+// routes the warning through the structured Pino logger, which JSON-escapes field+// values (CR/LF included) into a single record.+//+// T1: the log line is derived from the REAL producer (Pino) — not hand-written.+// We mock the logger module to hand `hostSpecValidation` a real Pino instance+// whose destination is an in-memory stream, so we capture Pino's actual wire+// serialization. T4: we assert the OBSERVABLE result — the sink received exactly+// ONE record, parseable as a single JSON object, with the CR/LF preserved INSIDE+// the `model` field (escaped on the wire), never a second forged/split line.++const logCapture = vi.hoisted(() => ({ lines: [] as string[] }))++vi.mock('../src/observability/logger.js', async () => {+ const { default: pino } = await import('pino')+ const stream = {+ write: (chunk: string) => {+ logCapture.lines.push(chunk)+ },+ }+ const rootLogger = pino({ level: 'warn', base: { svc: 'control-api' } }, stream)+ return { rootLogger }+})++const llm = vi.hoisted(() => ({+ isModelAllowed: vi.fn(),+ getModelAllowlistState: vi.fn(),+}))+vi.mock('../src/services/llmAllowedModels.js', async () => {+ const actual = await vi.importActual<typeof import('../src/services/llmAllowedModels.js')>(+ '../src/services/llmAllowedModels.js'+ )+ return {+ ...actual,+ isModelAllowed: llm.isModelAllowed,+ getModelAllowlistState: llm.getModelAllowlistState,+ }+})++const HOSTS_NS = config.hostsNamespace++function buildApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminResourcesRouter(gateway as never))+ return app+}++beforeEach(() => {+ logCapture.lines.length = 0+ llm.isModelAllowed.mockReset()+ llm.getModelAllowlistState.mockReset()+ // The model passes the allowlist gate (enabled) so the write proceeds to the+ // additive stale-warning lookup — which we force to reject, hitting the catch.+ llm.isModelAllowed.mockResolvedValue(true)+ llm.getModelAllowlistState.mockRejectedValue(new Error('db connection reset'))+})++describe('R1-M5 stale-warning catch: structured logging blocks log-record injection', () => {+ it('emits exactly ONE parseable JSON record (no forged/split line) for a CR/LF model name', async () => {+ // A request-derived model carrying an embedded newline + a forged record tail.+ const forgedModel = 'gpt-4\nlevel=fatal msg="forged log entry"'+ const gateway = new MockGateway(HOSTS_NS)++ const res = await request(buildApp(gateway))+ .post('/admin/hosts')+ .send({+ metadata: { name: 'h1' },+ spec: { model: { provider: 'claude', name: forgedModel } },+ })++ // Best-effort invariant unchanged: the write still persists (no 500).+ expect(res.status).toBe(201)++ // Observable result (T4): the log sink received EXACTLY ONE record for this+ // event. With the old console.warn the structured logger was never called, so+ // this filter is empty and the assertion fails against the buggy head.+ const staleWarnLines = logCapture.lines.filter(l =>+ l.includes('stale-model warning lookup failed')+ )+ expect(staleWarnLines).toHaveLength(1)++ const rawLine = staleWarnLines[0]++ // It is a SINGLE physical line: only Pino's own trailing "\n" separates+ // records. The embedded CR/LF was escaped (\n), so it did not split the record.+ expect(rawLine.replace(/\n$/, '').split('\n')).toHaveLength(1)++ // It parses as one JSON object, and the injected newline lives INSIDE the+ // `model` field value — not as a forged sibling record.+ const parsed = JSON.parse(rawLine) as { provider: string; model: string; err: string }+ expect(parsed.provider).toBe('claude')+ expect(parsed.model).toBe(forgedModel)+ expect(parsed.err).toBe('db connection reset')+ })+})