Files
codex-security/plugins/codex-security/scripts/threat_model_projection.py
5d65d253f7 fix(diagnostics): preserve saved-scan errors and recovery advice (#1266)
* fix(cli): preserve diagnostic context and saved-scan contracts

* fix(cli): escape publication diagnostic terminal controls

* test(cli): return canonical scan IDs from recipe fixtures

* fix(cli): preserve local failure classification through causes

* test: expect requested finding page sizes

* fix(diagnostics): preserve typed failures and report lookup errors once

* Preserve explicit cybersecurity policy refusal handling

* fix(cli): escape C1 controls in launcher failures

* fix: escape C1 controls in CLI failure diagnostics

* fix: recognize explicit nominal policy refusals

* fix(cli): retain quota advice and escape configuration diagnostics

* fix(cli): retain quota advice and format config failures

* fix(diagnostics): escape config errors and return accepted finding pages

* fix(diagnostics): escape component planning config errors

* fix(cli): format export failure diagnostics

* test(plugin): scope safe-path helper checks to Python 3.11+

* test(plugin): exercise isolated helper imports on Python 3.10

* fix(cli): retain explicit model permission advice

* test(cli): cover public export diagnostic controls

* fix(cli): retain recovery advice and Git failure status

* Recognize explicit policy refusals across response wording

* Keep source-access errors distinct from explicit policy refusals

* fix: retain explicit model and policy failure advice

* Recognize explicit policy-first review refusals

* Recognize explicit causal policy refusal responses

* fix(cli): preserve saved scan output modes

* fix(cli): retain expired token recovery advice

* Reuse executable fixture cleanup after Node launches

* fix: distinguish blocked artifact uploads from review refusals

* fix: preserve Git errors and distinguish operational refusals

* fix(review): distinguish publication failures from policy refusals

* test: use shared RPC request helper for diagnostic regression

* test: adapt ranking diagnostics to shared repository CLI fixture

* fix(cli): retain advice for token expiry code variants

* fix(review): recognize explicit policy accordance refusals

* fix(cli): preserve advice for canonical diagnostic codes

* fix: preserve operational failures and escape terminal controls

* fix(cli): require status context for numeric failure advice

* fix(cli): retain quoted status and terse refusal handling

* fix(cli): retain explicit HTTP code diagnostic advice

* Fix Windows direct Deep package fixture spawning

* fix: preserve explicit colon-form review refusals

* fix(contract): preserve exact checked file identities

* fix: recognize descriptive content refusal reasons

* fix: classify explicit policy refusals independently of reasons

* fix(cli): recognize separated response-code statuses

* fix: preserve structured review transport failures

* fix(diagnostics): keep operational policy failures distinct

* fix(cli): retain advice for named model failures

* fix(cli): keep local timeout diagnostics distinct

* fix: mark canceled patch review output as unsuccessful

* fix(cli): retain advice for response status fields

* fix(cli): keep local model errors free of credential advice

* fix(cli): retain saved results in full YAML and TOON failures

* test: forward directory probe arguments

* test(cli): use the existing artifact export import

* test(sdk): assert native scan artifact diagnostics

* ci: retry managed Code Quality after GitHub installation rate limit

* Keep local diagnostics distinct and surface inaccessible issue history

* Remove duplicate coordinator test import inherited from main

* Retain the SQLite diagnostic alongside the typed inspection exit

* Verify the printable path escaping used by export errors

* Classify long skill diagnostics without rescanning each suffix

* Preserve message structure when masking qualified model names

* Preserve backticks around provider-qualified model names

---------

Co-authored-by: Codex <codex@users.noreply.github.com>
Co-authored-by: mldangelo-oai <269034524+mldangelo-oai@users.noreply.github.com>
2026-11-04 17:22:45 -08:00

158 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""Render saved structured or Markdown threat models without running analysis."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
# Keep sibling helpers importable when Python starts in isolated mode.
sys.path.insert(0, str(Path(__file__).resolve().parent))
import report_projection as report
def _is_structured_model(model: dict[str, Any]) -> bool:
summary = model.get("summary")
return (
isinstance(summary, str)
and bool(summary)
and all(
isinstance(values := model.get(key, []), list)
and all(isinstance(value, str) and value for value in values)
for _, key in report.THREAT_MODEL_SECTIONS
)
)
def threat_model_body(model: dict[str, Any]) -> str:
"""Return the authored Markdown body verbatim or render a legacy summary and its sections.
Raises:
ValueError: Required content is absent or the saved model has invalid metadata or sections.
"""
content = report.markdown_threat_model_content(model)
if content is not None:
# The structured schema permits legacy metadata as extension fields.
if _is_structured_model(model):
return content
if "origin" in model and model["origin"] not in (
"generated",
"provided",
"reconciled",
"recovered",
):
raise ValueError("threatModel.origin: unsupported value")
if "scope" in model:
scope = model["scope"]
if not isinstance(scope, dict) or "includePaths" not in scope:
raise ValueError("threatModel.scope: expected an object with includePaths")
for key in ("includePaths", "excludePaths"):
if key in scope and (
not isinstance(scope[key], list)
or not all(isinstance(path, str) and path for path in scope[key])
):
raise ValueError(
f"threatModel.scope.{key}: expected an array of non-empty strings"
)
if "summary" in scope and (
not isinstance(scope["summary"], str) or not scope["summary"]
):
raise ValueError("threatModel.scope.summary: expected a non-empty string")
return content
summary = model.get("summary")
if not isinstance(summary, str) or not summary:
if model.get("format") == "markdown":
raise ValueError("threatModel.content: expected non-empty Markdown")
raise ValueError("threatModel.summary: expected a non-empty string")
sections = [
summary if summary.strip() else "No explicit canonical threat-model summary was recorded."
]
for heading, key in report.THREAT_MODEL_SECTIONS:
values = model.get(key, [])
if not isinstance(values, list):
raise ValueError(f"threatModel.{key}: expected an array")
if not values:
continue
for index, value in enumerate(values):
if not isinstance(value, str) or not value:
raise ValueError(f"threatModel.{key}[{index}]: expected a non-empty string")
sections.append(f"## {heading}")
sections.append("\n".join("- " + value.replace("\n", "\n ") for value in values))
return "\n\n".join(sections)
def _scope_lines(scope: Any, label: str) -> list[str]:
# Older structured models may use these extension names for unrelated data.
included = scope.get("includePaths") if isinstance(scope, dict) else None
if not isinstance(included, list) or not all(isinstance(path, str) for path in included):
return [f"- {label}: not recorded"]
included_text = ", ".join(report._path_text(path, ensure_ascii=True) for path in included)
lines = [f"- {label}: {included_text or 'none'}"]
excluded = scope.get("excludePaths")
if isinstance(excluded, list) and excluded and all(isinstance(path, str) for path in excluded):
excluded_text = ", ".join(report._path_text(path, ensure_ascii=True) for path in excluded)
lines.append(f"- {label} exclusions: {excluded_text or 'none'}")
summary = scope.get("summary")
if isinstance(summary, str) and summary:
lines.append(f"- {label} description: {report._text(summary, 'not recorded')}")
return lines
def render_threat_model(model: dict[str, Any], provenance: dict[str, Any] | None = None) -> bytes:
"""Return the saved threat model as UTF-8 Markdown, including its provenance footer.
Args:
model (dict): Authored Markdown or a legacy structured model from a scan.
provenance (dict | None): Optional saved scan identifiers, scope, and provisional status.
"""
body = threat_model_body(model)
if report.markdown_threat_model_content(model) is None:
body = "# Threat Model\n\n" + body
text = report._text
provenance = provenance or {}
footer = ["---", "", "## Saved Model Context", ""]
for key, label in (
("source", "Source"),
("scanId", "Scan"),
("target", "Target"),
("revision", "Revision"),
("snapshotDigest", "Snapshot"),
("status", "Result status"),
):
if provenance.get(key):
footer.append(f"- {label}: {text(str(provenance[key]), 'not recorded')}")
footer.append(f"- Model origin: {text(model.get('origin'), 'not recorded')}")
footer.extend(_scope_lines(model.get("scope"), "Model scope"))
scan_scope = provenance.get("scanScope")
if isinstance(scan_scope, dict):
footer.extend(_scope_lines(scan_scope, "Scan scope"))
if provenance.get("provisional"):
footer.extend(["", "This is a provisional model saved before successful completion."])
return (body + ("\n" if body.endswith("\n") else "\n\n") + "\n".join(footer) + "\n").encode(
"utf-8"
)
def main() -> int:
"""Render a JSON payload from stdin to UTF-8 Markdown on stdout and return zero on success."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input-json-stdin", action="store_true", required=True)
parser.parse_args()
try:
payload = json.load(sys.stdin)
if not isinstance(payload["threatModel"], dict):
raise ValueError("threatModel must be an object")
sys.stdout.buffer.write(
render_threat_model(payload["threatModel"], payload.get("provenance"))
)
except (KeyError, TypeError, ValueError) as exc:
parser.error(str(exc))
return 0
if __name__ == "__main__":
raise SystemExit(main())