codex-security icon indicating copy to clipboard operation
codex-security copied to clipboard

scan --diff always fails to save: scan.target.snapshotDigest: expected a non-empty string

Open pfilbin90 opened this issue 3 months ago • 8 comments

Summary

Every scan --diff run fails at the save step with:

Could not save the Codex Security scan: scan.target.snapshotDigest: expected a non-empty string

The scan itself completes successfully — the agent reviews the diff, builds a threat model, and writes scan-manifest.json, findings.json, and coverage.json. Only the final save is rejected, so the entire scan is discarded and the CLI exits 2.

The cause appears to be a schema mismatch inside the tool: for target.kind: "git_diff" the plugin writes a target block with no snapshotDigest field, but the save-side validator requires one.

Repository scans (no --diff) are unaffected and save normally.

Reproduction

Minimal, self-contained — a one-file repository with two commits:

mkdir -p /tmp/probe && cd /tmp/probe
git init -q && git config user.email [email protected] && git config user.name p
echo base > app.txt && git add -A && git commit -qm base
echo changed > app.txt && git add -A && git commit -qm change

npx --yes @openai/[email protected] scan . \
  --auth chatgpt \
  --model gpt-5.6-luna \
  --effort high \
  --max-cost 0.50 \
  --diff HEAD~1 \
  --output-dir /tmp/out \
  --verbose

Result:

[07:04] Running scan: building threat model (committed changes) | Files: 1/1
codex-security: debug: scan.failed classification="unknown" partial_output=true
Could not save the Codex Security scan: scan.target.snapshotDigest: expected a non-empty string
Partial output was kept at /tmp/out.

Removing --diff from the same command makes it succeed and print Scan complete.

Evidence

The preserved scan-manifest.json shows status: "completed" with all required artifacts present, and a target block with no snapshotDigest:

{
  "documentType": "codex-security.scan-manifest",
  "schemaVersion": "1.0",
  "scan": {
    "status": "completed",
    "producer": { "name": "codex-security-plugin", "version": "0.1.15" },
    "target": {
      "kind": "git_diff",
      "targetId": "target_sha256_ce9ecd19952d3cad45e46f75d207a5e82504efa390915e0e6c1e4bffea06e5cc",
      "displayName": "probe2",
      "baseRevision": "ac0c1def281595d9aeedf404af43602841724901",
      "headRevision": "975a26fc600c85942a1f9d648b902602d7f138e9"
    }
  }
}

findings.json, coverage.json, threat_model.md and the full artifacts/ tree are all written. On a real 12-file diff the same run produced three well-formed medium-severity findings before being discarded by the same error.

Affected versions

Version --diff repository scan
0.1.7 fails succeeds
0.1.6 fails not retested

Not a regression in 0.1.7 — 0.1.6 fails identically.

Impact

--diff is the natural mode for CI, where the point is scanning a pull request's changes rather than the whole tree. Falling back to a full repository scan is not a practical workaround: on a 3,600-file repository the diff scan of 12 files already took 27 minutes, so scanning everything per PR is out of reach.

Because the scan runs to completion before failing, each attempt costs full time and tokens and returns nothing.

Environment

  • @openai/codex-security 0.1.7 and 0.1.6, bundled plugin 0.1.15
  • codex 0.144.6, codex-sdk 0.144.6
  • Node 22, Ubuntu 24.04 container, x86-64
  • Auth: --auth chatgpt
  • Reproduced identically on a self-hosted GitHub Actions runner and in a bare docker run

Possibly related

In a container, the scan agent's sandbox cannot initialize, and the agent reports internally: "the terminal wrapper is unavailable in this host because its sandbox namespace cannot initialize". It then silently proceeds without a shell and fails much earlier with Scan agent did not create required draft artifacts: scan-manifest.json, findings.json, coverage.json.

Running the container with --security-opt seccomp=unconfined resolves that and lets the agent work normally. It may be worth surfacing a clearer diagnostic for that case, since the current message points at the scan directory rather than at sandbox initialization.

pfilbin90 avatar Aug 07 '26 03:08 pfilbin90

