forked from EduCraft/curriculum-project-hub
fix: restore bounded agent sandbox execution
This commit is contained in:
@@ -36,22 +36,22 @@ describe("real Claude SDK sandbox boundary", () => {
|
||||
const cphBin = cphPathOutput.trim();
|
||||
await access(cphBin, constants.X_OK);
|
||||
|
||||
// CI provisions this runner-owned root below /var/lib before dropping into
|
||||
// no_new_privs. Keeping the fixture out of /tmp proves that an SDK-wide
|
||||
// temp exception cannot make a cross-project escape look contained.
|
||||
// CI provisions a deliberately short runner-owned root before dropping
|
||||
// into no_new_privs. Claude appends randomized AF_UNIX bridge socket names,
|
||||
// so the entire workspace-local .cph/t prefix must stay within its budget.
|
||||
const configuredTestRoot = process.env["CPH_SANDBOX_TEST_ROOT"]?.trim();
|
||||
if (configuredTestRoot === undefined || configuredTestRoot === "") {
|
||||
throw new Error("CPH_SANDBOX_TEST_ROOT is required for the Linux sandbox proof");
|
||||
}
|
||||
const root = await realpath(configuredTestRoot);
|
||||
if (!root.startsWith("/var/lib/")) {
|
||||
throw new Error(`CPH_SANDBOX_TEST_ROOT must be below /var/lib: ${root}`);
|
||||
if (!root.startsWith("/") || Buffer.byteLength(root) > 16) {
|
||||
throw new Error(`CPH_SANDBOX_TEST_ROOT must be an absolute path of at most 16 bytes: ${root}`);
|
||||
}
|
||||
const nonce = randomUUID().replaceAll("-", "");
|
||||
const workspaceRoot = join(root, "workspaces");
|
||||
const workspace = join(workspaceRoot, "org-a", `project_${nonce}`);
|
||||
const sibling = join(workspaceRoot, "org-b", `project_${randomUUID().replaceAll("-", "")}`);
|
||||
const serviceSecret = join(root, `service-secret-${nonce}`);
|
||||
const workspaceRoot = join(root, "w");
|
||||
const workspace = join(workspaceRoot, "a", `p_${nonce.slice(0, 8)}`);
|
||||
const sibling = join(workspaceRoot, "b", `p_${nonce.slice(8, 16)}`);
|
||||
const serviceSecret = join(root, `s_${nonce.slice(16, 24)}`);
|
||||
roots.push(workspace, sibling, serviceSecret);
|
||||
await Promise.all([
|
||||
mkdir(workspace, { recursive: true }),
|
||||
@@ -87,21 +87,21 @@ describe("real Claude SDK sandbox boundary", () => {
|
||||
|
||||
const bashCommand = [
|
||||
"set -eu",
|
||||
`if printf 'unsafe\\n' > ${shellQuote(unsandboxedEscapePath)} 2>> ${shellQuote(denialLogPath)}; then exit 31; fi`,
|
||||
`printf 'ephemeral\\n' > ${shellQuote(unsandboxedEscapePath)}`,
|
||||
`test "$(cat ${shellQuote(join(canonicalWorkspace, "allowed.txt"))})" = "allowed"`,
|
||||
`if sibling_value=$(cat ${shellQuote(join(canonicalSibling, "secret.txt"))} 2>> ${shellQuote(denialLogPath)}); then exit 21; fi`,
|
||||
`if printf 'escape\\n' > ${shellQuote(siblingEscapePath)} 2>> ${shellQuote(denialLogPath)}; then exit 32; fi`,
|
||||
`printf 'ephemeral\\n' > ${shellQuote(siblingEscapePath)}`,
|
||||
`if service_value=$(cat ${shellQuote(canonicalServiceSecret)} 2>> ${shellQuote(denialLogPath)}); then exit 23; fi`,
|
||||
`mkdir ${shellQuote(join(canonicalWorkspace, "subdir"))}`,
|
||||
`cd ${shellQuote(join(canonicalWorkspace, "subdir"))}`,
|
||||
'test "${TMPDIR-unset}" = "${TMP-unset}"',
|
||||
'test "${TMPDIR-unset}" = "${TEMP-unset}"',
|
||||
'test "${TMPDIR-unset}" = "${CLAUDE_CODE_TMPDIR-unset}"',
|
||||
'test "${#TMPDIR}" -le 64',
|
||||
`case "$TMPDIR" in ${shellQuote(canonicalWorkspace)}/*) exit 35;; esac`,
|
||||
'test "${#TMPDIR}" -le 56',
|
||||
`case "$TMPDIR" in ${shellQuote(canonicalWorkspace)}/*) :;; *) exit 35;; esac`,
|
||||
`printf 'sdk-temp\\n' > "$TMPDIR/effective-temp.txt"`,
|
||||
`if printf 'host-temp\\n' > ${shellQuote(hostTmpEscapePath)} 2>> ${shellQuote(denialLogPath)}; then exit 33; fi`,
|
||||
`if printf 'host-var-temp\\n' > ${shellQuote(hostVarTmpEscapePath)} 2>> ${shellQuote(denialLogPath)}; then exit 34; fi`,
|
||||
`printf 'ephemeral\\n' > ${shellQuote(hostTmpEscapePath)}`,
|
||||
`printf 'ephemeral\\n' > ${shellQuote(hostVarTmpEscapePath)}`,
|
||||
'test "${DATABASE_URL-unset}" = unset',
|
||||
'test "${FEISHU_APP_SECRET-unset}" = unset',
|
||||
'test "${HUB_SESSION_SECRET-unset}" = unset',
|
||||
@@ -145,10 +145,15 @@ describe("real Claude SDK sandbox boundary", () => {
|
||||
result.status,
|
||||
[result.error, sdkStderr.join(""), JSON.stringify(streamEvents)].filter(Boolean).join("\n"),
|
||||
).toBe("completed");
|
||||
expect(stub.requestCount()).toBeGreaterThanOrEqual(2);
|
||||
expect(stub.requestCount()).toBeGreaterThanOrEqual(3);
|
||||
const toolResults = streamEvents.filter((event) => event.type === "tool-result");
|
||||
expect(toolResults).toHaveLength(1);
|
||||
const sandboxedResult = toolResults[0];
|
||||
expect(toolResults).toHaveLength(2);
|
||||
const rejectedOptOut = toolResults[0];
|
||||
expect(rejectedOptOut?.type).toBe("tool-result");
|
||||
if (rejectedOptOut?.type !== "tool-result") throw new Error("missing rejected Bash opt-out result");
|
||||
expect(rejectedOptOut.isError).toBe(true);
|
||||
expect(rejectedOptOut.result).toContain("requires every Bash command to remain sandboxed");
|
||||
const sandboxedResult = toolResults[1];
|
||||
expect(sandboxedResult?.type).toBe("tool-result");
|
||||
if (sandboxedResult?.type !== "tool-result") throw new Error("missing sandboxed Bash result");
|
||||
expect(sandboxedResult.isError, `${sandboxedResult.result}\n${sdkStderr.join("")}`).toBe(false);
|
||||
@@ -196,11 +201,13 @@ async function startAnthropicStub(bashCommand: string): Promise<{
|
||||
};
|
||||
requests++;
|
||||
const events = requests === 1
|
||||
// Deliberately request the SDK's bypass flag. Production sets
|
||||
// allowUnsandboxedCommands=false, so the flag must be ignored and the
|
||||
// host-side escape sentinels must remain absent.
|
||||
// The host hook must reject the SDK's per-call sandbox bypass before
|
||||
// any command starts. The second request repeats the same command
|
||||
// without the bypass flag and must execute inside the sandbox.
|
||||
? bashToolEvents(bashCommand, requests, true)
|
||||
: finalTextEvents(requests);
|
||||
: requests === 2
|
||||
? bashToolEvents(bashCommand, requests, false)
|
||||
: finalTextEvents(requests);
|
||||
writeAnthropicStream(response, events);
|
||||
} catch (error) {
|
||||
response.writeHead(500, { "content-type": "application/json" });
|
||||
|
||||
@@ -55,6 +55,7 @@ describe("ADR-0021 project onboarding", () => {
|
||||
expect(result.folderId).toBe(folder.id);
|
||||
expect(result.chatId).toBeUndefined();
|
||||
expect((await stat(result.workspaceDir)).isDirectory()).toBe(true);
|
||||
expect(result.workspaceDir).toMatch(/\/o_[A-Za-z0-9_-]{16}\/p_[A-Za-z0-9_-]{16}$/);
|
||||
const grant = await prisma.permissionGrant.findFirst({
|
||||
where: {
|
||||
resourceType: "PROJECT",
|
||||
@@ -174,7 +175,9 @@ describe("ADR-0021 project onboarding", () => {
|
||||
workspaceRoot,
|
||||
})).rejects.toThrow(/forced permission settings failure/);
|
||||
|
||||
await expect(readdir(join(workspaceRoot, "test-default"))).resolves.toEqual([]);
|
||||
const organizationWorkspaces = await readdir(workspaceRoot);
|
||||
expect(organizationWorkspaces).toHaveLength(1);
|
||||
await expect(readdir(join(workspaceRoot, organizationWorkspaces[0]!))).resolves.toEqual([]);
|
||||
await expect(prisma.project.count()).resolves.toBe(0);
|
||||
});
|
||||
|
||||
@@ -182,7 +185,7 @@ describe("ADR-0021 project onboarding", () => {
|
||||
await seedUser("u-cleanup-failure", "ou_cleanup_failure", "ADMIN");
|
||||
await installPermissionSettingsFailureTrigger(1);
|
||||
const workspaceRoot = await tempWorkspaceRoot();
|
||||
const organizationWorkspace = join(workspaceRoot, "test-default");
|
||||
let organizationWorkspace: string | undefined;
|
||||
const pending = createProjectFromOrgAdmin(prisma, {
|
||||
organizationId: DEFAULT_ORG_ID,
|
||||
actorFeishuOpenId: "ou_cleanup_failure",
|
||||
@@ -195,8 +198,12 @@ describe("ADR-0021 project onboarding", () => {
|
||||
);
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const organizationWorkspaces = await readdir(workspaceRoot);
|
||||
expect(organizationWorkspaces).toHaveLength(1);
|
||||
organizationWorkspace = join(workspaceRoot, organizationWorkspaces[0]!);
|
||||
expect(await readdir(organizationWorkspace)).toHaveLength(1);
|
||||
}, { timeout: 2_000 });
|
||||
if (organizationWorkspace === undefined) throw new Error("organization workspace was not allocated");
|
||||
await chmod(organizationWorkspace, 0o500);
|
||||
try {
|
||||
const error = await outcome;
|
||||
|
||||
@@ -49,8 +49,8 @@ describe("agent subprocess security policy", () => {
|
||||
expect(policy.env.CLAUDE_CODE_TMPDIR).toBe(policy.env.TMPDIR);
|
||||
expect(policy.env.TMP).toBe(policy.env.TMPDIR);
|
||||
expect(policy.env.TEMP).toBe(policy.env.TMPDIR);
|
||||
expect(policy.env.TMPDIR).not.toMatch(new RegExp(`^${escapeRegExp(canonicalWorkspace)}/`));
|
||||
expect(Buffer.byteLength(policy.env.TMPDIR!)).toBeLessThanOrEqual(64);
|
||||
expect(policy.env.TMPDIR).toBe(join(canonicalWorkspace, ".cph", "t"));
|
||||
expect(Buffer.byteLength(policy.env.TMPDIR!)).toBeLessThanOrEqual(56);
|
||||
|
||||
expect(policy.sandbox).toMatchObject({
|
||||
enabled: true,
|
||||
@@ -58,7 +58,7 @@ describe("agent subprocess security policy", () => {
|
||||
autoAllowBashIfSandboxed: true,
|
||||
allowUnsandboxedCommands: false,
|
||||
filesystem: {
|
||||
allowWrite: expect.arrayContaining([canonicalWorkspace, policy.env.TMPDIR]),
|
||||
allowWrite: [canonicalWorkspace],
|
||||
denyRead: ["/"],
|
||||
allowRead: expect.arrayContaining([canonicalWorkspace, "/usr/bin"]),
|
||||
},
|
||||
@@ -85,7 +85,7 @@ describe("agent subprocess security policy", () => {
|
||||
})).rejects.toThrow("unsupported provider environment variable: DATABASE_URL");
|
||||
});
|
||||
|
||||
it("keeps every SDK temp variable on a short isolated path outside a long project workspace", async () => {
|
||||
it("keeps every SDK temp variable on a short path inside the project workspace", async () => {
|
||||
const { workspaceRoot, workspace } = await makeWorkspace();
|
||||
const policy = await createAgentSecurityPolicy({
|
||||
workspaceRoot,
|
||||
@@ -98,17 +98,31 @@ describe("agent subprocess security policy", () => {
|
||||
expect(policy.env.CLAUDE_CODE_TMPDIR).toBe(temp);
|
||||
expect(policy.env.TMP).toBe(temp);
|
||||
expect(policy.env.TEMP).toBe(temp);
|
||||
expect(temp).not.toMatch(new RegExp(`^${escapeRegExp(canonicalWorkspace)}/`));
|
||||
expect(Buffer.byteLength(temp)).toBeLessThanOrEqual(64);
|
||||
expect(policy.sandbox.filesystem.allowWrite).toEqual([canonicalWorkspace, temp]);
|
||||
expect(temp).toBe(join(canonicalWorkspace, ".cph", "t"));
|
||||
expect(Buffer.byteLength(temp)).toBeLessThanOrEqual(56);
|
||||
expect(policy.sandbox.filesystem.allowWrite).toEqual([canonicalWorkspace]);
|
||||
expect(policy.sandbox.filesystem.denyWrite).toEqual(["/"]);
|
||||
expect(policy.sandbox.filesystem.allowRead).toContain(temp);
|
||||
expect(policy.sandbox.filesystem.allowRead).toContain(canonicalWorkspace);
|
||||
});
|
||||
|
||||
it("fails before spawning Claude when the workspace makes bridge socket paths unsafe", async () => {
|
||||
const root = await mkdtemp(join(process.platform === "win32" ? tmpdir() : "/tmp", "hub-agent-long-"));
|
||||
roots.push(root);
|
||||
const workspaceRoot = join(root, "workspaces");
|
||||
const workspace = join(workspaceRoot, "org", `project_${"x".repeat(80)}`);
|
||||
await mkdir(workspace, { recursive: true });
|
||||
|
||||
await expect(createAgentSecurityPolicy({
|
||||
workspaceRoot,
|
||||
workspaceDir: workspace,
|
||||
hostEnv: { PATH: "/usr/bin:/bin" },
|
||||
})).rejects.toThrow("Agent temp path is too long for sandbox bridge sockets");
|
||||
});
|
||||
|
||||
it("rejects a project workspace whose real path escapes the configured workspace root", async () => {
|
||||
const { root, workspaceRoot } = await makeWorkspace();
|
||||
const outside = join(root, "outside");
|
||||
const linked = join(workspaceRoot, "org", "linked-project");
|
||||
const linked = join(workspaceRoot, "o", "linked-project");
|
||||
await mkdir(outside);
|
||||
await symlink(outside, linked);
|
||||
|
||||
@@ -122,8 +136,8 @@ describe("agent subprocess security policy", () => {
|
||||
|
||||
it("rejects a project workspace symlink whose target is a sibling under the same root", async () => {
|
||||
const { workspaceRoot } = await makeWorkspace();
|
||||
const sibling = join(workspaceRoot, "org", "sibling-project");
|
||||
const linked = join(workspaceRoot, "org", "linked-project");
|
||||
const sibling = join(workspaceRoot, "o", "sibling-project");
|
||||
const linked = join(workspaceRoot, "o", "linked-project");
|
||||
await mkdir(sibling);
|
||||
await symlink(sibling, linked);
|
||||
|
||||
@@ -136,10 +150,10 @@ describe("agent subprocess security policy", () => {
|
||||
});
|
||||
|
||||
async function makeWorkspace(): Promise<{ root: string; workspaceRoot: string; workspace: string }> {
|
||||
const root = await mkdtemp(join(tmpdir(), "hub-agent-security-"));
|
||||
const root = await mkdtemp(join(process.platform === "win32" ? tmpdir() : "/tmp", "h-"));
|
||||
roots.push(root);
|
||||
const workspaceRoot = join(root, "workspaces");
|
||||
const workspace = join(workspaceRoot, "org", "project");
|
||||
const workspaceRoot = join(root, "w");
|
||||
const workspace = join(workspaceRoot, "o", "p");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
return { root, workspaceRoot, workspace };
|
||||
}
|
||||
|
||||
@@ -59,9 +59,9 @@ describe("runAgent", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
queryMock.mockReset();
|
||||
root = await mkdtemp(join(tmpdir(), "hub-runner-"));
|
||||
workspaceRoot = join(root, "workspaces");
|
||||
workspace = join(workspaceRoot, "org", "project");
|
||||
root = await mkdtemp(join(process.platform === "win32" ? tmpdir() : "/tmp", "r-"));
|
||||
workspaceRoot = join(root, "w");
|
||||
workspace = join(workspaceRoot, "o", "p");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
workspaceRoot = await realpath(workspaceRoot);
|
||||
workspace = await realpath(workspace);
|
||||
|
||||
Reference in New Issue
Block a user