Skip to content

Commit 0e6d4c8

Browse files
committed
feat: add per-agent web_fetch ssrf overrides
1 parent 7694a92 commit 0e6d4c8

13 files changed

Lines changed: 690 additions & 28 deletions

‎src/agents/openclaw-tools.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import { callGateway } from "../gateway/call.js";
33
import { getActiveRuntimeWebToolsMetadata } from "../secrets/runtime.js";
44
import { normalizeDeliveryContext } from "../utils/delivery-context.js";
55
import type { GatewayMessageChannel } from "../utils/message-channel.js";
6-
import { resolveAgentWorkspaceDir, resolveSessionAgentIds } from "./agent-scope.js";
6+
import {
7+
resolveAgentConfig,
8+
resolveAgentWorkspaceDir,
9+
resolveSessionAgentIds,
10+
} from "./agent-scope.js";
711
import { resolveOpenClawPluginToolsForOptions } from "./openclaw-plugin-tools.js";
812
import { applyNodesToolWorkspaceGuard } from "./openclaw-tools.nodes-workspace-guard.js";
913
import {
@@ -135,6 +139,9 @@ export function createOpenClawTools(
135139
threadId: options?.agentThreadId,
136140
});
137141
const runtimeWebTools = getActiveRuntimeWebToolsMetadata();
142+
const activeAgentTools = resolvedConfig
143+
? resolveAgentConfig(resolvedConfig, sessionAgentId)?.tools
144+
: undefined;
138145
const sandbox =
139146
options?.sandboxRoot && options?.sandboxFsBridge
140147
? { root: options.sandboxRoot, bridge: options.sandboxFsBridge }
@@ -190,6 +197,7 @@ export function createOpenClawTools(
190197
});
191198
const webFetchTool = createWebFetchTool({
192199
config: options?.config,
200+
agentTools: activeAgentTools,
193201
sandboxed: options?.sandboxed,
194202
runtimeWebFetch: runtimeWebTools?.fetch,
195203
});

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

