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

chore(codex-security): sync public projection

David Chouinard1f3394d4f42a
diff --git a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
index f3226a321..76d54231a 100644
--- a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
+++ b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
@@ -24,6 +24,7 @@ from typing import Any, BinaryIO, TextIO
from urllib.parse import quote, urlsplit
SCHEMA_VERSION = "1.0"
+PRODUCER_NAME = "codex-security-plugin"
FINGERPRINT_ALGORITHM = "codex-security/v1"
SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/schemas/sarif-schema-2.1.0.json"
SEVERITIES = {"critical", "high", "medium", "low", "informational"}
@@ -807,6 +808,7 @@ def _populate_unsealed_manifest_envelope(
scan["id"] = completion_binding["scanId"]
scan["startedAt"] = completion_binding["startedAt"]
scan["completedAt"] = completion_binding["completedAt"]
+ scan["producer"] = copy.deepcopy(completion_binding["producer"])
target = scan.get("target")
if isinstance(target, dict):
@@ -924,6 +926,8 @@ def _validate_completion_binding(
raise ContractError("manifest.scan.startedAt: must match the workbench scan")
if scan.get("completedAt") != completion_binding["completedAt"]:
raise ContractError("manifest.scan.completedAt: must match the workbench completion")
+ if scan.get("producer") != completion_binding["producer"]:
+ raise ContractError("manifest.scan.producer: must match the workbench producer")
target = _require_dict(scan, "target", "manifest.scan")
allowed_target_kinds = completion_binding["allowedTargetKinds"]
if target.get("kind") not in allowed_target_kinds:
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index e8fd631d0..fc7fb79dc 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -42,6 +42,7 @@ import workbench_scan_history as scan_history
from filesystem_identity import serialize_filesystem_identity as serialize_filesystem_identity
from filesystem_identity import stored_filesystem_identity_matches
from finalize_scan_contract import (
+ PRODUCER_NAME,
ContractError,
_prepare_scan_finalization,
_write_prepared_scan_finalization,
@@ -621,6 +622,12 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[s
contract = scan_contract(scan)
target_contract = contract["target"]
+ plugin_manifest = read_json_object(
+ Path(__file__).resolve().parent.parent / ".codex-plugin" / "plugin.json"
+ )
+ plugin_version = plugin_manifest.get("version")
+ if not isinstance(plugin_version, str) or not plugin_version:
+ raise SystemExit("plugin.json: expected a nonempty Codex Security plugin version.")
target: dict[str, Any] = {
"targetId": target_contract["targetId"],
"displayName": target_contract["displayName"],
@@ -633,8 +640,8 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[s
else:
if scan["target_revision"] != "unversioned":
target["revision"] = scan["target_revision"]
- if scan["target_snapshot_digest"]:
- target["snapshotDigest"] = scan["target_snapshot_digest"]
+ if "requiredSnapshotDigest" in target_contract:
+ target["snapshotDigest"] = target_contract["requiredSnapshotDigest"]
scope: dict[str, Any] = {
"includePaths": requested_scan_paths(scan),
@@ -645,6 +652,7 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[s
"scanId": scan["id"],
"startedAt": scan["started_at"],
"completedAt": completed_at,
+ "producer": {"name": PRODUCER_NAME, "version": plugin_version},
"target": target,
"allowedTargetKinds": target_contract["allowedKinds"],
"scope": scope,
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index f5d617623..5771c2e04 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -488,6 +488,7 @@ export class CodexSecurity {
CODEX_SECURITY_STATE_DIR: stateDirectory,
CODEX_SECURITY_SCAN_ID: scanId,
CODEX_SECURITY_TARGET_ID: targetId,
+ CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repo),
...(knowledgeBase === null
? {}
: { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
@@ -547,13 +548,19 @@ export class CodexSecurity {
scanDir,
pluginRoot: runtime.plugin.installedRoot,
expectation,
+ onFinalize: async () => {
+ await workbench(workbenchOptions, [
+ "complete-scan",
+ "--scan-id",
+ scanId,
+ ]);
+ activeScan = null;
+ },
onScanStarted: options.onScanStarted,
onReconnect: options.onReconnect,
onWorkerStatus: options.onWorkerStatus,
onObserverError: options.onObserverError,
});
- await workbench(workbenchOptions, ["complete-scan", "--scan-id", scanId]);
- activeScan = null;
checkOpen();
return result;
} catch (error) {
@@ -929,6 +936,7 @@ interface ScanEventRunOptions {
scanDir: string;
pluginRoot: string;
expectation: ScanExpectation;
+ onFinalize?: () => Promise<void>;
onScanStarted?: () => void;
onReconnect?: (attempt: number, maxAttempts: number) => void;
onWorkerStatus?: (status: ScanWorkerStatus) => void;
@@ -1015,6 +1023,7 @@ export async function runScanEvents(
"Codex Security did not report a thread ID.",
);
}
+ await options.onFinalize?.();
const result = await collectResult(
{ status, finalResponse, usage },
threadId,
@@ -1071,6 +1080,8 @@ async function scanPrompt(
'Use this exact scan directory for all scan output: "$CODEX_SECURITY_SCAN_DIR"',
'Use exactly "$CODEX_SECURITY_SCAN_ID" as the scan ID in the manifest, findings, and coverage.',
'Use exactly "$CODEX_SECURITY_TARGET_ID" as scan.target.targetId; do not derive a different target ID.',
+ 'Use exactly "$CODEX_SECURITY_TARGET_DISPLAY_NAME" as scan.target.displayName; do not infer a display name from the Git remote.',
+ 'Use exactly "codex-security-plugin" as scan.producer.name.',
...(hasConfigPath
? [
'For normal config-preflight helper calls, append --config "$CODEX_SECURITY_CONFIG_PATH" so preflight reads the sanitized active runtime config. Preserve the documented runtime and --effective-config arguments for session-only values.',
@@ -1089,7 +1100,7 @@ async function scanPrompt(
: []),
"Runtime paths are environment-backed; keep them quoted in POSIX shells and use the corresponding $env: names in PowerShell. Do not copy or reparse their values.",
targetInstruction(target),
- "Complete and seal the canonical JSON contract before returning.",
+ "Write the complete canonical scan-manifest.json, findings.json, and coverage.json, but do not finalize or seal them; the SDK workbench owns authoritative metadata, finalization, report generation, and sealing.",
].join("\n");
}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index bf16f51b6..472071c43 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -15,7 +15,7 @@ import * as fsPromises from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { basename, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Codex, type CodexOptions, type ThreadEvent } from "@openai/codex-sdk";
import { afterEach, describe, expect, mock, test } from "bun:test";
@@ -178,6 +178,42 @@ describe("one-shot scan events", () => {
});
});
+ test("lets the workbench seal artifacts before validating completed scans", async () => {
+ const root = await temporaryDirectory();
+ const scanDir = join(root, "scan");
+ const events = completedEvents();
+ let finalized = false;
+
+ const result = await runScanEvents({
+ thread: {
+ id: null,
+ async runStreamed() {
+ return { events };
+ },
+ },
+ events,
+ signal: new AbortController().signal,
+ scanDir,
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ repository: "/repository",
+ repositoryRevision: "deadbeef",
+ target: { kind: "repository", paths: [] },
+ mode: "standard",
+ pluginVersion: "0.1.0",
+ },
+ onFinalize: async () => {
+ expect(existsSync(join(scanDir, "scan-manifest.json"))).toBe(false);
+ await copyCompletedScan(root);
+ finalized = true;
+ },
+ });
+
+ expect(finalized).toBe(true);
+ expect(result.threadId).toBe("thread-1");
+ expect(result.turnResult.status).toBe("completed");
+ });
+
test("reports a scan as started only after the thread starts", async () => {
const scanDir = await copyCompletedScan(await temporaryDirectory());
const milestones: string[] = [];
@@ -1419,6 +1455,7 @@ describe("CodexSecurity orchestration", () => {
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
+ CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repository),
});
expect((codexOptions as CodexOptions | null)?.config).toMatchObject({
default_permissions: "codex_security_scan",
@@ -1439,6 +1476,8 @@ describe("CodexSecurity orchestration", () => {
);
expect(prompt).toContain('Repository root: "$CODEX_SECURITY_REPOSITORY"');
expect(prompt).toContain('Use "$PYTHON" as <python_command>');
+ expect(prompt).toContain("$CODEX_SECURITY_TARGET_DISPLAY_NAME");
+ expect(prompt).toContain("codex-security-plugin");
expect(prompt).not.toContain("CODEX_SECURITY_KNOWLEDGE_BASE");
expect(
JSON.parse(commands[0]![commands[0]!.indexOf("--recipe-json") + 1]!),
@@ -2037,6 +2076,7 @@ describe("CodexSecurity orchestration", () => {
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
+ CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repository),
});
expect(environment).not.toHaveProperty("CODEX_SECURITY_TARGET_PATHS_JSON");
const targetPathsFile = environment?.["CODEX_SECURITY_TARGET_PATHS_FILE"];