Skip to content

Commit e3320ba

Browse files
vincentkocafurm
andcommitted
fix(skills): bound installer downloads
Co-authored-by: Andrii Furmanets <[email protected]> Punchcard-Session: cobalt-brook-meadow-m9
1 parent 1f3d45b commit e3320ba

3 files changed

Lines changed: 193 additions & 9 deletions

File tree

‎docs/tools/skills.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,8 @@ metadata:
462462
env vars are read but never overwritten.
463463
- **Download:** `url` (required), `archive` (`tar.gz` | `tar.bz2` | `zip`),
464464
`extract` (default: auto when archive detected), `stripComponents`,
465-
`targetDir` (default: `~/.openclaw/tools/<skillKey>`).
465+
`targetDir` (default: `~/.openclaw/tools/<skillKey>`). Downloads are
466+
rejected when the advertised or streamed response exceeds 256 MiB.
466467
</Accordion>
467468
<Accordion title="Sandboxing notes">
468469
`requires.bins` is checked on the **host** at skill load time. If an agent

‎src/skills/lifecycle/install-download.test.ts‎

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ import {
1313
} from "../test-support/install-test-mocks.js";
1414
import { createCanonicalFixtureSkill } from "../test-support/test-helpers.js";
1515
import type { SkillEntry, SkillInstallSpec } from "../types.js";
16-
import { installDownloadSpec } from "./install-download.js";
16+
import { installDownloadSpec, installDownloadTesting } from "./install-download.js";
17+
18+
const MAX_SKILL_DOWNLOAD_BYTES = 256 * 1024 * 1024;
1719

