Skip to content

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

TypeScript

fix(control-api): send the host-access denial reason as a header

Alfredo Lopez72ff9f875336
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 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.json
index 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/config.ts b/control-api/src/config.ts
index 8e96800f9..c75074461 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -1103,11 +1103,11 @@ export const config: Config = {
),
// Default derived from the wake mechanism's worst case, not picked ad hoc.
// rpc-proxy's wake-and-hold loop re-triggers POST /rpc/hosts/:hostRef/wake
- // every wakeRetriggerMs=15000 for up to wakeMaxHoldMs=90000 (defaults in
+ // every wakeRetriggerMs=15000 for up to wakeMaxHoldMs=48000 (defaults in
// rpc-proxy/src/config.ts), so one held request costs
- // 1 + floor(90000/15000) = 7 calls per rpc-proxy instance; rpc-proxy runs
+ // 1 + floor(48000/15000) = 4 calls per rpc-proxy instance; rpc-proxy runs
// replicas: 2 (deploy/base/rpc-proxy/rpc-proxy.yaml) with per-instance
- // dedup, so the mechanism alone can emit 14 calls / 90s (~9.4/min) per
+ // dedup, so the mechanism alone can emit 8 calls / 48s (10.0/min) per
// host. Desktop prewarm adds a burst of up to 3 calls per device.
// Middleware order in routes/rpc-access/hosts.ts is limiter BEFORE
// handler, and the hostWakeCoalesceWindowMs coalescer runs INSIDE the
diff --git a/control-api/src/routes/rpc-access/users.ts b/control-api/src/routes/rpc-access/users.ts
index c6d5ea236..5dad840a1 100644
--- a/control-api/src/routes/rpc-access/users.ts
+++ b/control-api/src/routes/rpc-access/users.ts
@@ -1,5 +1,5 @@
import express, { Router } from 'express'
-import type { Request } from 'express'
+import type { Request, Response } from 'express'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { K8sGateway } from '../../k8s.js'
@@ -48,14 +48,25 @@ const HOST_ACCESS_SCOPES = [
type RpcAuthedRequest = Request & { rpcAuth?: RpcAccessClaims }
-function logHostAccessDenial(
+/**
+ * Response header that tells rpc-proxy why control-api denied Host access. The
+ * 403 body stays exactly `{"error":"Forbidden"}` (a pinned 21-byte contract);
+ * the reason travels out of band so rpc-proxy can tell removed access from
+ * other denials. Scope denials from the auth middleware carry no such header.
+ */
+export const HOST_ACCESS_DENIAL_REASON_HEADER = 'x-host-access-denial-reason'
+
+function denyHostAccess(
req: RpcAuthedRequest,
+ res: Response,
reason: RpcHostAccessDenialReason | 'claims_missing'
): void {
req.log?.warn(
{ event: 'rpc_host_access_denied', reason },
'rpc host access denied by control-plane authority'
)
+ res.setHeader(HOST_ACCESS_DENIAL_REASON_HEADER, reason)
+ res.status(403).json({ error: 'Forbidden' })
}
async function bindDirectRunWithinBudget(
@@ -187,8 +198,7 @@ export function createRpcAccessUsersRouter(
const hostRef = String(req.params.hostRef || '').trim()
const claims = req.rpcAuth
if (!claims) {
- logHostAccessDenial(req, 'claims_missing')
- res.status(403).json({ error: 'Forbidden' })
+ denyHostAccess(req, res, 'claims_missing')
return
}
const authorization = await authorizeRpcHostAccess(
@@ -199,8 +209,7 @@ export function createRpcAccessUsersRouter(
directory
)
if (!authorization.authorized) {
- logHostAccessDenial(req, authorization.reason)
- res.status(403).json({ error: 'Forbidden' })
+ denyHostAccess(req, res, authorization.reason)
return
}
res.status(200).json(authorization.connection)
@@ -221,8 +230,7 @@ export function createRpcAccessUsersRouter(
const claims = req.rpcAuth
const binding = parseDirectRunBindingRequest(req.body)
if (!claims) {
- logHostAccessDenial(req, 'claims_missing')
- res.status(403).json({ error: 'Forbidden' })
+ denyHostAccess(req, res, 'claims_missing')
return
}
if (!binding) {
@@ -238,8 +246,7 @@ export function createRpcAccessUsersRouter(
directory
)
if (!authorization.authorized) {
- logHostAccessDenial(req, authorization.reason)
- res.status(403).json({ error: 'Forbidden' })
+ denyHostAccess(req, res, authorization.reason)
return
}
diff --git a/control-api/test/config.hostWakeRateLimit.test.ts b/control-api/test/config.hostWakeRateLimit.test.ts
index b4ed3c88b..f46f7218b 100644
--- a/control-api/test/config.hostWakeRateLimit.test.ts
+++ b/control-api/test/config.hostWakeRateLimit.test.ts
@@ -30,15 +30,15 @@ import { readFileSync } from 'node:fs'
// Hard-coded mirrors (source files named above).
const WAKE_RETRIGGER_MS = 15_000
-const WAKE_MAX_HOLD_MS = 90_000
+const WAKE_MAX_HOLD_MS = 48_000
const RPC_PROXY_REPLICAS = 2
const PREWARM_CALLS_PER_DEVICE = 3 // 1 initial + PREWARM_REEMIT_MAX_ATTEMPTS
const PREWARM_CONCURRENT_DEVICES_BUDGET = 4
// Worst case of the wake-and-hold mechanism alone, in raw calls:
-// per instance: 1 initial + floor(maxHold / retrigger) retriggers = 7
-// fleet-wide: x replicas (per-instance dedup, no cross-instance dedup)
-// per minute: 14 calls / 90s = ~9.33/min
+// per instance: 1 initial + floor(maxHold / retrigger) retriggers = 4
+// fleet-wide: x replicas (per-instance dedup, no cross-instance dedup) = 8
+// per minute: 8 calls / 48s = 10.0/min
const HOLD_CALLS_PER_INSTANCE = 1 + Math.floor(WAKE_MAX_HOLD_MS / WAKE_RETRIGGER_MS)
const HOLD_CALLS_FLEET = HOLD_CALLS_PER_INSTANCE * RPC_PROXY_REPLICAS
const MECHANISM_CALLS_PER_MIN = HOLD_CALLS_FLEET * (60_000 / WAKE_MAX_HOLD_MS)
@@ -122,9 +122,9 @@ describe('host-wake rate limit budget (cross-service derivation guard)', () => {
const config = await loadConfigWith({})
// Sanity-pin the derivation arithmetic itself.
- expect(HOLD_CALLS_PER_INSTANCE).toBe(7)
- expect(HOLD_CALLS_FLEET).toBe(14)
- expect(MECHANISM_CALLS_PER_MIN).toBeCloseTo(9.333, 3)
+ expect(HOLD_CALLS_PER_INSTANCE).toBe(4)
+ expect(HOLD_CALLS_FLEET).toBe(8)
+ expect(MECHANISM_CALLS_PER_MIN).toBeCloseTo(10.0, 3)
// Invariant 1: >=3x the single-hold mechanism volume, so the backstop
// alone can never come close to exhausting the bucket.
diff --git a/control-api/test/routes.rpcAccessUsersMcpHost.test.ts b/control-api/test/routes.rpcAccessUsersMcpHost.test.ts
index 445643640..b380c7a0e 100644
--- a/control-api/test/routes.rpcAccessUsersMcpHost.test.ts
+++ b/control-api/test/routes.rpcAccessUsersMcpHost.test.ts
@@ -1,9 +1,10 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import type { K8sGateway } from '../src/k8s.js'
import { createRpcAccessUsersRouter } from '../src/routes/rpc-access/users.js'
import { DirectRunBindingConflictError } from '../src/services/tracing/directRunAttributionBindingService.js'
+import { signRpcAccessToken } from '../src/utils/auth/rpcAuthToken.js'
/**
* HTTP-level tests for the authorization gate on:
@@ -45,39 +46,56 @@ vi.mock('../src/services/directory/index.js', () => svc)
// token — the R2 per-session model-selector flow — is accepted, and that a
// `mcp:servers:list`-only token is still rejected) run against the REAL
// middleware + REAL signed tokens in routes.profile.test.ts.
-vi.mock('../src/middleware/rpcAccessAuth.js', () => ({
- requireValidRpcAccessToken:
- () =>
- (
- req: { params: Record<string, string>; rpcAuth?: Record<string, unknown> },
- _res: unknown,
- next: () => void
- ) => {
- req.rpcAuth = {
- ...req.rpcAuth,
- sub: req.params.userId,
- hostRefs: [req.params.hostRef],
- }
- next()
- },
- requireValidRpcAccessTokenAny:
- () =>
- (
- req: { params: Record<string, string>; rpcAuth?: Record<string, unknown> },
- _res: unknown,
- next: () => void
- ) => {
+//
+// The stub is steerable per test through `authState`, always reset in
+// afterEach: `claims` overrides fields the stub would otherwise derive from the
+// URL (so `sub` / `hostRefs` can be made to disagree with it), `omitClaims`
+// lets the request through with no `rpcAuth` at all, and `realMiddleware`
+// delegates to the REAL middleware so a genuine scope denial can be observed.
+const authState = vi.hoisted(() => ({
+ claims: {} as Record<string, unknown>,
+ omitClaims: false,
+ realMiddleware: false,
+}))
+
+vi.mock('../src/middleware/rpcAccessAuth.js', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/middleware/rpcAccessAuth.js')>()
+ type StubReq = { params: Record<string, string>; rpcAuth?: Record<string, unknown> }
+ const stubAuth = (req: StubReq, next: () => void) => {
+ if (!authState.omitClaims) {
req.rpcAuth = {
...req.rpcAuth,
sub: req.params.userId,
hostRefs: [req.params.hostRef],
+ ...authState.claims,
}
- next()
- },
- requireRpcTokenUserMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
- requireRpcTokenTeamMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
- requireRpcTokenHostMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
-}))
+ }
+ next()
+ }
+ return {
+ requireValidRpcAccessToken:
+ (...args: Parameters<typeof actual.requireValidRpcAccessToken>) =>
+ (req: StubReq, res: unknown, next: () => void) =>
+ authState.realMiddleware
+ ? actual.requireValidRpcAccessToken(...args)(req as never, res as never, next)
+ : stubAuth(req, next),
+ requireValidRpcAccessTokenAny:
+ (...args: Parameters<typeof actual.requireValidRpcAccessTokenAny>) =>
+ (req: StubReq, res: unknown, next: () => void) =>
+ authState.realMiddleware
+ ? actual.requireValidRpcAccessTokenAny(...args)(req as never, res as never, next)
+ : stubAuth(req, next),
+ requireRpcTokenUserMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
+ requireRpcTokenTeamMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
+ requireRpcTokenHostMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
+ }
+})
+
+afterEach(() => {
+ authState.claims = {}
+ authState.omitClaims = false
+ authState.realMiddleware = false
+})
type HostCRD = { metadata: { name: string }; spec?: { enabled?: boolean } }
@@ -107,6 +125,10 @@ function buildApp(hosts: HostCRD[], rpcAuth?: { teamId?: string }, bindingBudget
return { app, gatewayStub, bindingService }
}
+// Pinned literally on purpose: rpc-proxy reads this exact header name, so the
+// test must fail if the exported constant is ever renamed.
+const DENIAL_HEADER = 'x-host-access-denial-reason'
+
const DIRECT_BINDING_BODY = {
runId: '00000000-0000-4000-8000-000000000123',
sessionId: 'session-a',
@@ -187,6 +209,7 @@ describe('POST /rpc/access/users/:userId/mcp-hosts/:hostRef — atomic access an
.post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
.send(DIRECT_BINDING_BODY)
.expect(403)
+ .expect(DENIAL_HEADER, 'directory_grant_missing')
expect(gatewayStub.listResource).not.toHaveBeenCalled()
expect(bindingService.bind).not.toHaveBeenCalled()
@@ -344,6 +367,9 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #1 (user_ag
.get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
.expect(403)
+ // The reason travels out of band so the body below can stay byte-identical.
+ expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
+
// CRITICAL contract: the response body MUST be exactly {"error":"Forbidden"}.
// The Desktop App error "No permitted scopes/hostRefs for requested RPC token"
// is a CLIENT-SIDE translation of this 21-byte backend response. If you
@@ -366,6 +392,7 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #1 (user_ag
.get(`/rpc/access/users/user-has-chatllm-only/mcp-hosts/product`)
.expect(403)
expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
})
it("is an exact-string match (no substring bypass) — user with 'allinone' cannot access 'allinone2'", async () => {
@@ -423,6 +450,7 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #2 (Host CR
.get(`/rpc/access/users/user-orphan/mcp-hosts/researcher`)
.expect(403)
expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(res.headers[DENIAL_HEADER]).toBe('host_missing')
})
it('returns 403 when the gateway returns an empty list of hosts', async () => {
@@ -445,6 +473,7 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #3 (host mu
])
const res = await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(403)
expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(res.headers[DENIAL_HEADER]).toBe('host_disabled')
})
it('returns 200 when spec.enabled is undefined (default permissive, the common case)', async () => {
@@ -537,6 +566,7 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — team-level access
.get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
.expect(403)
expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
})
it('returns 403 when user_agents is empty AND no teamId is in the token', async () => {
@@ -547,6 +577,7 @@ describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — team-level access
const res = await request(app).get(`/rpc/access/users/u/mcp-hosts/development`).expect(403)
expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
// getTeamAgents must NOT be called when there is no teamId to look up
expect(svc.getTeamAgents).not.toHaveBeenCalled()
})
@@ -581,3 +612,177 @@ describe('Sibling endpoint sanity: GET /rpc/access/users/:userId/agents', () =>
expect(res.body).toEqual({ userId: 'u', agentNames: ['chatllm', 'product'] })
})
})
+
+describe('host access denial reason header (rpc-proxy contract)', () => {
+ beforeEach(() => {
+ svc.getUserAgents.mockReset()
+ svc.getCurrentTeam.mockReset()
+ svc.getTeamAgents.mockReset()
+ })
+
+ const HOST_URL = (userId: string, hostRef: string) =>
+ `/rpc/access/users/${userId}/mcp-hosts/${hostRef}`
+ const KNOWN_HOSTS: HostCRD[] = [{ metadata: { name: 'host-a' }, spec: { enabled: true } }]
+
+ type DenialCase = {
+ reason: string
+ arrange: (userId: string) => { hosts: HostCRD[]; rpcAuth?: { teamId?: string } }
+ }
+
+ // One case per control-api denial reason that reaches the handler. `arrange`
+ // wires the directory / claims / Host CRs so exactly that reason fires.
+ const DENIAL_CASES: DenialCase[] = [
+ {
+ reason: 'directory_grant_missing',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
+ return { hosts: KNOWN_HOSTS }
+ },
+ },
+ {
+ reason: 'team_membership_missing',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
+ svc.getCurrentTeam.mockResolvedValue(null)
+ return { hosts: KNOWN_HOSTS, rpcAuth: { teamId: 'team-gone' } }
+ },
+ },
+ {
+ reason: 'subject_mismatch',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
+ authState.claims = { sub: 'someone-else' }
+ return { hosts: KNOWN_HOSTS }
+ },
+ },
+ {
+ reason: 'host_claim_missing',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
+ authState.claims = { hostRefs: ['other-host'] }
+ return { hosts: KNOWN_HOSTS }
+ },
+ },
+ {
+ reason: 'host_missing',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
+ return { hosts: [] }
+ },
+ },
+ {
+ reason: 'host_disabled',
+ arrange: userId => {
+ svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
+ return { hosts: [{ metadata: { name: 'host-a' }, spec: { enabled: false } }] }
+ },
+ },
+ ]
+
+ it.each(DENIAL_CASES)(
+ 'GET 403 carries the reason $reason in the header and keeps the 21-byte body',
+ async ({ reason, arrange }) => {
+ const userId = 'user-1'
+ const { hosts, rpcAuth } = arrange(userId)
+ const { app } = buildApp(hosts, rpcAuth)
+
+ const res = await request(app).get(HOST_URL(userId, 'host-a')).expect(403)
+
+ expect(res.headers[DENIAL_HEADER]).toBe(reason)
+ expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
+ }
+ )
+
+ it.each(DENIAL_CASES)(
+ 'POST 403 carries the reason $reason in the header, keeps the 21-byte body and records no binding',
+ async ({ reason, arrange }) => {
+ const userId = 'user-1'
+ const { hosts, rpcAuth } = arrange(userId)
+ const { app, bindingService } = buildApp(hosts, rpcAuth)
+
+ const res = await request(app)
+ .post(HOST_URL(userId, 'host-a'))
+ .send(DIRECT_BINDING_BODY)
+ .expect(403)
+
+ expect(res.headers[DENIAL_HEADER]).toBe(reason)
+ expect(res.body).toEqual({ error: 'Forbidden' })
+ expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
+ // Witness for the negative: the route was entered and denied by the
+ // handler (header present above), and it never reached the binding step.
+ expect(bindingService.bind).not.toHaveBeenCalled()
+ }
+ )
+
+ it('GET without verified claims is denied with claims_missing', async () => {
+ authState.omitClaims = true
+ const { app } = buildApp(KNOWN_HOSTS)
+
+ const res = await request(app).get(HOST_URL('user-1', 'host-a')).expect(403)
+
+ expect(res.headers[DENIAL_HEADER]).toBe('claims_missing')
+ expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
+ expect(svc.getUserAgents).not.toHaveBeenCalled()
+ })
+
+ it('POST without verified claims is denied with claims_missing', async () => {
+ authState.omitClaims = true
+ const { app, bindingService } = buildApp(KNOWN_HOSTS)
+
+ const res = await request(app)
+ .post(HOST_URL('user-1', 'host-a'))
+ .send(DIRECT_BINDING_BODY)
+ .expect(403)
+
+ expect(res.headers[DENIAL_HEADER]).toBe('claims_missing')
+ expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
+ expect(bindingService.bind).not.toHaveBeenCalled()
+ })
+
+ it('a successful authorization carries no denial header', async () => {
+ svc.getUserAgents.mockResolvedValue({ userId: 'user-1', agentNames: ['host-a'] })
+ const { app } = buildApp(KNOWN_HOSTS)
+
+ const res = await request(app).get(HOST_URL('user-1', 'host-a')).expect(200)
+
+ expect(res.body.hostRef).toBe('host-a')
+ expect(res.headers[DENIAL_HEADER]).toBeUndefined()
+ })
+
+ it('a middleware scope denial carries no denial header (only handler denials do)', async () => {
+ authState.realMiddleware = true
+ svc.getUserAgents.mockResolvedValue({ userId: 'user-1', agentNames: [] })
+ const { app } = buildApp(KNOWN_HOSTS)
+ const tokenWith = (scopes: Array<'mcp:servers:list' | 'host:status:read'>, jti: string) =>
+ signRpcAccessToken({
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ role: 'member',
+ scopes,
+ hostRefs: ['host-a'],
+ jti,
+ })
+
+ // Scope not in the route's allow-list: the REAL middleware answers 403.
+ const scopeDenied = await request(app)
+ .get(HOST_URL('user-1', 'host-a'))
+ .set('x-rpc-access-token', tokenWith(['mcp:servers:list'], 'rpc-jti-scope-denied'))
+ .expect(403)
+ expect(scopeDenied.body).toEqual({ error: 'Forbidden' })
+ expect(scopeDenied.headers[DENIAL_HEADER]).toBeUndefined()
+ // Witness: the handler never ran for the scope denial.
+ expect(svc.getUserAgents).not.toHaveBeenCalled()
+
+ // Same real middleware, allowed scope: the handler runs and its denial DOES
+ // carry the header, proving the absence above is the middleware's doing.
+ const handlerDenied = await request(app)
+ .get(HOST_URL('user-1', 'host-a'))
+ .set('x-rpc-access-token', tokenWith(['host:status:read'], 'rpc-jti-handler-denied'))
+ .expect(403)
+ // The token carries a teamId and the directory stub knows no such team.
+ expect(handlerDenied.headers[DENIAL_HEADER]).toBe('team_membership_missing')
+ expect(svc.getUserAgents).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts
index 08731eacd..1b538325e 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts
@@ -59,6 +59,19 @@ function nestedArrays(depth: number): string {
return `{"x":${'['.repeat(depth)}${']'.repeat(depth)}}`
}
+/** Iterative (stack-free) depth of a JSON tree: the root container is level 1. */
+function nestingDepth(root: unknown): number {
+ let deepest = 0
+ const pending: Array<{ value: unknown; level: number }> = [{ value: root, level: 1 }]
+ for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
+ if (typeof next.value !== 'object' || next.value === null) continue
+ deepest = Math.max(deepest, next.level)
+ const children = Array.isArray(next.value) ? next.value : Object.values(next.value)
+ for (const child of children) pending.push({ value: child, level: next.level + 1 })
+ }
+ return deepest
+}
+
function nestedObjects(depth: number): string {
return `${'{"n":'.repeat(depth - 1)}{}${'}'.repeat(depth - 1)}`
}
@@ -87,19 +100,10 @@ describe('authorizeLlmProviderAttempt nesting depth guard', () => {
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))
- // Exercising serialization at this depth proves the fixture reaches
- // the scanner. Whether V8's JSON.stringify overflows the stack at
- // exactly this depth is platform-dependent; the depth guard below is
- // the platform-independent contract.
- if (depth === 150000) {
- try {
- JSON.stringify(body)
- } catch {
- // A RangeError here confirms the fixture exceeds serializer
- // limits; completing without an error is equally acceptable on
- // runtimes with deeper native stacks.
- }
- }
+ // Whether V8's JSON.stringify overflows the stack at this depth is
+ // platform-dependent, so the fixture is verified by measuring its
+ // depth instead; the guard below is the platform-independent contract.
+ expect(nestingDepth(body)).toBeGreaterThanOrEqual(depth)
const current = deps()
const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)
await expect(attempt).rejects.toBeInstanceOf(LlmProviderAttemptAuthorizeError)
@@ -111,6 +115,7 @@ describe('authorizeLlmProviderAttempt nesting depth guard', () => {
it(`rejects deep nesting under an unknown ${p.provider} body key before serializing`, async () => {
const body = wireBody(p, '{"type":"object"}', `,"extra":${nestedArrays(150000)}`)
+ expect(nestingDepth(body)).toBeGreaterThanOrEqual(150000)
const current = deps()
const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)
await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })