diff --git a/scripts/security/run-codex-scan-worker.test.ts b/scripts/security/run-codex-scan-worker.test.ts index ee8b0d7584..4ad9252ce4 100644 --- a/scripts/security/run-codex-scan-worker.test.ts +++ b/scripts/security/run-codex-scan-worker.test.ts @@ -1,6 +1,7 @@ /* @vitest-environment node */ -import { createHash } from "node:crypto"; -import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createHash, randomUUID } from "node:crypto"; +import { chmod, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createTestTempDirectories } from "../lib/testTempDirectories"; @@ -1148,6 +1149,62 @@ describe("run-codex-scan-worker diagnostics", () => { else process.env.GITHUB_ACTIONS = previousGitHubActions; }); + // Docker sandboxes leave root-owned files in the workspace. Their EACCES + // used to replace processJob's result and fail the whole shard. + it.skipIf(process.getuid?.() === 0)( + "keeps a recorded result when the workspace cannot be deleted", + async () => { + const jobId = `securityScanJobs:locked-${randomUUID()}`; + let lockedDir: string | undefined; + const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + const client = { + action: vi.fn(async (..._args: unknown[]) => { + const workspaceName = (await readdir(tmpdir())).find((name) => + name.startsWith(`clawhub-codex-scan-${jobId}-`), + ); + if (!workspaceName) throw new Error("scan workspace not found"); + const workspace = join(tmpdir(), workspaceName); + tempDirs.track(workspace); + lockedDir = join(workspace, "sandbox-output"); + await mkdir(lockedDir); + await writeFile(join(lockedDir, "log.txt"), "root-owned in production"); + await chmod(lockedDir, 0o500); + return null; + }), + }; + + try { + await expect( + processJob( + client, + "worker-token", + { + job: { + _id: jobId, + hasMaliciousSignal: false, + leaseToken: "lease-token", + scanMode: "endor-report-only", + source: "publish", + targetKind: "packageRelease", + }, + target: {}, + }, + undefined, + ), + ).resolves.toEqual({ completed: true, hardFailed: false, retryableFailed: false }); + const logged = stdoutWrite.mock.calls.map((call) => String(call[0])).join("\n"); + const cleanupLog = logged + .split("\n") + .find((line) => line.includes('"security_scan_workspace_cleanup_failed"')); + // Node reports EACCES here; Bun may report ENOTEMPTY for the same tree. + expect(JSON.parse(cleanupLog ?? "null")).toMatchObject({ jobId, code: "EACCES" }); + expect(logged).not.toContain(tmpdir()); + } finally { + if (lockedDir) await chmod(lockedDir, 0o700); + } + }, + ); + it("retains full ClawScan artifact and scanner outputs with secret-safe redaction", async () => { const diagnosticsRoot = await tempDirs.create(); const workspace = await tempDirs.create(); diff --git a/scripts/security/run-codex-scan-worker.ts b/scripts/security/run-codex-scan-worker.ts index 66f9ebcd2b..fc2ef4a297 100644 --- a/scripts/security/run-codex-scan-worker.ts +++ b/scripts/security/run-codex-scan-worker.ts @@ -2818,11 +2818,30 @@ export async function processJob( "preserving scan workspace because container removal was not confirmed", ); } else { - await rm(workspace, { recursive: true, force: true }); + await removeScanWorkspace(workspace, job.job._id); } } } +// Cleanup must never replace processJob's result or error. Docker sandboxes +// leave root-owned files in the bind mount, so this can fail; hosted runners +// are discarded after the run, so the leftover is logged and accepted. +async function removeScanWorkspace(workspace: string, jobId: string) { + try { + await rm(workspace, { recursive: true, force: true }); + } catch (error) { + const code = error instanceof Error && "code" in error ? error.code : undefined; + logger.warn( + { + event: "security_scan_workspace_cleanup_failed", + jobId, + code: typeof code === "string" ? code : "unknown", + }, + "security scan workspace cleanup failed; leaving it in place", + ); + } +} + function isTransientClaimError(error: unknown) { if (!(error instanceof Error)) return false; // Convex hides internal failures behind this message. Authentication and diff --git a/specs/plugin-qualified-runtime.md b/specs/plugin-qualified-runtime.md index 4b47672aef..bb4111aff7 100644 --- a/specs/plugin-qualified-runtime.md +++ b/specs/plugin-qualified-runtime.md @@ -70,6 +70,21 @@ production execution. The local native Convex authority fixture separately prove allowed Endor-only writes and rejection of stale/retired/substituted authority; only its Endor subprocess transport is simulated. Production was untouched. +## Scan workspace cleanup + +Deleting a Codex scan workspace must never change the job's result or error. +When the workspace is not preserved for container custody, the worker deletes +it on a best-effort basis. Docker sandboxes leave root-owned files in the bind +mount, so the delete can fail (EACCES on Linux). On Linux, Bun 1.4.4 leaves +only the undeletable subtree. On macOS it can stop early and leave more, +including the extracted artifact. +The worker logs `security_scan_workspace_cleanup_failed` with the errno code and +keeps going. Leftover workspaces can pile up until the runner is torn down. That +is accepted on hosted runners, which are discarded after each run. Local runs +(`CLAWHUB_ALLOW_LOCAL_CODEX_SCAN=1`) leave them in the temp dir. Removing them +for real would need the scoped privileged helper used by +`template-qualification-workspace.ts`. + ## Historical preparation record (superseded) The following source56/c3 records describe earlier preparation, not current