Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): log body refusals on the authorize route, drop the dead depth check
Alfredo Lopeze61c34c63f75
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 15465495b..6e248e919 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.653",+ "version": "0.1.654","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.653",+ "version": "0.1.654","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 99dedcfef..182cc1cf8 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.653",+ "version": "0.1.654","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/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex 69c2c70ed..1cb8d623c 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -29,7 +29,7 @@ import { llmProviderAttemptAuthorizeRateLimits } from '../workflows/shared/rateLconst log = rootLogger.child({ module: 'mcp-host-llm-provider-attempts' })-// A8 D4: JSON.parse allocates one heap object per container, so a body under+// JSON.parse allocates one heap object per container, so a body under// the byte limit can exhaust the heap before either authorizer runs. The// parser scans the raw bytes first. Every bound below is derived key-by-key// from both contracts at the larger of the two values, so the scan refuses no@@ -181,19 +181,25 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Rout// answered here, because body-parser attaches the raw body to them as// `err.body` and the global error handler would parse it again. The other// parser errors (`request.aborted`, `request.size.invalid`, `stream.*`)- // carry no body and go to the global handler, which logs no body.+ // carry no body and go to the global handler, which logs no body. The log+ // carries only the fixed parser `type` and the status: `err.message` of a+ // JSON.parse error can quote a fragment of the body.router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {const typed = err as { type?: string; status?: number }+ const refuse = (status: number, error: string): void => {+ log.warn({ event: 'llm_provider_attempt_body_refused', type: typed.type, status })+ res.status(status).json({ error })+ }if (typed.type === 'entity.too.large' || typed.status === 413) {- res.status(413).json({ error: 'payload_too_large' })+ refuse(413, 'payload_too_large')return}if (typed.type === 'encoding.unsupported' || typed.type === 'charset.unsupported') {- res.status(415).json({ error: 'unsupported_media_type' })+ refuse(415, 'unsupported_media_type')return}if (typed.type === 'entity.parse.failed' || typed.type === 'body.structure.too.deep') {- res.status(400).json({ error: 'invalid_request' })+ refuse(400, 'invalid_request')return}next(err)diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex c98c1151d..a2f29e3bd 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -158,11 +158,6 @@ const defaultDeps = (): LlmProviderAttemptAuthorizerDeps => ({export { computeCodexPolicyHash }-// body > request > messages[] > message > toolCalls[] > call > arguments: the-// deepest free-form tree the contracts accept sits six containers below the-// body root, and may itself nest maxNestingDepth containers.-const MAX_AUTHORIZE_BODY_DEPTH = Math.max(LIMITS.maxNestingDepth, GROK_LIMITS.maxNestingDepth) + 6-/*** #731 — room for the authorize envelope around the contract-capped `request`:* ids, revisions, hashes and recipe names, a few hundred bytes in practice.@@ -176,28 +171,6 @@ const MAX_AUTHORIZE_BODY_DEPTH = Math.max(LIMITS.maxNestingDepth, GROK_LIMITS.ma*/export const AUTHORIZE_ENVELOPE_ALLOWANCE_BYTES = ENVELOPE_ALLOWANCE_BYTES-/**- * Reject an over-deep body before anything serializes it. Iterative, so an- * attacker-controlled nesting depth cannot overflow the stack here; without it- * JSON.stringify throws a RangeError that surfaces as a 500.- */-function assertBodyNestingWithinLimit(body: Record<string, unknown>): void {- const stack: Array<[unknown, number]> = [[body, 1]]- while (stack.length > 0) {- const [node, depth] = stack.pop()!- if (depth > MAX_AUTHORIZE_BODY_DEPTH) {- throw new LlmProviderAttemptAuthorizeError(- 'invalid_request',- 'request body exceeds the maximum nesting depth'- )- }- const children = Array.isArray(node) ? node : Object.values(node as Record<string, unknown>)- for (const child of children) {- if (child !== null && typeof child === 'object') stack.push([child, depth + 1])- }- }-}-function firstUnknownKey(body: Record<string, unknown>): string | null {for (const key of Object.keys(body)) {if (!AUTHORIZE_BODY_KEYS.has(key)) return key@@ -277,7 +250,8 @@ async function authorizeGrokProviderAttempt('mcp-host JWT lacks the llm:grok:execute scope')}- assertBodyNestingWithinLimit(body)+ // The route's raw-body scan bounds nesting depth before parsing, so+ // JSON.stringify cannot overflow the stack here.const serialized = JSON.stringify(body)// Same budgets as the Codex path (#784): the larger of the non-image cap plus// the envelope allowance and the V2 visual envelope bounds the whole body;@@ -683,7 +657,8 @@ export async function authorizeLlmProviderAttempt('mcp-host JWT lacks the llm:codex:execute scope')}- assertBodyNestingWithinLimit(body)+ // The route's raw-body scan bounds nesting depth before parsing, so+ // JSON.stringify cannot overflow the stack here.const serialized = JSON.stringify(body)// The larger of the two budgets wins, as on the gateway's client_max_body_size:// the non-image cap plus the envelope allowance (#731), or the V2 visualdiff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.tsindex 9750cf6e8..98bc5f3b7 100644--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts@@ -21,6 +21,24 @@ import { LlmProviderAttemptAuthorizeError } from '../src/services/llmProviderAttimport * as authorizer from '../src/services/llmProviderAttemptAuthorizer.js'import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'+// Capture structured logs so the refusal event can be asserted without pino+// transports. Every other logger method is a no-op.+const { mockLogWarn } = vi.hoisted(() => ({ mockLogWarn: vi.fn() }))+vi.mock('../src/observability/logger.js', () => {+ const makeLogger = (): unknown =>+ new Proxy(+ {},+ {+ get(_t, prop) {+ if (prop === 'warn') return mockLogWarn+ if (prop === 'child') return () => makeLogger()+ return () => {}+ },+ }+ )+ return { rootLogger: makeLogger() }+})+vi.mock('../src/services/rateLimiterService.js', () => ({checkAndIncrement: vi.fn().mockResolvedValue({allowed: true,@@ -155,7 +173,7 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {// The route parser admits the Grok 35 MiB envelope for both providers, so a// Codex body between the two visual caps now reaches the Codex authorizer,- // and that authorizer is what must refuse it (#806 review, L1).+ // and that authorizer is what must refuse it (#806 review).it('refuses a Codex V2 body between the Codex and Grok visual caps in the Codex authorizer', async () => {const actual = await vi.importActual<typeof import('../src/services/llmProviderAttemptAuthorizer.js')@@ -346,11 +364,11 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {})})-// A8 D4: JSON.parse allocates one heap object per container, so a 35 MiB body+// JSON.parse allocates one heap object per container, so a 35 MiB body// of empty containers exhausts the heap before any authorizer check runs, and// a gzip body inflates past the byte limit's intent. The route parser refuses// both from the raw bytes.-describe('authorize raw-body scan before JSON.parse (A8 D4)', () => {+describe('authorize raw-body scan before JSON.parse', () => {const SCAN_LIMITS = MCP_HOST_BODY_STRUCTURE_LIMITSconst UNBOUNDED = {maxStructuralBytes: Infinity,@@ -363,6 +381,7 @@ describe('authorize raw-body scan before JSON.parse (A8 D4)', () => {beforeEach(() => {vi.mocked(authorizer.authorizeLlmProviderAttempt).mockReset()+ mockLogWarn.mockReset()})async function withRoute(run: (url: string) => Promise<void>): Promise<void> {@@ -630,6 +649,88 @@ describe('authorize raw-body scan before JSON.parse (A8 D4)', () => {expect(authorizer.authorizeLlmProviderAttempt).toHaveBeenCalledTimes(1)})})++ it('answers 400 to a 5000-deep and a 150000-deep body without recursion or the authorizer', async () => {+ // JSON.stringify overflows the stack on a body this deep, so the scan is+ // the only bound: the authorizer no longer checks nesting itself.+ await withRoute(async url => {+ for (const depth of [5000, 150000]) {+ const response = await fetch(url, {+ method: 'POST',+ headers: headers(),+ body: deepBody(depth),+ })+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: 'invalid_request' })+ }+ // Same depth under a key the authorizer does not accept: refused by the scan too.+ const unknownKey = await fetch(url, {+ method: 'POST',+ headers: headers(),+ body: `{"request":{},"extra":${'['.repeat(150000)}${']'.repeat(150000)}}`,+ })+ expect(unknownKey.status).toBe(400)+ expect(authorizer.authorizeLlmProviderAttempt).not.toHaveBeenCalled()+ // Witness: a body at the depth bound reaches the authorizer.+ fixtureAuthorizer()+ const atBound = await fetch(url, {+ method: 'POST',+ headers: headers(),+ body: deepBody(SCAN_LIMITS.maxDepth),+ })+ expect(atBound.status).toBe(400)+ expect(authorizer.authorizeLlmProviderAttempt).toHaveBeenCalledTimes(1)+ })+ })++ it('logs the fixed refusal type for a structural 413, a byte-limit 413, a too.deep 400 and a 415, never the body', async () => {+ const marker = 'BODY-TEXT-MUST-NOT-BE-LOGGED'+ const overContainers = `{"secret":"${marker}","pad":[${'[],'.repeat(SCAN_LIMITS.maxContainers)}[]]}`+ const tooDeep = `{"secret":"${marker}","pad":${'['.repeat(SCAN_LIMITS.maxDepth)}${']'.repeat(SCAN_LIMITS.maxDepth)}}`+ const byteLimit = Math.max(+ CODEX_LIMITS.maxVisualRequestBodyBytes,+ GROK_LIMITS.maxVisualRequestBodyBytes+ )+ const overBytes = `{"secret":"${marker}","pad":"${'x'.repeat(byteLimit)}"}`+ const refusalEvents = () =>+ mockLogWarn.mock.calls+ .map(([fields]) => fields as { event?: string; type?: string; status?: number })+ .filter(fields => fields?.event === 'llm_provider_attempt_body_refused')+ await withRoute(async url => {+ const structural = await fetch(url, {+ method: 'POST',+ headers: headers(),+ body: overContainers,+ })+ expect(structural.status).toBe(413)+ const deep = await fetch(url, { method: 'POST', headers: headers(), body: tooDeep })+ expect(deep.status).toBe(400)+ const bytes = await fetch(url, { method: 'POST', headers: headers(), body: overBytes })+ expect(bytes.status).toBe(413)+ const encoded = await fetch(url, {+ method: 'POST',+ headers: headers({ 'content-encoding': 'gzip' }),+ body: new Uint8Array(gzipSync('{}')),+ })+ expect(encoded.status).toBe(415)+ expect(authorizer.authorizeLlmProviderAttempt).not.toHaveBeenCalled()+ })+ // Liveness witness: the event was logged four times, once per refusal.+ expect(refusalEvents()).toEqual([+ {+ event: 'llm_provider_attempt_body_refused',+ type: 'body.structure.too.many.containers',+ status: 413,+ },+ { event: 'llm_provider_attempt_body_refused', type: 'body.structure.too.deep', status: 400 },+ { event: 'llm_provider_attempt_body_refused', type: 'entity.too.large', status: 413 },+ { event: 'llm_provider_attempt_body_refused', type: 'encoding.unsupported', status: 415 },+ ])+ // No logged argument carries the body text or the raw error message.+ for (const args of mockLogWarn.mock.calls) {+ expect(JSON.stringify(args)).not.toContain(marker)+ }+ }, 60_000)})describe('resolveHostAssignedAssignment', () => {diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.tsindex ed5e81864..bcef1cb9b 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts@@ -1,15 +1,15 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { config } from '../src/config.js'import {- LlmProviderAttemptAuthorizeError,type LlmProviderAttemptAuthorizerDeps,authorizeLlmProviderAttempt,} from '../src/services/llmProviderAttemptAuthorizer.js'import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'-// B-L6: a deeply nested authorize body must fail closed as invalid_request-// before the authorizer serializes it. Without the guard, JSON.stringify throws-// a RangeError that the route maps to a 500.+// The contracts cap nesting inside the authorizer (64 containers in tool+// parameters and tool-call arguments). The route's raw-body scan bounds the+// whole body at 70 containers before JSON.parse; its end-to-end depth test is+// in routes.mcp-host.llmProviderAttempts.test.ts.const PROVIDERS = [{@@ -55,24 +55,20 @@ function wireBody(p: ProviderCase, parametersJson: string, extra = ''): Record<s) as Record<string, unknown>}-function nestedArrays(depth: number): string {- return `{"x":${'['.repeat(depth)}${']'.repeat(depth)}}`-}-function nestedObjects(depth: number): string {return `${'{"n":'.repeat(depth - 1)}{}${'}'.repeat(depth - 1)}`}-const GUARD_PASSED = new Error('guard passed: assignment lookup reached')+const CAP_PASSED = new Error('contract cap passed: assignment lookup reached')function deps(): Partial<LlmProviderAttemptAuthorizerDeps> {return {enabled: true,- resolveAssignment: vi.fn().mockRejectedValue(GUARD_PASSED),+ resolveAssignment: vi.fn().mockRejectedValue(CAP_PASSED),}}-describe('authorizeLlmProviderAttempt nesting depth guard', () => {+describe('authorizeLlmProviderAttempt contract nesting cap', () => {const previousGrokFlag = config.grokSubscriptionEnabledbeforeEach(() => {@@ -84,36 +80,16 @@ describe('authorizeLlmProviderAttempt nesting depth guard', () => {})for (const p of PROVIDERS) {- for (const depth of [5000, 150000]) {- it(`rejects a ${depth}-deep ${p.provider} request with invalid_request, not a RangeError`, async () => {- const body = wireBody(p, nestedArrays(depth))- const current = deps()- const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)- await expect(attempt).rejects.toBeInstanceOf(LlmProviderAttemptAuthorizeError)- await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })- await expect(attempt).rejects.toThrow(/nesting depth/)- expect(current.resolveAssignment).not.toHaveBeenCalled()- })- }-- it(`rejects deep nesting under an unknown ${p.provider} body key before serializing`, async () => {- const body = wireBody(p, '{"type":"object"}', `,"extra":${nestedArrays(150000)}`)- const current = deps()- const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)- await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })- await expect(attempt).rejects.toThrow(/nesting depth/)- })-- it(`lets a ${p.provider} request with 64-deep tool parameters past the guard`, async () => {+ it(`lets a ${p.provider} request with 64-deep tool parameters past the contract cap`, async () => {const body = wireBody(p, nestedObjects(64))const current = deps()await expect(authorizeLlmProviderAttempt(claims(p.scope), body, current)).rejects.toBe(- GUARD_PASSED+ CAP_PASSED)expect(current.resolveAssignment).toHaveBeenCalledTimes(1)})- it(`lets a ${p.provider} request with 64-deep assistant tool-call arguments past the guard`, async () => {+ it(`lets a ${p.provider} request with 64-deep assistant tool-call arguments past the contract cap`, async () => {// The deepest accepted tree: body > request > messages[] > message >// toolCalls[] > call > arguments, then 64 levels inside arguments.const body = wireBody(p, '{"type":"object"}')@@ -123,7 +99,7 @@ describe('authorizeLlmProviderAttempt nesting depth guard', () => {)const current = deps()await expect(authorizeLlmProviderAttempt(claims(p.scope), body, current)).rejects.toBe(- GUARD_PASSED+ CAP_PASSED)})diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.mdindex cc6bd6298..de5c74e0a 100644--- a/docs/architecture/codex-subscription-transport-contract.md+++ b/docs/architecture/codex-subscription-transport-contract.md@@ -293,8 +293,8 @@ classifies it as `ContextLengthExceeded`, not retryable.Follow-up: a refusal metric by type (`body.structure.*`) and a histogram ofstructure counts per request, to check the bounds against real use. The-262144-member and 1048576-element values are subject to the separate V5-memory gate; the container measurements above do not validate them.+262144-member and 1048576-element values need a separate memory+measurement; the container measurements above do not validate them.### Compatibility and deployment order@@ -441,7 +441,7 @@ behavior changes:request acquires in the order visual slot, byte budget, stream slot, andno two requests can wait on each other.- **Per-principal visual share (B4).** In addition to the gate, each+ **Per-principal visual share.** In addition to the gate, eachplatform identity (`sub` plus sorted `hostRefs`) may hold at most 4visual entries (running or queued) of the gate's 10. A token whose `sub`is missing, empty or not a string is refused 401 before any gate or