Found the root cause in the bundled plugin (0.1.15). It's a one-line contradiction between the contract generator and the validator, not an agent-behaviour issue — which explains why it reproduces 100% of the time regardless of model, effort, or repository.

The contradiction

_bundled_plugin/scripts/workbench_db.py — scan_contract() refuses to set requiredSnapshotDigest in diff mode:

if (
    scan["mode"] != "diff"          # <-- diff mode can never get here
    and scan["target_snapshot_digest"]
    and (
        scan["target_revision"] == "unversioned"
        or scan["target_snapshot_digest"] != clean_worktree_content_digest()
    )
):
    target_contract["requiredSnapshotDigest"] = scan["target_snapshot_digest"]

But the same file maps diff mode to the one target kind that requires a digest:

def expected_target_kinds(scan):
    if scan["mode"] == "diff":
        return ["git_diff"]
    ...

And finalize_scan_contract.py enforces it:

"git_worktree": {"snapshotDigest"},
"git_diff": {"snapshotDigest"},
"directory_snapshot": {"snapshotDigest"},

So in diff mode the agent receives a target contract containing no requiredSnapshotDigest, has no supported way to compute one (workbench_target.py exposes digest helpers for worktrees and directory snapshots, but nothing for a commit range), emits a git_diff target without the field, and is rejected at save.

references/scan-contract.md documents the same gap from the other direction. It tells the agent how to source the digest for the two workbench-backed cases:

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.

There is no corresponding instruction for git_diff, whose row in the table immediately below nonetheless lists snapshotDigest as required.

Suggested fix

Either compute and record a diff snapshot digest in diff mode (so scan_contract() can hand it over like the worktree path does), or drop snapshotDigest from the required set for git_diff and rely on baseRevision/headRevision, which the agent already populates correctly.

Workaround, for anyone else hitting this

Reset the branch's changes into the working tree and scan that instead, which takes the non-diff branch and gets a digest:

git reset --soft "$BASE_SHA"
codex-security scan . --working-tree --base HEAD

Verified: same file set reviewed, scan saves, exit 0, and the manifest comes back with a well-formed snapshotDigest.

pfilbin90 avatar Aug 07 '26 15:08 pfilbin90

#449 addresses direct committed-diff finalization and binds the saved snapshot to the reviewed diff contents. Keeping this issue open until that change lands; #53 is being consolidated here.

mldangelo-oai avatar Aug 15 '26 07:08 mldangelo-oai

Still reproduces on 0.1.14 (Ubuntu 24.04.4 LTS, Node v22.23.2, Python 3.12.3, --auth chatgpt, --model gpt-5.6-sol) — so this has survived from 0.1.7 through 0.1.14.

Adding a scale data point, since the repro above is a one-file repository and the cost of this bug scales with scan size: a --diff BASE --head HEAD scan over a 196-file commit range (79 source-like files reviewed across 16 discovery shards, ~35 minutes, ~$30 estimated) completed every phase — discovery, validation, and attack-path analysis — and was then discarded at save with the same error, exit 2.

Practical note for anyone hitting this: the work is not lost. Everything survives under the scan state directory printed in the failure line:

  • artifacts/02_discovery/finding_discovery_report.md — what was reviewed and what survived discovery
  • artifacts/05_findings/<candidate-id>/validation_report.md and attack_path_analysis_report.md — the per-finding verdicts

Only the top-level findings.json is empty ("findings": []), and findings list / scans compare / export see nothing, since the save step is what populates them.

1wgrumph avatar Aug 20 '26 15:08 1wgrumph

Fixed on current main (d35019a4).

Committed diff scans now carry the authoritative diff content digest through the SDK/MCP contract and persist it as scan.target.snapshotDigest. The generated bundled plugin was rebuilt from the canonical source and the focused validation passed:

  • compact diff/MCP suite: 9 passed
  • plugin diff-target and completion-binding contracts: 6 passed

The original save-time snapshotDigest rejection no longer reproduces on the current source path, so I am closing this as fixed on main.

soyeon-oai avatar Aug 27 '26 22:08 soyeon-oai

Still reproduces on 0.1.24 (bundled plugin 0.1.79, codex 0.149.1) for headless terminal scans.

Command:

