Skip to content

Commit 8b21c23

Browse files
authored
feat(web-fetch): add tools.web.fetch.headers for operator request headers (#115545)
* feat(web-fetch): add tools.web.fetch.headers for operator request headers * docs(web-fetch): update cache discriminator comment * fix(web-fetch): reserve runtime and cookie headers * fix(web-fetch): harden operator header normalization * fix(web-fetch): align header safety contracts * fix(web-fetch): close header logging gaps * fix(web-fetch): report case-colliding headers * fix(web-fetch): reject stale colliding headers * fix(web-fetch): refuse credential token aliases * fix(web-fetch): preserve empty header values * fix(web-fetch): refuse credential-shaped headers * chore(config): refresh web fetch header baselines * test(web-fetch): cover header security contracts * fix(web-fetch): narrow credential header refusal * fix(web-fetch): preserve trace metadata headers * fix(web-fetch): keep header validation internal * test(web-fetch): satisfy strict test contracts * fix(web-fetch): refuse vendor credential headers * fix(web-fetch): refuse authentication signatures * fix(web-fetch): detect qualified auth signatures * fix(web-fetch): refuse auth-suffixed headers * fix(web-fetch): refuse compact credential headers * fix(secrets): audit authentication signatures * fix(web-fetch): redact operator headers in captures * fix(web-fetch): keep capture metadata internal * fix(web-fetch): allow sensitive operator headers * test(web-fetch): cover normalized operator headers * docs: note web fetch request headers * chore(config): refresh web fetch header baseline * chore: remove release-owned changelog entry
1 parent fa8774c commit 8b21c23

18 files changed

Lines changed: 624 additions & 12 deletions
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"core": 2307,
2+
"core": 2309,
33
"channel": 3692,
44
"plugin": 4057
55
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
6b02737084409d3a0c92611049077284826bafbe29e7227b3eda591ead80c2e3 config-baseline.json
2-
b89715475e4b18a0d32765fda42bcce38537f6d49f949bb4ff0c7d1630101882 config-baseline.core.json
1+
f1b338718b9a058fc3b472a2004c15d146aa83303804c76f7ea831ed3f5593b8 config-baseline.json
2+
063a781ea045218fcf4f8ddc7df152b89eaf9a2ab8ed8049cafce75301425a3a config-baseline.core.json
33
e9a81ee89ff032033012413e161316e4d07e8f6b206382a25fed2f8485151b5e config-baseline.channel.json
44
c097c0bee74849e691bf295b070ce189d4e0e501bd770e448922d9f399c4901f config-baseline.plugin.json

‎docs/tools/web-fetch.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ progress line is channel UI state only and never contains fetched page content.
101101
useTrustedEnvProxy: false, // let a trusted HTTP(S) env proxy resolve DNS
102102
readability: true, // use Readability extraction
103103
userAgent: "Mozilla/5.0 ...", // override User-Agent
104+
headers: {
105+
// optional; every value is treated as sensitive
106+
"X-Routing-Target": "staging",
107+
},
104108
ssrfPolicy: {
105109
allowRfc2544BenchmarkRange: true, // opt-in for trusted fake-IP proxies using 198.18.0.0/15
106110
allowIpv6UniqueLocalRange: true, // opt-in for trusted fake-IP proxies using fc00::/7
@@ -173,6 +177,63 @@ Current runtime behavior:
173177
- If Readability is disabled, `web_fetch` skips straight to the selected
174178
provider fallback. If no provider is available, it fails closed.
175179

180+
## Custom request headers
181+
182+
Set `tools.web.fetch.headers` when your deployment needs extra request metadata on
183+
outbound fetches, such as a routing or service-injection header that steers traffic
184+
to a gateway you control.
185+
186+
```json5
187+
{
188+
tools: {
189+
web: {
190+
fetch: {
191+
headers: {
192+
"X-Routing-Target": "${WEB_FETCH_ROUTING_TARGET}",
193+
},
194+
},
195+
},
196+
},
197+
}
198+
```
199+
200+
<Warning>
201+
Every configured value is treated as sensitive and redacted from exposed config
202+
and debug captures. The headers are still sent to every initial URL `web_fetch`
203+
requests, and the model chooses that URL. Configure credential headers only when
204+
that is the intended trust boundary.
205+
</Warning>
206+
207+
Behavior worth knowing:
208+
209+
- Values are plain strings and support `${VAR}` environment substitution like any
210+
other config string. Structured SecretRef values are not accepted.
211+
- Headers apply only to the direct `web_fetch` request. Provider fallbacks such as
212+
[Firecrawl](/tools/firecrawl) call their own API and never receive these headers.
213+
- Entries are validated when the request is built, not at config load, so one bad
214+
entry is dropped while the rest still apply. Config load stays permissive on
215+
purpose: a fail-closed validation error over a single header-name typo would
216+
disable the whole surface. Every dropped entry is logged by name.
217+
- Dropped names:
218+
- `Accept`, `Accept-Language`, and `User-Agent` belong to the fetch and
219+
readability contract. Use `tools.web.fetch.userAgent` for the user agent.
220+
- Framing and hop-by-hop names such as `Content-Length`, `Transfer-Encoding`,
221+
`Connection`, and `Upgrade`, which a request either rejects outright or ignores.
222+
- Names that are not valid HTTP tokens, such as `"X Routing Target"`.
223+
- Dropped values: bytes a request cannot carry (CR, LF, NUL, or any character above
224+
`U+00FF`). Missing environment variables are reported by config loading; the global
225+
`$${VAR}` escape remains available when the literal `${VAR}` text is intentional.
226+
- Two entries whose names differ only in case collapse to the later entry, so a
227+
request never carries a comma-joined value the receiving gateway cannot parse.
228+
The dropped name is logged without either value. If the later entry is unusable,
229+
neither value is sent.
230+
- Rejection happens before the cache key is computed, so the key always matches the
231+
bytes actually sent: changing a header that is really sent partitions the fetch
232+
cache, while adding one that gets dropped does not.
233+
- When a redirect crosses origins, the guarded-fetch safe allowlist is applied.
234+
Routing headers outside that list are dropped; standard safe headers such as
235+
`Cache-Control`, `Content-Type`, and `Range` are preserved.
236+
176237
## Trusted env proxy
177238

178239
If your deployment requires `web_fetch` to go through a trusted outbound
@@ -200,6 +261,9 @@ outbound policy after DNS resolution.
200261
for trusted fake-IP proxy stacks; leave them unset unless your proxy owns
201262
those synthetic ranges and enforces its own destination policy
202263
- Redirects are checked and limited by `maxRedirects` (default `3`)
264+
- `tools.web.fetch.headers` values are redacted from exposed config and debug
265+
captures, sent to the initial fetched host, and retained on redirects only when
266+
the existing guarded-fetch policy allows them
203267
- `useTrustedEnvProxy` is an explicit opt-in and should only be enabled for
204268
operator-controlled proxies that still enforce outbound policy after DNS
205269
resolution
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// tools.web.fetch.headers tests cover operator header delivery, transport
2+
// constraints, sensitive capture metadata, and cache partitioning.
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { LookupFn } from "../../infra/net/ssrf.js";
5+
import * as logger from "../../logger.js";
6+
import { withFetchPreconnect } from "../../test-utils/fetch-mock.js";
7+
import "./web-fetch.test-mocks.js";
8+
import { createWebFetchTool } from "./web-fetch.js";
9+
import * as webGuardedFetch from "./web-guarded-fetch.js";
10+
11+
const lookupMock = vi.fn();
12+
13+
function markdownResponse(body: string): Response {
14+
return new Response(body, {
15+
status: 200,
16+
headers: { "content-type": "text/markdown; charset=utf-8" },
17+
});
18+
}
19+
20+
function createToolWithHeaders(
21+
headers: Record<string, string>,
22+
opts?: { cacheTtlMinutes?: number },
23+
): ReturnType<typeof createWebFetchTool> {
24+
return createWebFetchTool({
25+
lookupFn: lookupMock as unknown as LookupFn,
26+
config: {
27+
tools: {
28+
web: {
29+
fetch: { cacheTtlMinutes: opts?.cacheTtlMinutes ?? 0, headers },
30+
},
31+
},
32+
},
33+
});
34+
}
35+
36+
function getRequestHeaders(
37+
fetchSpy: ReturnType<typeof vi.fn>,
38+
callIndex = 0,
39+
): Record<string, string> {
40+
const call = fetchSpy.mock.calls[callIndex];
41+
if (!call) {
42+
throw new Error(`expected fetch call at index ${callIndex}`);
43+
}
44+
return (call[1] as { headers?: Record<string, string> } | undefined)?.headers ?? {};
45+
}
46+
47+
describe("web_fetch configured request headers", () => {
48+
const priorFetch = global.fetch;
49+
50+
beforeEach(() => {
51+
lookupMock.mockImplementation(async (hostname: string) => {
52+
void hostname;
53+
return [{ address: "93.184.216.34", family: 4 }];
54+
});
55+
});
56+
57+
afterEach(() => {
58+
global.fetch = priorFetch;
59+
lookupMock.mockReset();
60+
vi.restoreAllMocks();
61+
});
62+
63+
it("sends configured headers with the direct fetch request", async () => {
64+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Routed"));
65+
global.fetch = withFetchPreconnect(fetchSpy);
66+
const fetchWithRealGuard = webGuardedFetch.fetchWithWebToolsNetworkGuard;
67+
const guardedFetchSpy = vi
68+
.spyOn(webGuardedFetch, "fetchWithWebToolsNetworkGuard")
69+
.mockImplementation((params) => fetchWithRealGuard(params));
70+
71+
const tool = createToolWithHeaders({
72+
"ATL-SG-SERVICE-INJECTION-URL": "http://host.docker.internal:9999",
73+
Authorization: "Bearer deployment-token",
74+
Cookie: "session=deployment-session",
75+
"X-Api-Key": "deployment-api-key",
76+
"X-Tokenizer-Version": "v2",
77+
"X-Trace-Token": "trace-context",
78+
});
79+
80+
await tool?.execute?.("call", { url: "https://example.com/routed" });
81+
82+
expect(getRequestHeaders(fetchSpy)["ATL-SG-SERVICE-INJECTION-URL"]).toBe(
83+
"http://host.docker.internal:9999",
84+
);
85+
expect(getRequestHeaders(fetchSpy).Authorization).toBe("Bearer deployment-token");
86+
expect(getRequestHeaders(fetchSpy).Cookie).toBe("session=deployment-session");
87+
expect(getRequestHeaders(fetchSpy)["X-Api-Key"]).toBe("deployment-api-key");
88+
expect(getRequestHeaders(fetchSpy)["X-Tokenizer-Version"]).toBe("v2");
89+
expect(getRequestHeaders(fetchSpy)["X-Trace-Token"]).toBe("trace-context");
90+
const captureMeta = guardedFetchSpy.mock.calls[0]?.[0].capture;
91+
expect(captureMeta === false ? undefined : captureMeta?.sensitiveRequestHeaderNames).toEqual([
92+
"ATL-SG-SERVICE-INJECTION-URL",
93+
"Authorization",
94+
"Cookie",
95+
"X-Api-Key",
96+
"X-Tokenizer-Version",
97+
"X-Trace-Token",
98+
]);
99+
});
100+
101+
it("refuses fetch-owned and framing headers", async () => {
102+
// Upgrade/Expect/Keep-Alive/Transfer-Encoding make fetch throw, so letting one
103+
// through would break every web_fetch call.
104+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Connection"));
105+
global.fetch = withFetchPreconnect(fetchSpy);
106+
107+
const tool = createToolWithHeaders({
108+
accept: "text/plain",
109+
"user-agent": "operator-agent/1.0",
110+
"Accept-Language": "de-DE",
111+
"Sec-Fetch-Mode": "same-origin",
112+
Upgrade: "h2c",
113+
Expect: "100-continue",
114+
"Keep-Alive": "timeout=5",
115+
"Transfer-Encoding": "chunked",
116+
Host: "elsewhere.example",
117+
Connection: "close",
118+
"Content-Length": "0",
119+
"X-Routing-Target": "staging",
120+
});
121+
122+
const result = await tool?.execute?.("call", { url: "https://example.com/connection" });
123+
124+
expect((result?.details as { status?: number } | undefined)?.status).toBe(200);
125+
expect(Object.keys(getRequestHeaders(fetchSpy))).toEqual([
126+
"Accept",
127+
"User-Agent",
128+
"Accept-Language",
129+
"X-Routing-Target",
130+
]);
131+
});
132+
133+
it("normalizes empty values without retaining a stale case-colliding value", async () => {
134+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Normalized"));
135+
global.fetch = withFetchPreconnect(fetchSpy);
136+
137+
const tool = createToolWithHeaders({
138+
"X-Presence-Flag": " \t ",
139+
"X-Routing-Target": "staging",
140+
"x-routing-target": "東京",
141+
});
142+
143+
await tool?.execute?.("call", { url: "https://example.com/normalized" });
144+
145+
const headers = getRequestHeaders(fetchSpy);
146+
expect(headers["X-Presence-Flag"]).toBe("");
147+
expect(headers["X-Routing-Target"]).toBeUndefined();
148+
expect(headers["x-routing-target"]).toBeUndefined();
149+
});
150+
151+
it("still fetches when every configured header is unusable, naming it in a warning", async () => {
152+
// The whole request must not fail because one config value is unsendable.
153+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Survives"));
154+
global.fetch = withFetchPreconnect(fetchSpy);
155+
const warnSpy = vi.spyOn(logger, "logWarn").mockImplementation(() => {});
156+
157+
const invalidName = "X-Bad\n[forged]\u001b[31m";
158+
const tool = createToolWithHeaders({
159+
"X-Survives-Unicode": "東京",
160+
[invalidName]: "ignored",
161+
});
162+
163+
const result = await tool?.execute?.("call", { url: "https://example.com/survives" });
164+
165+
expect(fetchSpy).toHaveBeenCalledTimes(1);
166+
expect((result?.details as { status?: number } | undefined)?.status).toBe(200);
167+
const warned = warnSpy.mock.calls
168+
.map(([message]) => message)
169+
.filter((message) => message.includes("X-Survives-Unicode"));
170+
expect(warned).toHaveLength(1);
171+
// Names are safe to log; values are not.
172+
expect(warned[0]).not.toContain("東京");
173+
const invalidNameWarning = warnSpy.mock.calls
174+
.map(([message]) => message)
175+
.find((message) => message.includes("X-Bad"));
176+
expect(invalidNameWarning).toContain(JSON.stringify(invalidName));
177+
expect(invalidNameWarning).not.toContain("\n");
178+
expect(invalidNameWarning).not.toContain("\u001b");
179+
});
180+
181+
it("partitions the fetch cache by configured headers", async () => {
182+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Cached"));
183+
global.fetch = withFetchPreconnect(fetchSpy);
184+
const url = "https://example.com/cache-partition";
185+
186+
await createToolWithHeaders(
187+
{ "ATL-SG-SERVICE-INJECTION-URL": "http://host.docker.internal:9999" },
188+
{ cacheTtlMinutes: 15 },
189+
)?.execute?.("call", { url });
190+
await createToolWithHeaders(
191+
{ "ATL-SG-SERVICE-INJECTION-URL": "http://host.docker.internal:8888" },
192+
{ cacheTtlMinutes: 15 },
193+
)?.execute?.("call", { url });
194+
// Same header set must still hit the cache written by the first call.
195+
await createToolWithHeaders(
196+
{ "ATL-SG-SERVICE-INJECTION-URL": "http://host.docker.internal:9999" },
197+
{ cacheTtlMinutes: 15 },
198+
)?.execute?.("call", { url });
199+
200+
expect(fetchSpy).toHaveBeenCalledTimes(2);
201+
expect(getRequestHeaders(fetchSpy, 1)["ATL-SG-SERVICE-INJECTION-URL"]).toBe(
202+
"http://host.docker.internal:8888",
203+
);
204+
});
205+
206+
it("does not partition the cache for headers the request never carries", async () => {
207+
const fetchSpy = vi.fn().mockResolvedValue(markdownResponse("# Unpartitioned"));
208+
global.fetch = withFetchPreconnect(fetchSpy);
209+
const url = "https://example.com/cache-unpartitioned";
210+
211+
const plain = createWebFetchTool({
212+
lookupFn: lookupMock as unknown as LookupFn,
213+
config: { tools: { web: { fetch: { cacheTtlMinutes: 15 } } } },
214+
});
215+
await plain?.execute?.("call", { url });
216+
// A refused or dropped header sends a byte-identical request, so both must
217+
// share the entry: rejection happens before the cache key is computed.
218+
await createToolWithHeaders({ accept: "text/plain" }, { cacheTtlMinutes: 15 })?.execute?.(
219+
"call",
220+
{ url },
221+
);
222+
await createToolWithHeaders(
223+
{ "X Invalid Name": "dropped", "Transfer-Encoding": "chunked" },
224+
{ cacheTtlMinutes: 15 },
225+
)?.execute?.("call", { url });
226+
227+
expect(fetchSpy).toHaveBeenCalledTimes(1);
228+
});
229+
});

0 commit comments

Comments
 (0)