Skip to content

Commit 9ed4480

Browse files
xing-xing-coderobviyus
authored andcommitted
fix(web-fetch): finalize RFC2544 SSRF policy support
1 parent ce32697 commit 9ed4480

9 files changed

Lines changed: 116 additions & 9 deletions

File tree

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
0a75b57f5dbb0bb1488eacb47111ee22ff42dd3747bfe07bb69c9445d5e55c3e config-baseline.json
2-
ff15bb8b4231fc80174249ae89bcb61439d7adda5ee6be95e4d304680253a59f config-baseline.core.json
1+
2595f0a5abe45b5066e722843d339afdadb6ff8a108893e1a2183cd835f591cc config-baseline.json
2+
3c8455d44a63d495ad295d2c9d76fed7a190b80344dabaa0e78ba433bf2d253b config-baseline.core.json
33
7f42b22b46c487d64aaac46001ba9d9096cf7bf0b1c263a54d39946303ff5018 config-baseline.channel.json
44
483d4f3c1d516719870ad6f2aba6779b9950f85471ee77b9994a077a7574a892 config-baseline.plugin.json

‎src/agents/tools/web-fetch.ssrf.test.ts‎

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2-
import type { LookupFn } from "../../infra/net/ssrf.js";
2+
import * as ssrf from "../../infra/net/ssrf.js";
33
import { type FetchMock, withFetchPreconnect } from "../../test-utils/fetch-mock.js";
44
import { makeFetchHeaders } from "./web-fetch.test-harness.js";
55
import "./web-fetch.test-mocks.js";
66

77
const lookupMock = vi.fn();
8+
const resolvePinnedHostname = ssrf.resolvePinnedHostname;
89

