Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(severity): use saved scan context for helper selection (#1815)

Michael D'Angeloa30f250f6969
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 93d72a878..1418eface 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -111,6 +111,7 @@ const distModules = [
"server/storage",
"targets",
"thread-source",
+ "timestamps",
"trusted-executable",
"value",
"version",
diff --git a/sdk/typescript/src/classify-scan-severity.ts b/sdk/typescript/src/classify-scan-severity.ts
index ada2a6bb9..51632ed11 100644
--- a/sdk/typescript/src/classify-scan-severity.ts
+++ b/sdk/typescript/src/classify-scan-severity.ts
@@ -10,12 +10,8 @@ import {
import { loadContractWithScanDirectory } from "./contract.js";
import { CodexSecurityError } from "./errors.js";
import type { Finding } from "./models.js";
-import {
- bundledPluginRoot,
- workbenchEnvironment,
- resolvePluginPython,
- runWorkbench,
-} from "./runtime.js";
+import { bundledPluginRoot } from "./runtime.js";
+import { savedScanWorkbench } from "./saved-scan-bootstrap.js";
import {
resolveCompletedScan,
type SavedScanDependencies,
@@ -53,25 +49,18 @@ export async function classifyScanSeverityInternal(
options.signal?.throwIfAborted();
const environment = options.environment ?? process.env;
const pluginRoot = await bundledPluginRoot();
+ const currentDirectory = dependencies.currentDirectory?.() ?? process.cwd();
+ const bootstrap = dependencies.runWorkbench
+ ? undefined
+ : await savedScanWorkbench(scanId, {
+ environment,
+ pluginRoot,
+ currentDirectory,
+ signal: options.signal,
+ });
const scan = await resolveCompletedScan(scanId, {
- currentDirectory: dependencies.currentDirectory ?? (() => process.cwd()),
- runWorkbench:
- dependencies.runWorkbench ??
- (async (args) => {
- const stateEnvironment = workbenchEnvironment(environment);
- return runWorkbench(
- {
- environment: stateEnvironment,
- pluginRoot,
- python: await resolvePluginPython({
- environment: stateEnvironment,
- }),
- signal: options.signal,
- failureMessage: "Could not read Codex Security scan history",
- },
- args,
- );
- }),
+ currentDirectory: () => currentDirectory,
+ runWorkbench: dependencies.runWorkbench ?? bootstrap!,
});
if (
options.expectedScanId !== undefined &&
@@ -83,6 +72,7 @@ export async function classifyScanSeverityInternal(
scan.scanDir,
{ ...options, expectedScanId: scan.scanId },
surface,
+ bootstrap?.protectedRoots,
);
}
@@ -99,6 +89,7 @@ export async function classifyScanDirectorySeverityInternal(
requestedDirectory: string,
options: ClassifyScanSeverityOptions = {},
surface: "sdk" | "cli" = "sdk",
+ protectedRoots: readonly string[] = [],
): Promise<ScanSeverityClassification> {
const { contract, scanDirectory } = await loadContractWithScanDirectory(
requestedDirectory,
@@ -116,6 +107,7 @@ export async function classifyScanDirectorySeverityInternal(
options.environment ?? process.env,
scanDirectory,
options.signal,
+ protectedRoots,
);
const result: ScanSeverityClassification = {
...(await classifySeverityInternal(
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 010ba7dd1..727dc0bd0 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -4,6 +4,7 @@ import { listenForAbort } from "./cli-signals.js";
import { appServerCyberAccessProgram } from "./cli-daybreak.js";
import { withCodexPreflightLock } from "./provider-profile.js";
import { isNonEmptyString, parseJson } from "./value.js";
+import { compareTimestamps } from "./timestamps.js";
import {
execFile as execFileCallback,
@@ -4191,7 +4192,18 @@ export async function main(
? await (
dependencies.classifyScanSeverity ??
classifyScanSeverityInternal
- )(options.scan, settings, dependencies, "cli")
+ )(
+ options.scan,
+ settings,
+ {
+ currentDirectory: () => currentDirectory,
+ ...(dependencies.runWorkbench ===
+ DEFAULT_DEPENDENCIES.runWorkbench
+ ? {}
+ : { runWorkbench: dependencies.runWorkbench }),
+ },
+ "cli",
+ )
: await (
dependencies.classifyScanDirectorySeverity ??
classifyScanDirectorySeverityInternal
@@ -5953,18 +5965,13 @@ export async function main(
scanId: string;
startedAt: string;
}[];
- let latest:
- { scanId: string; timestamp: number; fraction: string } | undefined;
+ let latest: (typeof scans)[number] | undefined;
for (const scan of scans) {
- const timestamp = Date.parse(scan.startedAt);
- const fraction =
- scan.startedAt.match(/\.\d{3}(\d*[1-9])/u)?.[1] ?? "";
if (
latest === undefined ||
- timestamp > latest.timestamp ||
- (timestamp === latest.timestamp && fraction > latest.fraction)
+ compareTimestamps(scan.startedAt, latest.startedAt) > 0
) {
- latest = { scanId: scan.scanId, timestamp, fraction };
+ latest = scan;
}
}
scanId = latest?.scanId;
diff --git a/sdk/typescript/src/saved-scan-bootstrap.ts b/sdk/typescript/src/saved-scan-bootstrap.ts
index d9cb80c13..d013cf8a8 100644
--- a/sdk/typescript/src/saved-scan-bootstrap.ts
+++ b/sdk/typescript/src/saved-scan-bootstrap.ts
@@ -1,4 +1,5 @@
import { isRecord } from "./record.js";
+import { compareTimestamps } from "./timestamps.js";
import { environmentEntry } from "./auth.js";
import { inspectTrustedExecutable } from "./trusted-executable.js";
import { realpath } from "node:fs/promises";
@@ -44,7 +45,10 @@ export async function savedScanWorkbench(
signal?: AbortSignal;
},
): Promise<
- SavedScanDependencies["runWorkbench"] & { environment: ProcessEnvironment }
+ SavedScanDependencies["runWorkbench"] & {
+ environment: ProcessEnvironment;
+ readonly protectedRoots: readonly string[];
+ }
> {
options.signal?.throwIfAborted();
const environment: ProcessEnvironment = workbenchEnvironment(
@@ -157,7 +161,10 @@ export async function savedScanWorkbench(
}
return result;
};
- return Object.assign(workbench, { environment });
+ return Object.assign(workbench, {
+ environment,
+ protectedRoots: [options.currentDirectory, ...protectedRoots],
+ });
}
async function readTargets(
@@ -356,15 +363,33 @@ async function latestTargets(
related.add(target.id);
}
}
- const scans = readRows<ScanTarget>(
+ const scans = readRows<
+ ScanTarget & {
+ updated_at: string;
+ progress_updated_at: string;
+ started_at: string;
+ }
+ >(
database,
- `SELECT scans.id, scans.target_path,
+ `SELECT scans.id, scans.target_path, scans.updated_at, scans.started_at,
+ progress.updated_at AS progress_updated_at,
${columns.has("target_id") ? "scans.target_id" : "scans.target_path"} AS target_id
FROM scans JOIN scan_progress AS progress ON progress.scan_id = scans.id
WHERE scans.status = 'complete' ${columns.has("canceled_at") ? "AND scans.canceled_at IS NULL" : ""}
- ORDER BY MAX(scans.updated_at, progress.updated_at) DESC,
- scans.started_at DESC, scans.id`,
- );
+ ORDER BY scans.id`,
+ )
+ .map((scan) => ({
+ ...scan,
+ updatedAt:
+ compareTimestamps(scan.updated_at, scan.progress_updated_at) > 0
+ ? scan.updated_at
+ : scan.progress_updated_at,
+ }))
+ .sort(
+ (a, b) =>
+ compareTimestamps(b.updatedAt, a.updatedAt) ||
+ compareTimestamps(b.started_at, a.started_at),
+ );
for (const scan of scans) {
signal?.throwIfAborted();
if (
diff --git a/sdk/typescript/src/severity-store.ts b/sdk/typescript/src/severity-store.ts
index 20013ca04..040d132fd 100644
--- a/sdk/typescript/src/severity-store.ts
+++ b/sdk/typescript/src/severity-store.ts
@@ -26,6 +26,7 @@ export class SeverityStore {
private readonly environment: NodeJS.ProcessEnv,
private readonly scanDirectory: string,
private readonly signal?: AbortSignal,
+ private readonly protectedRoots: readonly string[] = [],
) {}
checkpoint(
@@ -119,6 +120,7 @@ export class SeverityStore {
environment,
protectedRoot: [
this.scanDirectory,
+ ...this.protectedRoots,
...(await gitProtectionRoots(process.cwd(), this.signal)),
...(await gitProtectionRoots(this.scanDirectory, this.signal)),
],
diff --git a/sdk/typescript/src/timestamps.ts b/sdk/typescript/src/timestamps.ts
new file mode 100644
index 000000000..3f5d5d42c
--- /dev/null
+++ b/sdk/typescript/src/timestamps.ts
@@ -0,0 +1,12 @@
+/** Compare timestamps without dropping their sub-millisecond digits. */
+export function compareTimestamps(left: string, right: string): number {
+ const timestamp = Date.parse(left) - Date.parse(right);
+ if (timestamp !== 0) return timestamp;
+ const leftFraction = left.match(/\.\d{3}(\d*[1-9])/u)?.[1] ?? "";
+ const rightFraction = right.match(/\.\d{3}(\d*[1-9])/u)?.[1] ?? "";
+ return leftFraction < rightFraction
+ ? -1
+ : leftFraction > rightFraction
+ ? 1
+ : 0;
+}
diff --git a/sdk/typescript/tests-ts/classify-scan-severity.test.ts b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
index cf9d3bd01..927c1a283 100644
--- a/sdk/typescript/tests-ts/classify-scan-severity.test.ts
+++ b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
@@ -25,6 +25,7 @@ import type { JsonObject } from "../src/config.js";
import type { Finding, FindingsDocument, ScanManifest } from "../src/models.js";
import { prepareScanPublication } from "../src/publication.js";
import { publishScanInternal } from "../src/publish.js";
+import { resolvePluginPython, runWorkbench } from "../src/runtime.js";
import { copyCompletedScanFixture, PLUGIN_ROOT } from "./plugin-root.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -35,8 +36,8 @@ const { temporaryDirectory, cleanup } = createApiTestFixtures(
const destination = { destination: "linear", teamId: "team-example" } as const;
afterEach(cleanup);
-async function fixture(scanId?: string) {
- const root = await temporaryDirectory();
+async function fixture(scanId?: string, savedRoot?: string) {
+ const root = savedRoot ?? (await temporaryDirectory());
const scanDirectory = join(root, "scan");
await copyCompletedScanFixture(scanDirectory);
if (process.platform !== "win32") await chmod(scanDirectory, 0o700);
@@ -90,6 +91,51 @@ async function fixture(scanId?: string) {
};
}
+async function savedFixture() {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const caller = join(root, "caller");
+ const scanDirectory = join(root, "scan");
+ for (const directory of [repository, caller, scanDirectory])
+ await mkdir(directory, { mode: 0o700 });
+ const environment = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: join(root, "codex"),
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ CODEX_SECURITY_NO_UPDATE_NOTICE: "1",
+ };
+ const python = await resolvePluginPython({ environment });
+ const workbench = { environment, python, pluginRoot: PLUGIN_ROOT };
+ const registered = await runWorkbench(workbench, [
+ "register-cli-scan",
+ "--repository",
+ repository,
+ "--scan-dir",
+ scanDirectory,
+ "--recipe-json",
+ JSON.stringify({
+ config: {},
+ mode: "standard",
+ repository,
+ target: { kind: "repository", paths: [] },
+ }),
+ ]);
+ const scanId = registered["scanId"] as string;
+ const artifacts = await fixture(scanId, root);
+ const path = join(scanDirectory, "scan-manifest.json");
+ const manifest = JSON.parse(await readFile(path, "utf8"));
+ delete manifest.scan.sealedAt;
+ delete manifest.scan.artifacts;
+ manifest.scan.target.kind = "directory_snapshot";
+ delete manifest.scan.target.revision;
+ await writeFile(path, JSON.stringify(manifest));
+ await runWorkbench(workbench, ["complete-scan", "--scan-id", scanId]);
+ return { ...artifacts, environment, repository, caller, python };
+}
+
function classifier(finding: Finding, excluded = false) {
return jsonCodex(() => ({
findingId: finding.findingId,
@@ -205,6 +251,127 @@ await classifyScanDirectorySeverity(${JSON.stringify(scanDirectory)}, { environm
await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
});
+for (const surface of ["SDK", "CLI"]) {
+ test.skipIf(process.platform === "win32")(
+ `saved severity ${surface} lookup rejects target Python before probing`,
+ async () => {
+ const f = await savedFixture();
+ const marker = join(f.root, "python-probed");
+ const executable = join(f.repository, "python3");
+ await writeFile(
+ executable,
+ `#!/bin/sh\nprintf probed > '${marker.replaceAll("'", "'\\''")}'\nprintf "codex-security-python-ok\\n"\n`,
+ { mode: 0o700 },
+ );
+ const python =
+ surface === "CLI" ? join(f.root, "linked-python") : executable;
+ if (surface === "CLI") await symlink(executable, python);
+ const environment = {
+ ...f.environment,
+ PYTHON: python,
+ };
+ if (surface === "SDK") {
+ const failure = await classifyScanSeverityInternal(
+ f.scanId,
+ { environment },
+ { currentDirectory: () => f.caller },
+ ).catch((error: unknown) => error);
+ await expect(readFile(marker)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ expect(failure).toMatchObject({
+ message: expect.stringContaining(
+ "PYTHON interpreter is unavailable or unusable",
+ ),
+ });
+ } else {
+ const cli = new URL("../src/cli.ts", import.meta.url);
+ const result = spawnSync(
+ process.execPath,
+ [
+ "--eval",
+ `const { main } = await import(${JSON.stringify(cli.href)});
+process.exitCode = await main(["classify-severity", "--scan", ${JSON.stringify(f.scanId.slice(0, 8))}, "--json"]);`,
+ ],
+ { cwd: f.caller, encoding: "utf8", env: environment },
+ );
+ await expect(readFile(marker)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ expect(result.status, result.stderr).toBe(2);
+ expect(result.stderr).toContain(
+ "PYTHON interpreter is unavailable or unusable",
+ );
+ }
+ await expect(
+ readFile(join(f.scanDirectory, "severity-classification.json")),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ },
+ );
+}
+
+test.each(["id", "prefix", "latest", "missing target"])(
+ "saved severity supports %s without modifying sealed inputs or the environment",
+ async (selection) => {
+ const f = await savedFixture();
+ const environment = Object.freeze({ ...f.environment, PYTHON: f.python });
+ const before = await readFile(join(f.scanDirectory, "scan-manifest.json"));
+ if (selection === "missing target")
+ await rm(f.repository, { recursive: true });
+ const result = await classifyScanSeverityInternal(
+ selection === "latest"
+ ? "latest"
+ : selection === "prefix"
+ ? f.scanId.slice(0, 8)
+ : f.scanId,
+ { environment, expectedScanId: f.scanId },
+ {
+ currentDirectory: () =>
+ selection === "latest" ? f.repository : f.caller,
+ },
+ );
+ expect(result.scanId).toBe(f.scanId);
+ expect(result.assessments).toHaveLength(f.findings.length);
+ expect(await readFile(join(f.scanDirectory, "scan-manifest.json"))).toEqual(
+ before,
+ );
+ expect(environment).toEqual({ ...f.environment, PYTHON: f.python });
+ },
+);
+
+test("saved severity protects repository and caller tools across concurrent lookups", async () => {
+ const results = await Promise.allSettled(
+ (["repository", "caller"] as const).map(async (location) => {
+ const f = await savedFixture();
+ const marker = join(f.root, "node-probed");
+ await writeFile(
+ join(f[location], process.platform === "win32" ? "node.exe" : "node"),
+ process.platform === "win32"
+ ? "synthetic invalid executable"
+ : '#!/bin/sh\nprintf probed > "$NODE_MARKER"\nexit 91\n',
+ { mode: 0o700 },
+ );
+ const result = await classifyScanSeverityInternal(
+ f.scanId,
+ {
+ environment: {
+ ...f.environment,
+ PYTHON: f.python,
+ PATH: [f[location], dirname(Bun.which("node")!)].join(delimiter),
+ NODE_MARKER: marker,
+ },
+ },
+ { currentDirectory: () => f.caller },
+ );
+ expect(result.scanId).toBe(f.scanId);
+ expect(result.assessments).toHaveLength(f.findings.length);
+ await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
+ }),
+ );
+ for (const result of results)
+ if (result.status === "rejected") throw result.reason;
+});
+
function recordingClassifier() {
const calls: string[] = [];
const control = { failOn: "", excluded: false };
diff --git a/sdk/typescript/tests-ts/saved-scan-bootstrap.test.ts b/sdk/typescript/tests-ts/saved-scan-bootstrap.test.ts
index 3c1e9a78f..09d65cf76 100644
--- a/sdk/typescript/tests-ts/saved-scan-bootstrap.test.ts
+++ b/sdk/typescript/tests-ts/saved-scan-bootstrap.test.ts
@@ -1133,6 +1133,91 @@ connection.close()
});
}
+test.each([
+ ["offsets", "2026-08-01T03:00:00+02:00", "2026-08-01T01:30:00Z"],
+ ["fractional seconds", "2026-08-01T01:00:00Z", "2026-08-01T01:00:00.100000Z"],
+ [
+ "microseconds",
+ "2026-08-01T01:00:00.000001Z",
+ "2026-08-01T01:00:00.000002Z",
+ ],
+ [
+ "millisecond boundaries",
+ "2026-08-01T01:00:00.481998Z",
+ "2026-08-01T01:00:00.482012Z",
+ ],
+ [
+ "offset microseconds",
+ "2026-08-01T03:00:00.000001+02:00",
+ "2026-08-01T01:00:00.000002Z",
+ ],
+])(
+ "latest orders timestamps chronologically with %s",
+ async (_, older, newer) => {
+ const f = await fixture();
+ const db = new Database(
+ join(f.environment.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),
+ );
+ try {
+ // The older scan wins an ID tie, so lost timestamp precision cannot pass.
+ const [olderScan, newerScan] =
+ f.first.scanId < f.second.scanId
+ ? ([f.first, f.second] as const)
+ : ([f.second, f.first] as const);
+ for (const [scan, timestamp] of [
+ [olderScan, older],
+ [newerScan, newer],
+ ] as const) {
+ db.query(
+ "UPDATE scans SET updated_at = ?, started_at = '2000-01-01T00:00:00Z' WHERE id = ?",
+ ).run(timestamp, scan.scanId);
+ db.query(
+ "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",
+ ).run(older, scan.scanId);
+ }
+ async function latest() {
+ const workbench = await savedScanWorkbench("latest", {
+ environment: { ...f.environment, PYTHON: f.python },
+ pluginRoot: PLUGIN_ROOT,
+ currentDirectory: f.repository,
+ });
+ return (
+ await resolveCompletedScan("latest", {
+ currentDirectory: () => f.repository,
+ runWorkbench: workbench,
+ })
+ ).scanId;
+ }
+ expect(await latest()).toBe(newerScan.scanId);
+ // Either the scan or its progress may hold the latest update.
+ db.query("UPDATE scans SET updated_at = ?").run(older);
+ db.query("UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?").run(
+ newer,
+ newerScan.scanId,
+ );
+ expect(await latest()).toBe(newerScan.scanId);
+ // Equal updates fall back to the scans' chronological start times.
+ db.query("UPDATE scans SET updated_at = '2099-01-01T00:00:00Z'").run();
+ db.query(
+ "UPDATE scan_progress SET updated_at = '2099-01-01T00:00:00Z'",
+ ).run();
+ db.query("UPDATE scans SET started_at = ? WHERE id = ?").run(
+ older,
+ olderScan.scanId,
+ );
+ db.query("UPDATE scans SET started_at = ? WHERE id = ?").run(
+ newer,
+ newerScan.scanId,
+ );
+ expect(await latest()).toBe(newerScan.scanId);
+ db.query("UPDATE scans SET started_at = ?").run(older);
+ expect(await latest()).toBe(olderScan.scanId);
+ } finally {
+ db.close();
+ }
+ },
+);
+
test("latest follows progress timestamps and excludes canceled scans", async () => {
const f = await fixture();
const db = new Database(