Result: Could not save the Codex Security scan: scan.target.snapshotDigest: expected a non-empty string

Generated scan-manifest.json target block — snapshotDigest is absent entirely:

{
  "kind": "git_diff",
  "targetId": "target_sha256_4b520daf...",
  "displayName": "codex-poc-test",
  "revision": "4fb924a0ef0edd93bb9835fc90b50a1d6f3a0bc4",
  "baseRevision": "eee286ac52a8d0ec465c8a8311468bcd9f6a7551",
  "headRevision": "4fb924a0ef0edd93bb9835fc90b50a1d6f3a0bc4"
}

Likely cause — the fix appears to cover the workbench/MCP path only. In dist/api.js:491:

const diffTarget = isRecord(contract) ? contract["diffTarget"] : undefined;
const snapshotDigest = targetKind === "git_diff" && isRecord(diffTarget)
    ? diffTarget["contentDigest"]
    : ...

contract["diffTarget"]["contentDigest"] originates from the workbench scan registration. For a headless terminal scan without a scanId there is no workbench, so contract is absent, snapshotDigest is undefined, and at api.js:602 the spread omits CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST entirely. The agent instruction at api.js:1852 ("When CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST is set, use its exact value...") therefore never fires, and the field is never written.

For the headless path the CLI would need to compute the digest itself from base/head revisions rather than relying on a workbench-supplied contract.

Also observed downstream (with --output-dir set, on 0.1.20): once snapshotDigest is manually patched in, finalization then fails on coverage.mode: must match selected scan mode branch_diff — the generated coverage.json carries "mode": "diff" while expectedCoverageMode() in dist/contract.js returns "branch_diff" for target.kind === "refs". This looks like the same class of gap (workbench-owned metadata unfilled on the headless path) and may need fixing together. Possibly related to #50.

Environment: Ubuntu 24.04 (WSL2), Node v22.23.2, Python 3.12.3, provider amazon-bedrock.

Inkayuyu04 avatar Sep 01 '26 22:09 Inkayuyu04

Request to reopen based on the published @openai/codex-security 0.1.25 artifact. I have not performed another usage-consuming scan on 0.1.25, so this is source-level verification rather than a claimed runtime reproduction. The headless committed-range handoff still appears incomplete:

  • register_cli_scan supplies contentDigest for working_tree, but not for refs;
  • the SDK derives CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST for git_diff from contract.diffTarget.contentDigest;
  • the finalizer still requires a non-empty scan.target.snapshotDigest;
  • coverage.mode must also be branch_diff for the refs target.

The saved-results/MCP fallback can derive the digest, but that fallback was already present in 0.1.24 and did not prevent the September 2 headless terminal failure reported above.

Could the issue be reopened until an end-to-end regression using scan --diff BASE --head HEAD --headless passes through normal sealing, with both snapshotDigest and coverage.mode: branch_diff verified?

niklas-stake avatar Sep 03 '26 17:09 niklas-stake

Confirmed runtime failure in published 0.1.27

Could this issue be reopened for the published headless CLI path? We reproduced the same failure with @openai/[email protected], beyond the 0.1.24 runtime and 0.1.25 source-level reports above.

A headless committed-range scan wrote its analysis artifacts, then failed while saving:

Could not save the Codex Security scan: scan.target.snapshotDigest: expected a non-empty string

The retained manifest had kind: "git_diff", the intended baseRevision and headRevision, and no snapshotDigest. Coverage was marked complete. The JSON result expected on stdout was not produced. This was an actual model-backed run; the reproduction below isolates its finalization failure without another model call.

Environment:

  • Published npm package: @openai/[email protected].
  • Package gitHead: c40d059935592adc1ae04119eb7ad5286d9de554.
  • Bundled plugin version: 0.1.95.
  • Affected invocation: scan --headless --json --diff <base> --head <head>.
  • The synthetic reproduction below was verified offline in a Linux container.

This report concerns the published artifact. We have not reproduced against current upstream main and are not claiming its source fix never worked.

Offline reproduction

The reproduce-codex-security-299.py script below creates a synthetic two-commit repository, calls the installed package's real register-cli-scan, writes minimal draft artifacts, and calls real complete-scan. It requires Python and Git but no credentials or model access. It can run with networking disabled.

With the pinned package already installed:

python3 reproduce-codex-security-299.py \
  "$(npm root -g)/@openai/codex-security"

Expected: finalization derives the authoritative target metadata from the registered immutable revisions, produces a sealed report, and sets coverage.mode to branch_diff.

Observed in the unpatched 0.1.27 package:

Package version: 0.1.27
Registered diff target: {"baseRevision": "...", "headRevision": "...", "kind": "range"}
Completion exit: 1
scan.target.snapshotDigest: expected a non-empty string

This exit code is from the workbench helper, not a claim about the top-level CLI's exit code. The draft deliberately omits finalizer-owned envelope fields and contains no real security findings.

Cause in the published package

In _bundled_plugin/scripts/workbench_db.py, register_cli_scan creates a range target for refs, but only assigns contentDigest for working_tree. The registered contract exists; its committed-range target lacks the digest.

dist/api.js obtains CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST from contract.diffTarget.contentDigest for git_diff, so it does not supply that environment variable for this range. workbench_completion_binding also fills the digest only for working-tree diffs. Meanwhile, finalize_scan_contract.py::_validate_target requires it for every git_diff.

An important test gap: dist/mock-scan.js::writeMockScanDraft computes and inserts the missing digest itself for immutable diffs. Consequently, scan --mock can pass while the normal draft-finalization path fails. A regression should omit the digest from the agent draft and exercise normal registration/completion.

Tested downstream workaround and requested upstream action

Our version-pinned workaround adds the immutable-diff digest to workbench_completion_binding, using the calculation already present in workbench_saved_results.py and dist/mock-scan.js:

"codex-security-snapshot/v1:sha256:" + SHA256(
  "codex-security-diff/v1" + NUL + kind + NUL + baseRevision + NUL + headRevision
)

This is an identity derived from immutable revisions, not a newly computed digest of the reviewed file contents. We are describing a downstream workaround, not proposing it as a replacement for upstream's intended content-binding design.

With that change, the same offline reproduction completes with a saved digest and coverage.mode: branch_diff. Additional real workbench tests pass for incorrect agent-supplied metadata, full-repository and working-tree targets, and rejection of a modified sealed manifest. Schema and seal validation remain enabled.

Please consider:

  1. Reopening #299 until the published headless committed-range path is verified.
  2. Adding the offline draft-finalization regression above alongside a headless SDK/CLI integration test that does not inject the digest through --mock.
  3. Fixing the canonical plugin source, regenerating the bundled npm plugin, and identifying the published version that includes the correction.
  4. Documenting whether failed scans with retained artifacts can be finalized through a supported recovery command without repeating paid analysis.
