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: preserve authoritative security scan targets (#103)

ianw-oai8d9eb30dcf71
diff --git a/sdk/typescript/_bundled_plugin/references/scan-contract.md b/sdk/typescript/_bundled_plugin/references/scan-contract.md
index 4fbd5f24e..e57dc537f 100644
--- a/sdk/typescript/_bundled_plugin/references/scan-contract.md
+++ b/sdk/typescript/_bundled_plugin/references/scan-contract.md
@@ -31,6 +31,8 @@ A sealed manifest records the completed timestamp and hashes for the canonical d
Choose the target kind based on the reviewed content, not the scan invocation:
`git_worktree` for a checked-out Git workspace, `directory_snapshot` for a non-Git directory, `git_diff` for a Git-backed change set, and `git_revision` for an exact immutable Git tree.
+For a workbench-backed scan, use the recorded target contract instead of inferring the kind from the checkout. A clean Git checkout has `allowedKinds: ["git_revision"]`: use its recorded revision and omit `snapshotDigest`. A dirty checkout has `allowedKinds: ["git_worktree"]`: copy `requiredSnapshotDigest` exactly.
+
| Kind | Required snapshot fields |
| --- | --- |
| `git_revision` | `revision` |
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
index 01c418b8c..8e0c38e98 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
@@ -210,6 +210,10 @@ def parse_args(description: str) -> argparse.Namespace:
update_progress.add_argument("--deep-review-pass", type=positive_int)
update_progress.add_argument("--claim-token")
+ prepare_scan_completion = subparsers.add_parser("prepare-scan-completion")
+ prepare_scan_completion.add_argument("--scan-id", required=True)
+ prepare_scan_completion.add_argument("--claim-token")
+
complete_scan = subparsers.add_parser("complete-scan")
complete_scan.add_argument("--scan-id", required=True)
complete_scan.add_argument("--claim-token")
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index 59b841464..ebee840c0 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -86,6 +86,7 @@ from workbench_scan_start import (
safe_segment,
scan_diff_identity,
scan_target_identity,
+ stored_diff_target,
)
from workbench_schema import MIGRATIONS, normalize_pre_release_migrations, sql_statements
from workbench_source_excerpt import finding_source_excerpt
@@ -504,19 +505,6 @@ def expected_target_kinds(scan: sqlite3.Row) -> list[str]:
return ["git_worktree"]
-def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:
- if not row["diff_target_kind"]:
- return None
- target = {
- "baseRevision": row["diff_base_revision"],
- "headRevision": row["diff_head_revision"],
- "kind": row["diff_target_kind"],
- }
- if row["diff_content_digest"]:
- target["contentDigest"] = row["diff_content_digest"]
- return target
-
-
def requested_scan_paths(scan: sqlite3.Row) -> list[str]:
if "recipe_json" in scan.keys() and scan["recipe_json"] is not None:
recipe = json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json)
@@ -1374,11 +1362,15 @@ def pin_legacy_manifest_digest(
raise
-def complete_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
+def complete_scan(
+ connection: sqlite3.Connection, args: argparse.Namespace, *, prepare_only: bool = False
+) -> dict[str, Any]:
scan_id = require_uuid(args.scan_id, "scan-id")
- cost_json = parse_scan_cost(args.cost_json)
+ cost_json = None if prepare_only else parse_scan_cost(args.cost_json)
with scan_completion_lock(scan_id):
- return complete_scan_locked(connection, scan_id, args.claim_token, cost_json)
+ return complete_scan_locked(
+ connection, scan_id, args.claim_token, cost_json, prepare_only=prepare_only
+ )
def complete_scan_locked(
@@ -1386,6 +1378,8 @@ def complete_scan_locked(
scan_id: str,
claim_token: str | None,
cost_json: str | None,
+ *,
+ prepare_only: bool = False,
) -> dict[str, Any]:
scan = require_scan(connection, scan_id)
if scan["status"] == "complete":
@@ -1412,9 +1406,9 @@ def complete_scan_locked(
)
if scan["recipe_json"] is None:
deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
- warnings = []
+ warnings = json.loads(scan["completion_warnings_json"])
warning = scan_target_warning(scan)
- if warning is not None:
+ if warning is not None and warning not in warnings:
warnings.append(warning)
scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))
completion_timestamp = now()
@@ -1443,9 +1437,23 @@ def complete_scan_locked(
for kind, filename in ARTIFACTS.items()
}
manifest_digest = published_manifest_digest(scan_dir, manifest)
+ if prepare_only:
+ connection.execute("BEGIN IMMEDIATE")
+ try:
+ updated = connection.execute(
+ "UPDATE scans SET completion_warnings_json = ? WHERE id = ? AND status = 'running'",
+ (json.dumps(warnings), scan["id"]),
+ )
+ if updated.rowcount != 1:
+ raise SystemExit("Only a running scan can be prepared for completion.")
+ connection.commit()
+ except BaseException:
+ connection.rollback()
+ raise
+ return scan_context(connection, scan["id"])
connection.execute("BEGIN IMMEDIATE")
try:
- timestamp = completion_timestamp
+ timestamp = manifest["scan"]["completedAt"]
scan = require_scan(connection, scan["id"])
if scan["status"] == "complete":
connection.commit()
@@ -1609,7 +1617,14 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
except BaseException:
connection.rollback()
raise
- return {"scanDir": str(scan_dir), "scanId": scan_id, "targetId": target_id}
+ scan = require_scan(connection, scan_id)
+ return {
+ "contract": scan_contract(scan),
+ "scanDir": str(scan_dir),
+ "scanId": scan_id,
+ "targetId": target_id,
+ "targetRevision": scan["target_revision"],
+ }
def parse_scan_recipe(value: str, repository: Path) -> dict[str, Any]:
@@ -3596,8 +3611,10 @@ def main() -> None:
require_scan=require_scan,
scan_context=scan_context,
)
- elif args.command == "complete-scan":
- result = complete_scan(connection, args)
+ elif args.command in {"prepare-scan-completion", "complete-scan"}:
+ result = complete_scan(
+ connection, args, prepare_only=args.command == "prepare-scan-completion"
+ )
elif args.command == "cancel-scan":
result = cancel_scan(connection, args)
elif args.command == "fail-scan":
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py
index fa02b0367..103b1e654 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py
@@ -72,6 +72,19 @@ def scan_diff_identity(
)
+def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:
+ if not row["diff_target_kind"]:
+ return None
+ target = {
+ "baseRevision": row["diff_base_revision"],
+ "headRevision": row["diff_head_revision"],
+ "kind": row["diff_target_kind"],
+ }
+ if row["diff_content_digest"]:
+ target["contentDigest"] = row["diff_content_digest"]
+ return target
+
+
def archive_scan(
connection: sqlite3.Connection,
args: argparse.Namespace,
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 43fd54d44..2699a634b 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -303,6 +303,7 @@ export class CodexSecurity {
let targetPathsFile: string | null = null;
let knowledgeBase: PreparedKnowledgeBase | null = null;
let costTracker: ScanCostTracker | null = null;
+ let completionCost: ScanCost | null = null;
let activeScan: {
id: string;
options: WorkbenchCommandOptions;
@@ -567,15 +568,50 @@ export class CodexSecurity {
]);
const scanId = registration["scanId"];
const targetId = registration["targetId"];
+ const contract = registration["contract"];
+ const contractTarget = isRecord(contract)
+ ? contract["target"]
+ : undefined;
+ const allowedKinds = isRecord(contractTarget)
+ ? contractTarget["allowedKinds"]
+ : undefined;
+ const targetKind =
+ Array.isArray(allowedKinds) && allowedKinds.length === 1
+ ? allowedKinds[0]
+ : undefined;
+ const diffTarget = isRecord(contract)
+ ? contract["diffTarget"]
+ : undefined;
+ const snapshotDigest =
+ targetKind === "git_diff" && isRecord(diffTarget)
+ ? diffTarget["contentDigest"]
+ : isRecord(contractTarget)
+ ? contractTarget["requiredSnapshotDigest"]
+ : undefined;
+ const registeredRevision = registration["targetRevision"];
if (
typeof scanId !== "string" ||
typeof targetId !== "string" ||
- registration["scanDir"] !== scanDir
+ registration["scanDir"] !== scanDir ||
+ typeof targetKind !== "string" ||
+ ![
+ "git_revision",
+ "git_worktree",
+ "git_diff",
+ "directory_snapshot",
+ ].includes(targetKind) ||
+ (snapshotDigest !== undefined && typeof snapshotDigest !== "string") ||
+ ((targetKind === "git_worktree" ||
+ targetKind === "directory_snapshot") &&
+ typeof snapshotDigest !== "string") ||
+ typeof registeredRevision !== "string"
) {
throw new CodexSecurityError(
"The Codex Security workbench returned an invalid scan registration.",
);
}
+ const targetRevision =
+ registeredRevision === "unversioned" ? null : registeredRevision;
activeScan = { id: scanId, options: workbenchOptions };
checkOpen();
const feedback = await workbench(
@@ -642,6 +678,13 @@ export class CodexSecurity {
CODEX_SECURITY_SCAN_ID: scanId,
CODEX_SECURITY_TARGET_ID: targetId,
CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repo),
+ CODEX_SECURITY_TARGET_KIND: targetKind,
+ ...(targetRevision === null
+ ? {}
+ : { CODEX_SECURITY_TARGET_REVISION: targetRevision }),
+ ...(typeof snapshotDigest === "string"
+ ? { CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST: snapshotDigest }
+ : {}),
...(knowledgeBase === null
? {}
: { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
@@ -703,6 +746,7 @@ export class CodexSecurity {
scanDir,
pluginRoot: runtime.plugin.installedRoot,
expectation,
+ workbenchValidated: true,
model,
onThreadStarted: (threadId) => tracker.start(threadId),
onFinalize: async (usage) => {
@@ -716,30 +760,12 @@ export class CodexSecurity {
"Scan completed, but its cost limit could not be verified because model pricing or token usage is unavailable.",
);
}
- const cost = snapshot.cost;
- const completion = await workbench(workbenchOptions, [
- "complete-scan",
+ completionCost = snapshot.cost;
+ await workbench(workbenchOptions, [
+ "prepare-scan-completion",
"--scan-id",
scanId,
- ...(cost === null ? [] : ["--cost-json", JSON.stringify(cost)]),
]);
- activeScan = null;
- const completedScan = completion["scan"];
- if (
- isRecord(completedScan) &&
- Array.isArray(completedScan["warnings"])
- ) {
- for (const warning of completedScan["warnings"]) {
- if (typeof warning === "string") {
- notifyObserver(
- "onWarning",
- options.onWarning,
- options.onObserverError,
- warning,
- );
- }
- }
- }
return snapshot.usage;
},
onScanStarted: options.onScanStarted,
@@ -748,6 +774,28 @@ export class CodexSecurity {
onObserverError: options.onObserverError,
});
checkOpen();
+ const completion = await workbench(workbenchOptions, [
+ "complete-scan",
+ "--scan-id",
+ scanId,
+ ...(completionCost === null
+ ? []
+ : ["--cost-json", JSON.stringify(completionCost)]),
+ ]);
+ activeScan = null;
+ const completedScan = completion["scan"];
+ if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
+ for (const warning of completedScan["warnings"]) {
+ if (typeof warning === "string") {
+ notifyObserver(
+ "onWarning",
+ options.onWarning,
+ options.onObserverError,
+ warning,
+ );
+ }
+ }
+ }
return result;
} catch (error) {
const snapshot = await costTracker?.stop().catch(() => null);
@@ -1154,6 +1202,7 @@ interface ScanEventRunOptions {
scanDir: string;
pluginRoot: string;
expectation: ScanExpectation;
+ workbenchValidated?: boolean;
model?: string;
onFinalize?: (usage: unknown) => Promise<unknown>;
onThreadStarted?: (threadId: string) => void;
@@ -1273,6 +1322,7 @@ export async function runScanEvents(
options.pluginRoot,
options.expectation,
options.signal,
+ options.workbenchValidated,
);
if (options.signal.aborted) {
throw new ScanInterruptedError(
@@ -1326,6 +1376,9 @@ async function scanPrompt(
'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_TARGET_KIND" as scan.target.kind; do not infer the target kind from the checkout.',
+ 'When "$CODEX_SECURITY_TARGET_REVISION" is set, use its exact value as scan.target.revision.',
+ 'When "$CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST" is set, use its exact value as scan.target.snapshotDigest. For git_revision, omit scan.target.snapshotDigest.',
'Use exactly "codex-security-plugin" as scan.producer.name.',
...(hasConfigPath
? [
@@ -1416,6 +1469,7 @@ async function collectResult(
pluginRoot: string,
expectation: ScanExpectation,
signal: AbortSignal,
+ workbenchValidated = false,
): Promise<ScanResult> {
const required = [
"scan-manifest.json",
@@ -1440,6 +1494,7 @@ async function collectResult(
const { manifest, findings, coverage } = await loadContract(scanDir, {
pluginRoot,
expectation,
+ workbenchValidated,
signal,
});
let sarifPath: string | null = null;
diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.ts
index c19980730..7508bd609 100644
--- a/sdk/typescript/src/contract.ts
+++ b/sdk/typescript/src/contract.ts
@@ -90,6 +90,7 @@ export async function loadContract(
options: {
pluginRoot: string;
expectation?: ScanExpectation;
+ workbenchValidated?: boolean;
signal?: AbortSignal;
},
): Promise<LoadedContract> {
@@ -184,7 +185,12 @@ export async function loadContract(
scanRoot,
);
if (options.expectation !== undefined) {
- validateExpectation(manifest, coverage, options.expectation);
+ validateExpectation(
+ manifest,
+ coverage,
+ options.expectation,
+ options.workbenchValidated === true,
+ );
}
await verifyScanRoot(scanRoot, options.signal);
return { manifest, findings, coverage };
@@ -465,6 +471,7 @@ function validateExpectation(
manifest: ScanManifest,
coverage: CoverageDocument,
expectation: ScanExpectation,
+ workbenchValidated = false,
): void {
const scan = manifest.scan;
if (scan.producer.name !== PRODUCER_NAME) {
@@ -488,37 +495,34 @@ function validateExpectation(
);
}
- const target = scan.target;
const requested = expectation.target;
- if (requested.kind === "refs" || requested.kind === "working_tree") {
- if (target.kind !== "git_diff") {
- throw new ContractValidationError(
- "Diff scan manifest target must be git_diff.",
- );
- }
- if (target.baseRevision !== requested.base) {
- throw new ContractValidationError(
- "Diff scan base revision does not match the request.",
- );
- }
- if (target.headRevision !== requested.head) {
- throw new ContractValidationError(
- "Diff scan head revision does not match the request.",
- );
- }
- } else if (expectation.repositoryRevision === null) {
- if (target.kind !== "directory_snapshot") {
- throw new ContractValidationError(
- "Unversioned scan manifest target must be directory_snapshot.",
- );
- }
- } else {
- if (target.kind !== "git_revision" && target.kind !== "git_worktree") {
+ if (!workbenchValidated) {
+ const target = scan.target;
+ if (requested.kind === "refs" || requested.kind === "working_tree") {
+ if (target.kind !== "git_diff") {
+ throw new ContractValidationError(
+ "Diff scan manifest target must be git_diff.",
+ );
+ }
+ if (target.baseRevision !== requested.base) {
+ throw new ContractValidationError(
+ "Diff scan base revision does not match the request.",
+ );
+ }
+ if (target.headRevision !== requested.head) {
+ throw new ContractValidationError(
+ "Diff scan head revision does not match the request.",
+ );
+ }
+ } else if (target.kind === "git_diff") {
throw new ContractValidationError(
- "Repository scan manifest target must be Git-backed.",
+ "Repository scan manifest target must not be git_diff.",
);
- }
- if (target.revision !== expectation.repositoryRevision) {
+ } else if (
+ target.kind !== "directory_snapshot" &&
+ expectation.repositoryRevision !== null &&
+ target.revision !== expectation.repositoryRevision
+ ) {
throw new ContractValidationError(
"Scan target revision does not match the repository.",
);
diff --git a/sdk/typescript/src/trusted-executable.ts b/sdk/typescript/src/trusted-executable.ts
index 55da804d2..e45b1bd42 100644
--- a/sdk/typescript/src/trusted-executable.ts
+++ b/sdk/typescript/src/trusted-executable.ts
@@ -65,7 +65,7 @@ export async function resolveTrustedExecutable(
process.platform === "win32" ? constants.F_OK : constants.X_OK,
);
if (!(await stat(canonical)).isFile()) continue;
- executable ??= canonical;
+ executable ??= pathLike ? canonical : current.path;
} catch {
continue;
}
diff --git a/sdk/typescript/tests-ts/api-events.test.ts b/sdk/typescript/tests-ts/api-events.test.ts
index 2f0ac0fe0..dca44fda3 100644
--- a/sdk/typescript/tests-ts/api-events.test.ts
+++ b/sdk/typescript/tests-ts/api-events.test.ts
@@ -45,6 +45,35 @@ describe("one-shot scan events", () => {
});
});
+ test("accepts target identity validated by the workbench", async () => {
+ const scanDir = await copyCompletedScan(await temporaryDirectory());
+ const events = completedEvents();
+
+ const result = await runScanEvents({
+ thread: {
+ id: null,
+ async runStreamed() {
+ return { events };
+ },
+ },
+ events,
+ signal: new AbortController().signal,
+ scanDir,
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ repository: "/repository",
+ repositoryRevision: "different-revision",
+ target: { kind: "repository", paths: [] },
+ mode: "standard",
+ pluginVersion: "0.1.0",
+ },
+ workbenchValidated: true,
+ });
+
+ expect(result.threadId).toBe("thread-1");
+ expect(result.turnResult.status).toBe("completed");
+ });
+
test("lets the workbench seal artifacts before validating completed scans", async () => {
const root = await temporaryDirectory();
const scanDir = join(root, "scan");
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 378bc262d..d835e2a99 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -51,11 +51,40 @@ type ScanObserverName = Parameters<
const REPOSITORY_ROOT = fileURLToPath(new URL("../../..", import.meta.url));
const EXAMPLE = join(PLUGIN_ROOT, "examples", "completed-scan");
const temporaryDirectories: string[] = [];
+const TEST_SNAPSHOT_DIGEST = `codex-security-snapshot/v1:sha256:${"a".repeat(64)}`;
const TestClientBase = CodexSecurity as unknown as new (
config: Record<string, unknown>,
dependencies: Record<string, unknown>,
) => CodexSecurity;
+function mockScanRegistration(args: readonly string[]) {
+ const recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!) as {
+ repositoryRevision?: string;
+ target: { kind: string };
+ };
+ const kind =
+ recipe.target.kind === "refs" || recipe.target.kind === "working_tree"
+ ? "git_diff"
+ : recipe.repositoryRevision === undefined
+ ? "directory_snapshot"
+ : "git_revision";
+
+ return {
+ scanId: "scan_example_001",
+ targetId: "target_sha256_example",
+ targetRevision: recipe.repositoryRevision ?? "unversioned",
+ scanDir: args[args.indexOf("--scan-dir") + 1],
+ contract: {
+ target: {
+ allowedKinds: [kind],
+ ...(kind === "directory_snapshot"
+ ? { requiredSnapshotDigest: TEST_SNAPSHOT_DIGEST }
+ : {}),
+ },
+ },
+ };
+}
+
class TestClient extends TestClientBase {
public constructor(
config: Record<string, unknown>,
@@ -64,11 +93,7 @@ class TestClient extends TestClientBase {
super(config, {
runWorkbench: async (_options: unknown, args: readonly string[]) => {
if (args[0] === "register-cli-scan") {
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir: args[args.indexOf("--scan-dir") + 1],
- };
+ return mockScanRegistration(args);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -942,11 +967,7 @@ describe("CodexSecurity orchestration", () => {
}
if (args[0] !== "register-cli-scan") return {};
registration = args;
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir: output,
- };
+ return mockScanRegistration(args);
},
createCodex: () => ({
startThread: () => ({
@@ -1308,11 +1329,7 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (_options: unknown, args: readonly string[]) => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir,
- };
+ return mockScanRegistration(args);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -1382,7 +1399,12 @@ describe("CodexSecurity orchestration", () => {
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repository),
+ CODEX_SECURITY_TARGET_KIND: "git_revision",
+ CODEX_SECURITY_TARGET_REVISION: "deadbeef",
});
+ expect((codexOptions as CodexOptions | null)?.env).not.toHaveProperty(
+ "CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST",
+ );
expect((codexOptions as CodexOptions | null)?.config).toMatchObject({
default_permissions: "codex_security_scan",
allow_login_shell: false,
@@ -1403,6 +1425,9 @@ 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_TARGET_KIND");
+ expect(prompt).toContain("$CODEX_SECURITY_TARGET_REVISION");
+ expect(prompt).toContain("$CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST");
expect(prompt).toContain("codex-security-plugin");
expect(prompt).not.toContain("CODEX_SECURITY_KNOWLEDGE_BASE");
expect(prompt).not.toContain("false_positive_feedback.json");
@@ -1432,6 +1457,11 @@ describe("CodexSecurity orchestration", () => {
"scan_example_001",
]);
expect(commands[2]).toEqual([
+ "prepare-scan-completion",
+ "--scan-id",
+ "scan_example_001",
+ ]);
+ expect(commands[3]).toEqual([
"complete-scan",
"--scan-id",
"scan_example_001",
@@ -1439,6 +1469,164 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
+ test("passes the workbench snapshot contract to dirty Git scans", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ let codexOptions: CodexOptions | null = null;
+
+ const client = new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => preparedRuntime(codexHome),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ runWorkbench: async (_options: unknown, args: readonly string[]) => {
+ if (args[0] === "register-cli-scan") {
+ return {
+ ...mockScanRegistration(args),
+ targetRevision: "cafebabe",
+ contract: {
+ target: {
+ allowedKinds: ["git_worktree"],
+ requiredSnapshotDigest: TEST_SNAPSHOT_DIGEST,
+ },
+ },
+ };
+ }
+ if (args[0] === "get-scan-feedback") {
+ return {
+ scanId: "scan_example_001",
+ targetId: "target_sha256_example",
+ falsePositives: [],
+ };
+ }
+ return {};
+ },
+ createCodex: (options: CodexOptions) => {
+ codexOptions = options;
+ return {
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ throw new Error("target contract captured");
+ },
+ }),
+ };
+ },
+ },
+ );
+
+ await expect(client.run(repository)).rejects.toThrow(
+ "target contract captured",
+ );
+ expect((codexOptions as CodexOptions | null)?.env).toMatchObject({
+ CODEX_SECURITY_TARGET_KIND: "git_worktree",
+ CODEX_SECURITY_TARGET_REVISION: "cafebabe",
+ CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST: TEST_SNAPSHOT_DIGEST,
+ });
+ await client.close();
+ });
+
+ test("rejects a scan registration without an authoritative target contract", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+
+ const client = new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => preparedRuntime(codexHome),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ runWorkbench: async (_options: unknown, args: readonly string[]) =>
+ args[0] === "register-cli-scan"
+ ? {
+ ...mockScanRegistration(args),
+ contract: { target: { allowedKinds: [] } },
+ }
+ : {},
+ createCodex: () => {
+ throw new Error("Codex must not start");
+ },
+ },
+ );
+
+ await expect(client.run(repository)).rejects.toThrow(
+ "invalid scan registration",
+ );
+ await client.close();
+ });
+
+ test("fails a prepared scan before publishing rejected scan artifacts", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ const commands: string[] = [];
+
+ const client = new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => preparedRuntime(codexHome),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ runWorkbench: async (_options: unknown, args: readonly string[]) => {
+ commands.push(args[0]!);
+ if (args[0] === "register-cli-scan") {
+ return mockScanRegistration(args);
+ }
+ if (args[0] === "get-scan-feedback") {
+ return {
+ scanId: "scan_example_001",
+ targetId: "target_sha256_example",
+ falsePositives: [],
+ };
+ }
+ if (args[0] === "prepare-scan-completion") {
+ await writeFile(join(scanDir, "findings.json"), "corrupted\n");
+ }
+ return {};
+ },
+ createCodex: () => ({
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ await copyCompletedScan(root);
+ return { events: completedEvents() };
+ },
+ }),
+ }),
+ },
+ );
+
+ await expect(client.run(repository)).rejects.toThrow();
+ expect(commands).toEqual([
+ "register-cli-scan",
+ "get-scan-feedback",
+ "prepare-scan-completion",
+ "fail-scan",
+ ]);
+ await client.close();
+ });
+
test("provides only reviewed false positives to validation as a scan artifact", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -1478,11 +1666,7 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (_options: unknown, args: readonly string[]) => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir,
- };
+ return mockScanRegistration(args);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -1562,7 +1746,7 @@ describe("CodexSecurity orchestration", () => {
repositoryRevision: async () => "deadbeef",
runWorkbench: async (_options: unknown, args: readonly string[]) => {
if (args[0] === "register-cli-scan") {
- return { scanId, targetId, scanDir };
+ return mockScanRegistration(args);
}
return args[0] === "get-scan-feedback" ? feedback : {};
},
@@ -1608,11 +1792,7 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (_options: unknown, args: readonly string[]) => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir,
- };
+ return mockScanRegistration(args);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -1726,11 +1906,7 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (_options: unknown, args: readonly string[]) => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir,
- };
+ return mockScanRegistration(args);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -1771,6 +1947,7 @@ describe("CodexSecurity orchestration", () => {
expect(commands.map(([command]) => command)).toEqual([
"register-cli-scan",
"get-scan-feedback",
+ "prepare-scan-completion",
"complete-scan",
]);
expect(commands.some((args) => args[0] === "fail-scan")).toBe(false);
@@ -1811,11 +1988,7 @@ describe("CodexSecurity orchestration", () => {
}
if (args[0] !== "register-cli-scan") return {};
recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!);
- return {
- scanId: "scan_example_001",
- targetId: "target_sha256_example",
- scanDir,
- };
+ return mockScanRegistration(args);
},
createCodex: (options: CodexOptions) => ({
startThread: () => ({
diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.ts
index a372625cf..c61322ea0 100644
--- a/sdk/typescript/tests-ts/contract.test.ts
+++ b/sdk/typescript/tests-ts/contract.test.ts
@@ -822,6 +822,80 @@ describe("canonical scan contract", () => {
}
});
+ test("accepts Git-backed scans when the SDK cannot resolve a revision", async () => {
+ const scanDir = await copyExample();
+
+ await expect(
+ loadContract(scanDir, {
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ ...expectation({ kind: "repository", paths: [] }),
+ repositoryRevision: null,
+ },
+ }),
+ ).resolves.toBeDefined();
+ });
+
+ test("accepts directory scans without requiring a Git repository", async () => {
+ const scanDir = await copyExample();
+ const manifestPath = join(scanDir, "scan-manifest.json");
+ const coveragePath = join(scanDir, "coverage.json");
+ const manifest = await readJson(manifestPath);
+ const coverage = await readJson(coveragePath);
+ manifest["scan"]["target"]["kind"] = "directory_snapshot";
+ delete manifest["scan"]["target"]["revision"];
+ delete manifest["scan"]["target"]["remote"];
+ coverage["inventoryStrategy"] = "directory";
+ await writeJson(manifestPath, manifest);
+ await writeJson(coveragePath, coverage);
+ await reseal(scanDir);
+
+ for (const repositoryRevision of [null, "deadbeef"]) {
+ await expect(
+ loadContract(scanDir, {
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ ...expectation({ kind: "repository", paths: [] }),
+ repositoryRevision,
+ },
+ }),
+ ).resolves.toBeDefined();
+ }
+ });
+
+ test("rejects Git-backed scans for a different revision", async () => {
+ const scanDir = await copyExample();
+
+ await expect(
+ loadContract(scanDir, {
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ ...expectation({ kind: "repository", paths: [] }),
+ repositoryRevision: "different-revision",
+ },
+ }),
+ ).rejects.toThrow("Scan target revision does not match the repository.");
+ });
+
+ test("rejects diff targets for repository scans", async () => {
+ const scanDir = await copyExample();
+ const manifestPath = join(scanDir, "scan-manifest.json");
+ const manifest = await readJson(manifestPath);
+ manifest["scan"]["target"]["kind"] = "git_diff";
+ await writeJson(manifestPath, manifest);
+ await reseal(scanDir);
+
+ await expect(
+ loadContract(scanDir, {
+ pluginRoot: PLUGIN_ROOT,
+ expectation: {
+ ...expectation({ kind: "repository", paths: [] }),
+ repositoryRevision: null,
+ },
+ }),
+ ).rejects.toThrow("Repository scan manifest target must not be git_diff.");
+ });
+
test("binds requested path scope, mode, and plugin version", async () => {
const scanDir = await copyExample();
const coveragePath = join(scanDir, "coverage.json");
diff --git a/sdk/typescript/tests-ts/scan-recovery.test.ts b/sdk/typescript/tests-ts/scan-recovery.test.ts
index 014fcd033..cf9af4850 100644
--- a/sdk/typescript/tests-ts/scan-recovery.test.ts
+++ b/sdk/typescript/tests-ts/scan-recovery.test.ts
@@ -75,9 +75,11 @@ type SarifDocument = {
type ScanFixture = {
python: string;
+ repository: string;
stateDir: string;
scanDir: string;
scanId: string;
+ registration: Record<string, unknown>;
};
const temporaryDirectories: string[] = [];
@@ -112,7 +114,9 @@ async function workbench(fixture: ScanFixture, args: readonly string[]) {
);
}
-async function startDraftScan(): Promise<ScanFixture> {
+async function startDraftScan(
+ repositoryKind: "directory" | "clean" | "dirty" = "directory",
+): Promise<ScanFixture> {
const root = await realpath(
await mkdtemp(join(tmpdir(), "codex-security-scan-recovery-")),
);
@@ -126,11 +130,38 @@ async function startDraftScan(): Promise<ScanFixture> {
await writeFile(join(target, "src", "extract.py"), "# fixture\n");
await mkdir(scanDir, { mode: 0o700 });
+ if (repositoryKind !== "directory") {
+ for (const args of [
+ ["init", "--quiet", target],
+ ["-C", target, "add", "--", "src/extract.py"],
+ [
+ "-C",
+ target,
+ "-c",
+ "user.name=Codex Security",
+ "-c",
+ "commit",
+ "--quiet",
+ "-m",
+ "fixture",
+ ],
+ ]) {
+ const result = spawnSync("git", args, { encoding: "utf8" });
+ expect(result.status, result.stderr).toBe(0);
+ }
+ if (repositoryKind === "dirty") {
+ await writeFile(join(target, "src", "extract.py"), "# changed fixture\n");
+ }
+ }
+
const fixture: ScanFixture = {
python: python!,
+ repository: target,
stateDir: join(root, "state"),
scanDir,
scanId: "",
+ registration: {},
};
const registration = await workbench(fixture, [
"register-cli-scan",
@@ -147,6 +178,7 @@ async function startDraftScan(): Promise<ScanFixture> {
}),
]);
fixture.scanId = String(registration["scanId"]);
+ fixture.registration = registration;
await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), scanDir, {
recursive: true,
@@ -161,7 +193,12 @@ async function startDraftScan(): Promise<ScanFixture> {
};
}>(manifestPath);
manifest.scan.id = fixture.scanId;
- manifest.scan.target.kind = "directory_snapshot";
+ manifest.scan.target.kind =
+ repositoryKind === "directory"
+ ? "directory_snapshot"
+ : repositoryKind === "clean"
+ ? "git_revision"
+ : "git_worktree";
delete manifest.scan.sealedAt;
delete manifest.scan.artifacts;
await writeJson(manifestPath, manifest);
@@ -186,6 +223,111 @@ async function completeScan(fixture: ScanFixture): Promise<ScanSummary> {
}
describe("malformed scan artifact recovery", () => {
+ test("returns the authoritative directory snapshot contract at registration", async () => {
+ const fixture = await startDraftScan();
+ const registration = fixture.registration;
+ const contract = registration["contract"] as {
+ target: {
+ allowedKinds: string[];
+ displayName: string;
+ targetId: string;
+ requiredSnapshotDigest?: string;
+ };
+ };
+
+ expect(registration["targetRevision"]).toBe("unversioned");
+ expect(contract.target).toMatchObject({
+ allowedKinds: ["directory_snapshot"],
+ displayName: "repository",
+ targetId: registration["targetId"],
+ requiredSnapshotDigest: expect.stringMatching(
+ /^codex-security-snapshot\/v1:sha256:[a-f0-9]{64}$/,
+ ),
+ });
+ });
+
+ test("returns authoritative clean and dirty Git target contracts", async () => {
+ for (const kind of ["clean", "dirty"] as const) {
+ const fixture = await startDraftScan(kind);
+ const registration = fixture.registration;
+ const contract = registration["contract"] as {
+ target: {
+ allowedKinds: string[];
+ targetId: string;
+ requiredSnapshotDigest?: string;
+ };
+ };
+ const revision = spawnSync(
+ "git",
+ ["-C", fixture.repository, "rev-parse", "HEAD"],
+ { encoding: "utf8" },
+ );
+
+ expect(revision.status, revision.stderr).toBe(0);
+ expect(registration["targetRevision"]).toBe(revision.stdout.trim());
+ expect(registration["targetId"]).toBe(contract.target.targetId);
+ expect(contract.target.allowedKinds).toEqual([
+ kind === "clean" ? "git_revision" : "git_worktree",
+ ]);
+ if (kind === "clean") {
+ expect(contract.target).not.toHaveProperty("requiredSnapshotDigest");
+ } else {
+ expect(contract.target.requiredSnapshotDigest).toMatch(
+ /^codex-security-snapshot\/v1:sha256:[a-f0-9]{64}$/,
+ );
+ }
+ }
+ });
+
+ test("seals a prepared scan without publishing it before acceptance", async () => {
+ const fixture = await startDraftScan();
+
+ const prepared = await workbench(fixture, [
+ "prepare-scan-completion",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+
+ expect((prepared["scan"] as ScanSummary).progress.status).toBe("running");
+ const manifest = await readJson<{
+ scan: { sealedAt: string; completedAt: string };
+ }>(join(fixture.scanDir, "scan-manifest.json"));
+ expect(manifest.scan.sealedAt).toBe(manifest.scan.completedAt);
+ const running = await workbench(fixture, [
+ "get-scan",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ expect((running["scan"] as ScanSummary).progress.status).toBe("running");
+ expect((await completeScan(fixture)).progress.status).toBe("complete");
+ });
+
+ test("marks rejected prepared scans as failed without publishing completion", async () => {
+ const fixture = await startDraftScan();
+ await workbench(fixture, [
+ "prepare-scan-completion",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ await writeFile(join(fixture.scanDir, "findings.json"), "corrupted\n");
+
+ const failed = await workbench(fixture, [
+ "fail-scan",
+ "--scan-id",
+ fixture.scanId,
+ "--message",
+ "Sealed scan could not be accepted.",
+ ]);
+
+ expect((failed["scan"] as ScanSummary).progress.status).toBe("failed");
+ const stored = await workbench(fixture, [
+ "get-scan",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ expect((stored["scan"] as ScanSummary).progress.status).toBe("failed");
+ });
+
test("normalizes finding identities and persists recovery warnings", async () => {
const fixture = await startDraftScan();
const path = join(fixture.scanDir, "findings.json");
@@ -219,6 +361,33 @@ describe("malformed scan artifact recovery", () => {
);
});
+ test("preserves recovery warnings across prepared scan completion", async () => {
+ const fixture = await startDraftScan();
+ const path = join(fixture.scanDir, "findings.json");
+ const document = await readJson<FindingsDocument>(path);
+ document.findings[0]!.identity.anchor = "Archive Entry Without Containment";
+ await writeJson(path, document);
+
+ const prepared = await workbench(fixture, [
+ "prepare-scan-completion",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ const warning = "Recovered finding 1: normalized semantic anchor.";
+
+ expect((prepared["scan"] as ScanSummary).progress.status).toBe("running");
+ expect((prepared["scan"] as ScanSummary).warnings).toEqual([warning]);
+ const completed = await completeScan(fixture);
+ expect(completed.progress.status).toBe("complete");
+ expect(completed.warnings).toEqual([warning]);
+ const saved = await workbench(fixture, [
+ "get-scan",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ expect((saved["scan"] as ScanSummary).warnings).toEqual([warning]);
+ });
+
test("keeps valid findings and skips malformed or duplicate findings", async () => {
const fixture = await startDraftScan();
const path = join(fixture.scanDir, "findings.json");
diff --git a/sdk/typescript/tests-ts/trusted-executable.test.ts b/sdk/typescript/tests-ts/trusted-executable.test.ts
index 7978e4466..34db45018 100644
--- a/sdk/typescript/tests-ts/trusted-executable.test.ts
+++ b/sdk/typescript/tests-ts/trusted-executable.test.ts
@@ -1,5 +1,6 @@
import { spawnSync } from "node:child_process";
import {
+ chmod,
mkdir,
mkdtemp,
realpath,
@@ -76,6 +77,39 @@ async function resolveWindowsExecutable(
}
describe("trusted executable resolution", () => {
+ test.skipIf(process.platform === "win32")(
+ "preserves the invocation name of a trusted symlinked executable",
+ async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const trusted = join(root, "trusted");
+ const wrapper = join(trusted, "wrapper");
+ const git = join(trusted, "git");
+ await Promise.all([mkdir(repository), mkdir(trusted)]);
+ await writeFile(wrapper, "#!/bin/sh\nprintf '%s\\n' \"$0\"\n");
+ await chmod(wrapper, 0o700);
+ await symlink(wrapper, git);
+
+ const resolved = await resolveTrustedExecutable(
+ "git",
+ { PATH: trusted },
+ repository,
+ );
+ expect(resolved).toEqual({
+ executable: git,
+ environment: { PATH: trusted },
+ });
+ if (resolved === null) throw new Error("trusted Git was not resolved");
+
+ const result = spawnSync(resolved.executable, [], {
+ encoding: "utf8",
+ env: resolved.environment,
+ });
+ expect(result.status).toBe(0);
+ expect(result.stdout.trim()).toBe(git);
+ },
+ );
+
test("selects runnable Windows executables ahead of extensionless and batch files", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");