Lines changed: 73 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,20 @@ function setMockFetch(
3535

3636
async function createWebFetchToolForTest(params?: {
3737
firecrawlApiKey?: string;
38-
ssrfPolicy?: { allowRfc2544BenchmarkRange?: boolean };
38+
globalSsrFPolicy?: {
39+
allowPrivateNetwork?: boolean;
40+
dangerouslyAllowPrivateNetwork?: boolean;
41+
allowedHostnames?: string[];
42+
hostnameAllowlist?: string[];
43+
allowRfc2544BenchmarkRange?: boolean;
44+
};
45+
agentSsrFPolicy?: {
46+
allowPrivateNetwork?: boolean;
47+
dangerouslyAllowPrivateNetwork?: boolean;
48+
allowedHostnames?: string[];
49+
hostnameAllowlist?: string[];
50+
allowRfc2544BenchmarkRange?: boolean;
51+
};
3952
cacheTtlMinutes?: number;
4053
}) {
4154
const { createWebFetchTool } = await import("./web-tools.js");
@@ -58,12 +71,21 @@ async function createWebFetchToolForTest(params?: {
5871
web: {
5972
fetch: {
6073
cacheTtlMinutes: params?.cacheTtlMinutes ?? 0,
61-
ssrfPolicy: params?.ssrfPolicy,
74+
ssrfPolicy: params?.globalSsrFPolicy,
6275
...(params?.firecrawlApiKey ? { provider: "firecrawl" } : {}),
6376
},
6477
},
6578
},
6679
},
80+
agentTools: params?.agentSsrFPolicy
81+
? {
82+
web: {
83+
fetch: {
84+
ssrfPolicy: params.agentSsrFPolicy,
85+
},
86+
},
87+
}
88+
: undefined,
6789
lookupFn: lookupMock,
6890
});
6991
}
@@ -165,7 +187,7 @@ describe("web_fetch SSRF protection", () => {
165187

166188
const fetchSpy = setMockFetch().mockResolvedValue(textResponse("benchmark ok"));
167189
const allowedTool = await createWebFetchToolForTest({
168-
ssrfPolicy: { allowRfc2544BenchmarkRange: true },
190+
globalSsrFPolicy: { allowRfc2544BenchmarkRange: true },
169191
cacheTtlMinutes: 1,
170192
});
171193

@@ -178,4 +200,52 @@ describe("web_fetch SSRF protection", () => {
178200
const stricterTool = await createWebFetchToolForTest({ cacheTtlMinutes: 1 });
179201
await expectBlockedUrl(stricterTool, url, /private|internal|blocked/i);
180202
});
203+
204+
it("allows private-network targets when a named agent opts in", async () => {
205+
const url = "http://127.0.0.1/private";
206+
const deniedTool = await createWebFetchToolForTest({
207+
globalSsrFPolicy: { dangerouslyAllowPrivateNetwork: false },
208+
});
209+
await expectBlockedUrl(deniedTool, url, /private|internal|blocked/i);
210+
211+
const fetchSpy = setMockFetch().mockResolvedValue(textResponse("agent ok"));
212+
const allowedTool = await createWebFetchToolForTest({
213+
globalSsrFPolicy: { dangerouslyAllowPrivateNetwork: false },
214+
agentSsrFPolicy: { dangerouslyAllowPrivateNetwork: true },
215+
});
216+
217+
const result = await allowedTool?.execute?.("call", { url });
218+
expect(result?.details).toMatchObject({ status: 200, extractor: "raw" });
219+
expect(fetchSpy).toHaveBeenCalledTimes(1);
220+
});
221+
222+
it("allows narrow hostname exceptions from a named agent", async () => {
223+
lookupMock.mockResolvedValue([{ address: "10.0.0.5", family: 4 }]);
224+
const fetchSpy = setMockFetch().mockResolvedValue(textResponse("hostname ok"));
225+
const tool = await createWebFetchToolForTest({
226+
globalSsrFPolicy: { allowedHostnames: ["global-only.internal"] },
227+
agentSsrFPolicy: { allowedHostnames: ["matrix.home.arpa"] },
228+
});
229+
230+
const result = await tool?.execute?.("call", { url: "https://matrix.home.arpa/status" });
231+
expect(result?.details).toMatchObject({ status: 200, extractor: "raw" });
232+
expect(fetchSpy).toHaveBeenCalledTimes(1);
233+
});
234+
235+
it("does not reuse broader-policy cache entries for stricter policies", async () => {
236+
const url = "http://198.18.0.153/file";
237+
lookupMock.mockResolvedValue([{ address: "198.18.0.153", family: 4 }]);
238+
239+
const fetchSpy = setMockFetch().mockResolvedValue(textResponse("broad cache"));
240+
const broadTool = await createWebFetchToolForTest({
241+
agentSsrFPolicy: { dangerouslyAllowPrivateNetwork: true },
242+
cacheTtlMinutes: 1,
243+
});
244+
await broadTool?.execute?.("call", { url });
245+
expect(fetchSpy).toHaveBeenCalledTimes(1);
246+
247+
const strictTool = await createWebFetchToolForTest({ cacheTtlMinutes: 1 });
248+
await expectBlockedUrl(strictTool, url, /private|internal|blocked/i);
249+
expect(fetchSpy).toHaveBeenCalledTimes(1);
250+
});
181251
});

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

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import { Type } from "@sinclair/typebox";
22
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3-
import { SsrFBlockedError, type LookupFn } from "../../infra/net/ssrf.js";
3+
import type { AgentToolsConfig } from "../../config/types.tools.js";
4+
import {
5+
mergeSsrFPolicies,
6+
serializeSsrFPolicy,
7+
SsrFBlockedError,
8+
type LookupFn,
9+
type SsrFPolicy,
10+
} from "../../infra/net/ssrf.js";
411
import { logDebug } from "../../logger.js";
512
import type { RuntimeWebFetchMetadata } from "../../secrets/runtime-web-tools.types.js";
613
import { wrapExternalContent, wrapWebContent } from "../../security/external-content.js";
@@ -74,10 +81,38 @@ type WebFetchConfig = NonNullable<OpenClawConfig["tools"]>["web"] extends infer
7481
: undefined
7582
: undefined;
7683

