Skip to content

Commit 3d4ca2f

Browse files
committed
fix(skills): bind archive extraction to verified root
1 parent d8f4575 commit 3d4ca2f

2 files changed

Lines changed: 317 additions & 114 deletions

File tree

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

Lines changed: 151 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import { createServer, type ServerResponse } from "node:http";
55
import type { Socket } from "node:net";
66
import path from "node:path";
77
import { Readable } from "node:stream";
8-
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
8+
import { __setFsSafeTestHooksForTest, getFsSafeTestHooks } from "@openclaw/fs-safe/test-hooks";
9+
import JSZip from "jszip";
10+
import * as tar from "tar";
11+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
912
import type { OpenClawTestState } from "../../test-utils/openclaw-test-state.js";
1013
import { resolveSkillToolsRootDir } from "../runtime/tools-dir.js";
1114
import { createInstallDownloadTestState } from "../test-support/install-download-test-utils.js";
@@ -228,6 +231,10 @@ beforeEach(() => {
228231
hasBinaryMock.mockReturnValue(true);
229232
});
230233

234+
afterEach(() => {
235+
__setFsSafeTestHooksForTest(undefined);
236+
});
237+
231238
describe("installDownloadSpec extraction safety", () => {
232239
it("rejects oversized advertised HTTP downloads before staging the response body", async () => {
233240
let responseCompleted = false;
@@ -526,6 +533,149 @@ describe("installDownloadSpec extraction safety", () => {
526533
await expect(fs.readdir(path.join(toolsRoot, "runtime"))).resolves.toEqual(["runtime.tar.bz2"]);
527534
});
528535

536+
it.runIf(process.platform !== "win32")(
537+
"fails closed when the tools root is replaced after verified archive publication",
538+
async () => {
539+
const verifiedArchive = Buffer.from("verified archive bytes");
540+
const replacementArchive = Buffer.from("unverified replacement archive bytes");
541+
const entry = buildEntry("verified-post-publication-root-replacement");
542+
const toolsRoot = resolveSkillToolsRootDir(entry);
543+
const displacedRoot = `${toolsRoot}-displaced`;
544+
const archivePath = path.join(toolsRoot, "runtime", "runtime.tar.bz2");
545+
const replacementOutput = path.join(toolsRoot, "runtime", "runtime.txt");
546+
let extractionArchivePath = "";
547+
let extractedArchiveBytes: Buffer | undefined;
548+
const release = vi.fn(async () => {
549+
const publishedIdentity = await fs.stat(archivePath);
550+
await getFsSafeTestHooks()?.afterPublishTargetCreated?.(
551+
"exclusive-copy",
552+
archivePath,
553+
publishedIdentity,
554+
);
555+
});
556+
fetchWithSsrFGuardMock.mockResolvedValue({
557+
response: {
558+
ok: true,
559+
status: 200,
560+
statusText: "OK",
561+
headers: new Headers(),
562+
body: Readable.from([verifiedArchive]),
563+
},
564+
release,
565+
});
566+
runCommandWithTimeoutMock.mockImplementation(async (...argv: unknown[]) => {
567+
const command = (argv[0] ?? []) as string[];
568+
if (command[1] === "tf") {
569+
return runCommandResult({ stdout: "runtime.txt\n" });
570+
}
571+
if (command[1] === "tvf") {
572+
return runCommandResult({
573+
stdout: "-rw-r--r-- 0 0 0 0 Jan 1 00:00 runtime.txt\n",
574+
});
575+
}
576+
if (command[1] === "xf") {
577+
extractionArchivePath = command[2] ?? "";
578+
extractedArchiveBytes = await fs.readFile(extractionArchivePath);
579+
const extractionDir = command[command.indexOf("-C") + 1] ?? "";
580+
await fs.writeFile(path.join(extractionDir, "runtime.txt"), extractedArchiveBytes);
581+
}
582+
return runCommandResult();
583+
});
584+
585+
__setFsSafeTestHooksForTest({
586+
afterPublishTargetCreated: async (_method, publishedPath) => {
587+
if (publishedPath !== archivePath) {
588+
return;
589+
}
590+
await fs.rename(toolsRoot, displacedRoot);
591+
await fs.mkdir(path.join(toolsRoot, "runtime"), { recursive: true });
592+
await fs.writeFile(archivePath, replacementArchive);
593+
},
594+
});
595+
596+
let result;
597+
try {
598+
result = await installDownloadSpec({
599+
entry,
600+
spec: {
601+
...buildDownloadSpec({
602+
url: "https://example.invalid/runtime.tar.bz2",
603+
archive: "tar.bz2",
604+
targetDir: "runtime",
605+
}),
606+
sha256: createHash("sha256").update(verifiedArchive).digest("hex"),
607+
},
608+
timeoutMs: 30_000,
609+
});
610+
} finally {
611+
__setFsSafeTestHooksForTest(undefined);
612+
}
613+
614+
expect(result.ok).toBe(false);
615+
expect(release).toHaveBeenCalledOnce();
616+
expect(extractedArchiveBytes).toEqual(verifiedArchive);
617+
expect(extractionArchivePath).not.toBe(archivePath);
618+
await expect(fileExists(extractionArchivePath)).resolves.toBe(false);
619+
await expect(fileExists(replacementOutput)).resolves.toBe(false);
620+
await expect(fs.readFile(archivePath)).resolves.toEqual(replacementArchive);
621+
await expect(
622+
fs.readFile(path.join(displacedRoot, "runtime", "runtime.tar.bz2")),
623+
).resolves.toEqual(verifiedArchive);
624+
expect(getFsSafeTestHooks()).toBeUndefined();
625+
},
626+
);
627+
628+
it.each(["tar.gz", "zip"] as const)(
629+
"publishes verified %s archives with executable files and empty directories",
630+
async (archiveType) => {
631+
const entry = buildEntry(`verified-published-${archiveType}`);
632+
const fixtureRoot = path.join(workspaceDir, `archive-fixture-${archiveType}`);
633+
const packageDir = path.join(fixtureRoot, "package");
634+
const executableContents = "#!/bin/sh\nprintf verified\\n\n";
635+
await fs.mkdir(path.join(packageDir, "empty"), { recursive: true });
636+
await fs.writeFile(path.join(packageDir, "run.sh"), executableContents, { mode: 0o755 });
637+
638+
let archive: Buffer;
639+
if (archiveType === "zip") {
640+
const zip = new JSZip();
641+
zip.folder("package/empty/");
642+
zip.file("package/run.sh", executableContents, { unixPermissions: 0o755 });
643+
archive = await zip.generateAsync({ type: "nodebuffer", platform: "UNIX" });
644+
} else {
645+
const fixtureArchive = path.join(fixtureRoot, "runtime.tar.gz");
646+
await tar.c({ cwd: fixtureRoot, file: fixtureArchive, gzip: true }, ["package"]);
647+
archive = await fs.readFile(fixtureArchive);
648+
}
649+
mockArchiveResponse(archive);
650+
651+
const archiveName = `runtime.${archiveType}`;
652+
const result = await installDownloadSpec({
653+
entry,
654+
spec: {
655+
...buildDownloadSpec({
656+
url: `https://example.invalid/${archiveName}`,
657+
archive: archiveType,
658+
targetDir: "runtime",
659+
stripComponents: 1,
660+
}),
661+
sha256: createHash("sha256").update(archive).digest("hex"),
662+
},
663+
timeoutMs: 30_000,
664+
});
665+
666+
const destinationDir = path.join(resolveSkillToolsRootDir(entry), "runtime");
667+
expect(result.ok).toBe(true);
668+
await expect(fs.readFile(path.join(destinationDir, archiveName))).resolves.toEqual(archive);
669+
await expect(fs.readFile(path.join(destinationDir, "run.sh"), "utf8")).resolves.toBe(
670+
executableContents,
671+
);
672+
expect((await fs.stat(path.join(destinationDir, "empty"))).isDirectory()).toBe(true);
673+
if (process.platform !== "win32") {
674+
expect((await fs.stat(path.join(destinationDir, "run.sh"))).mode & 0o111).toBe(0o111);
675+
}
676+
},
677+
);
678+
529679
it("rejects targetDir escapes outside the per-skill tools root", async () => {
530680
const beforeFetchCalls = fetchWithSsrFGuardMock.mock.calls.length;
531681
const entry = buildEntry("relative-traversal");

0 commit comments

Comments
 (0)