Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(guardrails): redact on_error error projection; enforce DuplicatePath fail-closed (§8.1/§1.2)
Andy Pavia9bf55229f1fb
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 1437fd8eb..fbfcd57b1 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.259",+ "version": "0.1.260","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.259",+ "version": "0.1.260","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex e0571f565..e7929ffab 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.259",+ "version": "0.1.260","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/guardrailHookResolver.test.ts b/mcp-host/src/__tests__/guardrailHookResolver.test.tsindex a7cb068e7..581e0f710 100644--- a/mcp-host/src/__tests__/guardrailHookResolver.test.ts+++ b/mcp-host/src/__tests__/guardrailHookResolver.test.ts@@ -137,6 +137,51 @@ describe('resolveGuardrailHookDescriptors', () => {expect(out[0].capabilities).toEqual(['may_deny'])})+ it('quarantines a DuplicatePath collision loser (Ready=False/DuplicatePath), even with a matching digest', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'dup' },+ spec: {+ target: { image: { ref: 'repo/img@sha256:x', port: 8080 } },+ lifecyclePoints: ['preCall'],+ capabilities: ['may_rewrite'],+ },+ status: {+ observedDigest: 'sha256:x',+ conditions: [+ { type: 'Ready', status: 'False', reason: 'DuplicatePath', message: 'path collides' },+ ],+ } as unknown as LlmHookCR['status'],+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'dup', digest: 'sha256:x' }] }),+ deps({ dup: cr })+ )+ // The loser must not hit the winner's handler → quarantine, fail-closed.+ expect(out).toHaveLength(1)+ expect(out[0].quarantined).toBe(true)+ })++ it('does NOT quarantine a Ready hook (digest matches, no DuplicatePath condition)', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'ok' },+ spec: {+ target: { image: { ref: 'repo/img@sha256:x', port: 8080 } },+ lifecyclePoints: ['preCall'],+ capabilities: ['may_deny'],+ },+ status: {+ observedDigest: 'sha256:x',+ conditions: [{ type: 'Ready', status: 'True', reason: 'Ready' }],+ } as unknown as LlmHookCR['status'],+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'ok', digest: 'sha256:x' }] }),+ deps({ ok: cr })+ )+ expect(out).toHaveLength(1)+ expect(out[0].quarantined).toBeUndefined()+ })+it('drops unknown capabilities and hooks with no known lifecycle points', async () => {const good: LlmHookCR = {spec: {diff --git a/mcp-host/src/core/adapters/llmPortAdapter.ts b/mcp-host/src/core/adapters/llmPortAdapter.tsindex 198e9a39c..c3e7344d4 100644--- a/mcp-host/src/core/adapters/llmPortAdapter.ts+++ b/mcp-host/src/core/adapters/llmPortAdapter.ts@@ -9,6 +9,7 @@ import type { SessionTokenUsage } from '../conversation/conversationStore'import { LlmError } from '../errors'import { LlmPort } from '../interfaces'import type { SystemPromptParts } from '../reasoning/systemPrompt'+import { redactDiagnosticField } from '../redactDiagnostics.js'import type { TokenCounter } from '../tokenizer/tokenCounter'import {ChatMessage,@@ -47,16 +48,6 @@ function errorField(value: unknown, field: string): string | null {return trimmed ? redactDiagnosticField(trimmed).slice(0, 120) : null}-function redactDiagnosticField(value: string): string {- return value- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')- .replace(/\bsk-[A-Za-z0-9_-]{6,}/gi, 'sk-[redacted]')- .replace(- /\b(api[_-]?key|access[_-]?token|refresh[_-]?token|secret)=([^\s,;]+)/gi,- '$1=[redacted]'- )-}-function providerErrorDiagnostics(err: unknown): string {const fields: Record<string, string> = {}const name = errorField(err, 'name')diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.tsindex 2d65ba2eb..75a1353b8 100644--- a/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.ts+++ b/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.ts@@ -128,4 +128,40 @@ describe('post_call / on_error projection', () => {expect(req.systemPromptParts).toBeUndefined()expect((req.messages as ChatMessage[]).every(m => m.role !== 'system')).toBe(true)})++ it('on_error projects ONLY {code,message,retryable}, dropping provider/cause/status, and redacts the message', () => {+ const err = {+ code: 'LLM_RATE_LIMITED',+ message: 'rate limited; Authorization: Bearer sk-abc123secret',+ retryable: true,+ provider: 'openai',+ status: 429,+ cause: { headers: { 'x-request-id': 'req_leak' }, response: {} },+ }+ const body = projectForHook(desc(), 'on_error', { request: request(), error: err }) as Record<+ string,+ unknown+ >+ const e = body.error as Record<string, unknown>+ expect(Object.keys(e).sort()).toEqual(['code', 'message', 'retryable'])+ expect(e.code).toBe('LLM_RATE_LIMITED')+ expect(e.retryable).toBe(true)+ // provider / status / cause (→ headers/request metadata) are never forwarded.+ expect(e.provider).toBeUndefined()+ expect(e.status).toBeUndefined()+ expect(e.cause).toBeUndefined()+ // Secrets in the free-text message are redacted.+ expect(e.message as string).not.toContain('sk-abc123secret')+ expect(e.message as string).toContain('[redacted]')+ })++ it('on_error recovers a real Error message (Error.prototype.message is non-enumerable)', () => {+ const err = Object.assign(new Error('upstream failed'), { code: 'X' })+ const body = projectForHook(desc(), 'on_error', { request: request(), error: err }) as Record<+ string,+ unknown+ >+ // A naive {...err} spread would drop `message` entirely; projectError reads it by access.+ expect((body.error as Record<string, unknown>).message).toBe('upstream failed')+ })})diff --git a/mcp-host/src/core/guardrails/hooks/hookProjection.ts b/mcp-host/src/core/guardrails/hooks/hookProjection.tsindex dc5e6be35..411db5593 100644--- a/mcp-host/src/core/guardrails/hooks/hookProjection.ts+++ b/mcp-host/src/core/guardrails/hooks/hookProjection.ts@@ -20,6 +20,7 @@* `metadata`-only shaper (§8.7). A `metadata` `pre_call` hook gets model + params +* tool schemas but no message bodies, which is what lets it egress at low trust.*/+import { redactDiagnosticField } from '../../redactDiagnostics.js'import type { ChatMessage, ToolCompletionRequest, ToolCompletionResponse } from '../../types'import type { HookDescriptor, LifecyclePoint } from './types'@@ -55,6 +56,29 @@ export function preCallIncludesContent(descriptor: HookDescriptor): boolean {return descriptor.contentAccess !== 'metadata'}+/**+ * Project an error for an `on_error` hook to ONLY the §8.1 wire fields+ * {code, message, retryable}. The raw error is never forwarded: an LlmError's+ * enumerable own props (`provider`, and a `cause` chain to the provider SDK+ * error carrying status / response headers / request metadata) would leak, and+ * `Error.prototype.message` is non-enumerable so a straight pass-through drops+ * the very message the hook exists to recover from. `message` is read by+ * property access (so it's included) and run through the shared diagnostic+ * redaction (+120-char cap); `code` is a fixed enum; everything else is dropped.+ */+function projectError(error: unknown): {+ code?: string+ message?: string+ retryable?: boolean+} {+ const e = (error ?? {}) as { code?: unknown; message?: unknown; retryable?: unknown }+ const out: { code?: string; message?: string; retryable?: boolean } = {}+ if (typeof e.code === 'string') out.code = e.code+ if (typeof e.message === 'string') out.message = redactDiagnosticField(e.message).slice(0, 120)+ if (typeof e.retryable === 'boolean') out.retryable = e.retryable+ return out+}+/** Build the `/v1/{point}` request body for a hook, per the §8.4 projection contract. */export function projectForHook(descriptor: HookDescriptor,@@ -83,7 +107,7 @@ export function projectForHook(case 'on_error':return {request: projectRequest(ctx.request as ToolCompletionRequest, true),- error: ctx.error,+ error: projectError(ctx.error),}default:return {}diff --git a/mcp-host/src/core/redactDiagnostics.ts b/mcp-host/src/core/redactDiagnostics.tsnew file mode 100644index 000000000..e66427660--- /dev/null+++ b/mcp-host/src/core/redactDiagnostics.ts@@ -0,0 +1,15 @@+/**+ * Redact common secret shapes from a free-text diagnostic string before it+ * crosses a trust boundary. Shared by llmPortAdapter's provider-error+ * diagnostics and the `on_error` hook projection (§8.1) — a single source so the+ * two cannot drift.+ */+export function redactDiagnosticField(value: string): string {+ return value+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')+ .replace(/\bsk-[A-Za-z0-9_-]{6,}/gi, 'sk-[redacted]')+ .replace(+ /\b(api[_-]?key|access[_-]?token|refresh[_-]?token|secret)=([^\s,;]+)/gi,+ '$1=[redacted]'+ )+}diff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.tsindex 79db913e5..6a5e09807 100644--- a/mcp-host/src/guardrailHookResolver.ts+++ b/mcp-host/src/guardrailHookResolver.ts@@ -113,6 +113,28 @@ function endpointFor(cr: LlmHookCR, ns: string): ResolvedEndpoint | null {return null}+/**+ * §1.2 path-collision loser: two co-located hooks (same pod key) declaring the+ * same `spec.path` share one handler, so a loser dialed at that path would+ * inherit the winner's admin-granted capabilities. The host-context-controller+ * flags losers with a `Ready=False / reason=DuplicatePath` condition ("fail+ * closed"), but nothing enforced it — the resolver only ever read+ * `observedDigest`. Honor the condition here.+ */+function isDuplicatePathLoser(cr: LlmHookCR): boolean {+ const conditions = (+ cr.status as+ | { conditions?: Array<{ type?: string; status?: string; reason?: string }> }+ | undefined+ )?.conditions+ return (+ Array.isArray(conditions) &&+ conditions.some(+ c => c?.type === 'Ready' && c?.status === 'False' && c?.reason === 'DuplicatePath'+ )+ )+}+/*** Resolve every referenced hook into a `HookDescriptor`. Dangling refs, targets* with no resolvable endpoint, and (for image hooks) digest mismatches are@@ -188,16 +210,27 @@ export async function resolveGuardrailHookDescriptors(// /v1 call short-circuits to unavailable, so a `may_deny` (fail-closed) hook// DENIES and an advisory hook contributes nothing (§8.6/N11). Never a silent// allow for a deny-authoritative hook whose integrity check failed.- const quarantined =+ const digestMismatch =ep.kind === 'image' &&!!refDigest &&!!cr.status?.observedDigest &&refDigest !== cr.status.observedDigest- if (quarantined) {+ // A path-collision loser is fail-closed the same way: quarantine it so its+ // /v1 calls short-circuit to unavailable (may_deny → deny; advisory →+ // nothing) instead of hitting the co-located winner's handler and inheriting+ // its capabilities.+ const duplicatePathLoser = isDuplicatePathLoser(cr)+ const quarantined = digestMismatch || duplicatePathLoser+ if (digestMismatch) {console.warn(`[Guardrails] LlmHook ${id} digest mismatch (ref=${refDigest} observed=${cr.status?.observedDigest}); quarantining (fail-closed for may_deny)`)}+ if (duplicatePathLoser) {+ console.warn(+ `[Guardrails] LlmHook ${id} is a DuplicatePath collision loser (Ready=False); quarantining (fail-closed for may_deny)`+ )+ }out.push({id,@@ -213,7 +246,7 @@ export async function resolveGuardrailHookDescriptors(...(quarantined ? { quarantined: true } : {}),})console.log(- `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}${external ? ' external=true(SSRF-guarded)' : ''}${quarantined ? ' quarantined=true(digest-mismatch)' : ''}`+ `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}${external ? ' external=true(SSRF-guarded)' : ''}${quarantined ? ` quarantined=true(${duplicatePathLoser ? 'duplicate-path' : 'digest-mismatch'})` : ''}`)}