Skip to content

Commit c853f36

Browse files
fix(web): redact request credentials from provider errors
Bind bounded error diagnostics to the actual outgoing request headers for shared web tools and both Perplexity transports. Preserve caller cancellation and replace case-insensitive owned headers without combining credentials. Reuse the provider error redactor and remove duplicate xAI parser-only test paths while retaining real HTTP and sibling coverage. Production -18 lines; total -14 lines including regression tests and documentation. Refs #120200, #117304, #119536. Co-authored-by: zenglingbiao <[email protected]>
1 parent c1c6e97 commit c853f36

12 files changed

Lines changed: 196 additions & 210 deletions

‎docs/tools/web.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,10 @@ payload carrying an `error` key is always reported as `kind: "error"` with the
205205
raw provider code preserved inside the wrapped message. Raw passthrough
206206
payloads keep whatever markers the provider set.
207207

208+
Perplexity, Tavily, and xAI HTTP errors retain the status code and bounded
209+
diagnostics, with reflected request credentials redacted. Review diagnostics
210+
before sharing them; redaction does not remove every kind of sensitive content.
211+
208212
## Auto-detection
209213

210214
Provider lists in docs and setup flows are alphabetical. Auto-detection uses a

‎extensions/perplexity/src/perplexity-web-search-provider.runtime.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -234,20 +234,24 @@ async function runPerplexitySearchApi(params: {
234234
body.max_tokens_per_page = params.maxTokensPerPage;
235235
}
236236

237+
const headers = buildPerplexityRequestHeaders(params.apiKey, true);
237238
return withTrustedWebSearchEndpoint(
238239
{
239240
url: PERPLEXITY_SEARCH_ENDPOINT,
240241
timeoutSeconds: params.timeoutSeconds,
241242
signal: params.signal,
242243
init: {
243244
method: "POST",
244-
headers: buildPerplexityRequestHeaders(params.apiKey, true),
245+
headers,
245246
body: JSON.stringify(body),
246247
},
247248
},
248249
async (res) => {
249250
if (!res.ok) {
250-
return await throwWebSearchApiError(res, "Perplexity Search");
251+
return await throwWebSearchApiError(res, "Perplexity Search", {
252+
headers,
253+
signal: params.signal,
254+
});
251255
}
252256
const data = await readProviderJsonResponse<PerplexitySearchApiResponse>(
253257
res,
@@ -282,20 +286,21 @@ async function runPerplexitySearch(params: {
282286
body.search_recency_filter = params.freshness;
283287
}
284288

289+
const headers = buildPerplexityRequestHeaders(params.apiKey);
285290
return withTrustedWebSearchEndpoint(
286291
{
287292
url: endpoint,
288293
timeoutSeconds: params.timeoutSeconds,
289294
signal: params.signal,
290295
init: {
291296
method: "POST",
292-
headers: buildPerplexityRequestHeaders(params.apiKey),
297+
headers,
293298
body: JSON.stringify(body),
294299
},
295300
},
296301
async (res) => {
297302
if (!res.ok) {
298-
return await throwWebSearchApiError(res, "Perplexity");
303+
return await throwWebSearchApiError(res, "Perplexity", { headers, signal: params.signal });
299304
}
300305
const data = await readProviderJsonResponse<PerplexitySearchResponse>(res, "Perplexity");
301306
const content = data.choices?.[0]?.message?.content;

‎extensions/perplexity/src/perplexity-web-search-provider.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ function mockPerplexityResponseOnce(body: unknown): void {
3333
);
3434
}
3535

36-
function createConfiguredPerplexityTool(structured: boolean) {
36+
function createConfiguredPerplexityTool(structured: boolean, apiKey = directPerplexityApiKey) {
3737
const webSearch = {
38-
apiKey: directPerplexityApiKey,
38+
apiKey,
3939
...(structured ? {} : { baseUrl: "https://api.perplexity.ai" }),
4040
};
4141
const tool = createPerplexityWebSearchProvider().createTool({
@@ -49,6 +49,21 @@ function createConfiguredPerplexityTool(structured: boolean) {
4949
}
5050

5151
describe("perplexity web search provider", () => {
52+
it.each([true, false])(
53+
"redacts reflected request credentials (native=%s)",
54+
async (structured) => {
55+
withTrustedWebSearchEndpointMock.mockReset();
56+
withTrustedWebSearchEndpointMock.mockImplementationOnce(
57+
async (_params: unknown, run: (response: Response) => Promise<unknown>) =>
58+
run(new Response("rejected s7Key", { status: 401 })),
59+
);
60+
const label = structured ? "Perplexity Search" : "Perplexity";
61+
await expect(
62+
createConfiguredPerplexityTool(structured, "s7Key").execute({ query: "redaction" }),
63+
).rejects.toThrow(`${label} API error (401): rejected ***`);
64+
},
65+
);
66+
5267
it("points missing-key users to fetch/browser alternatives", async () => {
5368
await withEnvAsync(
5469
{ [perplexityApiKeyEnv]: undefined, [openRouterApiKeyEnv]: undefined },

‎extensions/xai/code-execution.test.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,7 @@ function firstFetchInit(mockFetch: ReturnType<typeof installCodeExecutionFetch>)
6767
}
6868

6969
function firstAuthorizationHeader(mockFetch: ReturnType<typeof installCodeExecutionFetch>) {
70-
const headers = firstFetchInit(mockFetch).headers;
71-
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
72-
throw new Error("expected code_execution request headers");
73-
}
74-
return (headers as Record<string, string>).Authorization;
70+
return new Headers(firstFetchInit(mockFetch).headers).get("Authorization");
7571
}
7672

7773
function parseFirstRequestBody(mockFetch: ReturnType<typeof installCodeExecutionFetch>) {

‎extensions/xai/src/responses-tool-shared.test.ts‎

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Xai tests cover responses tool shared plugin behavior.
22
import { describe, expect, it } from "vitest";
33
import {
4-
extractXaiWebSearchContent,
54
requireXaiResponseTextAndCitations,
65
requireXaiResponseTextCitationsAndInline,
76
} from "./responses-tool-shared.js";
@@ -77,30 +76,33 @@ describe("xai responses tool helpers", () => {
7776

7877
it("ignores malformed output, content, and annotation entries", () => {
7978
expect(
80-
extractXaiWebSearchContent({
81-
output: [
82-
null,
83-
{
84-
type: "message",
85-
content: [
86-
null,
87-
{
88-
type: "output_text",
89-
text: "Found it",
90-
annotations: [
91-
null,
92-
{ type: "url_citation", url: "https://example.com/a" },
93-
{ type: "url_citation", url: "https://example.com/a" },
94-
{ type: "url_citation" },
95-
],
96-
},
97-
],
98-
},
99-
],
100-
}),
79+
requireXaiResponseTextAndCitations(
80+
{
81+
output: [
82+
null,
83+
{
84+
type: "message",
85+
content: [
86+
null,
87+
{
88+
type: "output_text",
89+
text: "Found it",
90+
annotations: [
91+
null,
92+
{ type: "url_citation", url: "https://example.com/a" },
93+
{ type: "url_citation", url: "https://example.com/a" },
94+
{ type: "url_citation" },
95+
],
96+
},
97+
],
98+
},
99+
],
100+
},
101+
"xAI tool failed",
102+
),
101103
).toEqual({
102-
text: "Found it",
103-
annotationCitations: ["https://example.com/a"],
104+
content: "Found it",
105+
citations: ["https://example.com/a"],
104106
});
105107
});
106108

‎extensions/xai/src/responses-tool-shared.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export async function requestXaiResponsesTool<T>(
9898
);
9999
}
100100

101-
export function extractXaiWebSearchContent(
101+
function extractXaiWebSearchContent(
102102
data: XaiWebSearchResponse,
103103
maxContentChars?: number,
104104
): {

‎extensions/xai/src/web-search-provider.runtime.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import {
2525
} from "openclaw/plugin-sdk/provider-web-search";
2626
import {
2727
buildXaiWebSearchPayload,
28-
extractXaiWebSearchContent,
2928
requestXaiWebSearch,
3029
resolveXaiInlineCitations,
3130
resolveXaiWebSearchEndpoint,
@@ -423,7 +422,6 @@ export async function executeXaiWebSearchProviderTool(
423422

424423
export const testing = {
425424
buildXaiWebSearchPayload,
426-
extractXaiWebSearchContent,
427425
resolveXaiToolSearchConfig,
428426
resolveXaiInlineCitations,
429427
resolveXaiWebSearchCredential,

‎extensions/xai/src/web-search-shared.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import {
99
resolveXaiResponsesEndpoint,
1010
} from "./responses-tool-shared.js";
1111
import type { XaiWebSearchResponse } from "./web-search-response.types.js";
12-
export { extractXaiWebSearchContent } from "./responses-tool-shared.js";
1312
export type { XaiWebSearchResponse } from "./web-search-response.types.js";
1413

1514
const XAI_DEFAULT_WEB_SEARCH_MODEL = XAI_DEFAULT_MODEL_ID;

‎extensions/xai/web-search.test.ts‎

Lines changed: 0 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -39,45 +39,7 @@ vi.mock("openclaw/plugin-sdk/provider-auth-runtime", async (importOriginal) => {
3939
};
4040
});
4141

42-
vi.mock("openclaw/plugin-sdk/provider-web-search", async (importOriginal) => {
43-
const original = await importOriginal<typeof import("openclaw/plugin-sdk/provider-web-search")>();
44-
return {
45-
...original,
46-
postTrustedWebToolsJson: async (
47-
params: {
48-
url: string;
49-
apiKey: string;
50-
body: Record<string, unknown>;
51-
extraHeaders?: Record<string, string>;
52-
signal?: AbortSignal;
53-
},
54-
parseResponse: (response: Response) => Promise<unknown>,
55-
) => {
56-
const response = await globalThis.fetch(params.url, {
57-
method: "POST",
58-
headers: {
59-
...params.extraHeaders,
60-
Accept: "application/json",
61-
Authorization: `Bearer ${params.apiKey}`,
62-
"Content-Type": "application/json",
63-
},
64-
body: JSON.stringify(params.body),
65-
...(params.signal ? { signal: params.signal } : {}),
66-
});
67-
if (!response.ok) {
68-
const detail =
69-
typeof response.text === "function"
70-
? await response.text()
71-
: response.statusText || String(response.status);
72-
throw new Error(`xAI API error (${response.status}): ${detail || response.statusText}`);
73-
}
74-
return await parseResponse(response);
75-
},
76-
};
77-
});
78-
7942
const {
80-
extractXaiWebSearchContent,
8143
resolveXaiInlineCitations,
8244
resolveXaiToolSearchConfig,
8345
resolveXaiWebSearchCredential,
@@ -879,71 +841,6 @@ describe("xai web search config resolution", () => {
879841
});
880842
});
881843

882-
describe("xai web search response parsing", () => {
883-
it("extracts content from Responses API message blocks", () => {
884-
const result = extractXaiWebSearchContent({
885-
output: [
886-
{
887-
type: "message",
888-
content: [{ type: "output_text", text: "hello from output" }],
889-
},
890-
],
891-
});
892-
expect(result.text).toBe("hello from output");
893-
expect(result.annotationCitations).toStrictEqual([]);
894-
});
895-
896-
it("extracts url_citation annotations from content blocks", () => {
897-
const result = extractXaiWebSearchContent({
898-
output: [
899-
{
900-
type: "message",
901-
content: [
902-
{
903-
type: "output_text",
904-
text: "hello with citations",
905-
annotations: [
906-
{ type: "url_citation", url: "https://example.com/a" },
907-
{ type: "url_citation", url: "https://example.com/b" },
908-
{ type: "url_citation", url: "https://example.com/a" },
909-
],
910-
},
911-
],
912-
},
913-
],
914-
});
915-
expect(result.text).toBe("hello with citations");
916-
expect(result.annotationCitations).toEqual(["https://example.com/a", "https://example.com/b"]);
917-
});
918-
919-
it("falls back to deprecated output_text", () => {
920-
const result = extractXaiWebSearchContent({ output_text: "hello from output_text" });
921-
expect(result.text).toBe("hello from output_text");
922-
expect(result.annotationCitations).toStrictEqual([]);
923-
});
924-
925-
it("returns undefined text when no content found", () => {
926-
const result = extractXaiWebSearchContent({});
927-
expect(result.text).toBeUndefined();
928-
expect(result.annotationCitations).toStrictEqual([]);
929-
});
930-
931-
it("extracts output_text blocks directly in output array", () => {
932-
const result = extractXaiWebSearchContent({
933-
output: [
934-
{ type: "web_search_call" },
935-
{
936-
type: "output_text",
937-
text: "direct output text",
938-
annotations: [{ type: "url_citation", url: "https://example.com/direct" }],
939-
},
940-
],
941-
});
942-
expect(result.text).toBe("direct output text");
943-
expect(result.annotationCitations).toEqual(["https://example.com/direct"]);
944-
});
945-
});
946-
947844
describe("xai provider models", () => {
948845
it("publishes only current selectable chat models newest first", () => {
949846
expect(buildXaiCatalogModels().map((model) => model.id)).toEqual([

‎extensions/xai/x-search.test.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,7 @@ function firstFetchInit(mockFetch: ReturnType<typeof installXSearchFetch>): Requ
6161
}
6262

6363
function firstAuthorizationHeader(mockFetch: ReturnType<typeof installXSearchFetch>) {
64-
const headers = firstFetchInit(mockFetch).headers;
65-
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
66-
throw new Error("expected x_search request headers");
67-
}
68-
return (headers as Record<string, string>).Authorization;
64+
return new Headers(firstFetchInit(mockFetch).headers).get("Authorization");
6965
}
7066

7167
function parseFirstRequestBody(mockFetch: ReturnType<typeof installXSearchFetch>) {

0 commit comments

Comments
 (0)