|
| 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