910
function redirectResponse(location: string): Response {
1011
return {
@@ -32,7 +33,11 @@ function setMockFetch(
3233
return fetchSpy;
3334
}
3435

35-
async function createWebFetchToolForTest(params?: { firecrawlApiKey?: string }) {
36+
async function createWebFetchToolForTest(params?: {
37+
firecrawlApiKey?: string;
38+
ssrfPolicy?: { allowRfc2544BenchmarkRange?: boolean };
39+
cacheTtlMinutes?: number;
40+
}) {
3641
const { createWebFetchTool } = await import("./web-tools.js");
3742
return createWebFetchTool({
3843
config: {
@@ -52,13 +57,14 @@ async function createWebFetchToolForTest(params?: { firecrawlApiKey?: string })
5257
tools: {
5358
web: {
5459
fetch: {
55-
cacheTtlMinutes: 0,
60+
cacheTtlMinutes: params?.cacheTtlMinutes ?? 0,
61+
ssrfPolicy: params?.ssrfPolicy,
5662
...(params?.firecrawlApiKey ? { provider: "firecrawl" } : {}),
5763
},
5864
},
5965
},
6066
},
61-
lookupFn: lookupMock as unknown as LookupFn,
67+
lookupFn: lookupMock,
6268
});
6369
}
6470

@@ -74,13 +80,15 @@ describe("web_fetch SSRF protection", () => {
7480
const priorFetch = global.fetch;
7581

7682
beforeEach(() => {
77-
vi.stubEnv("FIRECRAWL_API_KEY", "");
83+
vi.spyOn(ssrf, "resolvePinnedHostname").mockImplementation((hostname) =>
84+
resolvePinnedHostname(hostname, lookupMock),
85+
);
7886
});
7987

8088
afterEach(() => {
8189
global.fetch = priorFetch;
8290
lookupMock.mockClear();
83-
vi.unstubAllEnvs();
91+
vi.restoreAllMocks();
8492
});
8593

8694
it("blocks localhost hostnames before fetch/firecrawl", async () => {
@@ -147,4 +155,31 @@ describe("web_fetch SSRF protection", () => {
147155
extractor: "raw",
148156
});
149157
});
158+
159+
it("allows RFC2544 benchmark-range URLs only when web_fetch ssrfPolicy opts in", async () => {
160+
const url = "http://198.18.0.153/file";
161+
lookupMock.mockResolvedValue([{ address: "198.18.0.153", family: 4 }]);
162+
163+
const deniedTool = await createWebFetchToolForTest({ cacheTtlMinutes: 1 });
164+
await expectBlockedUrl(deniedTool, url, /private|internal|blocked/i);
165+
166+
const fetchSpy = setMockFetch().mockResolvedValue(textResponse("benchmark ok"));
167+
const allowedTool = await createWebFetchToolForTest({
168+
ssrfPolicy: { allowRfc2544BenchmarkRange: true },
169+
cacheTtlMinutes: 1,
170+
});
171+
172+
const allowed = await allowedTool?.execute?.("call", { url });
173+
expect(allowed?.details).toMatchObject({
174+
status: 200,
175+
extractor: "raw",
176+
});
177+
expect(fetchSpy).toHaveBeenCalledTimes(1);
178+
179+
// A stricter tool instance must still block the same URL instead of reusing
180+
// the permissive-policy cache entry.
181+
const stricterTool = await createWebFetchToolForTest({ cacheTtlMinutes: 1 });
182+
await expectBlockedUrl(stricterTool, url, /private|internal|blocked/i);
183+
});
184+
150185
});

‎src/agents/tools/web-fetch.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,9 @@ type WebFetchRuntimeParams = {
247247
cacheTtlMs: number;
248248
userAgent: string;
249249
readabilityEnabled: boolean;
250+
ssrfPolicy?: {
251+
allowRfc2544BenchmarkRange?: boolean;
252+
};
250253
lookupFn?: LookupFn;
251254
resolveProviderFallback: () => ReturnType<typeof resolveWebFetchDefinition>;
252255
};
@@ -360,8 +363,14 @@ async function maybeFetchProviderWebFetchPayload(
360363
}
361364

362365
async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string, unknown>> {
366+
const policy =
367+
params.ssrfPolicy?.allowRfc2544BenchmarkRange === true
368+
? { allowRfc2544BenchmarkRange: true }
369+
: undefined;
370+
// Include the effective SSRF policy in the cache key to prevent cross-policy cache bypass
371+
const ssrfPolicySuffix = policy ? `:${JSON.stringify(policy)}` : "";
363372
const cacheKey = normalizeCacheKey(
364-
`fetch:${params.url}:${params.extractMode}:${params.maxChars}`,
373+
`fetch:${params.url}:${params.extractMode}:${params.maxChars}${ssrfPolicySuffix}`,
365374
);
366375
const cached = readCache(FETCH_CACHE, cacheKey);
367376
if (cached) {
@@ -382,12 +391,14 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
382391
let res: Response;
383392
let release: (() => Promise<void>) | null = null;
384393
let finalUrl = params.url;
394+
385395
try {
386396
const result = await fetchWithWebToolsNetworkGuard({
387397
url: params.url,
388398
maxRedirects: params.maxRedirects,
389399
timeoutSeconds: params.timeoutSeconds,
390400
lookupFn: params.lookupFn,
401+
policy,
391402
init: {
392403
headers: {
393404
Accept: "text/markdown, text/html;q=0.9, */*;q=0.1",
@@ -573,6 +584,7 @@ export function createWebFetchTool(options?: {
573584
return null;
574585
}
575586
const readabilityEnabled = resolveFetchReadabilityEnabled(fetch);
587+
const ssrfPolicy = fetch?.ssrfPolicy;
576588
const userAgent =
577589
(fetch && "userAgent" in fetch && typeof fetch.userAgent === "string" && fetch.userAgent) ||
578590
DEFAULT_FETCH_USER_AGENT;
@@ -617,6 +629,7 @@ export function createWebFetchTool(options?: {
617629
cacheTtlMs: resolveCacheTtlMs(fetch?.cacheTtlMinutes, DEFAULT_CACHE_TTL_MINUTES),
618630
userAgent,
619631
readabilityEnabled,
632+
ssrfPolicy,
620633
lookupFn: options?.lookupFn,
621634
resolveProviderFallback,
622635
});

‎src/config/schema.base.generated.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7353,6 +7353,21 @@ export const GENERATED_BASE_CONFIG_SCHEMA: BaseConfigSchemaResponse = {
73537353
description:
73547354
"Use Readability to extract main content from HTML (fallbacks to basic HTML cleanup).",
73557355
},
7356+
ssrfPolicy: {
7357+
type: "object",
7358+
properties: {
7359+
allowRfc2544BenchmarkRange: {
7360+
type: "boolean",
7361+
title: "Web Fetch Allow RFC 2544 Benchmark Range",
7362+
description:
7363+
"Allow RFC 2544 benchmark-range IPs (198.18.0.0/15) for fake-IP proxy compatibility such as Clash or Surge.",
7364+
},
7365+
},
7366+
additionalProperties: false,
7367+
title: "Web Fetch SSRF Policy",
7368+
description:
7369+
"Scoped SSRF policy overrides for web_fetch. Keep this narrow and opt in only for known local-network proxy environments.",
7370+
},
73567371
firecrawl: {
73577372
type: "object",
73587373
properties: {
@@ -23885,6 +23900,16 @@ export const GENERATED_BASE_CONFIG_SCHEMA: BaseConfigSchemaResponse = {
2388523900
help: "Use Readability to extract main content from HTML (fallbacks to basic HTML cleanup).",
2388623901
tags: ["tools"],
2388723902
},
23903+
"tools.web.fetch.ssrfPolicy": {
23904+
label: "Web Fetch SSRF Policy",
23905+
help: "Scoped SSRF policy overrides for web_fetch. Keep this narrow and opt in only for known local-network proxy environments.",
23906+
tags: ["access", "tools"],
23907+
},
23908+
"tools.web.fetch.ssrfPolicy.allowRfc2544BenchmarkRange": {
23909+
label: "Web Fetch Allow RFC 2544 Benchmark Range",
23910+
help: "Allow RFC 2544 benchmark-range IPs (198.18.0.0/15) for fake-IP proxy compatibility such as Clash or Surge.",
23911+
tags: ["access", "tools"],
23912+
},
2388823913
"gateway.controlUi.basePath": {
2388923914
label: "Control UI Base Path",
2389023915
help: "Optional URL prefix where the Control UI is served (e.g. /openclaw).",

‎src/config/schema.help.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,10 @@ export const FIELD_HELP: Record<string, string> = {
720720
"tools.web.fetch.userAgent": "Override User-Agent header for web_fetch requests.",
721721
"tools.web.fetch.readability":
722722
"Use Readability to extract main content from HTML (fallbacks to basic HTML cleanup).",
723+
"tools.web.fetch.ssrfPolicy":
724+
"Scoped SSRF policy overrides for web_fetch. Keep this narrow and opt in only for known local-network proxy environments.",
725+
"tools.web.fetch.ssrfPolicy.allowRfc2544BenchmarkRange":
726+
"Allow RFC 2544 benchmark-range IPs (198.18.0.0/15) for fake-IP proxy compatibility such as Clash or Surge.",
723727
models:
724728
"Model catalog root for provider definitions, merge/replace behavior, and optional Bedrock discovery integration. Keep provider definitions explicit and validated before relying on production failover paths.",
725729
"models.mode":

‎src/config/schema.labels.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ export const FIELD_LABELS: Record<string, string> = {
254254
"tools.web.fetch.maxRedirects": "Web Fetch Max Redirects",
255255
"tools.web.fetch.userAgent": "Web Fetch User-Agent",
256256
"tools.web.fetch.readability": "Web Fetch Readability Extraction",
257+
"tools.web.fetch.ssrfPolicy": "Web Fetch SSRF Policy",
258+
"tools.web.fetch.ssrfPolicy.allowRfc2544BenchmarkRange":
259+
"Web Fetch Allow RFC 2544 Benchmark Range",
257260
"gateway.controlUi.basePath": "Control UI Base Path",
258261
"gateway.controlUi.root": "Control UI Assets Root",
259262
"gateway.controlUi.allowedOrigins": "Control UI Allowed Origins",

‎src/config/schema.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,22 @@ describe("config schema", () => {
289289
expect(parsed?.web?.fetch?.maxResponseBytes).toBe(2_000_000);
290290
});
291291

292+
it("accepts web fetch ssrfPolicy in the runtime zod schema", () => {
293+
const parsed = ToolsSchema.parse({
294+
web: {
295+
fetch: {
296+
ssrfPolicy: {
297+
allowRfc2544BenchmarkRange: true,
298+
},
299+
},
300+
},
301+
});
302+
303+
expect(parsed?.web?.fetch?.ssrfPolicy).toEqual({
304+
allowRfc2544BenchmarkRange: true,
305+
});
306+
});
307+
292308
it("rejects unknown keys inside web fetch firecrawl config", () => {
293309
expect(() =>
294310
ToolsSchema.parse({

‎src/config/types.tools.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,11 @@ export type ToolsConfig = {
550550
userAgent?: string;
551551
/** Use Readability to extract main content (default: true). */
552552
readability?: boolean;
553+
/** SSRF policy configuration for web_fetch. */
554+
ssrfPolicy?: {
555+
/** Allow RFC 2544 benchmark range IPs (198.18.0.0/15) for fake-IP proxy compatibility (e.g., Clash TUN mode, Surge). */
556+
allowRfc2544BenchmarkRange?: boolean;
557+
};
553558
};
554559
};
555560
media?: MediaToolsConfig;

‎src/config/zod-schema.agent-runtime.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,12 @@ export const ToolsWebFetchSchema = z
330330
maxRedirects: z.number().int().nonnegative().optional(),
331331
userAgent: z.string().optional(),
332332
readability: z.boolean().optional(),
333+
ssrfPolicy: z
334+
.object({
335+
allowRfc2544BenchmarkRange: z.boolean().optional(),
336+
})
337+
.strict()
338+
.optional(),
333339
// Keep the legacy Firecrawl fetch shape loadable so existing installs can
334340
// start and then migrate cleanly through doctor.
335341
firecrawl: z

0 commit comments

Comments
 (0)