1820
vi.mock("../../process/exec.js", () => ({
1921
runCommandWithTimeout: (...args: unknown[]) => runCommandWithTimeoutMock(...args),
@@ -90,6 +92,7 @@ function mockArchiveResponse(buffer: Uint8Array): void {
9092
ok: true,
9193
status: 200,
9294
statusText: "OK",
95+
headers: new Headers(),
9396
body: Readable.from([Buffer.from(buffer)]),
9497
},
9598
release: async () => undefined,
@@ -212,6 +215,132 @@ describe("installDownloadSpec extraction safety", () => {
212215
).toBe("payload");
213216
});
214217

218+
it("rejects downloads whose advertised size exceeds the skill download limit", async () => {
219+
const response = new Response("payload", {
220+
status: 200,
221+
headers: { "content-length": String(MAX_SKILL_DOWNLOAD_BYTES + 1) },
222+
});
223+
const cancel = vi.spyOn(response.body!, "cancel").mockResolvedValue(undefined);
224+
fetchWithSsrFGuardMock.mockResolvedValue({
225+
response,
226+
release: async () => undefined,
227+
});
228+
const entry = buildEntry("oversized-download-header");
229+
const toolsRoot = resolveSkillToolsRootDir(entry);
230+
231+
const result = await installDownloadSpec({
232+
entry,
233+
spec: {
234+
kind: "download",
235+
id: "dl",
236+
url: "https://example.invalid/payload.bin",
237+
extract: false,
238+
targetDir: "runtime",
239+
},
240+
timeoutMs: 30_000,
241+
});
242+
243+
expect(result).toMatchObject({
244+
ok: false,
245+
stderr: `download too large: ${MAX_SKILL_DOWNLOAD_BYTES + 1} bytes (limit: ${MAX_SKILL_DOWNLOAD_BYTES} bytes)`,
246+
});
247+
expect(cancel).toHaveBeenCalledOnce();
248+
await expect(fileExists(path.join(toolsRoot, "runtime", "payload.bin"))).resolves.toBe(false);
249+
await expect(fs.readdir(path.join(toolsRoot, ".openclaw-download-staging"))).resolves.toEqual(
250+
[],
251+
);
252+
});
253+
254+
it("rejects malformed advertised sizes before reading the response body", async () => {
255+
const response = new Response("payload", {
256+
status: 200,
257+
headers: { "content-length": "1e9" },
258+
});
259+
const cancel = vi.spyOn(response.body!, "cancel").mockResolvedValue(undefined);
260+
fetchWithSsrFGuardMock.mockResolvedValue({
261+
response,
262+
release: async () => undefined,
263+
});
264+
const entry = buildEntry("malformed-download-header");
265+
const toolsRoot = resolveSkillToolsRootDir(entry);
266+
267+
const result = await installDownloadSpec({
268+
entry,
269+
spec: {
270+
kind: "download",
271+
id: "dl",
272+
url: "https://example.invalid/payload.bin",
273+
extract: false,
274+
targetDir: "runtime",
275+
},
276+
timeoutMs: 30_000,
277+
});
278+
279+
expect(result).toMatchObject({
280+
ok: false,
281+
stderr: "invalid content-length header: 1e9",
282+
});
283+
expect(cancel).toHaveBeenCalledOnce();
284+
await expect(fileExists(path.join(toolsRoot, "runtime", "payload.bin"))).resolves.toBe(false);
285+
await expect(fs.readdir(path.join(toolsRoot, ".openclaw-download-staging"))).resolves.toEqual(
286+
[],
287+
);
288+
});
289+
290+
it("rejects headerless streamed overflow and removes the partial staging file", async () => {
291+
const maxBytes = 8;
292+
const partialChunk = Buffer.from("partial");
293+
const overflowChunk = Buffer.from("!!");
294+
const chunks = [partialChunk, overflowChunk];
295+
let chunkIndex = 0;
296+
const body = new Readable({
297+
read() {
298+
if (chunkIndex < chunks.length) {
299+
this.push(chunks[chunkIndex++]);
300+
}
301+
},
302+
});
303+
const destroy = vi.spyOn(body, "destroy");
304+
fetchWithSsrFGuardMock.mockResolvedValue({
305+
response: {
306+
ok: true,
307+
status: 200,
308+
statusText: "OK",
309+
headers: new Headers(),
310+
body,
311+
},
312+
release: async () => undefined,
313+
});
314+
const entry = buildEntry("oversized-download-stream");
315+
const toolsRoot = resolveSkillToolsRootDir(entry);
316+
317+
const result = await installDownloadTesting.installDownloadSpecWithLimit(
318+
{
319+
entry,
320+
spec: {
321+
kind: "download",
322+
id: "dl",
323+
url: "https://example.invalid/payload.bin",
324+
extract: false,
325+
targetDir: "runtime",
326+
},
327+
timeoutMs: 30_000,
328+
},
329+
maxBytes,
330+
);
331+
332+
expect(result).toMatchObject({
333+
ok: false,
334+
stderr: `download too large: ${partialChunk.byteLength + overflowChunk.byteLength} bytes (limit: ${maxBytes} bytes)`,
335+
});
336+
expect(destroy).toHaveBeenCalled();
337+
expect(body.destroyed).toBe(true);
338+
await expect(fileExists(path.join(toolsRoot, "runtime", "payload.bin"))).resolves.toBe(false);
339+
await expect(fs.readdir(path.join(toolsRoot, ".openclaw-download-staging"))).resolves.toEqual(
340+
[],
341+
);
342+
});
343+
215344
it("cancels failed download response bodies before returning the error", async () => {
216345
const { stream, wasCanceled } = createCancelableBody();
217346
const release = vi.fn(async () => undefined);
@@ -256,6 +385,7 @@ describe("installDownloadSpec extraction safety", () => {
256385
ok: true,
257386
status: 200,
258387
statusText: "OK",
388+
headers: new Headers(),
259389
body: Readable.from(
260390
(async function* () {
261391
yield Buffer.from("payload");

‎src/skills/lifecycle/install-download.ts‎

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
import { randomUUID } from "node:crypto";
33
import fs from "node:fs";
44
import path from "node:path";
5-
import { Readable } from "node:stream";
5+
import { Readable, Transform } from "node:stream";
66
import { pipeline } from "node:stream/promises";
77
import type { ReadableStream as NodeReadableStream } from "node:stream/web";
8+
import { parseMediaContentLength } from "@openclaw/media-core/content-length";
89
import { normalizeOptionalLowercaseString } from "@openclaw/normalization-core/string-coerce";
910
import { isWindowsDrivePath } from "../../infra/archive-path.js";
1011
import { formatErrorMessage } from "../../infra/errors.js";
@@ -19,6 +20,14 @@ import type { SkillEntry, SkillInstallSpec } from "../types.js";
1920
import { formatInstallFailureMessage } from "./install-output.js";
2021
import type { SkillInstallResult } from "./install-types.js";
2122

23+
const MAX_SKILL_DOWNLOAD_BYTES = 256 * 1024 * 1024;
24+
25+
type InstallDownloadSpecParams = {
26+
entry: SkillEntry;
27+
spec: SkillInstallSpec;
28+
timeoutMs: number;
29+
};
30+
2231
const extractModuleLoader = createLazyImportLoader(() => import("./install-extract.js"));
2332

2433
async function loadExtractModule() {
@@ -41,6 +50,38 @@ async function cancelIgnoredResponseBody(response: Response): Promise<void> {
4150
await Promise.resolve(cancel.call(body)).catch(() => undefined);
4251
}
4352

53+
function formatDownloadTooLargeError(bytes: number, maxBytes: number): string {
54+
return `download too large: ${bytes} bytes (limit: ${maxBytes} bytes)`;
55+
}
56+
57+
async function assertDownloadResponseSize(response: Response, maxBytes: number): Promise<void> {
58+
let contentLength: number | null;
59+
try {
60+
contentLength = parseMediaContentLength(response.headers.get("content-length"));
61+
} catch (err) {
62+
await cancelIgnoredResponseBody(response);
63+
throw err;
64+
}
65+
if (contentLength !== null && contentLength > maxBytes) {
66+
await cancelIgnoredResponseBody(response);
67+
throw new Error(formatDownloadTooLargeError(contentLength, maxBytes));
68+
}
69+
}
70+
71+
function createDownloadSizeLimitTransform(maxBytes: number): Transform {
72+
let downloadedBytes = 0;
73+
return new Transform({
74+
transform(chunk: Uint8Array, _encoding, callback) {
75+
downloadedBytes += chunk.byteLength;
76+
if (downloadedBytes > maxBytes) {
77+
callback(new Error(formatDownloadTooLargeError(downloadedBytes, maxBytes)));
78+
return;
79+
}
80+
callback(null, chunk);
81+
},
82+
});
83+
}
84+
4485
function resolveDownloadTargetDir(entry: SkillEntry, spec: SkillInstallSpec): string {
4586
const root = resolveSkillToolsRootDir(entry);
4687
const raw = spec.targetDir?.trim();
@@ -88,6 +129,7 @@ async function downloadFile(params: {
88129
rootDir: string;
89130
relativePath: string;
90131
timeoutMs: number;
132+
maxBytes: number;
91133
}): Promise<{ bytes: number }> {
92134
const destPath = path.resolve(params.rootDir, params.relativePath);
93135
const stagingDir = path.join(params.rootDir, ".openclaw-download-staging");
@@ -107,12 +149,13 @@ async function downloadFile(params: {
107149
await cancelIgnoredResponseBody(response);
108150
throw new Error(`Download failed (${response.status} ${response.statusText})`);
109151
}
152+
await assertDownloadResponseSize(response, params.maxBytes);
110153
const file = fs.createWriteStream(tempPath);
111154
const body = response.body as unknown;
112155
const readable = isNodeReadableStream(body)
113156
? body
114157
: Readable.fromWeb(body as NodeReadableStream);
115-
await pipeline(readable, file);
158+
await pipeline(readable, createDownloadSizeLimitTransform(params.maxBytes), file);
116159
const root = await fsRoot(params.rootDir);
117160
await root.copyIn(params.relativePath, tempPath);
118161
const stat = await fs.promises.stat(destPath);
@@ -123,11 +166,10 @@ async function downloadFile(params: {
123166
}
124167
}
125168

126-
export async function installDownloadSpec(params: {
127-
entry: SkillEntry;
128-
spec: SkillInstallSpec;
129-
timeoutMs: number;
130-
}): Promise<SkillInstallResult> {
169+
async function installDownloadSpecWithLimit(
170+
params: InstallDownloadSpecParams,
171+
maxBytes: number,
172+
): Promise<SkillInstallResult> {
131173
const { entry, spec, timeoutMs } = params;
132174
const root = resolveSkillToolsRootDir(entry);
133175
const url = spec.url?.trim();
@@ -200,6 +242,7 @@ export async function installDownloadSpec(params: {
200242
rootDir: canonicalRoot,
201243
relativePath: archiveRelativePath,
202244
timeoutMs,
245+
maxBytes,
203246
});
204247
downloaded = result.bytes;
205248
} catch (err) {
@@ -259,3 +302,13 @@ export async function installDownloadSpec(params: {
259302
code: extractResult.code,
260303
};
261304
}
305+
306+
export async function installDownloadSpec(
307+
params: InstallDownloadSpecParams,
308+
): Promise<SkillInstallResult> {
309+
return installDownloadSpecWithLimit(params, MAX_SKILL_DOWNLOAD_BYTES);
310+
}
311+
312+
export const installDownloadTesting = {
313+
installDownloadSpecWithLimit,
314+
};

0 commit comments

Comments
 (0)