Standalone offline reproduction (save as reproduce-codex-security-299.py)
#!/usr/bin/env python3
"""Reproduce issue #299 without credentials, model calls, or private source."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile


package = Path(sys.argv[1]).resolve()
print("Package version:", json.loads((package / "package.json").read_text())["version"])
workbench = package / "_bundled_plugin/scripts/workbench_db.py"

with tempfile.TemporaryDirectory() as temporary:
    root = Path(temporary)
    repo = root / "repo"
    repo.mkdir()
    scan_dir = root / "scan"
    scan_dir.mkdir(mode=0o700)
    environment = {**os.environ, "CODEX_SECURITY_STATE_DIR": str(root / "state")}

    def git(*args):
        return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip()

    def run(*args):
        return subprocess.run([sys.executable, str(workbench), *args],
                              env=environment, capture_output=True, text=True)

    git("init", "-q")
    git("config", "user.name", "Reproduction")
    git("config", "user.email", "[email protected]")
    (repo / "example.txt").write_text("base\n")
    git("add", "example.txt")
    git("commit", "-qm", "test(repro): add base")
    base = git("rev-parse", "HEAD")
    (repo / "example.txt").write_text("head\n")
    git("commit", "-qam", "test(repro): change fixture")
    head = git("rev-parse", "HEAD")
    recipe = {"repository": str(repo), "mode": "standard", "config": {},
              "target": {"kind": "refs", "paths": [], "base": base, "head": head}}
    registration = run("register-cli-scan", "--repository", str(repo),
                       "--scan-dir", str(scan_dir), "--recipe-json", json.dumps(recipe))
    if registration.returncode:
        sys.exit(registration.stderr)
    registered = json.loads(registration.stdout)
    print("Registered diff target:", json.dumps(registered["contract"]["diffTarget"]))
    documents = {
        "scan-manifest.json": {"scan": {
            "target": {"kind": "git_diff"},
            "scope": {"summary": "Synthetic reproduction", "runtimeStatus": "not_run",
                      "limitations": ["Synthetic fixture; no security analysis performed."]},
        }},
        "findings.json": {"findings": []},
        "coverage.json": {
            "completeness": "complete", "inventoryStrategy": "diff",
            "surfaces": [{"id": "example", "label": "Synthetic fixture",
                          "disposition": "reviewed_no_finding", "receiptRefs": [],
                          "notes": "Synthetic fixture; no security analysis performed."}],
            "explicitExclusions": [], "deferred": [],
        },
    }
    for name, document in documents.items():
        (scan_dir / name).write_text(json.dumps(document))
    result = run("complete-scan", "--scan-id", registered["scanId"])
    print("Completion exit:", result.returncode)
    if result.returncode:
        print(result.stderr.strip())
    else:
        manifest = json.loads((scan_dir / "scan-manifest.json").read_text())
        coverage = json.loads((scan_dir / "coverage.json").read_text())
        print("Saved digest:", manifest["scan"]["target"]["snapshotDigest"])
        print("Coverage mode:", coverage["mode"])
        assert (scan_dir / "report.md").is_file()
    sys.exit(result.returncode)

esukram avatar Sep 15 '26 07:09 esukram

Adding cost data from a separate reproduction, since the economic impact of this bug is not yet on the record here.

We hit the same failure independently on 0.1.20, 0.1.24 and 0.1.26 via the Amazon Bedrock provider (--provider amazon-bedrock --model openai.gpt-5.6-terra), on Ubuntu 24.04 (WSL2), Node v22.23.2, Python 3.12.3. Same signature every time: every analysis phase completes, then finalization rejects the result.

What the wasted spend looks like on a trivial repository. Our test target was a single 94-line Python file with deliberately planted vulnerabilities. Five runs, all discarded at save:

Run Version / options Failure Cost
1 0.1.20, Terra, high snapshotDigest $0.69
2 0.1.20, Terra, high, --output-dir coverage.mode $0.73
3 0.1.20, Terra, medium, --json snapshotDigest $0.72
4 0.1.21, Terra, medium snapshotDigest $0.95
5 0.1.24, Terra, medium snapshotDigest $0.70

Roughly $3.80 for zero retrievable output through the supported path. Token usage was ~1.4–1.9M input per run (>90% cached), so cost is dominated by fixed scan overhead rather than diff size — a 3-line diff and a 94-line diff cost within 0.5% of each other. The practical consequence is that cost scales with number of scans, not with how much code changed, so every failed finalization is a full-price loss regardless of how small the change was.

Note on --output-dir. Setting it changes which validation fires first: the failure moves from snapshotDigest to coverage.mode: must match selected scan mode branch_diff. The generated coverage.json carries "mode": "diff" while expectedCoverageMode() in dist/contract.js returns "branch_diff" for target.kind === "refs". Patching snapshotDigest alone is therefore not sufficient — this matches the analysis above, and both need to land together.

The findings themselves were sound. Reading findings.json out of the retained artifact directory showed 15 findings with no false positives, complete with remediation guidance, suggested tests and preventive controls, plus severity calibrated on reachability rather than pattern presence. The analysis quality is not in question here; only the ability to retrieve it through a supported path is.

This makes the fourth request above — documenting whether retained artifacts can be finalized through a supported recovery command without repeating paid analysis — the single highest-value item for anyone evaluating this for CI. Every finalization failure today means paying again from scratch to retry.

Supporting the request to reopen until the published headless committed-range path is verified end to end, without --mock supplying the digest.

yuyu04 avatar Sep 15 '26 22:09 yuyu04