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(deep-scan): preserve differing threat models and use primary repair sites (#2306)
Michael D'Angelo1d9f7c379b4a
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.tsindex 43bc5e437..618e0432f 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts@@ -1,5 +1,6 @@import { createHash } from "node:crypto";import { dirname, join, posix, relative, sep } from "node:path";+import { isDeepStrictEqual } from "node:util";import { asRecord } from "../record.js";import type { JsonObject } from "../types.js";import { artifactSourcePath, type ArtifactContext } from "../artifact-io.js";@@ -142,6 +143,7 @@ export async function validateDiscoveryArtifacts(export function scanCoverage(worker: AcceptedDiscovery,scanDir: string,+ additionalModel?: ScanDraftInput["threatModel"],): ScanDraftInput["reviewState"] {const coverage = worker.result.reviewState;const artifactPrefix = relative(scanDir, dirname(worker.resultPath))@@ -202,7 +204,11 @@ export function scanCoverage(};});return {- reviews: [provenance],+ reviews: [+ additionalModel+ ? { ...provenance, threatModel: additionalModel }+ : provenance,+ ],surfaces,explicitExclusions: coverage.explicitExclusions.map(project),deferred: coverage.deferred.map((item, index) => ({@@ -239,7 +245,13 @@ export function addScanCoverage(worker: AcceptedDiscovery,scanDir: string,): void {- const coverage = scanCoverage(worker, scanDir);+ const model = worker.result.threatModel;+ aggregate.threatModel ??= model;+ const additionalModel =+ model && !isDeepStrictEqual(model, aggregate.threatModel)+ ? model+ : undefined;+ const coverage = scanCoverage(worker, scanDir, additionalModel);const previous = aggregate.sourceCoverage;if (!previous) {aggregate.sourceCoverage = coverage;diff --git a/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts b/plugins/codex-security/mcp-app/src/deep-scan/coordinator.tsindex 32a92af2e..9b1e949ac 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts@@ -868,10 +868,11 @@ export class DeepScanCoordinator {);dispatched += count;this.state = { ...this.state, dispatchedCount: dispatched };- const previousFindings = result.findings.map(- ({ title, locations: [site] }) =>- `${site.path}:${site.startLine} ${title}`,- );+ const previousFindings = result.findings.map(({ title, locations }) => {+ const site =+ locations.find(({ role }) => role === "root_control") ?? locations[0];+ return `${site.path}:${site.startLine} ${title}`;+ });const outcomes = await this.scanBatch(count, scanLabel, previousFindings);signal.throwIfAborted();batch = [];diff --git a/plugins/codex-security/mcp-app/src/deep-scan/iteration.ts b/plugins/codex-security/mcp-app/src/deep-scan/iteration.tsindex 1f17e564e..7ab6d82e4 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/iteration.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/iteration.ts@@ -511,7 +511,6 @@ export async function mergeBatch(}aggregate.scope = merged;}- aggregate.threatModel ??= worker.result.threatModel;}// A later worker can add a separately fixable path to a previously merged group.for (const group of retained.slice(0, previous)) {diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.tsindex 33dfbb35e..90608f08f 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts@@ -42,6 +42,7 @@ try {await testWorkerPublicationBeforeCheckpoint(root);await testLegacyDeferredPublication(root);testResolvedDeferredPublication();+ testDistinctThreatModels();await testMissingReceiptRepair(root);for (const reverse of [false, true])await testMissingReceiptRepair(root, { shared: true, reverse });@@ -71,6 +72,33 @@ try {console.log("deep scan artifact validation tests passed");+function testDistinctThreatModels() {+ const aggregate: ScanUnion = { scanId, findings: [] };+ const first = { summary: "An unauthenticated caller can reach the service." };+ const other = {+ format: "markdown",+ content: "A worker can also submit a job.",+ };+ for (const [i, threatModel] of [first, { ...first }, other].entries()) {+ addScanCoverage(+ aggregate,+ {+ id: `worker-${i}`,+ attempt: 1,+ resultPath: "worker/output/result.json",+ result: draft([], { threatModel }),+ },+ ".",+ );+ }+ assert.deepEqual(aggregate.threatModel, first);+ assert.deepEqual(aggregate.sourceCoverage?.reviews, [+ { workerId: "worker-0", attempt: 1 },+ { workerId: "worker-1", attempt: 1 },+ { workerId: "worker-2", attempt: 1, threatModel: other },+ ]);+}+function testResolvedDeferredPublication() {const source = {surfaces: [],diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_iterations.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_iterations.tsindex c9fb0fb6c..151f90df4 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_iterations.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_iterations.ts@@ -316,7 +316,13 @@ test("overlapping lists of affected endpoints retain the additional fix", async});test("a new instance extends the loop and an unfinished final batch respects the cap", async () => {- const other = { ...base, locations: [{ path: "fixture.py", startLine: 22 }] };+ const other = {+ ...base,+ locations: [+ { path: "fixture.py", startLine: 22, role: "entrypoint" },+ { path: "fixture.py", startLine: 35, role: "root_control" },+ ],+ };const gate = Promise.withResolvers<void>();const { terminal, draft, started, previousByPass } = await scanLoop([[base], [other], [base]],@@ -335,7 +341,7 @@ test("a new instance extends the loop and an unfinished final batch respects theassert.deepEqual(previousByPass, [[],[],- [`fixture.py:1 ${base.title}`, `fixture.py:22 ${other.title}`],+ [`fixture.py:1 ${base.title}`, `fixture.py:35 ${other.title}`],]);assert.equal(terminal.terminalReason, "capped");assert.deepEqual(diff --git a/plugins/codex-security/references/scan-contract.md b/plugins/codex-security/references/scan-contract.mdindex 7cf7d17c6..374073dbc 100644--- a/plugins/codex-security/references/scan-contract.md+++ b/plugins/codex-security/references/scan-contract.md@@ -174,7 +174,7 @@ The two canonical JSON files are also the only semantic inputs to final report gRecord report-specific semantics without duplicating data already represented elsewhere:- `scan.scope`: optional narrative `summary`, reviewed artifact names, runtime/test status, validation mode, scan context, and limitations. Include/exclude paths remain the authoritative scope boundaries.-- `scan.threatModel`: structured summary plus assets, trust boundaries, attacker capabilities, security objectives, and assumptions, or `{ "format": "markdown", "content": "<exact model text>" }` for a retained document. Optional model `scope` and `origin` identify the modeled paths and source separately from the scan's scope. The host derives `<scan_dir>/threatmodel.md` from this content; it is an exportable projection, not an independently authored input.+- `scan.threatModel`: structured summary plus assets, trust boundaries, attacker capabilities, security objectives, and assumptions, or `{ "format": "markdown", "content": "<exact model text>" }` for a retained document. Optional model `scope` and `origin` identify the modeled paths and source separately from the scan's scope. When completed Deep reviews supply different models, the parent retains the first model here and the other models on their worker records in `scan.reviewState.reviews`. The host derives `<scan_dir>/threatmodel.md` from the primary model; it is an exportable projection, not an independently authored input.- finding `validation`: validation method, direct evidence, counterevidence, and the conclusion used by the report.- finding `codeEvidence`: stable, exact source snippets with labels, locations, language, and explanations; `rootCause`, `validation`, and `attackPath` select the snippets they need through `evidenceRefs`.- finding `rootCause`: the violated invariant and the code that breaks it. Do not substitute a path/line restatement for the explanation.diff --git a/plugins/codex-security/scripts/report_projection.py b/plugins/codex-security/scripts/report_projection.pyindex b6a0a329b..e4a98cd20 100644--- a/plugins/codex-security/scripts/report_projection.py+++ b/plugins/codex-security/scripts/report_projection.py@@ -878,6 +878,20 @@ def build_report_markdown(values = _strings(threat_model.get(key))if values:lines.extend(["", f"### {heading}", "", *(f"- {value}" for value in values)])+ reviews = scan.get("reviewState", {}).get("reviews")+ if isinstance(reviews, list) and any(+ isinstance(review, dict) and isinstance(review.get("threatModel"), dict)+ for review in reviews+ ):+ lines.extend(+ [+ "",+ (+ "Other reviews recorded different threat models. See the `threatModel` fields "+ "in `scan.reviewState.reviews` in the [scan manifest](scan-manifest.json)."+ ),+ ]+ )lines.extend(["", "## Findings", ""])informational_count = sum(finding["severity"]["level"] == "informational" for finding in findings_document["findings"]diff --git a/plugins/codex-security/skills/deep-security-scan/SKILL.md b/plugins/codex-security/skills/deep-security-scan/SKILL.mdindex 36a923dec..18ac4937b 100644--- a/plugins/codex-security/skills/deep-security-scan/SKILL.md+++ b/plugins/codex-security/skills/deep-security-scan/SKILL.md@@ -9,6 +9,6 @@ The host runs Standard audits and merges their findings. Workers in the same sca1. Resolve the authorized target and scope. For a scoped directory use that directory as `targetPath` and `scope: "."`. For a continuation, call `get_codex_security_scan_context` with its `scanId` and supplied `handoffClaimToken`. Use its saved identity and scope. If its mode is Standard or diff, continue with the corresponding scan skill. Follow `../../references/scan-prologue.md` for source access and context updates.2. For a new target, call `inspect_codex_security_setup({ targetPath, scope: ".", mode: "deep", projectConfigPath? })`. Show the effective settings and their sources. `max_discovery_runs` caps the total number of Standard scans, including when several run together. Pass a project file only when the user selected it. Existing scans use their saved configuration.-3. For a newly launched native scan, inspect `otherRunningDeepScans` once. If another Deep scan is active, show its target, phase and human-friendly start time. Explain the additional CPU, memory and token use. Offer **Cancel (Recommended)** and **Continue** using `request_user_input`, then `request_codex_security_user_input` or plain chat if unavailable. Wait for an explicit choice. A dismissed dialog is not a cancellation. Cancel only the new scan if requested.-4. Follow `../../references/access-advisory.md`, then call `start_codex_security_deep_scan` with the existing scan ID and claim token, or with the new target, scope, exact user context and selected project file. Await the tool. If the tool runner returns a running cell ID, wait on that cell until it returns the scan result. If the connection closes, rejoin with the same arguments. Report a terminal failure with its saved results. For a policy refusal, identify the worker from its saved error when available. On explicit cancellation call `cancel_codex_security_scan`.+3. For a newly launched native scan with a supplied scan ID, inspect `otherRunningDeepScans` in the result of `get_codex_security_scan_context` once. Target-based setup previews have no scan ID. If another Deep scan is active, show its target, phase and human-friendly start time. Explain the additional CPU, memory and token use. Offer **Cancel (Recommended)** and **Continue** using `request_user_input`, then `request_codex_security_user_input` or plain chat if unavailable. Wait for an explicit choice. A dismissed dialog is not a cancellation. Cancel only the new scan if requested.+4. Follow `../../references/access-advisory.md`, then call `start_codex_security_deep_scan({ scanId, handoffClaimToken? })` for an existing scan or `start_codex_security_deep_scan({ targetPath, scope: ".", userContext?, projectConfigPath? })` for a new target. Reuse the project file selected at setup. Await the tool. If the tool runner returns a running cell ID, wait on that cell until it returns the scan result. If the connection closes, rejoin with the same arguments. Report a terminal failure with its saved results. For a policy refusal, identify the worker from its saved error when available. On explicit cancellation call `cancel_codex_security_scan({ scanId })` from the owning thread.5. For an SDK-owned scan, return the host's scan ID and manifest path so the SDK can finalize it. When the tool returns `completion`, link its generated `report.md` and canonical artifacts. Use `completion.scan.usage` and any separate cost estimate to report usage per `../../references/final-report.md`. Distinguish a completed audit with zero findings from a deadline reached before any audit completed.diff --git a/plugins/codex-security/tests/test_report_projection.py b/plugins/codex-security/tests/test_report_projection.pyindex 09c12b9bf..baf53eedf 100644--- a/plugins/codex-security/tests/test_report_projection.py+++ b/plugins/codex-security/tests/test_report_projection.py@@ -3,6 +3,7 @@from __future__ import annotationsimport copy+from pathlib import Pathimport pytestfrom workbench_test_support import load_script@@ -50,6 +51,17 @@ def canonical_documents() -> tuple[dict[str, object], dict[str, object], dict[streturn manifest, findings, coverage+def test_report_points_to_distinct_worker_models_in_the_manifest(monkeypatch) -> None:+ monkeypatch.syspath_prepend(Path(PROJECTION.__file__).parent)+ manifest, findings, coverage = canonical_documents()+ manifest["scan"].update(+ review={},+ reviewState={"reviews": [{"workerId": "worker", "threatModel": {"summary": "Job state"}}]},+ )+ markdown = PROJECTION.build_report_markdown(manifest, findings, coverage)+ assert "scan.reviewState.reviews" in markdown++def report_with_finding(**fields: object) -> str:manifest, findings, coverage = canonical_documents()findings["findings"][0].update(fields)