84+
type AgentWebFetchConfig = NonNullable<AgentToolsConfig["web"]>["fetch"];
85+
7786
function resolveFetchConfig(cfg?: OpenClawConfig): WebFetchConfig {
7887
return resolveWebProviderConfig<"fetch", NonNullable<WebFetchConfig>>(cfg, "fetch");
7988
}
8089

90+
function resolveAgentFetchConfig(agentTools?: AgentToolsConfig): AgentWebFetchConfig | undefined {
91+
const fetch = agentTools?.web?.fetch;
92+
if (!fetch || typeof fetch !== "object") {
93+
return undefined;
94+
}
95+
return fetch as AgentWebFetchConfig;
96+
}
97+
98+
function resolveEffectiveFetchConfig(params: {
99+
config?: OpenClawConfig;
100+
agentTools?: AgentToolsConfig;
101+
}): WebFetchConfig | undefined {
102+
const globalFetch = resolveFetchConfig(params.config);
103+
const agentFetch = resolveAgentFetchConfig(params.agentTools);
104+
if (!globalFetch && !agentFetch) {
105+
return undefined;
106+
}
107+
if (!agentFetch?.ssrfPolicy) {
108+
return globalFetch;
109+
}
110+
return {
111+
...globalFetch,
112+
ssrfPolicy: mergeSsrFPolicies(globalFetch?.ssrfPolicy, agentFetch.ssrfPolicy),
113+
};
114+
}
115+
81116
function resolveFetchEnabled(params: { fetch?: WebFetchConfig; sandboxed?: boolean }): boolean {
82117
if (typeof params.fetch?.enabled === "boolean") {
83118
return params.fetch.enabled;
@@ -247,9 +282,7 @@ type WebFetchRuntimeParams = {
247282
cacheTtlMs: number;
248283
userAgent: string;
249284
readabilityEnabled: boolean;
250-
ssrfPolicy?: {
251-
allowRfc2544BenchmarkRange?: boolean;
252-
};
285+
ssrfPolicy?: SsrFPolicy;
253286
lookupFn?: LookupFn;
254287
resolveProviderFallback: () => ReturnType<typeof resolveWebFetchDefinition>;
255288
};
@@ -363,9 +396,8 @@ async function maybeFetchProviderWebFetchPayload(
363396
}
364397

365398
async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string, unknown>> {
366-
const allowRfc2544BenchmarkRange = params.ssrfPolicy?.allowRfc2544BenchmarkRange === true;
367399
const cacheKey = normalizeCacheKey(
368-
`fetch:${params.url}:${params.extractMode}:${params.maxChars}${allowRfc2544BenchmarkRange ? ":allow-rfc2544" : ""}`,
400+
`fetch:${params.url}:${params.extractMode}:${params.maxChars}:${serializeSsrFPolicy(params.ssrfPolicy)}`,
369401
);
370402
const cached = readCache(FETCH_CACHE, cacheKey);
371403
if (cached) {
@@ -392,7 +424,7 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
392424
maxRedirects: params.maxRedirects,
393425
timeoutSeconds: params.timeoutSeconds,
394426
lookupFn: params.lookupFn,
395-
policy: allowRfc2544BenchmarkRange ? { allowRfc2544BenchmarkRange } : undefined,
427+
policy: params.ssrfPolicy,
396428
init: {
397429
headers: {
398430
Accept: "text/markdown, text/html;q=0.9, */*;q=0.1",
@@ -569,11 +601,15 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
569601

570602
export function createWebFetchTool(options?: {
571603
config?: OpenClawConfig;
604+
agentTools?: AgentToolsConfig;
572605
sandboxed?: boolean;
573606
runtimeWebFetch?: RuntimeWebFetchMetadata;
574607
lookupFn?: LookupFn;
575608
}): AnyAgentTool | null {
576-
const fetch = resolveFetchConfig(options?.config);
609+
const fetch = resolveEffectiveFetchConfig({
610+
config: options?.config,
611+
agentTools: options?.agentTools,
612+
});
577613
if (!resolveFetchEnabled({ fetch, sandboxed: options?.sandboxed })) {
578614
return null;
579615
}

0 commit comments

Comments
 (0)