Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 59 additions & 2 deletions scripts/security/run-codex-scan-worker.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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();
Expand Down
21 changes: 20 additions & 1 deletion scripts/security/run-codex-scan-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions specs/plugin-qualified-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading