Skip to content

Commit 6ccc57b

Browse files
sjudsonjoshavant
andauthored
fix: add ssrf protection to Beam fetches (#123848)
* Add ssrf protection to Beam fetches. * Additional robustness following initial comments. * fix(beam): make redirect failures terminal * chore(plugin-sdk): refresh surface budget * docs(beam): define redirect restart behavior * docs(beam): align redirect config help * test(beam): cover warning before redirect block * fix(beam): always report terminal redirect blocks --------- Co-authored-by: joshavant <[email protected]>
1 parent 6d49503 commit 6ccc57b

8 files changed

Lines changed: 351 additions & 20 deletions

File tree

‎docs/plugins/beam.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ Beam can also act as the sender: an opt-in mirror that continuously publishes th
140140
}
141141
```
142142

143-
- `endpoint` (required): the remote receiver URL. HTTPS is enforced for non-loopback hosts; plaintext `http://` is accepted only for `localhost`/`127.0.0.1`/`::1` development.
143+
- `endpoint` (required): the final remote receiver URL. Redirect responses (301, 302, 303, 307, and 308) are not followed; configure the destination URL directly. After a redirect, repeated polls are suppressed for the current mirror service instance. A Gateway restart probes the configured endpoint once again so a receiver corrected at the same URL can recover. HTTPS is enforced for non-loopback hosts; plaintext `http://` is accepted only for `localhost`/`127.0.0.1`/`::1` development.
144144
- `token`: Gateway credential for the remote receiver, sent as `Authorization: Bearer`. Accepts a plain string or a secret reference; a configured-but-unresolved token pauses mirroring instead of sending unauthenticated requests. Deployments fronted by an identity-aware proxy need an ingress that accepts this bearer credential.
145145
- `catalogs` (required): the session catalog ids to mirror, as explicit per-catalog consent — an omitted or empty list mirrors nothing. The local `beam` receiver catalog is always excluded so two mirrored Gateways cannot re-mirror each other's rows.
146146
- `pollSeconds` (default 30, minimum 10): how often the mirror scans local catalogs.
@@ -170,6 +170,10 @@ The mirror applies the same redaction contract as the beam skill before anything
170170

171171
: The authenticated client exceeded the bounded request or concurrency limit. Retry after the current minute window.
172172

173+
`beam mirror upload blocked ... receiver returned redirect`
174+
175+
: The configured mirror endpoint returned a redirect. Beam does not follow redirects and suppresses repeated attempts for the current service instance; set `mirror.endpoint` to the final receiver URL. A Gateway restart probes the configured endpoint once again.
176+
173177
## Related
174178

175179
- [Control UI](/web/control-ui)

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ usage endpoint failed or returned no usable usage data.
201201
| `plugin-sdk/security-runtime` | Deprecated broad barrel for trust, DM gating, root-bounded file/path helpers including create-only writes, sync/async atomic file replacement, sibling temp writes, cross-device move fallback, private file-store helpers, symlink-parent guards, external-content, sensitive text redaction, constant-time secret comparison, and secret-collection helpers; prefer focused security/SSRF/secret subpaths |
202202
| `plugin-sdk/ssrf-policy` | Host allowlist and private-network SSRF policy helpers |
203203
| `plugin-sdk/ssrf-dispatcher` | Private-local after July 2026; Narrow pinned-dispatcher helpers without the broad infra runtime surface |
204-
| `plugin-sdk/ssrf-runtime` | Pinned-dispatcher, SSRF-guarded fetch, SSRF error, SSRF policy helpers, and loopback/private host classification |
204+
| `plugin-sdk/ssrf-runtime` | Pinned-dispatcher, SSRF-guarded fetch, `SsrFBlockedError` and `GuardedFetchRedirectError`, SSRF policy helpers, and loopback/private host classification |
205205
| `plugin-sdk/secret-input` | Secret input parsing helpers |
206206
| `plugin-sdk/secret-ref-readonly` | Closed available/missing/blocked resolution and provider-policy checks for read-only env SecretRefs |
207207
| `plugin-sdk/webhook-ingress` | Webhook request/target helpers and raw websocket/body coercion |

