Skip to content

Commit 31a6d09

Browse files
authored
test(qa): cover guarded media fetch boundaries (#118857)
1 parent 9dfc74e commit 31a6d09

2 files changed

Lines changed: 277 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
title: Media guarded fetch boundaries
2+
3+
scenario:
4+
id: media-fetch-boundaries
5+
surface: media
6+
category: media.media-intake-and-access
7+
coverage:
8+
primary:
9+
- media.safe-remote-fetch
10+
- media.size-caps-and-bounded-reads
11+
objective: Prove remote media intake enforces SSRF, redirect, header, and bounded-write policy before publishing media-store artifacts.
12+
successCriteria:
13+
- A private loopback target is rejected before any network request or media-store publication.
14+
- Redirect targets are revalidated against exact-origin policy.
15+
- Cross-origin redirects preserve safe headers while stripping authorization, cookie, and API-key material.
16+
- Declared content-length and chunked streaming overflows fail at the configured byte cap.
17+
- Failed guarded fetches leave no final or temporary media-store artifact.
18+
docsRefs:
19+
- docs/tools/media-overview.md
20+
- docs/gateway/security/secure-file-operations.md
21+
- docs/help/testing.md
22+
codeRefs:
23+
- src/infra/net/fetch-guard.ts
24+
- src/media/fetch.ts
25+
- src/media/store.ts
26+
- test/e2e/qa-lab/media/media-fetch-boundaries.e2e.test.ts
27+
execution:
28+
kind: vitest
29+
path: test/e2e/qa-lab/media/media-fetch-boundaries.e2e.test.ts
30+
summary: Runs real loopback HTTP redirects and bounded streams through canonical guarded media fetch and atomic store publication.
Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
import fs from "node:fs/promises";
2+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
3+
import path from "node:path";
4+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
5+
import { MediaFetchError, saveRemoteMedia } from "../../../../src/media/fetch.js";
6+
import { withEnvAsync } from "../../../../src/test-utils/env.js";
7+
import { useAutoCleanupTempDirTracker } from "../../../helpers/temp-dir.js";
8+
9+
type SeenRequest = {
10+
headers: IncomingMessage["headers"];
11+
url: string;
12+
};
13+
14+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
15+
const sourceRequests: SeenRequest[] = [];
16+
const targetRequests: SeenRequest[] = [];
17+
18+
let sourceServer: Server;
19+
let sourceOrigin: string;
20+
let targetServer: Server;
21+
let targetOrigin: string;
22+
23+
async function listenOnLoopback(server: Server): Promise<string> {
24+
await new Promise<void>((resolve, reject) => {
25+
const onError = (error: Error) => {
26+
server.off("error", onError);
27+
reject(error);
28+
};
29+
server.once("error", onError);
30+
server.listen(0, "127.0.0.1", () => {
31+
server.off("error", onError);
32+
resolve();
33+
});
34+
});
35+
const address = server.address();
36+
if (!address || typeof address === "string") {
37+
throw new Error("loopback media server did not expose a TCP port");
38+
}
39+
return `http://127.0.0.1:${address.port}`;
40+
}
41+
42+
async function closeLoopbackServer(server: Server): Promise<void> {
43+
const closed = new Promise<void>((resolve, reject) => {
44+
server.close((error) => (error ? reject(error) : resolve()));
45+
});
46+
server.closeAllConnections();
47+
await closed;
48+
}
49+
50+
function recordRequest(request: IncomingMessage, requests: SeenRequest[]): void {
51+
requests.push({
52+
headers: request.headers,
53+
url: request.url ?? "/",
54+
});
55+
}
56+
57+
function handleSourceRequest(request: IncomingMessage, response: ServerResponse): void {
58+
recordRequest(request, sourceRequests);
59+
switch (request.url) {
60+
case "/private":
61+
response.writeHead(200, { "content-type": "text/plain" });
62+
response.end("private media");
63+
return;
64+
case "/redirect":
65+
response.writeHead(302, { location: `${targetOrigin}/payload` });
66+
response.end();
67+
return;
68+
case "/oversized-file":
69+
response.writeHead(200, {
70+
"content-length": "128",
71+
"content-type": "application/octet-stream",
72+
});
73+
response.end("declared oversized file");
74+
return;
75+
case "/oversized-stream":
76+
response.writeHead(200, { "content-type": "application/octet-stream" });
77+
response.write(Buffer.alloc(12, 0x61));
78+
response.end(Buffer.alloc(12, 0x62));
79+
return;
80+
default:
81+
response.writeHead(404);
82+
response.end();
83+
}
84+
}
85+
86+
function handleTargetRequest(request: IncomingMessage, response: ServerResponse): void {
87+
recordRequest(request, targetRequests);
88+
if (request.url !== "/payload") {
89+
response.writeHead(404);
90+
response.end();
91+
return;
92+
}
93+
response.writeHead(200, { "content-type": "text/plain" });
94+
response.end("redirected media");
95+
}
96+
97+
async function expectNoPublishedMediaFiles(stateDir: string): Promise<void> {
98+
const mediaDir = path.join(stateDir, "media");
99+
const files: string[] = [];
100+
101+
const visit = async (directory: string): Promise<void> => {
102+
const entries = await fs
103+
.readdir(directory, { withFileTypes: true })
104+
.catch((error: NodeJS.ErrnoException) => {
105+
if (error.code === "ENOENT") {
106+
return [];
107+
}
108+
throw error;
109+
});
110+
for (const entry of entries) {
111+
const entryPath = path.join(directory, entry.name);
112+
if (entry.isDirectory()) {
113+
await visit(entryPath);
114+
} else {
115+
files.push(path.relative(mediaDir, entryPath));
116+
}
117+
}
118+
};
119+
120+
await visit(mediaDir);
121+
expect(files.toSorted()).toStrictEqual([]);
122+
}
123+
124+
describe("media guarded fetch product boundaries", () => {
125+
beforeAll(async () => {
126+
targetServer = createServer(handleTargetRequest);
127+
targetOrigin = await listenOnLoopback(targetServer);
128+
sourceServer = createServer(handleSourceRequest);
129+
sourceOrigin = await listenOnLoopback(sourceServer);
130+
});
131+
132+
beforeEach(() => {
133+
sourceRequests.length = 0;
134+
targetRequests.length = 0;
135+
});
136+
137+
afterAll(async () => {
138+
await Promise.all([closeLoopbackServer(sourceServer), closeLoopbackServer(targetServer)]);
139+
});
140+
141+
it("rejects private targets before the network or media store is reached", async () => {
142+
const stateDir = tempDirs.make("openclaw-media-private-fetch-");
143+
144+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
145+
const error = await saveRemoteMedia({
146+
url: `${sourceOrigin}/private`,
147+
maxBytes: 64,
148+
subdir: "private-target",
149+
}).catch((caught: unknown) => caught);
150+
151+
expect(error).toBeInstanceOf(MediaFetchError);
152+
expect(error).toMatchObject({
153+
code: "fetch_failed",
154+
cause: { name: "SsrFBlockedError" },
155+
});
156+
expect(sourceRequests).toHaveLength(0);
157+
await expectNoPublishedMediaFiles(stateDir);
158+
});
159+
});
160+
161+
it("revalidates redirect targets and strips sensitive cross-origin headers", async () => {
162+
const stateDir = tempDirs.make("openclaw-media-safe-redirect-");
163+
164+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
165+
const blocked = await saveRemoteMedia({
166+
url: `${sourceOrigin}/redirect`,
167+
requestInit: {
168+
headers: {
169+
Accept: "text/plain",
170+
Authorization: "Bearer private-token",
171+
Cookie: "session=private",
172+
"X-Api-Key": "private-key",
173+
},
174+
},
175+
maxBytes: 64,
176+
subdir: "blocked-redirect",
177+
ssrfPolicy: { allowedOrigins: [sourceOrigin] },
178+
}).catch((caught: unknown) => caught);
179+
180+
expect(blocked).toBeInstanceOf(MediaFetchError);
181+
expect(blocked).toMatchObject({
182+
code: "fetch_failed",
183+
cause: { name: "SsrFBlockedError" },
184+
});
185+
expect(sourceRequests).toHaveLength(1);
186+
expect(targetRequests).toHaveLength(0);
187+
await expectNoPublishedMediaFiles(stateDir);
188+
189+
sourceRequests.length = 0;
190+
const saved = await saveRemoteMedia({
191+
url: `${sourceOrigin}/redirect`,
192+
requestInit: {
193+
headers: {
194+
Accept: "text/plain",
195+
Authorization: "Bearer private-token",
196+
Cookie: "session=private",
197+
"X-Api-Key": "private-key",
198+
},
199+
},
200+
maxBytes: 64,
201+
subdir: "safe-redirect",
202+
ssrfPolicy: { allowedOrigins: [sourceOrigin, targetOrigin] },
203+
});
204+
205+
expect(sourceRequests[0]?.headers.authorization).toBe("Bearer private-token");
206+
expect(targetRequests).toHaveLength(1);
207+
expect(targetRequests[0]?.headers.accept).toBe("text/plain");
208+
expect(targetRequests[0]?.headers.authorization).toBeUndefined();
209+
expect(targetRequests[0]?.headers.cookie).toBeUndefined();
210+
expect(targetRequests[0]?.headers["x-api-key"]).toBeUndefined();
211+
await expect(fs.readFile(saved.path, "utf8")).resolves.toBe("redirected media");
212+
});
213+
});
214+
215+
it("rejects declared and streamed overflows without publishing store artifacts", async () => {
216+
const stateDir = tempDirs.make("openclaw-media-bounded-fetch-");
217+
const allowedOrigins = [sourceOrigin];
218+
219+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
220+
await expect(
221+
saveRemoteMedia({
222+
url: `${sourceOrigin}/oversized-file`,
223+
maxBytes: 16,
224+
subdir: "oversized-file",
225+
ssrfPolicy: { allowedOrigins },
226+
}),
227+
).rejects.toMatchObject({
228+
name: "MediaFetchError",
229+
code: "max_bytes",
230+
});
231+
await expectNoPublishedMediaFiles(stateDir);
232+
233+
await expect(
234+
saveRemoteMedia({
235+
url: `${sourceOrigin}/oversized-stream`,
236+
maxBytes: 16,
237+
subdir: "oversized-stream",
238+
ssrfPolicy: { allowedOrigins },
239+
}),
240+
).rejects.toMatchObject({
241+
name: "MediaFetchError",
242+
code: "max_bytes",
243+
});
244+
await expectNoPublishedMediaFiles(stateDir);
245+
});
246+
});
247+
});

0 commit comments

Comments
 (0)