Skip to content

Commit 6f01c23

Browse files
mmapspgondhi987
andauthored
fix: guard generated video downloads (#101854)
Co-authored-by: Pavan Kumar Gondhi <[email protected]>
1 parent d1a97f5 commit 6f01c23

2 files changed

Lines changed: 170 additions & 44 deletions

File tree

‎src/cli/capability-cli.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2130,6 +2130,86 @@ describe("capability cli", () => {
21302130
expect(outputs[0]?.size).toBe(11);
21312131
});
21322132

2133+
it("blocks private-network url-only generated video downloads by default", async () => {
2134+
mocks.loadConfig.mockReturnValue({});
2135+
mocks.generateVideo.mockResolvedValue({
2136+
provider: "vydra",
2137+
model: "veo3",
2138+
attempts: [],
2139+
videos: [
2140+
{
2141+
url: "http://127.0.0.2:40123/private-video.mp4?sig=secret-presigned-token",
2142+
mimeType: "video/mp4",
2143+
fileName: "provider-name.mp4",
2144+
},
2145+
],
2146+
});
2147+
const fetchMock = vi.fn(
2148+
async () =>
2149+
new Response(Buffer.from("video-bytes"), {
2150+
status: 200,
2151+
headers: { "content-type": "video/mp4" },
2152+
}),
2153+
);
2154+
vi.stubGlobal("fetch", fetchMock);
2155+
2156+
await expect(
2157+
runRegisteredCli({
2158+
register: registerCapabilityCli as (program: Command) => void,
2159+
argv: ["capability", "video", "generate", "--prompt", "friendly lobster", "--json"],
2160+
}),
2161+
).rejects.toThrow("exit 1");
2162+
2163+
expect(fetchMock).not.toHaveBeenCalled();
2164+
expectRuntimeErrorContains("Blocked hostname or private/internal/special-use IP address");
2165+
expect(runtimeErrorMessages().join("\n")).not.toContain("secret-presigned-token");
2166+
expect(runtimeErrorMessages().join("\n")).not.toContain("/private-video.mp4");
2167+
});
2168+
2169+
it("allows private-network generated video downloads when the provider request opts in", async () => {
2170+
mocks.loadConfig.mockReturnValue({
2171+
models: {
2172+
providers: {
2173+
vydra: {
2174+
request: { allowPrivateNetwork: true },
2175+
},
2176+
},
2177+
},
2178+
});
2179+
mocks.generateVideo.mockResolvedValue({
2180+
provider: "vydra",
2181+
model: "veo3",
2182+
attempts: [],
2183+
videos: [
2184+
{
2185+
url: "http://127.0.0.2:40123/private-video.mp4",
2186+
mimeType: "video/mp4",
2187+
fileName: "provider-name.mp4",
2188+
},
2189+
],
2190+
});
2191+
const fetchMock = vi.fn(
2192+
async () =>
2193+
new Response(Buffer.from("video-bytes"), {
2194+
status: 200,
2195+
headers: { "content-type": "video/mp4" },
2196+
}),
2197+
);
2198+
vi.stubGlobal("fetch", fetchMock);
2199+
2200+
await runRegisteredCli({
2201+
register: registerCapabilityCli as (program: Command) => void,
2202+
argv: ["capability", "video", "generate", "--prompt", "friendly lobster", "--json"],
2203+
});
2204+
2205+
const fetchCalls = fetchMock.mock.calls as unknown as Array<[string]>;
2206+
expect(fetchCalls[0]?.[0]).toBe("http://127.0.0.2:40123/private-video.mp4");
2207+
const output = firstJsonOutput();
2208+
expect(output?.capability).toBe("video.generate");
2209+
expect(output?.provider).toBe("vydra");
2210+
expect(output?.outputs as Array<Record<string, unknown>>).toHaveLength(1);
2211+
});
2212+
21332213
it("passes video generation parameters through to runtime", async () => {
21342214
mocks.generateVideo.mockResolvedValue({
21352215
provider: "minimax",

‎src/cli/capability-cli.ts‎

Lines changed: 90 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ import { resolveGeneratedMediaMaxBytes } from "../media/configured-max-bytes.js"
7373
import { convertHeicToJpeg, getImageMetadata } from "../media/media-services.js";
7474
import { saveMediaBuffer } from "../media/store.js";
7575
import { createEmbeddingProvider } from "../plugin-sdk/memory-core-bundled-runtime.js";
76+
import {
77+
fetchWithTimeoutGuarded,
78+
resolveProviderHttpRequestConfig,
79+
sanitizeConfiguredModelProviderRequest,
80+
} from "../plugin-sdk/provider-http.js";
7681
import { listEmbeddingProviders } from "../plugins/embedding-provider-runtime.js";
7782
import { listMemoryEmbeddingProviders } from "../plugins/memory-embedding-providers.js";
7883
import { writeRuntimeJson, defaultRuntime, type RuntimeEnv } from "../runtime.js";
@@ -119,6 +124,7 @@ import { collectOption } from "./program/helpers.js";
119124
type CapabilityTransport = "local" | "gateway";
120125
const IMAGE_OUTPUT_FORMATS = ["png", "jpeg", "webp"] as const;
121126
const IMAGE_BACKGROUNDS = ["transparent", "opaque", "auto"] as const;
127+
const GENERATED_VIDEO_DOWNLOAD_TIMEOUT_MS = 120_000;
122128
const LOCAL_MODEL_RUN_SYSTEM_PROMPT = "You are a personal assistant running inside OpenClaw.";
123129
const HEIC_MODEL_RUN_MIMES = new Set(["image/heic", "image/heif"]);
124130

@@ -1306,6 +1312,43 @@ function normalizeVideoResolution(raw: string | undefined): VideoGenerationResol
13061312
throw new Error("video resolution must be one of 360P, 480P, 540P, 720P, 768P, or 1080P");
13071313
}
13081314

1315+
async function fetchGeneratedVideoDownload(params: {
1316+
cfg: OpenClawConfig;
1317+
provider: string;
1318+
url: string;
1319+
}) {
1320+
const providerConfig = params.cfg.models?.providers?.[params.provider];
1321+
const { allowPrivateNetwork, dispatcherPolicy } = resolveProviderHttpRequestConfig({
1322+
baseUrl: params.url,
1323+
defaultBaseUrl: params.url,
1324+
request: sanitizeConfiguredModelProviderRequest(providerConfig?.request),
1325+
provider: params.provider,
1326+
capability: "video",
1327+
transport: "http",
1328+
});
1329+
const result = await fetchWithTimeoutGuarded(
1330+
params.url,
1331+
{ method: "GET" },
1332+
GENERATED_VIDEO_DOWNLOAD_TIMEOUT_MS,
1333+
fetch,
1334+
{
1335+
...(allowPrivateNetwork ? { ssrfPolicy: { allowPrivateNetwork: true } } : {}),
1336+
...(dispatcherPolicy ? { dispatcherPolicy } : {}),
1337+
auditContext: `${params.provider}-generated-video-download`,
1338+
},
1339+
);
1340+
try {
1341+
await assertOkOrThrowHttpError(
1342+
result.response,
1343+
`${params.provider} generated video download failed`,
1344+
);
1345+
return result;
1346+
} catch (error) {
1347+
await result.release();
1348+
throw error;
1349+
}
1350+
}
1351+
13091352
async function runVideoGenerate(params: {
13101353
prompt: string;
13111354
model?: string;
@@ -1344,51 +1387,54 @@ async function runVideoGenerate(params: {
13441387

13451388
let videoBuffer = video.buffer;
13461389
if (!videoBuffer && video.url) {
1347-
const response = await fetch(video.url, { signal: AbortSignal.timeout(120_000) });
1348-
if (!response.ok) {
1349-
await assertOkOrThrowHttpError(
1350-
response,
1351-
`${result.provider} generated video download failed`,
1352-
);
1353-
}
1354-
if (params.output && response.body) {
1355-
const mimeType = normalizeMimeType(video.mimeType);
1356-
const ext =
1357-
extensionForMime(mimeType) ||
1358-
path.extname(video.fileName ?? "") ||
1359-
path.extname(params.output ?? "");
1360-
const resolvedOutput = path.resolve(params.output);
1361-
const parsed = path.parse(resolvedOutput);
1362-
const filePath =
1363-
result.videos.length <= 1
1364-
? path.join(parsed.dir, `${parsed.name}${ext}`)
1365-
: path.join(parsed.dir, `${parsed.name}-${String(index + 1)}${ext}`);
1366-
await fs.mkdir(path.dirname(filePath), { recursive: true });
1367-
await pipeline(
1368-
Readable.fromWeb(response.body as import("node:stream/web").ReadableStream),
1369-
createWriteStream(filePath),
1370-
);
1371-
const stat = await fs.stat(filePath);
1372-
return { path: filePath, mimeType: video.mimeType, size: stat.size };
1373-
}
1374-
// Provider-supplied video URLs are untrusted external sources, and the
1375-
// in-memory fallback (no --output) must not buffer an unbounded body:
1376-
// generated videos routinely exceed tens of MiB and a hostile/buggy
1377-
// provider could exhaust process memory. Cap the read (fail-closed:
1378-
// overflow cancels the stream and throws rather than silently
1379-
// truncating) using the same shared bounded reader the rest of the
1380-
// media stack relies on. The --output branch above already streams
1381-
// straight to disk, so only this buffered path needs the guard. The
1382-
// overflow error reports only the provider label and byte cap (never
1383-
// the raw URL, which may be signed/tokenized) to match the sibling
1384-
// generated-media downloaders.
1385-
const videoMaxBytes = resolveGeneratedMediaMaxBytes(cfg, "video");
1386-
videoBuffer = await readResponseWithLimit(response, videoMaxBytes, {
1387-
onOverflow: ({ maxBytes }) =>
1388-
new Error(
1389-
`${result.provider} generated video download exceeds ${maxBytes} bytes; pass --output to stream large videos to disk`,
1390-
),
1390+
const download = await fetchGeneratedVideoDownload({
1391+
cfg,
1392+
provider: result.provider,
1393+
url: video.url,
13911394
});
1395+
const response = download.response;
1396+
try {
1397+
if (params.output && response.body) {
1398+
const mimeType = normalizeMimeType(video.mimeType);
1399+
const ext =
1400+
extensionForMime(mimeType) ||
1401+
path.extname(video.fileName ?? "") ||
1402+
path.extname(params.output ?? "");
1403+
const resolvedOutput = path.resolve(params.output);
1404+
const parsed = path.parse(resolvedOutput);
1405+
const filePath =
1406+
result.videos.length <= 1
1407+
? path.join(parsed.dir, `${parsed.name}${ext}`)
1408+
: path.join(parsed.dir, `${parsed.name}-${String(index + 1)}${ext}`);
1409+
await fs.mkdir(path.dirname(filePath), { recursive: true });
1410+
await pipeline(
1411+
Readable.fromWeb(response.body as import("node:stream/web").ReadableStream),
1412+
createWriteStream(filePath),
1413+
);
1414+
const stat = await fs.stat(filePath);
1415+
return { path: filePath, mimeType: video.mimeType, size: stat.size };
1416+
}
1417+
// Provider-supplied video URLs are untrusted external sources, and the
1418+
// in-memory fallback (no --output) must not buffer an unbounded body:
1419+
// generated videos routinely exceed tens of MiB and a hostile/buggy
1420+
// provider could exhaust process memory. Cap the read (fail-closed:
1421+
// overflow cancels the stream and throws rather than silently
1422+
// truncating) using the same shared bounded reader the rest of the
1423+
// media stack relies on. The --output branch above already streams
1424+
// straight to disk, so only this buffered path needs the guard. The
1425+
// overflow error reports only the provider label and byte cap (never
1426+
// the raw URL, which may be signed/tokenized) to match the sibling
1427+
// generated-media downloaders.
1428+
const videoMaxBytes = resolveGeneratedMediaMaxBytes(cfg, "video");
1429+
videoBuffer = await readResponseWithLimit(response, videoMaxBytes, {
1430+
onOverflow: ({ maxBytes }) =>
1431+
new Error(
1432+
`${result.provider} generated video download exceeds ${maxBytes} bytes; pass --output to stream large videos to disk`,
1433+
),
1434+
});
1435+
} finally {
1436+
await download.release();
1437+
}
13921438
}
13931439

13941440
return {

0 commit comments

Comments
 (0)