Skip to content

Commit 58a5387

Browse files
authored
fix(security): centralize provider diagnostic redaction (#121599)
* fix(security): centralize provider diagnostic redaction * fix(workers): redact finishing diagnostics * fix(security): fail closed on malformed diagnostics * fix(security): redact media wrapper diagnostics * fix(security): normalize diagnostic field redaction * fix(security): redact diagnostic media URIs * fix(ai): preserve diagnostic compatibility in error projection * refactor(ai): simplify diagnostic error handling * fix(security): redact credential query diagnostics * fix(security): redact diagnostic media arrays * fix(security): redact diagnostic credential headers * test: align shared expectations with current runtime contracts * test(ui): align managed media and picker expectations * fix(security): redact plural media diagnostics * fix(ai): preserve bracketed provider errors * fix(security): cover generic diagnostic credentials * fix(security): redact prefixed diagnostic JSON * fix(security): redact embedded diagnostic JSON * test(agents): align cache trace media redaction * fix(security): redact cookie diagnostics * refactor(ai): isolate diagnostic host policy * refactor(ai): narrow diagnostic helper exports * fix(security): bound diagnostic descriptor reads * fix(security): bound diagnostic graph traversal
1 parent ba58803 commit 58a5387

41 files changed

Lines changed: 1762 additions & 585 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/ai/src/provider-transport-parity.test.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ type ParityFixture = {
5252
name: string;
5353
provider: "anthropic" | "openai";
5454
outcome: "success" | "error";
55-
snapshot: string;
55+
snapshot?: string;
5656
};
5757

5858
const anthropicModel = {
@@ -340,7 +340,6 @@ const fixtures: ParityFixture[] = [
340340
name: "Anthropic structured request failure",
341341
provider: "anthropic",
342342
outcome: "error",
343-
snapshot: "anthropic-error.snap.txt",
344343
},
345344
{
346345
name: "OpenAI successful request and event trace",
@@ -352,7 +351,6 @@ const fixtures: ParityFixture[] = [
352351
name: "OpenAI structured request failure",
353352
provider: "openai",
354353
outcome: "error",
355-
snapshot: "openai-error.snap.txt",
356354
},
357355
];
358356

@@ -375,9 +373,26 @@ describe("provider and transport observable parity fixtures", () => {
375373
const run = provider === "anthropic" ? runAnthropic : runOpenAi;
376374
const providerResult = await run("provider", outcome);
377375
const transportResult = await run("transport", outcome);
378-
// Stage 1 freezes both observable baselines, including the known gaps that
379-
// stages 3-4 will close. Equality here would either start those later stages
380-
// or hide the exact request/event differences this safety net must preserve.
376+
if (outcome === "error") {
377+
for (const result of [providerResult, transportResult]) {
378+
expect(result.terminal.stopReason).toBe("error");
379+
expect(result.errorFields.errorMessage).toEqual(expect.any(String));
380+
}
381+
if (provider === "openai") {
382+
expect(providerResult.errorFields).toEqual(transportResult.errorFields);
383+
} else {
384+
expect(providerResult.errorFields).toMatchObject({
385+
errorCode: "429",
386+
errorType: "rate_limit_error",
387+
errorBody: expect.stringContaining("synthetic Anthropic rejection"),
388+
});
389+
expect(transportResult.errorFields.errorMessage).toContain("Retry-After: 2 seconds");
390+
}
391+
return;
392+
}
393+
if (!snapshot) {
394+
throw new Error("success parity fixture requires a snapshot");
395+
}
381396
await expect(
382397
`${JSON.stringify({ provider: providerResult, transport: transportResult }, null, 2)}\n`,
383398
).toMatchFileSnapshot(

‎packages/ai/src/providers/anthropic.test.ts‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1782,10 +1782,54 @@ describe("Anthropic provider", () => {
17821782
expect(result.errorMessage).toBe('{"code":"ECONNRESET","self":"[Circular]"}');
17831783
});
17841784

1785+
it("terminates the stream when provider terminal accessors throw", async () => {
1786+
const hostile = Object.create(null) as Record<string, unknown>;
1787+
Object.defineProperties(hostile, {
1788+
code: { enumerable: true, value: "ECONNRESET" },
1789+
safe: { enumerable: true, value: "socket failed" },
1790+
status: {
1791+
enumerable: true,
1792+
get: () => {
1793+
throw new Error("status getter");
1794+
},
1795+
},
1796+
body: {
1797+
enumerable: true,
1798+
get: () => {
1799+
throw new Error("body getter");
1800+
},
1801+
},
1802+
message: {
1803+
enumerable: true,
1804+
get: () => {
1805+
throw new Error("message getter");
1806+
},
1807+
},
1808+
});
1809+
const asResponse = vi.fn().mockRejectedValue(hostile);
1810+
const client = { messages: { create: vi.fn(() => ({ asResponse })) } };
1811+
const stream = streamAnthropic(
1812+
makeAnthropicModel({ id: "claude-fable-5", name: "Claude Fable 5" }),
1813+
{ messages: [{ role: "user", content: "hello", timestamp: 0 }] },
1814+
{ apiKey: "sk-ant-provider", client: client as never },
1815+
);
1816+
const eventTypes: string[] = [];
1817+
for await (const event of stream) {
1818+
eventTypes.push(event.type);
1819+
}
1820+
const result = await stream.result();
1821+
1822+
expect(eventTypes).toEqual(["error"]);
1823+
expect(result).toMatchObject({
1824+
stopReason: "error",
1825+
errorCode: "ECONNRESET",
1826+
});
1827+
expect(result.errorMessage).toContain("socket failed");
1828+
});
1829+
17851830
it("keeps the message for Anthropic errors that carry no HTTP body", async () => {
1786-
// formatProviderError only substitutes status+body when a body is present, so
1787-
// ordinary Error rejections must still surface error.message — retry
1788-
// classification in src/llm/utils/retry.ts parses this string.
1831+
// Ordinary Error rejections with no body must still surface error.message;
1832+
// retry classification in src/llm/utils/retry.ts parses this string.
17891833
const asResponse = vi
17901834
.fn()
17911835
.mockRejectedValue(Object.assign(new Error("Overloaded"), { status: 529 }));
@@ -1806,7 +1850,7 @@ describe("Anthropic provider", () => {
18061850
const result = await stream.result();
18071851

18081852
expect(eventTypes).toEqual(["error"]);
1809-
expect(result.errorMessage).toBe("Overloaded");
1853+
expect(result.errorMessage).toBe("529: Overloaded");
18101854
});
18111855

18121856
it("strips Fable thinking when replay targets Anthropic Vertex", async () => {

‎packages/ai/src/providers/anthropic.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ import { AssistantMessageEventStream } from "../utils/event-stream.js";
4343
import { headersToRecord } from "../utils/headers.js";
4444
import { parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.js";
4545
import { notifyLlmRequestActivity } from "../utils/llm-request-activity.js";
46-
import { formatProviderError } from "../utils/provider-error.js";
46+
import { projectProviderError } from "../utils/provider-error.js";
4747
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
4848
import {
4949
splitSystemPromptCacheBoundary,
@@ -660,13 +660,9 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
660660
refusalBuffer.discard();
661661
output.content = [];
662662
}
663-
output.stopReason = requestOptions?.signal?.aborted ? "aborted" : "error";
664-
// A bare JSON.stringify here dies on the circular error objects HTTP/socket
665-
// layers raise, and the throw escapes this catch so stream.end() never runs
666-
// and the consumer hangs. formatProviderError guards that conversion, matching
667-
// the other provider terminal paths.
668-
output.errorMessage = formatProviderError(error);
669-
stream.push({ type: "error", reason: output.stopReason, error: output });
663+
const terminal = projectProviderError(error, requestOptions?.signal);
664+
Object.assign(output, terminal);
665+
stream.push({ type: "error", reason: terminal.stopReason, error: output });
670666
stream.end();
671667
}
672668
})();

‎packages/ai/src/providers/azure-openai-responses.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -36,22 +36,6 @@ function resolveDeploymentName(
3636
});
3737
}
3838

39-
function formatAzureOpenAIError(error: unknown): string {
40-
if (error instanceof Error) {
41-
const status = (error as Error & { status?: unknown }).status;
42-
const statusCode = typeof status === "number" ? status : undefined;
43-
if (statusCode !== undefined) {
44-
return `Azure OpenAI API error (${statusCode}): ${error.message}`;
45-
}
46-
return error.message;
47-
}
48-
try {
49-
return JSON.stringify(error);
50-
} catch {
51-
return String(error);
52-
}
53-
}
54-
5539
// Azure OpenAI Responses-specific options
5640
interface AzureOpenAIResponsesOptions extends BaseOpenAIStreamOptions {
5741
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
@@ -98,7 +82,6 @@ export const streamAzureOpenAIResponses: StreamFunction<
9882
resolveDeploymentName(model, options),
9983
replayMode,
10084
),
101-
formatError: formatAzureOpenAIError,
10285
});
10386

10487
return stream;

‎packages/ai/src/providers/google-shared.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,23 @@ describe("runGoogleGenerateContentLifecycle", () => {
765765

766766
expect(output.errorMessage).toBe("502: gateway maintenance");
767767
});
768+
769+
it("redacts generated video bytes from Google terminal fields", async () => {
770+
const media = "QUJDRA==";
771+
const error = Object.assign(new Error("502 status code (no body)"), {
772+
status: 502,
773+
body: { generatedVideos: [{ video: { videoBytes: media, mimeType: "video/mp4" } }] },
774+
});
775+
776+
const { output } = await runGoogleFixture([], {
777+
generateContentStream: async () => {
778+
throw error;
779+
},
780+
});
781+
782+
expect(output.errorCode).toBe("502");
783+
expect(JSON.stringify(output)).not.toContain(media);
784+
});
768785
});
769786

770787
describe("buildGoogleGenerateContentParams", () => {

‎packages/ai/src/providers/google-shared.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import type {
3636
} from "../types.js";
3737
import type { AssistantMessageEventStream } from "../utils/event-stream.js";
3838
import { sortPromptCacheToolsByName } from "../utils/prompt-cache-stability.js";
39-
import { formatProviderError } from "../utils/provider-error.js";
4039
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
4140
import { stripSystemPromptCacheBoundary } from "../utils/system-prompt-cache-boundary.js";
4241
import {
@@ -452,16 +451,6 @@ export async function runGoogleGenerateContentLifecycle<T extends GoogleApiType>
452451
}
453452
const failure = options?.signal?.aborted ? transportAbortError(options.signal) : error;
454453
assignTransportErrorDetails(output, failure, options?.signal);
455-
const formattedError = formatProviderError(failure);
456-
const status = failure instanceof Error && "status" in failure ? failure.status : undefined;
457-
if (typeof status === "number" && Number.isFinite(status)) {
458-
output.errorCode ||= String(status);
459-
output.errorMessage = formattedError.startsWith(`${status}:`)
460-
? formattedError
461-
: `${status}: ${formattedError}`;
462-
} else {
463-
output.errorMessage = formattedError;
464-
}
465454
stream.push({
466455
type: "error",
467456
reason: output.stopReason === "aborted" ? "aborted" : "error",

‎packages/ai/src/providers/mistral.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ describe("Mistral provider", () => {
225225
expect((mistralMockState.payloads[0] as { stop?: unknown }).stop).toEqual(["STOP"]);
226226
});
227227

228-
it("keeps truncated Mistral error bodies UTF-16 safe with an exact omitted count", async () => {
228+
it("preserves Mistral messages while keeping error bodies UTF-16 safe and bounded", async () => {
229229
const prefix = "a".repeat(3_999);
230230
mistralMockState.streamError = Object.assign(new Error("invalid request"), {
231231
statusCode: 400,
@@ -234,7 +234,8 @@ describe("Mistral provider", () => {
234234

235235
const result = await runMistralFixture();
236236

237-
expect(result.errorMessage).toBe(`Mistral API error (400): ${prefix}... [truncated 6 chars]`);
237+
expect(result.errorMessage).toBe("invalid request");
238+
expect(result.errorBody).toBe(`${prefix.slice(0, 500)}... [truncated]`);
238239
});
239240

240241
it("routes the Mistral HTTPClient through the host guarded fetch", async () => {

‎packages/ai/src/providers/mistral.ts‎

Lines changed: 4 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import type {
99
FunctionTool,
1010
} from "@mistralai/mistralai/models/components";
1111
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12-
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1312
import { getEnvApiKey } from "../env-api-keys.js";
1413
import { getAiTransportHost } from "../host.js";
1514
import { calculateCost, clampThinkingLevel } from "../model-utils.js";
@@ -31,6 +30,7 @@ import type {
3130
import { AssistantMessageEventStream } from "../utils/event-stream.js";
3231
import { shortHash } from "../utils/hash.js";
3332
import { parseStreamingJson } from "../utils/json-parse.js";
33+
import { projectProviderError } from "../utils/provider-error.js";
3434
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
3535
import { createSseByteGuard } from "../utils/streaming-byte-guard.js";
3636
import { stripSystemPromptCacheBoundary } from "../utils/system-prompt-cache-boundary.js";
@@ -43,7 +43,6 @@ import {
4343
import { transformMessages } from "./transform-messages.js";
4444

4545
const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
46-
const MAX_MISTRAL_ERROR_BODY_CHARS = 4000;
4746

4847
// 16 MiB cap on Mistral streaming success bodies, matching the
4948
// `PROVIDER_TEXT_RESPONSE_MAX_BYTES` / `PROVIDER_JSON_RESPONSE_MAX_BYTES`
@@ -194,9 +193,9 @@ export const streamMistral: StreamFunction<"mistral-conversations", MistralOptio
194193
} catch (error) {
195194
// Failed or canceled generations must never retain partially repaired tool calls.
196195
output.content = output.content.filter((block) => block.type !== "toolCall");
197-
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
198-
output.errorMessage = formatMistralError(error);
199-
stream.push({ type: "error", reason: output.stopReason, error: output });
196+
const terminal = projectProviderError(error, options?.signal);
197+
Object.assign(output, terminal);
198+
stream.push({ type: "error", reason: terminal.stopReason, error: output });
200199
stream.end();
201200
}
202201
})();
@@ -294,39 +293,6 @@ function deriveMistralToolCallId(id: string, attempt: number): string {
294293
.slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);
295294
}
296295

297-
function formatMistralError(error: unknown): string {
298-
if (error instanceof Error) {
299-
const sdkError = error as Error & { statusCode?: unknown; body?: unknown };
300-
const statusCode = typeof sdkError.statusCode === "number" ? sdkError.statusCode : undefined;
301-
const bodyText = typeof sdkError.body === "string" ? sdkError.body.trim() : undefined;
302-
if (statusCode !== undefined && bodyText) {
303-
return `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;
304-
}
305-
if (statusCode !== undefined) {
306-
return `Mistral API error (${statusCode}): ${error.message}`;
307-
}
308-
return error.message;
309-
}
310-
return safeJsonStringify(error);
311-
}
312-
313-
function truncateErrorText(text: string, maxChars: number): string {
314-
if (text.length <= maxChars) {
315-
return text;
316-
}
317-
const truncated = truncateUtf16Safe(text, maxChars);
318-
return `${truncated}... [truncated ${text.length - truncated.length} chars]`;
319-
}
320-
321-
function safeJsonStringify(value: unknown): string {
322-
try {
323-
const serialized = JSON.stringify(value);
324-
return serialized === undefined ? String(value) : serialized;
325-
} catch {
326-
return String(value);
327-
}
328-
}
329-
330296
function buildChatPayload(
331297
model: Model<"mistral-conversations">,
332298
context: Context,

‎packages/ai/src/providers/openai-chatgpt-responses.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import {
6868
import { AssistantMessageEventStream } from "../utils/event-stream.js";
6969
import { headersToRecord } from "../utils/headers.js";
7070
import { resolveOpenAICodexAccountId } from "../utils/oauth/openai-chatgpt-jwt.js";
71+
import { projectProviderError } from "../utils/provider-error.js";
7172
import {
7273
createFirstStreamEventAbortController,
7374
getFirstStreamEventTimeoutHandler,
@@ -588,10 +589,9 @@ export const streamOpenAICodexResponses: StreamFunction<
588589
// partialJson is only a streaming scratch buffer; never persist it.
589590
delete (block as { partialJson?: string }).partialJson;
590591
}
591-
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
592-
output.errorMessage =
593-
normalizedError instanceof Error ? normalizedError.message : String(normalizedError);
594-
stream.push({ type: "error", reason: output.stopReason, error: output });
592+
const terminal = projectProviderError(normalizedError, options?.signal);
593+
Object.assign(output, terminal);
594+
stream.push({ type: "error", reason: terminal.stopReason, error: output });
595595
stream.end();
596596
} finally {
597597
firstEventAbort?.dispose();

‎packages/ai/src/providers/openai-completions.compat.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,4 +913,25 @@ describe("OpenAI-compatible completions compatibility", () => {
913913

914914
expect(result.errorMessage).toBe("502: gateway maintenance");
915915
});
916+
917+
it("redacts OpenRouter terminal body and raw metadata from one error projection", async () => {
918+
const media = "QUJDRA==";
919+
mockOpenAI.nextError = Object.assign(new Error("400 status code (no body)"), {
920+
status: 400,
921+
body: { data: [{ b64_json: media }] },
922+
error: {
923+
code: "bad_image",
924+
type: "invalid_request_error",
925+
metadata: { raw: `render failed data:image/png;base64,${media}` },
926+
},
927+
});
928+
929+
const result = await streamOpenAICompletions(baseModel, context, { apiKey: "test" }).result();
930+
931+
expect(result).toMatchObject({
932+
errorCode: "bad_image",
933+
errorType: "invalid_request_error",
934+
});
935+
expect(JSON.stringify(result)).not.toContain(media);
936+
});
916937
});

0 commit comments

Comments
 (0)