Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
31 changes: 31 additions & 0 deletions scripts/security/run-codex-scan-worker-clawscan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,37 @@ describe("run-codex-scan-worker clawscan authority", () => {
);
});

it("saves a failed Endor-only scan on the release instead of failing the job", async () => {
const workspace = await tempDir();
await configureEndorFakeCommands({
clawScan: "/missing/must-not-launch-clawscan",
dockerBody: fakeEndorDockerBody({
endorDoneMarker: join(workspace, "endor-done"),
exitCode: 1,
stdout: "",
}),
workspace,
});
const job = pluginPackageJob("securityScanJobs:report-only-failed");
job.job.scanMode = "endor-report-only";
job.target.package = { name: "@community/fixture-plugin", family: "code-plugin" };
const client = { action: vi.fn(async (..._args: unknown[]) => ({})) };

await expect(processJob(client, "worker-auth", job, undefined)).resolves.toEqual({
completed: true,
hardFailed: false,
retryableFailed: false,
});
expect(client.action).toHaveBeenCalledTimes(1);
expect(client.action.mock.calls[0]?.[1]).toMatchObject({
endorAnalysis: {
status: "failed",
reason: "Endor analysis failed. Request a rescan to try again.",
},
});
expect(client.action.mock.calls[0]?.[1]).not.toHaveProperty("error");
});

it("keeps scan eligibility unknown when artifact preparation fails before any judge call", async () => {
const job = skillVersionJob("securityScanJobs:input-unproven");
job.target.files![0]!.sha256 = "0".repeat(64);
Expand Down
52 changes: 25 additions & 27 deletions scripts/security/run-codex-scan-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2489,6 +2489,27 @@ export function scanHealthClassification(input: {
} as const;
}

// Endor is report-only: a scanner failure is saved on the release as a failed
// analysis and never fails or retries the job.
async function runEndorReport(
job: ClaimedJob,
workspace: string,
endor: EndorCommandDiagnostic,
): Promise<EndorAnalysis> {
try {
return await runEndorPluginScan({
workspace,
packageRelease: job.target,
onDiagnostic: (next) => Object.assign(endor, next),
});
} catch (reason) {
endor.error = sanitizeWorkerErrorMessage(
reason instanceof Error ? reason.message : String(reason),
);
return { status: "failed", checkedAt: Date.now(), reason: ENDOR_SCAN_FAILED_REASON };
}
}

export async function processJob(
client: CodexScanWorkerClient,
token: string,
Expand Down Expand Up @@ -2517,11 +2538,7 @@ export async function processJob(
readString(asRecord(job.target.package) ?? {}, ["family"]),
);
const report = enabled
? await runEndorPluginScan({
workspace,
packageRelease: job.target,
onDiagnostic: (next) => Object.assign(endor, next),
})
? await runEndorReport(job, workspace, endor)
: {
status: "skipped" as const,
checkedAt: Date.now(),
Expand All @@ -2548,15 +2565,7 @@ export async function processJob(
// Endor is report-only: its result is saved on the release and never
// passed to the ClawScan judge, so it cannot change moderation.
const [endorResult, skillSpectorResult] = await Promise.allSettled([
shouldRunEndor
? runEndorPluginScan({
workspace,
packageRelease: job.target,
onDiagnostic: (next) => {
Object.assign(endor, next);
},
})
: Promise.resolve(undefined),
shouldRunEndor ? runEndorReport(job, workspace, endor) : Promise.resolve(undefined),
job.job.targetKind === "packageRelease" &&
asRecord(job.target.package)?.family !== "claw" &&
!(await usesWholePluginScanForTarget(job.job.targetKind, job.target.package))
Expand All @@ -2565,19 +2574,8 @@ export async function processJob(
})
: Promise.resolve(undefined),
]);
if (endorResult.status === "fulfilled") {
endorAnalysis = endorResult.value;
} else {
const { reason } = endorResult;
endor.error = sanitizeWorkerErrorMessage(
reason instanceof Error ? reason.message : String(reason),
);
endorAnalysis = {
status: "failed",
checkedAt: Date.now(),
reason: ENDOR_SCAN_FAILED_REASON,
};
}
// runEndorReport never rejects.
if (endorResult.status === "fulfilled") endorAnalysis = endorResult.value;
if (skillSpectorResult.status === "rejected") throw skillSpectorResult.reason;
const mapped = await runClawScan(
job,
Expand Down
30 changes: 29 additions & 1 deletion scripts/security/run-endor-plugin-scan.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* @vitest-environment node */
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
Expand Down Expand Up @@ -263,6 +263,34 @@ describe("runEndorPluginScan", () => {
expect(message.includes("Endor container removal also failed")).toBe(scenario.recorded);
});

it("lets the container user read files the artifact stored as owner-only", async () => {
const workspace = await tempDir();
const root = await packageRoot(workspace);
await mkdir(join(root, "private-dir"));
await writeFile(join(root, "private-dir", "openclaw.plugin.json"), '{"id":"fixture"}\n');
await chmod(join(root, "private-dir", "openclaw.plugin.json"), 0o600);
await chmod(join(root, "private-dir"), 0o700);
await writeFile(join(workspace, "docker-run-stdout"), report());

await expect(runScan(workspace)).resolves.toMatchObject({ status: "completed" });
const copied = join(workspace, "endor-artifact", "private-dir");
expect((await stat(copied)).mode & 0o555).toBe(0o555);
expect((await stat(join(copied, "openclaw.plugin.json"))).mode & 0o444).toBe(0o444);
});

it("skips pnpm packages, which the scanner image cannot resolve", async () => {
const workspace = await tempDir();
const root = await packageRoot(workspace);
await writeFile(join(root, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\n");
await expect(runScan(workspace)).resolves.toMatchObject({
status: "skipped",
reason: "Endor cannot scan pnpm packages yet.",
});
await expect(readFile(join(workspace, "docker-run-args"))).rejects.toMatchObject({
code: "ENOENT",
});
});

it("skips artifacts without a package manifest instead of reporting a clean scan", async () => {
const workspace = await tempDir();
await mkdir(join(workspace, "artifact"), { recursive: true });
Expand Down
26 changes: 24 additions & 2 deletions scripts/security/run-endor-plugin-scan.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { cp, lstat, readFile, readdir, rename, writeFile } from "node:fs/promises";
import { chmod, cp, lstat, readFile, readdir, rename, writeFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { z } from "zod";
import type { EndorAnalysis } from "../../convex/lib/endorAnalysis";
Expand All @@ -25,7 +25,9 @@ const CHILD_RUNTIME_ENV_KEYS = [
] as const;
const DEFAULT_ENDOR_TIMEOUT_MS = 20 * 60 * 1000;
const DOCKER_REMOVE_TIMEOUT_MS = 10_000;
const MAX_ENDOR_REPORT_BYTES = 8 * 1024 * 1024;
// Community packages with large dependency trees produce reports over 8 MiB.
// Only the bounded summary is kept; diagnostics are capped separately.
const MAX_ENDOR_REPORT_BYTES = 64 * 1024 * 1024;
const MAX_ENDOR_COMMAND_DIAGNOSTIC_BYTES = 128 * 1024;
const MAX_ENDOR_DIAGNOSTIC_CHARS = 20_000;
const MAX_SUMMARY_FINDINGS = 50;
Expand Down Expand Up @@ -119,6 +121,16 @@ async function normalizePackageTree(scanRoot: string, directory = scanRoot): Pro
}
}

// The container's node user must be able to read files the artifact stored as
// owner-only. The mount is read-only, so this only adds read and search bits.
async function makeTreeReadable(path: string): Promise<void> {
const info = await lstat(path);
if (info.isSymbolicLink()) return;
await chmod(path, info.mode | (info.isDirectory() ? 0o555 : 0o444));
if (!info.isDirectory()) return;
for (const name of await readdir(path)) await makeTreeReadable(join(path, name));
}

function endorTimeoutMs(env: NodeJS.ProcessEnv) {
const parsed = Number(env.CODEX_SECURITY_SCAN_ENDOR_TIMEOUT_MS);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ENDOR_TIMEOUT_MS;
Expand Down Expand Up @@ -208,11 +220,21 @@ export async function runEndorPluginScan(input: {
};
}

// endorctl needs pnpm for these, and the scanner image only isolates npm and Yarn.
if (await isRegularFile(join(sourceRoot, "pnpm-lock.yaml"))) {
return {
status: "skipped",
checkedAt: Date.now(),
reason: "Endor cannot scan pnpm packages yet.",
};
}

const image = env.CODEX_SECURITY_SCAN_ENDOR_IMAGE?.trim();
if (!image) throw new Error("CODEX_SECURITY_SCAN_ENDOR_IMAGE is required when Endor is enabled");
const scanRoot = join(input.workspace, "endor-artifact");
await cp(sourceRoot, scanRoot, { recursive: true, errorOnExist: true, force: false });
await normalizePackageTree(scanRoot);
await makeTreeReadable(scanRoot);

const containerName = `clawhub-endor-${randomUUID()}`;
const args = [
Expand Down
4 changes: 3 additions & 1 deletion specs/endor-plugin-scans.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ they are scanned for any reason (new publication, owner rescan, admin rescan).
- Store a bounded summary on the release: at most 50 findings with 2,000-character
summaries, plus the total reachable-function count.
- An artifact without `package.json` at its root or under `package/` (including
legacy ZIP layouts) is saved as `skipped`, never as a clean scan.
legacy ZIP layouts) is saved as `skipped`, never as a clean scan. So is a
package with a root `pnpm-lock.yaml`: `endorctl` needs pnpm for it, and the
scanner image only runs npm and Yarn through credential-stripping shims.
- A scanner failure or timeout is saved as `failed` with a generic reason. It
does not fail or retry the job; owners or admins can request a rescan.
- A later scan replaces the stored result; this is not a report archive. The
Expand Down
Loading