‎extensions/beam/openclaw.plugin.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"uiHints": {
88
"mirror.endpoint": {
99
"label": "Mirror Endpoint",
10-
"help": "Remote Beam receiver URL, e.g. https://team.example.com/api/v1/beam/sessions."
10+
"help": "Final Beam receiver URL, e.g. https://team.example.com/api/v1/beam/sessions. Redirects are not followed; retries pause until the service restarts or the endpoint changes."
1111
},
1212
"mirror.token": {
1313
"label": "Mirror Token",

‎extensions/beam/src/mirror.test.ts‎

Lines changed: 277 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
import { createServer, type IncomingMessage, type Server } from "node:http";
12
import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";
23
import type {
34
SessionCatalogHost,
45
SessionCatalogTranscriptItem,
56
SessionsCatalogReadResult,
67
} from "openclaw/plugin-sdk/session-catalog";
78
import type { ActiveSessionCatalog } from "openclaw/plugin-sdk/session-catalog-runtime";
9+
import * as ssrfRuntime from "openclaw/plugin-sdk/ssrf-runtime";
810
import { describe, expect, it, vi } from "vitest";
911
import {
1012
beamMirrorId,
@@ -92,7 +94,7 @@ function captureFetch(
9294
status = 200,
9395
onCancel?: () => void | Promise<void>,
9496
): typeof fetch {
95-
return (async (url: unknown, init?: RequestInit) => {
97+
return vi.fn(async (url: unknown, init?: RequestInit) => {
9698
const headers = (init?.headers ?? {}) as Record<string, string>;
9799
sent.push({
98100
url: String(url),
@@ -105,11 +107,44 @@ function captureFetch(
105107
})
106108
: "{}";
107109
return new Response(body, { status });
108-
}) as typeof fetch;
110+
}) as unknown as typeof fetch;
109111
}
110112

111113
const silentLogger = { warn: () => {}, info: () => {} };
112114

115+
async function listenOnLoopback(server: Server): Promise<string> {
116+
await new Promise<void>((resolve, reject) => {
117+
server.once("error", reject);
118+
server.listen(0, "127.0.0.1", () => {
119+
server.off("error", reject);
120+
resolve();
121+
});
122+
});
123+
const address = server.address();
124+
if (!address || typeof address === "string") {
125+
throw new Error("test server did not expose a TCP address");
126+
}
127+
return `http://127.0.0.1:${address.port}`;
128+
}
129+
130+
async function closeTestServer(server: Server): Promise<void> {
131+
if (!server.listening) {
132+
return;
133+
}
134+
server.closeAllConnections();
135+
await new Promise<void>((resolve, reject) => {
136+
server.close((error) => (error ? reject(error) : resolve()));
137+
});
138+
}
139+
140+
async function readRequestBody(req: IncomingMessage): Promise<string> {
141+
const chunks: Buffer[] = [];
142+
for await (const chunk of req) {
143+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
144+
}
145+
return Buffer.concat(chunks).toString("utf8");
146+
}
147+
113148
describe("parseBeamMirrorConfig", () => {
114149
it("returns undefined without mirror config", () => {
115150
expect(parseBeamMirrorConfig({ plugins: { entries: { beam: { enabled: true } } } })).toBe(
@@ -223,6 +258,205 @@ describe("fitBeamMirrorUpload", () => {
223258
});
224259

225260
describe("createBeamMirrorRunner", () => {
261+
it("does not replay mirror uploads across redirects to another private origin", async () => {
262+
const redirectedBodies: string[] = [];
263+
const internalServer = createServer((req, res) => {
264+
void readRequestBody(req).then(
265+
(body) => {
266+
redirectedBodies.push(body);
267+
res.statusCode = 200;
268+
res.end("ok");
269+
},
270+
(error: unknown) => {
271+
res.destroy(error instanceof Error ? error : new Error(String(error)));
272+
},
273+
);
274+
});
275+
const internalOrigin = await listenOnLoopback(internalServer);
276+
const receiverBodies: string[] = [];
277+
const receiverServer = createServer((req, res) => {
278+
void readRequestBody(req).then(
279+
(body) => {
280+
receiverBodies.push(body);
281+
res.statusCode = 307;
282+
res.setHeader("Location", `${internalOrigin}/internal-action`);
283+
res.end();
284+
},
285+
(error: unknown) => {
286+
res.destroy(error instanceof Error ? error : new Error(String(error)));
287+
},
288+
);
289+
});
290+
try {
291+
const receiverOrigin = await listenOnLoopback(receiverServer);
292+
const runner = createBeamMirrorRunner({
293+
runtime: fakeRuntime(mirrorConfig({ endpoint: `${receiverOrigin}/beam` })),
294+
logger: silentLogger,
295+
now: () => NOW,
296+
listCatalogs: () => [
297+
fakeCatalog({ id: "claude", sessions: [{ threadId: "t1", recencyAt: NOW }] }),
298+
],
299+
});
300+
301+
await runner.tick();
302+
303+
expect(receiverBodies).toHaveLength(1);
304+
expect(receiverBodies[0]).toContain("Fix the flow.");
305+
expect(redirectedBodies).toEqual([]);
306+
} finally {
307+
await Promise.all([closeTestServer(receiverServer), closeTestServer(internalServer)]);
308+
}
309+
});
310+
311+
it.each([
312+
{ label: "301", status: 301, location: "/redirected?private=do-not-log" },
313+
{ label: "302", status: 302, location: "/redirected?private=do-not-log" },
314+
{ label: "303", status: 303, location: "/redirected?private=do-not-log" },
315+
{ label: "307", status: 307, location: "/redirected?private=do-not-log" },
316+
{ label: "308", status: 308, location: "/redirected?private=do-not-log" },
317+
{ label: "307 without Location", status: 307, location: undefined },
318+
])(
319+
"blocks a $label redirect without retrying the configured endpoint",
320+
async ({ status, location }) => {
321+
const warnings: string[] = [];
322+
const receiverBodies: string[] = [];
323+
const redirectedBodies: string[] = [];
324+
const server = createServer((req, res) => {
325+
void readRequestBody(req).then(
326+
(body) => {
327+
if (req.url === "/redirected") {
328+
redirectedBodies.push(body);
329+
res.statusCode = 200;
330+
res.end("ok");
331+
return;
332+
}
333+
receiverBodies.push(body);
334+
res.statusCode = status;
335+
if (location) {
336+
res.setHeader("Location", location);
337+
}
338+
res.end();
339+
},
340+
(error: unknown) => {
341+
res.destroy(error instanceof Error ? error : new Error(String(error)));
342+
},
343+
);
344+
});
345+
try {
346+
const origin = await listenOnLoopback(server);
347+
const runner = createBeamMirrorRunner({
348+
runtime: fakeRuntime(mirrorConfig({ endpoint: `${origin}/beam` })),
349+
logger: { warn: (message) => warnings.push(message), info: () => {} },
350+
now: () => NOW,
351+
listCatalogs: () => [
352+
fakeCatalog({ id: "claude", sessions: [{ threadId: "t1", recencyAt: NOW }] }),
353+
],
354+
});
355+
356+
await runner.tick();
357+
await runner.tick();
358+
359+
expect(receiverBodies).toHaveLength(1);
360+
expect(redirectedBodies).toEqual([]);
361+
expect(warnings).toEqual([
362+
`beam mirror upload blocked for claude: receiver returned redirect (${status}); redirects are not followed; configure the final endpoint`,
363+
]);
364+
expect(warnings.join(" ")).not.toContain("do-not-log");
365+
} finally {
366+
await closeTestServer(server);
367+
}
368+
},
369+
);
370+
371+
it("logs a terminal redirect block after a recent transient warning", async () => {
372+
const warnings: string[] = [];
373+
let requestCount = 0;
374+
const server = createServer((req, res) => {
375+
void readRequestBody(req).then(
376+
() => {
377+
requestCount += 1;
378+
res.statusCode = requestCount === 1 ? 503 : 307;
379+
res.end();
380+
},
381+
(error: unknown) => {
382+
res.destroy(error instanceof Error ? error : new Error(String(error)));
383+
},
384+
);
385+
});
386+
try {
387+
const origin = await listenOnLoopback(server);
388+
const runner = createBeamMirrorRunner({
389+
runtime: fakeRuntime(mirrorConfig({ endpoint: `${origin}/beam` })),
390+
logger: { warn: (message) => warnings.push(message), info: () => {} },
391+
now: () => NOW,
392+
listCatalogs: () => [
393+
fakeCatalog({ id: "claude", sessions: [{ threadId: "t1", recencyAt: NOW }] }),
394+
],
395+
});
396+
397+
await runner.tick();
398+
await runner.tick();
399+
await runner.tick();
400+
401+
expect(requestCount).toBe(2);
402+
expect(warnings).toEqual([
403+
"beam mirror upload failed (503) for claude",
404+
"beam mirror upload blocked for claude: receiver returned redirect (307); redirects are not followed; configure the final endpoint",
405+
]);
406+
} finally {
407+
await closeTestServer(server);
408+
}
409+
});
410+
411+
it("rechecks once after runner restart and resumes after the endpoint changes", async () => {
412+
const requests: string[] = [];
413+
const server = createServer((req, res) => {
414+
void readRequestBody(req).then(
415+
() => {
416+
requests.push(req.url ?? "");
417+
if (req.url === "/redirecting") {
418+
res.statusCode = 307;
419+
res.setHeader("Location", "/redirected");
420+
} else {
421+
res.statusCode = 200;
422+
}
423+
res.end();
424+
},
425+
(error: unknown) => {
426+
res.destroy(error instanceof Error ? error : new Error(String(error)));
427+
},
428+
);
429+
});
430+
try {
431+
const origin = await listenOnLoopback(server);
432+
let endpoint = `${origin}/redirecting`;
433+
const runtime = {
434+
config: { current: () => mirrorConfig({ endpoint }) },
435+
} as unknown as PluginRuntime;
436+
const createRunner = () =>
437+
createBeamMirrorRunner({
438+
runtime,
439+
logger: silentLogger,
440+
now: () => NOW,
441+
listCatalogs: () => [
442+
fakeCatalog({ id: "claude", sessions: [{ threadId: "t1", recencyAt: NOW }] }),
443+
],
444+
});
445+
const runner = createRunner();
446+
447+
await runner.tick();
448+
await runner.tick();
449+
const restartedRunner = createRunner();
450+
await restartedRunner.tick();
451+
endpoint = `${origin}/direct`;
452+
await restartedRunner.tick();
453+
454+
expect(requests).toEqual(["/redirecting", "/redirecting", "/direct"]);
455+
} finally {
456+
await closeTestServer(server);
457+
}
458+
});
459+
226460
it("uploads active local sessions and skips unchanged ones", async () => {
227461
const sent: SentRequest[] = [];
228462
const reads: string[] = [];
@@ -299,6 +533,47 @@ describe("createBeamMirrorRunner", () => {
299533
expect(warnings).toEqual([]);
300534
});
301535

536+
it("bounds guarded uploads and releases their response resources", async () => {
537+
const cancel = vi.fn();
538+
const release = vi.fn();
539+
const response = new Response(
540+
new ReadableStream<Uint8Array>({
541+
cancel,
542+
}),
543+
{ status: 200 },
544+
);
545+
const guardedFetch = vi.spyOn(ssrfRuntime, "fetchWithSsrFGuard").mockResolvedValue({
546+
response,
547+
finalUrl: "https://team.example/api/v1/beam/sessions",
548+
release,
549+
});
550+
const runner = createBeamMirrorRunner({
551+
runtime: fakeRuntime(mirrorConfig()),
552+
logger: silentLogger,
553+
now: () => NOW,
554+
listCatalogs: () => [
555+
fakeCatalog({ id: "claude", sessions: [{ threadId: "t1", recencyAt: NOW }] }),
556+
],
557+
});
558+
559+
try {
560+
await runner.tick();
561+
562+
expect(guardedFetch).toHaveBeenCalledWith(
563+
expect.objectContaining({
564+
url: "https://team.example/api/v1/beam/sessions",
565+
timeoutMs: 15_000,
566+
maxRedirects: 0,
567+
policy: { allowedOrigins: ["https://team.example"] },
568+
}),
569+
);
570+
expect(cancel).toHaveBeenCalledOnce();
571+
expect(release).toHaveBeenCalledOnce();
572+
} finally {
573+
guardedFetch.mockRestore();
574+
}
575+
});
576+
302577
it("ignores idle sessions, node hosts, the beam catalog, and unlisted catalogs", async () => {
303578
const sent: SentRequest[] = [];
304579
const idle = fakeCatalog({

0 commit comments

Comments
 (0)