OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(artifacts): adopt the registered target kind when sealing a scan draft (#828)
Ivan Caceresb51dbcdd7a7f
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.pyindex e4863f305..ffbfb6069 100644--- a/plugins/codex-security/scripts/finalize_scan_contract.py+++ b/plugins/codex-security/scripts/finalize_scan_contract.py@@ -1401,19 +1401,53 @@ def _populate_unsealed_manifest_envelope(allowed_kinds = completion_binding["allowedTargetKinds"]if len(allowed_kinds) == 1:target.setdefault("kind", allowed_kinds[0])- _populate_unsealed_target_binding(target, completion_binding["target"])+ _populate_unsealed_target_binding(target, completion_binding["target"], allowed_kinds)scope = scan.setdefault("scope", {})if isinstance(scope, dict):scope.update(copy.deepcopy(completion_binding["scope"]))+def _populate_unsealed_target_kind(+ target: dict[str, Any],+ target_binding: dict[str, Any],+ allowed_kinds: Any,+) -> None:+ """Adopt the registered target kind when the binding owns every coordinate it needs.++ The workbench, not the draft, knows how the target was registered: a scan agent+ that infers the kind from the checkout (a clean worktree registered as+ git_revision is the common case) used to discard the whole completed scan at the+ seal step. The kind carries no draft-owned information when the registration+ allows a single value, so take that value instead of failing.++ Rewriting the kind also reinterprets the coordinates that kind requires, and a+ coordinate the binding does not own survives the replacement below with whatever+ the draft computed under its own reading of the target. Adopting git_diff without+ a bound snapshotDigest, for example, would seal a whole-worktree digest as the+ diff digest. Leave the kind alone whenever the binding cannot restate every+ coordinate the registered kind requires, and let the binding check reject the+ draft instead.+ """++ if not isinstance(allowed_kinds, list) or len(allowed_kinds) != 1:+ return+ registered_kind = allowed_kinds[0]+ if not isinstance(registered_kind, str) or target.get("kind") == registered_kind:+ return+ if not TARGET_REQUIRED_COORDINATE_FIELDS.get(registered_kind, set()) <= target_binding.keys():+ return+ target["kind"] = registered_kind++def _populate_unsealed_target_binding(target: dict[str, Any],target_binding: dict[str, Any],+ allowed_kinds: Any = None,) -> None:"""Replace workbench-owned target coordinates without retaining incompatible drafts."""+ _populate_unsealed_target_kind(target, target_binding, allowed_kinds)target_kind = target.get("kind")required_coordinates = (TARGET_REQUIRED_COORDINATE_FIELDS.get(target_kind, set())diff --git a/plugins/codex-security/tests/test_workbench_completion_binding.py b/plugins/codex-security/tests/test_workbench_completion_binding.pyindex 0e17aefd3..5e885f6a1 100644--- a/plugins/codex-security/tests/test_workbench_completion_binding.py+++ b/plugins/codex-security/tests/test_workbench_completion_binding.py@@ -518,6 +518,184 @@ def test_cli_completion_accepts_sealed_clean_git_revision_without_snapshot_digesassert "snapshotDigest" not in sealed_manifest["scan"]["target"]+def test_scoped_cli_completion_adopts_registered_revision_kind(tmp_path: Path) -> None:+ # Regression for a path-scoped scan of a clean checkout: registration allows+ # only git_revision, while the scan agent infers git_worktree from the+ # checkout. Sealing adopts the registered kind instead of failing the scan.+ state_dir = tmp_path / "state"+ target = tmp_path / "target"+ initialize_git_repository(target)+ (target / "app").mkdir()+ (target / "app" / "main.py").write_text("print('fixture')\n")+ subprocess.run(["git", "add", "app"], cwd=target, check=True)+ subprocess.run(["git", "commit", "-qm", "Add app"], cwd=target, check=True)+ revision = subprocess.run(+ ["git", "rev-parse", "HEAD"],+ cwd=target,+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ scan_dir = tmp_path / "scan"+ scan_dir.mkdir(mode=0o700)+ registered = run_workbench(+ state_dir,+ "register-cli-scan",+ "--repository",+ str(target),+ "--scan-dir",+ str(scan_dir),+ "--recipe-json",+ json.dumps(+ {+ "config": {},+ "mode": "standard",+ "repository": str(target),+ "target": {"kind": "paths", "paths": ["app"]},+ }+ ),+ )+ assert registered["contract"]["target"]["allowedKinds"] == ["git_revision"]+ scan_id = str(registered["scanId"])+ write_completed_contract(+ scan_dir,+ scan_id,+ target,+ relative_path="app/main.py",+ target_kind="git_worktree",+ target_revision=revision,+ include_paths=["app"],+ coverage_mode="scoped_path",+ inventory_strategy="scoped_path",+ )++ completed = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id)++ assert completed["scan"]["progress"]["status"] == "complete"+ sealed_manifest = json.loads((scan_dir / "scan-manifest.json").read_text())+ assert sealed_manifest["scan"]["target"]["kind"] == "git_revision"+ assert sealed_manifest["scan"]["target"]["revision"] == revision+ assert "snapshotDigest" not in sealed_manifest["scan"]["target"]+ assert sealed_manifest["scan"]["scope"]["includePaths"] == ["app"]+ sealed_coverage = json.loads((scan_dir / "coverage.json").read_text())+ assert sealed_coverage["mode"] == "scoped_path"+++def test_full_repository_completion_adopts_registered_revision_kind(tmp_path: Path) -> None:+ # A full-repository bulk scan uses a clean detached checkout. Its worktree+ # draft seals with the same registered revision kind as a path-scoped scan.+ state_dir = tmp_path / "state"+ target = tmp_path / "target"+ revision = initialize_git_repository(target)+ subprocess.run(["git", "checkout", "--detach", revision], cwd=target, check=True)+ scan_dir = tmp_path / "scan"+ registered = register_cli_scan(state_dir, target, scan_dir)+ assert registered["contract"]["target"]["allowedKinds"] == ["git_revision"]+ scan_id = str(registered["scanId"])+ write_completed_contract(+ scan_dir,+ scan_id,+ target,+ relative_path="README.md",+ target_kind="git_worktree",+ target_revision=revision,+ snapshot_digest=f"codex-security-snapshot/v1:sha256:{'b' * 64}",+ )++ completed = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id)++ assert completed["scan"]["progress"]["status"] == "complete"+ manifest = json.loads((scan_dir / "scan-manifest.json").read_text())+ assert manifest["scan"]["target"]["kind"] == "git_revision"+ assert manifest["scan"]["target"]["revision"] == revision+ assert "snapshotDigest" not in manifest["scan"]["target"]+ assert manifest["scan"]["scope"]["includePaths"] == ["."]+ coverage = json.loads((scan_dir / "coverage.json").read_text())+ assert coverage["mode"] == "repository"+ assert (scan_dir / "report.md").is_file()+++def test_cli_completion_adopts_registered_worktree_kind_for_revision_draft(+ tmp_path: Path,+) -> None:+ state_dir = tmp_path / "state"+ target = tmp_path / "target"+ revision = initialize_git_repository(target)+ (target / "README.md").write_text("changed after commit\n")+ scan_dir = tmp_path / "scan"+ registered = register_cli_scan(state_dir, target, scan_dir)+ contract_target = registered["contract"]["target"]+ assert contract_target["allowedKinds"] == ["git_worktree"]+ scan_id = str(registered["scanId"])+ write_completed_contract(+ scan_dir,+ scan_id,+ target,+ relative_path="README.md",+ target_kind="git_revision",+ target_revision=revision,+ )++ completed = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id)++ assert completed["scan"]["progress"]["status"] == "complete"+ sealed_manifest = json.loads((scan_dir / "scan-manifest.json").read_text())+ assert sealed_manifest["scan"]["target"]["kind"] == "git_worktree"+ assert (+ sealed_manifest["scan"]["target"]["snapshotDigest"]+ == contract_target["requiredSnapshotDigest"]+ )+++def test_cli_completion_adopts_diff_kind_with_bound_range_digest(tmp_path: Path) -> None:+ # A range diff binds its own snapshotDigest, so adopting git_diff replaces the+ # draft's whole-worktree digest instead of sealing it as the diff digest.+ state_dir = tmp_path / "state"+ target = tmp_path / "target"+ initialize_git_repository(target)+ (target / "README.md").write_text("second fixture\n")+ subprocess.run(["git", "commit", "-qam", "Second commit"], cwd=target, check=True)+ scan_dir = tmp_path / "scan"+ scan_dir.mkdir(mode=0o700)+ registered = run_workbench(+ state_dir,+ "register-cli-scan",+ "--repository",+ str(target),+ "--scan-dir",+ str(scan_dir),+ "--recipe-json",+ json.dumps(+ {+ "config": {},+ "mode": "standard",+ "repository": str(target),+ "target": {"kind": "refs", "paths": [], "base": "HEAD~1", "head": "HEAD"},+ }+ ),+ )+ assert registered["contract"]["target"]["allowedKinds"] == ["git_diff"]+ scan_id = str(registered["scanId"])+ write_completed_contract(+ scan_dir,+ scan_id,+ target,+ relative_path="README.md",+ target_kind="git_worktree",+ coverage_mode="branch_diff",+ inventory_strategy="diff",+ )++ draft_target = json.loads((scan_dir / "scan-manifest.json").read_text())["scan"]["target"]++ completed = scan_command(state_dir, "complete-scan", scan_id)++ assert completed["scan"]["progress"]["status"] == "complete"+ sealed_target = json.loads((scan_dir / "scan-manifest.json").read_text())["scan"]["target"]+ assert sealed_target["kind"] == "git_diff"+ assert sealed_target["snapshotDigest"] != draft_target["snapshotDigest"]++def test_completion_populates_coverage_mode_from_selected_scan_mode(tmp_path: Path) -> None:state_dir = tmp_path / "state"codex_home = tmp_path / "codex-home"@@ -687,17 +865,17 @@ def test_completion_keeps_invalid_prewrite_drafts_resumable() -> None:state_dir, scan_id, scan_dir = _start_scan_with_draft_findings(tmp_path)manifest = json.loads((scan_dir / "scan-manifest.json").read_text())- target_kind = manifest["scan"]["target"]["kind"]- manifest["scan"]["target"]["kind"] = "git_worktree"+ # The workbench binding never owns the remote, so this stays a draft error.+ manifest["scan"]["target"]["remote"] = "not-a-url"(scan_dir / "scan-manifest.json").write_text(json.dumps(manifest))failed = scan_command(state_dir, "complete-scan", scan_id, check=False)assert failed["returncode"] != 0- assert "target.kind" in str(failed["stderr"])+ assert "target.remote" in str(failed["stderr"])pending = get_scan(state_dir, scan_id)["scan"]assert pending["progress"]["status"] == "running"- manifest["scan"]["target"]["kind"] = target_kind+ del manifest["scan"]["target"]["remote"](scan_dir / "scan-manifest.json").write_text(json.dumps(manifest))completed = scan_command(state_dir, "complete-scan", scan_id)["scan"]assert completed["progress"]["status"] == "complete"@@ -800,9 +978,9 @@ def test_rejected_completion_restores_parent_head_before_corrected_retry(path.name: (path.read_bytes(), path.stat().st_mtime_ns)for path in (scan_dir / "checkpoints").glob("*.json")}- target_kind = manifest["scan"]["target"]["kind"]if defect == "target":- manifest["scan"]["target"]["kind"] = "unsupported_target"+ # The workbench binding never owns the remote, so this stays a draft error.+ manifest["scan"]["target"]["remote"] = "not-a-url"else:coverage["deferred"][0]["reason"] = "Invalid review: \ud800"manifest_path.write_text(json.dumps(manifest))@@ -816,7 +994,7 @@ def test_rejected_completion_restores_parent_head_before_corrected_retry(failed = scan_command(state_dir, command, scan_id, check=False)assert failed["returncode"] != 0- assert ("target.kind" if defect == "target" else "coverage") in failed["stderr"]+ assert ("target.remote" if defect == "target" else "coverage") in failed["stderr"]assert head_state() == previous_headassert {path.name: (path.read_bytes(), path.stat().st_mtime_ns)@@ -825,7 +1003,7 @@ def test_rejected_completion_restores_parent_head_before_corrected_retry(assert all(path.read_bytes() == contents for path, contents in original_documents.items())# Correct the rejected documents without rewriting unchanged findings.if defect == "target":- manifest["scan"]["target"]["kind"] = target_kind+ del manifest["scan"]["target"]["remote"]manifest_path.write_text(json.dumps(manifest))os.utime(manifest_path, ns=(300, 300))coverage["deferred"] = []@@ -877,7 +1055,8 @@ def test_deep_completion_rejects_invalid_target_even_with_recoverable_inventory(state_dir, scan_id, scan_dir = _start_deep_scan_with_draft_findings(tmp_path)manifest_path = scan_dir / "scan-manifest.json"manifest = json.loads(manifest_path.read_text())- manifest["scan"]["target"]["kind"] = "git_worktree"+ # The workbench binding never owns the remote, so this stays a draft error.+ manifest["scan"]["target"]["remote"] = "not-a-url"manifest_path.write_text(json.dumps(manifest))coverage_path = scan_dir / "coverage.json"coverage = json.loads(coverage_path.read_text())@@ -887,7 +1066,7 @@ def test_deep_completion_rejects_invalid_target_even_with_recoverable_inventory(failed = scan_command(state_dir, "complete-scan", scan_id, check=False)assert failed["returncode"] != 0- assert "target.kind" in str(failed["stderr"])+ assert "target.remote" in str(failed["stderr"])recorded = get_scan(state_dir, scan_id)["scan"]assert recorded["progress"]["status"] == "failed"assert recorded["resultsRecoveryNeeded"] is Truediff --git a/plugins/codex-security/tests/test_workbench_db.py b/plugins/codex-security/tests/test_workbench_db.pyindex 47af92867..e6770a0e0 100644--- a/plugins/codex-security/tests/test_workbench_db.py+++ b/plugins/codex-security/tests/test_workbench_db.py@@ -3235,10 +3235,15 @@ def test_workbench_preserves_dirty_git_scan_after_worktree_changes(tmp_path: Pattarget_kind="git_revision",target_revision=revision,)- failed = scan_command(state_dir, "complete-scan", scan_id, check=False)- assert failed["returncode"] != 0- assert "scan.target.kind" in str(failed["stderr"])- assert get_scan(state_dir, scan_id)["scan"]["progress"]["status"] == "running"+ # A draft that inferred git_revision from the checkout seals with the+ # registered worktree kind and digest instead of discarding the scan.+ completed = scan_command(state_dir, "complete-scan", scan_id)+ assert completed["scan"]["progress"]["status"] == "complete"+ manifest = json.loads(+ (Path(str(started["results"]["scanDir"])) / "scan-manifest.json").read_text()+ )+ assert manifest["scan"]["target"]["kind"] == "git_worktree"+ assert manifest["scan"]["target"]["snapshotDigest"] == contract["requiredSnapshotDigest"]started = start_delivered_scan(state_dir, "--workspace-id", str(saved["id"]))scan_id = str(started["results"]["scanId"])