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(sdk): respect Deep and diff scan completion ownership (#457)
Dane Schneider1fc1a8ce9e49
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex 1fc4ff72b..c5cb73c34 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -1443,6 +1443,8 @@ def complete_scan_locked(verify_manifest_binding(scan, manifest)manifest_digest = published_manifest_digest(scan_dir, manifest)pin_legacy_manifest_digest(connection, scan["id"], manifest_digest)+ if cost_json is not None and scan["recipe_json"] is not None:+ scan_usage.reconcile_completed_scan_cost(connection, scan, cost_json)return scan_context(connection, scan["id"])if scan["status"] != "running":raise SystemExit("Only a running scan can be completed.")diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_usage.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_usage.pyindex be5bc9282..db987d20c 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_usage.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_usage.py@@ -55,6 +55,32 @@ def measured_scan_cost_json(usage: Mapping[str, Any]) -> str:return json.dumps({"usage": dict(usage)}, separators=(",", ":"), allow_nan=False)+def reconcile_completed_scan_cost(+ connection: sqlite3.Connection,+ scan: sqlite3.Row,+ cost_json: str,+) -> None:+ """Persist authoritative SDK cost without discarding measured worker usage."""++ existing = json.loads(scan["cost_json"]) if scan["cost_json"] is not None else {}+ if isinstance(existing, dict) and "usage" in existing:+ cost_json = json.dumps(+ {**existing, "cost": json.loads(cost_json)},+ separators=(",", ":"),+ allow_nan=False,+ )+ connection.execute("BEGIN IMMEDIATE")+ try:+ connection.execute(+ "UPDATE scans SET cost_json = ? WHERE id = ? AND status = 'complete'",+ (cost_json, scan["id"]),+ )+ connection.commit()+ except BaseException:+ connection.rollback()+ raise++def collect_scan_usage(connection: sqlite3.Connection,scan: sqlite3.Row,diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 3fde8e860..2c56b64bb 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -914,6 +914,7 @@ export class CodexSecurity {runtime.configPath !== undefined,knowledgeBase !== null,options.scanPrompt,+ options.maxCostUsd !== undefined,);checkOpen();const feedback = await workbench(@@ -2384,6 +2385,7 @@ function scanPrompt(hasConfigPath = false,hasKnowledgeBase = false,additionalPrompt?: string,+ enforceCostLimit = false,): string {const python = `${process.platform === "win32" ? "& " : ""}${shellEnvironmentReference("PYTHON")}`;return [@@ -2445,7 +2447,13 @@ 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, python),- "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.",+ ...(skillName === "security-scan" || enforceCostLimit+ ? [+ "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.",+ ]+ : [+ "Use record_codex_security_scan_draft and complete_codex_security_scan as directed by the selected skill; the workbench owns authoritative metadata, finalization, report generation, and sealing.",+ ]),...(additionalPrompt?.trim()? ["Additional scan instructions:", additionalPrompt]: []),diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex a4e0fcdea..2b4847613 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1923,6 +1923,7 @@ describe("CodexSecurity orchestration", () => {expect(prompt).toContain("$codex-security:security-scan");expect(prompt).toContain("The SDK has already registered this scan.");expect(prompt).toContain("never call a scan-start or completion tool");+ expect(prompt).toContain("do not finalize or seal them");expect(prompt).toContain("This Standard scan authorizes its independent baseline auditor and focused investigators",);@@ -5182,6 +5183,8 @@ describe("CodexSecurity orchestration", () => {`Scan target: Git diff from ${revision} to ${revision}.`,);expect(prompt).toContain("$codex-security:security-diff-scan");+ expect(prompt).toContain("complete_codex_security_scan");+ expect(prompt).not.toContain("do not finalize or seal them");expect(prompt).toContain("This exhaustive scan authorizes the delegated-worker phases",);@@ -5192,6 +5195,8 @@ describe("CodexSecurity orchestration", () => {"prompt captured",);expect(prompt).toContain("$codex-security:deep-security-scan");+ expect(prompt).toContain("complete_codex_security_scan");+ expect(prompt).not.toContain("do not finalize or seal them");expect(prompt).toContain('start_codex_security_deep_scan with {"scanId":"scan_example_001"}',);@@ -5199,6 +5204,21 @@ describe("CodexSecurity orchestration", () => {"This exhaustive scan authorizes the delegated-worker phases",);+ await expect(+ client.run(repository, { mode: "deep", maxCostUsd: 1 }),+ ).rejects.toThrow("prompt captured");+ expect(prompt).toContain("do not finalize or seal them");+ expect(prompt).not.toContain("complete_codex_security_scan");++ await expect(+ client.run(repository, {+ target: DiffTarget.refs({ base, head }),+ maxCostUsd: 1,+ }),+ ).rejects.toThrow("prompt captured");+ expect(prompt).toContain("do not finalize or seal them");+ expect(prompt).not.toContain("complete_codex_security_scan");+await expect(client.run(repository, { target: DiffTarget.workingTree({ base }) }),).rejects.toThrow("prompt captured");diff --git a/sdk/typescript/tests-ts/scan-recovery.test.ts b/sdk/typescript/tests-ts/scan-recovery.test.tsindex fa2c7c912..e6709d55d 100644--- a/sdk/typescript/tests-ts/scan-recovery.test.ts+++ b/sdk/typescript/tests-ts/scan-recovery.test.ts@@ -460,6 +460,94 @@ describe("malformed scan artifact recovery", () => {expect((await completeScan(fixture)).progress.status).toBe("complete");});+ test.each([+ ["unavailable", undefined],+ [+ "worker-inclusive",+ {+ coverage: "complete",+ source: "codex_rollout",+ threadCount: 3,+ inputTokens: 5_000,+ cachedInputTokens: 400,+ cacheWriteInputTokens: 0,+ outputTokens: 120,+ reasoningOutputTokens: 20,+ totalTokens: 5_120,+ },+ ],+ ] as const)(+ "reconciles authoritative scan cost without replacing %s usage or sealed artifacts",+ async (_scenario, measuredUsage) => {+ const fixture = await startDraftScan();+ const firstCompletion = await workbench(fixture, [+ "complete-scan",+ "--scan-id",+ fixture.scanId,+ ...(measuredUsage === undefined+ ? []+ : ["--cost-json", JSON.stringify({ usage: measuredUsage })]),+ ]);+ const initiallyCompleted = firstCompletion["scan"] as ScanSummary & {+ usage: Record<string, unknown>;+ cost?: unknown;+ };+ expect(initiallyCompleted.progress.status).toBe("complete");+ expect(initiallyCompleted.usage).toBeDefined();+ if (measuredUsage !== undefined) {+ expect(initiallyCompleted.usage).toEqual(measuredUsage);+ }+ expect(initiallyCompleted.cost).toBeUndefined();++ const artifactNames = [+ "scan-manifest.json",+ "findings.json",+ "coverage.json",+ "report.md",+ ];+ const sealedArtifacts = await Promise.all(+ artifactNames.map((name) => readFile(join(fixture.scanDir, name))),+ );+ const cost = {+ model: "gpt-5.6-sol",+ inputTokens: 1_250,+ cachedInputTokens: 200,+ cacheWriteInputTokens: 0,+ outputTokens: 30,+ estimatedUsd: 0.00625,+ };++ const reconciled = await workbench(fixture, [+ "complete-scan",+ "--scan-id",+ fixture.scanId,+ "--cost-json",+ JSON.stringify(cost),+ ]);+ expect(reconciled["scan"]).toMatchObject({+ progress: { status: "complete" },+ usage: initiallyCompleted.usage,+ cost,+ });++ const persisted = await workbench(fixture, [+ "get-scan",+ "--scan-id",+ fixture.scanId,+ ]);+ expect(persisted["scan"]).toMatchObject({+ progress: { status: "complete" },+ usage: initiallyCompleted.usage,+ cost,+ });+ expect(+ await Promise.all(+ artifactNames.map((name) => readFile(join(fixture.scanDir, name))),+ ),+ ).toEqual(sealedArtifacts);+ },+ );+test("preserves target-drift classification from prepared completion", async () => {const fixture = await startDraftScan();const source = join(fixture.repository, "src", "extract.py");