Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

feat: add ServiceNow AVIT CSV export (#2103)

ianw-oai6625739ef81b
diff --git a/README.md b/README.md
index e13c6155a..0778fd269 100644
--- a/README.md
+++ b/README.md
@@ -188,7 +188,8 @@ cs export --scan SCAN_ID --artifact threat-model --output threatmodel.md
Omit `--scan` to use the current repository's latest completed scan. The
[export guide](sdk/typescript/docs/cli.md#exports-and-ci) also covers findings,
-SARIF output for CI, and the offline TypeScript API.
+SARIF output for CI, and the offline TypeScript API. For ServiceNow Application
+Vulnerability Response, see [Export findings for ServiceNow](sdk/typescript/docs/cli.md#export-findings-for-servicenow).
## GitHub Actions
diff --git a/examples/servicenow-avit-template.csv b/examples/servicenow-avit-template.csv
new file mode 100644
index 000000000..2abd1fad1
--- /dev/null
+++ b/examples/servicenow-avit-template.csv
@@ -0,0 +1,2 @@
+Risk rating,Requested by,CWE category,Vulnerability ID,Application,Purpose of application,Types of sensitive data,List of compliance programs,Technology stack details,Application team,URLs to test,Steps to reproduce,Technical details,Assigned to,Assignment group
+,Example Requester,,,Invoice Desk,Generates invoices,Billing records,None,Node.js,Billing Engineering,https://invoice.example.test,,,Example Tester,Application Security
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.json
index 1c434c25a..e34af7d86 100644
--- a/plugins/codex-security/plugin-files.json
+++ b/plugins/codex-security/plugin-files.json
@@ -73,6 +73,7 @@
"scripts/report_projection.py",
"scripts/review_state.py",
"scripts/reserved_artifact_paths.json",
+ "scripts/servicenow_avit.py",
"scripts/snapshot_sqlite.py",
"scripts/threat_model_projection.py",
"scripts/validate_scan_contract.py",
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.py
index 05ea0df9f..98efc61d6 100644
--- a/plugins/codex-security/scripts/finalize_scan_contract.py
+++ b/plugins/codex-security/scripts/finalize_scan_contract.py
@@ -26,6 +26,7 @@ from urllib.parse import quote, urlsplit
# Keep sibling helpers importable when Python starts in isolated mode.
sys.path.insert(0, str(Path(__file__).resolve().parent))
import report_projection
+import servicenow_avit
import threat_model_projection
from review_state import checkpoint_review_state, review_state, review_summary
@@ -78,6 +79,7 @@ SOURCE_READ_CHUNK_SIZE = 64 * 1024
MAX_JSON_INTEGER = (1 << 53) - 1
EXPORT_PATHS = {
"csv": "exports/findings.csv",
+ "servicenow-avit": "exports/servicenow-avit.csv",
"json": "exports/findings.json",
"sarif": "exports/results.sarif",
}
@@ -2977,11 +2979,21 @@ def build_csv_projection(findings: dict[str, Any], coverage: dict[str, Any]) ->
return output.getvalue().encode("utf-8")
+def _avit_fields(finding: dict[str, Any]) -> dict[str, str]:
+ attack_path = dict(finding.get("attackPath") or {})
+ _normalize_legacy_string_list_fields(attack_path, ("steps",))
+ steps = "\n".join(attack_path.get("steps", []))
+ return servicenow_avit.finding_fields(
+ finding, _sarif_primary_location(finding), csv_cell(steps)
+ )
+
+
def build_findings_export(
scan_dir: Path,
export_format: str,
source_root: Path | None = None,
schema_dir: Path | None = None,
+ avit_template: Path | None = None,
) -> bytes:
if export_format not in EXPORT_PATHS:
raise ContractError(f"unsupported export format: {export_format}")
@@ -2994,6 +3006,13 @@ def build_findings_export(
)
if export_format == "json":
return findings_bytes
+ if export_format == "servicenow-avit":
+ if avit_template is None:
+ raise ContractError("--export-format servicenow-avit requires --avit-template")
+ try:
+ return servicenow_avit.render(avit_template, map(_avit_fields, findings["findings"]))
+ except ValueError as exc:
+ raise ContractError(str(exc)) from exc
return build_csv_projection(findings, coverage)
@@ -3407,6 +3426,7 @@ def main() -> int:
"--export-artifact", choices=("findings", "threat-model"), default="findings"
)
parser.add_argument("--export-format", choices=[*sorted(EXPORT_PATHS), "md"])
+ parser.add_argument("--avit-template", type=Path)
parser.add_argument("--export-output", type=Path)
parser.add_argument("--export-metadata", action="store_true")
parser.add_argument("--describe-threat-model", action="store_true")
@@ -3414,6 +3434,18 @@ def main() -> int:
args = parser.parse_args()
try:
args.scan_dir = args.scan_dir.resolve()
+ if args.avit_template is not None:
+ if args.export_format != "servicenow-avit":
+ parser.error(
+ "--avit-template is only supported with --export-format servicenow-avit"
+ )
+ if (
+ args.export_output
+ and args.export_output.exists()
+ and args.avit_template.exists()
+ and args.export_output.samefile(args.avit_template)
+ ):
+ parser.error("AVIT export output cannot overwrite the reusable template")
if args.describe_threat_model:
sys.stdout.buffer.write(
_json_bytes(describe_threat_model(args.scan_dir, args.schema_dir))
@@ -3448,7 +3480,11 @@ def main() -> int:
description, contents = saved
else:
contents = build_findings_export(
- args.scan_dir, args.export_format, args.source_root, args.schema_dir
+ args.scan_dir,
+ args.export_format,
+ args.source_root,
+ args.schema_dir,
+ avit_template=args.avit_template,
)
if args.export_output is None:
sys.stdout.buffer.write(contents)
diff --git a/plugins/codex-security/scripts/servicenow_avit.py b/plugins/codex-security/scripts/servicenow_avit.py
new file mode 100644
index 000000000..3e9710926
--- /dev/null
+++ b/plugins/codex-security/scripts/servicenow_avit.py
@@ -0,0 +1,107 @@
+"""ServiceNow Manual AVIT Ingestion CSV template and finding fields."""
+
+from __future__ import annotations
+
+import csv
+import io
+import re
+import sys
+from collections.abc import Iterable
+from pathlib import Path
+from typing import Any
+
+AVIT_APP_FIELDS = {
+ "Application": 255,
+ "Requested by": 151,
+ "Purpose of application": 4000,
+ "Types of sensitive data": 40,
+ "List of compliance programs": 4000,
+ "Technology stack details": 4000,
+ "Application team": 100,
+ "URLs to test": 4000,
+ "Assigned to": 151,
+ "Assignment group": 151,
+}
+AVIT_FINDING_FIELDS = (
+ "Risk rating",
+ "CWE category",
+ "Vulnerability ID",
+ "Steps to reproduce",
+ "Technical details",
+)
+
+
+def read_template(path: Path) -> tuple[list[str], dict[str, str]]:
+ try:
+ with path.open(encoding="utf-8-sig", newline="") as source:
+ rows = (row for row in csv.reader(source, strict=True) if row)
+ headers = next(rows, [])
+ values = next(rows, [])
+ if len(headers) != len(values) or next(rows, None) is not None:
+ raise ValueError("AVIT template must have a header and one application row")
+ except (OSError, UnicodeError, csv.Error) as exc:
+ raise ValueError(f"Could not read AVIT template {path}: {exc}") from exc
+
+ row = {header.strip().casefold(): value for header, value in zip(headers, values, strict=True)}
+ if len(row) != len(headers):
+ raise ValueError("AVIT template has duplicate column names")
+ for field in (*AVIT_APP_FIELDS, *AVIT_FINDING_FIELDS):
+ if field.casefold() not in row:
+ raise ValueError(f"AVIT template is missing column {field!r}")
+ for field, limit in AVIT_APP_FIELDS.items():
+ value = row[field.casefold()]
+ if not value.strip() or len(value) > limit:
+ raise ValueError(
+ f"AVIT template {field!r} requires a value of at most {limit} characters"
+ )
+ return headers, row
+
+
+def _narrative(text: str) -> str:
+ return text if len(text) <= 1000 else text[:997] + "..."
+
+
+def finding_fields(finding: dict[str, Any], location: dict[str, Any], steps: str) -> dict[str, str]:
+ details = (
+ f"{finding['findingId']} | {location['path']}:{location['startLine']}\n"
+ f"{finding['title']}\n{finding['summary']}\n{finding['remediation']}"
+ )
+ cwe = next(
+ (
+ value.upper()
+ for value in finding["taxonomy"]["cwe"]
+ if len(value) <= 255 and re.fullmatch(r"CWE-[0-9]+", value, re.I)
+ ),
+ "",
+ )
+ level = finding["severity"]["level"]
+ return {
+ "Risk rating": "None" if level == "informational" else level.title(),
+ "CWE category": cwe,
+ "Vulnerability ID": "" if cwe else finding["findingId"],
+ "Steps to reproduce": _narrative(steps),
+ "Technical details": _narrative(details),
+ }
+
+
+def render(template: Path, rows: Iterable[dict[str, str]]) -> bytes:
+ headers, row = read_template(template)
+ output = io.StringIO(newline="")
+ writer = csv.writer(output)
+ writer.writerow(headers)
+ missing_steps = 0
+ has_findings = False
+ for fields in rows:
+ has_findings = True
+ if not fields["Steps to reproduce"]:
+ missing_steps += 1
+ for field, value in fields.items():
+ row[field.casefold()] = value
+ writer.writerow(row.values())
+ if has_findings:
+ print(
+ "Review Steps to reproduce before uploading. Populated steps describe the recorded "
+ f"attack path. Rows with no recorded steps: {missing_steps}.",
+ file=sys.stderr,
+ )
+ return output.getvalue().encode("utf-8")
diff --git a/plugins/codex-security/tests/test_finalize_scan_contract.py b/plugins/codex-security/tests/test_finalize_scan_contract.py
index f4584e2bf..98fccb592 100644
--- a/plugins/codex-security/tests/test_finalize_scan_contract.py
+++ b/plugins/codex-security/tests/test_finalize_scan_contract.py
@@ -172,6 +172,56 @@ class FinalizeScanContractTest(FinalizerSarifCases, ScanFixtureTestCase):
contents = FINALIZER.build_csv_projection({"findings": [finding]}, self.coverage)
return csv.DictReader(io.StringIO(contents.decode("utf-8"), newline=""))
+ def test_avit_reuses_template_columns_and_maps_findings_individually(self) -> None:
+ template = self.scan_dir.parent / "app.csv"
+ headers = [
+ *FINALIZER.servicenow_avit.AVIT_APP_FIELDS,
+ *(name.upper() for name in FINALIZER.servicenow_avit.AVIT_FINDING_FIELDS),
+ "Release",
+ ]
+ defaults = dict.fromkeys(FINALIZER.servicenow_avit.AVIT_APP_FIELDS, "Example")
+ defaults.update({"Release": "v1, beta", "Application": "Billing", "CWE CATEGORY": "stale"})
+ with template.open("w", encoding="utf-8-sig", newline="") as file:
+ writer = csv.DictWriter(file, fieldnames=headers)
+ writer.writeheader()
+ writer.writerow(defaults)
+ first = self.findings["findings"][0]
+ first["taxonomy"]["cwe"] = ["=bad", "CWE-" + "9" * 252, "cwe-22"]
+ self.findings["findings"].append(
+ {
+ **first,
+ "identity": {**first["identity"], "instance": "second"},
+ "taxonomy": {**first["taxonomy"], "cwe": []},
+ "severity": {**first["severity"], "level": "informational"},
+ "summary": "x" * 1200,
+ "attackPath": {"steps": ["=Read the cell", "Inspect the result."]},
+ }
+ )
+ _, findings, _ = self.write_sealed_scan()
+ contents = FINALIZER.build_findings_export(
+ self.scan_dir, "servicenow-avit", avit_template=template
+ )
+ reader = csv.DictReader(io.StringIO(contents.decode(), newline=""))
+ self.assertEqual(reader.fieldnames, headers)
+ a, b = reader
+ self.assertEqual(a["STEPS TO REPRODUCE"], "")
+ self.assertEqual((a["CWE CATEGORY"], a["VULNERABILITY ID"]), ("CWE-22", ""))
+ self.assertEqual(
+ (b["CWE CATEGORY"], b["VULNERABILITY ID"]), ("", findings["findings"][1]["findingId"])
+ )
+ self.assertEqual(b["RISK RATING"], "None")
+ self.assertEqual(b["STEPS TO REPRODUCE"], "'=Read the cell\nInspect the result.")
+ self.assertEqual(len(b["TECHNICAL DETAILS"]), 1000)
+ for row in (a, b):
+ self.assertEqual((row["Application"], row["Release"]), ("Billing", "v1, beta"))
+
+ with template.open("a", encoding="utf-8", newline="") as file:
+ csv.writer(file).writerow(["unexpected second row"])
+ with self.assertRaisesRegex(FINALIZER.ContractError, "one application row"):
+ FINALIZER.build_findings_export(
+ self.scan_dir, "servicenow-avit", avit_template=template
+ )
+
def write_sealed_receipt_scan(self, receipt_ref: str) -> Path:
self.coverage["surfaces"][0]["receiptRefs"] = [receipt_ref]
self.write_scan()
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index a6ccbc2f0..d64f87140 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -2281,6 +2281,33 @@ be unchanged since the scan. `--source-root` is supported only for SARIF.
If export fails, it exits with `2`. Fix the reported error and rerun the export;
the saved scan remains available, so you don't need to run another scan.
+### Export findings for ServiceNow
+
+Use `servicenow-avit` to prepare a CSV for ServiceNow Application Vulnerability
+Response. In ServiceNow, open **All > Manual AVIT Ingestion > Upload File UI**
+and download the CSV template. Keep the headers and a single row per template
+file. Fill in the exact ServiceNow application name, requester, assignee, and
+assignment group. Supply the application team, purpose, sensitive data types,
+compliance programs, technology stack, and URLs to test. Leave the finding
+columns blank and reuse this file for future exports of the same application. See the
+[example template](https://github.com/openai/codex-security/blob/main/examples/servicenow-avit-template.csv).
+
+```bash
+codex-security export --scan latest --export-format servicenow-avit \
+ --avit-template invoice-desk.csv --output findings-avit.csv
+```
+
+The command writes one row per saved finding. It fills the risk rating and uses
+the first CWE when available, otherwise the Codex finding ID. Technical details
+include that ID, the primary file and line, the summary, and remediation. For
+**Steps to reproduce**, review any recorded attack-path steps and complete blank
+cells before uploading. Both text fields have a 1,000-character limit. An ellipsis
+marks shortened text. Other template columns keep their original values.
+
+The output defaults to `servicenow-avit.csv`. Upload the completed file in the
+same ServiceNow screen. Each upload creates a new penetration-test form for the
+application. See [ServiceNow's upload instructions](https://www.servicenow.com/docs/r/security-management/application-vulnerability-response/ingest-vulnerabilities-manually-avr.html).
+
### Export a threat model
To save a scan's threat model as Markdown, run:
@@ -2323,6 +2350,8 @@ console.log(exported.path, exported.provenance);
```
Use `artifact: "findings"` with `format: "csv" | "json" | "sarif"` for findings.
+For ServiceNow, use `format: "servicenow-avit"` and set `avitTemplate` to the
+path of the application's populated CSV template.
`output: "-"` streams stdout and returns null path/provenance. `pythonPath`
selects an interpreter; `signal` cancels.
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index 4b9faecd2..b0543bab0 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -7,6 +7,7 @@ import { Writable as NodeWritable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { promisify } from "node:util";
import type { JsonObject } from "./config.js";
+import { resolveConfigPath } from "./config-path.js";
import { CodexSecurityError } from "./errors.js";
import { relativePathIsOutside as isOutsidePath } from "./targets.js";
import {
@@ -26,6 +27,7 @@ export type ArtifactOutput = Pick<NodeJS.WriteStream, "write">;
export const ARTIFACT_EXPORT_FILENAMES = {
csv: "findings.csv",
+ "servicenow-avit": "servicenow-avit.csv",
json: "findings.json",
sarif: "results.sarif",
md: "threatmodel.md",
@@ -39,6 +41,7 @@ export interface ArtifactExportArguments {
format: ExportFormat;
output: string;
sourceRoot?: string;
+ avitTemplate?: string;
pythonPath?: string;
signal?: AbortSignal;
includeMetadata?: boolean;
@@ -52,11 +55,23 @@ export type ExportArtifactOptions = {
pythonPath?: string;
signal?: AbortSignal;
} & (
- | { artifact: "threat-model"; format?: "md"; sourceRoot?: never }
+ | {
+ artifact: "threat-model";
+ format?: "md";
+ sourceRoot?: never;
+ avitTemplate?: never;
+ }
| {
artifact?: "findings";
format?: "csv" | "json" | "sarif";
sourceRoot?: string;
+ avitTemplate?: never;
+ }
+ | {
+ artifact?: "findings";
+ format: "servicenow-avit";
+ avitTemplate: string;
+ sourceRoot?: never;
}
);
@@ -77,13 +92,24 @@ interface HelperOptions {
export function resolveArtifactFormat(
artifact: ExportArtifactKind,
format?: ExportFormat,
+ avitTemplate?: string,
): ExportFormat {
const selected = format ?? (artifact === "threat-model" ? "md" : "sarif");
if ((artifact === "threat-model") !== (selected === "md")) {
throw new CodexSecurityError(
artifact === "threat-model"
? "Threat-model exports only support --export-format md."
- : "Findings exports support --export-format csv, json, or sarif.",
+ : "Findings exports support --export-format csv, json, sarif, or servicenow-avit.",
+ );
+ }
+ if (selected === "servicenow-avit" && !avitTemplate) {
+ throw new CodexSecurityError(
+ "--export-format servicenow-avit requires --avit-template.",
+ );
+ }
+ if (selected !== "servicenow-avit" && avitTemplate !== undefined) {
+ throw new CodexSecurityError(
+ "--avit-template is only supported with --export-format servicenow-avit.",
);
}
return selected;
@@ -190,9 +216,10 @@ export async function readThreatModelPath(
export async function runArtifactExport(
arguments_: ArtifactExportArguments,
output?: ArtifactOutput,
+ diagnostics: ArtifactOutput = process.stderr,
): Promise<string | undefined> {
const artifact = arguments_.artifact ?? "findings";
- resolveArtifactFormat(artifact, arguments_.format);
+ resolveArtifactFormat(artifact, arguments_.format, arguments_.avitTemplate);
const result = await runArtifactHelper(
[
"--scan-dir",
@@ -200,6 +227,9 @@ export async function runArtifactExport(
...(artifact === "findings" ? [] : ["--export-artifact", artifact]),
"--export-format",
arguments_.format,
+ ...(arguments_.avitTemplate === undefined
+ ? []
+ : ["--avit-template", arguments_.avitTemplate]),
...(arguments_.output === "-"
? []
: ["--export-output", arguments_.output]),
@@ -222,6 +252,9 @@ export async function runArtifactExport(
...(arguments_.output === "-" && output !== undefined ? { output } : {}),
},
);
+ if (arguments_.format === "servicenow-avit" && result.stderr) {
+ diagnostics.write(result.stderr);
+ }
return (arguments_.output === "-" && output === undefined) ||
arguments_.includeMetadata
? result.stdout
@@ -315,14 +348,20 @@ export async function resolveArtifactExportOutput(
break;
}
}
- return { ...arguments_, scanDir: canonicalScan, output: outputPath };
+ return {
+ ...arguments_,
+ scanDir: canonicalScan,
+ output: outputPath,
+ avitTemplate:
+ arguments_.avitTemplate &&
+ resolveConfigPath(currentDirectory, arguments_.avitTemplate),
+ };
}
/** Resolve saved artifacts after the workbench validates their recorded identity. */
export async function resolveSavedArtifactDirectory(
scanId: string,
artifact: ExportArtifactKind,
- format: ExportFormat,
workbench: (args: readonly string[]) => Promise<JsonObject>,
): Promise<string> {
// Reuse the workbench's recorded digest and scan binding checks without
@@ -331,7 +370,6 @@ export async function resolveSavedArtifactDirectory(
workbenchArgs("export-findings", {
scanId,
artifact,
- format,
validateOnly: true,
}),
);
@@ -348,7 +386,11 @@ export async function exportArtifact(
options: ExportArtifactOptions,
): Promise<ArtifactExportResult> {
const artifact = options.artifact ?? "findings";
- const format = resolveArtifactFormat(artifact, options.format);
+ const format = resolveArtifactFormat(
+ artifact,
+ options.format,
+ options.avitTemplate,
+ );
const sourceRoot =
options.sourceRoot === undefined
? undefined
@@ -372,7 +414,6 @@ export async function exportArtifact(
directory = await resolveSavedArtifactDirectory(
options.source.scanId,
artifact,
- format,
(args) =>
runWorkbench(
{
@@ -396,7 +437,8 @@ export async function exportArtifact(
pythonPath: options.pythonPath,
signal: options.signal,
includeMetadata: artifact === "threat-model" && options.output !== "-",
- ...(sourceRoot === undefined ? {} : { sourceRoot }),
+ avitTemplate: options.avitTemplate,
+ sourceRoot,
},
process.cwd(),
);
diff --git a/sdk/typescript/src/cli-help.ts b/sdk/typescript/src/cli-help.ts
index 6893c532a..33ccf4ebf 100644
--- a/sdk/typescript/src/cli-help.ts
+++ b/sdk/typescript/src/cli-help.ts
@@ -83,6 +83,7 @@ const VALUE_LABELS: Record<string, string> = {
"scan-dir": "path",
"plugin-path": "path",
"source-root": "path",
+ "avit-template": "file",
python: "path",
codex: "key=value",
"max-cost": "usd",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 84e89545a..37db9ad43 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -1264,6 +1264,7 @@ interface CliDependencies {
exportFindings(
arguments_: ArtifactExportArguments,
output?: Writable,
+ diagnostics?: Writable,
): Promise<string | Uint8Array | undefined>;
runCodex(
args: readonly string[],
@@ -5545,18 +5546,23 @@ export async function main(
scan: optionValue("--scan")
.optional()
.describe(
- "Saved scan ID or unique prefix; cannot be combined with a result directory.",
+ "Saved scan ID, unique prefix, or latest completed scan ('latest').",
),
exportFormat: z
- .enum(["csv", "json", "sarif", "md"])
+ .enum(["csv", "json", "sarif", "md", "servicenow-avit"])
.optional()
.describe(
- "Findings: csv, json, or sarif (default); threat-model: md (default).",
+ "Findings: csv, json, servicenow-avit, or sarif (default). Threat models use md.",
+ ),
+ avitTemplate: optionValue("--avit-template")
+ .optional()
+ .describe(
+ "Per-application CSV template required for servicenow-avit exports.",
),
output: optionValue("--output")
.optional()
.describe(
- "FILE or '-' for stdout (default: results.sarif, findings.json, findings.csv, or threatmodel.md).",
+ "FILE or '-' for stdout (default: results.sarif, findings.json, findings.csv, servicenow-avit.csv, or threatmodel.md).",
),
sourceRoot: optionValue("--source-root")
.optional()
@@ -5590,6 +5596,7 @@ export async function main(
const format = resolveArtifactFormat(
options.artifact,
options.exportFormat,
+ options.avitTemplate,
);
const sourceRoot =
options.sourceRoot === undefined
@@ -5601,16 +5608,20 @@ export async function main(
: [currentDirectory, sourceRoot];
let scanDir = args.scanDir;
if (scanDir === undefined) {
- const scanId =
- options.scan ??
- (
- await latestScans(1, "complete", options.python, protectedRoot)
- )?.[0]?.scanId;
+ let scanId = options.scan;
+ if (!scanId || scanId === "latest") {
+ const scans = await latestScans(
+ 1,
+ "complete",
+ options.python,
+ protectedRoot,
+ );
+ scanId = scans?.[0]?.scanId;
+ }
if (scanId === undefined) return;
scanDir = await resolveSavedArtifactDirectory(
scanId,
options.artifact,
- format,
(args) =>
dependencies.runWorkbench(
args,
@@ -5621,33 +5632,34 @@ export async function main(
),
);
}
- const arguments_: ArtifactExportArguments = {
- scanDir: resolveCliPath(currentDirectory, scanDir),
- artifact: options.artifact,
- format,
- output:
- options.output === "-"
- ? "-"
- : resolveCliPath(
- currentDirectory,
- options.output ?? EXPORT_DEFAULT_OUTPUTS[format],
- ),
- sourceRoot,
- pythonPath: options.python,
- };
+ const destination = options.output ?? EXPORT_DEFAULT_OUTPUTS[format];
+ const outputPath =
+ destination === "-"
+ ? "-"
+ : resolveCliPath(currentDirectory, destination);
const prepared = await resolveArtifactExportOutput(
- arguments_,
- dependencies.currentDirectory(),
+ {
+ scanDir: resolveCliPath(currentDirectory, scanDir),
+ artifact: options.artifact,
+ format,
+ output: outputPath,
+ sourceRoot,
+ avitTemplate: options.avitTemplate,
+ pythonPath: options.python,
+ },
+ currentDirectory,
+ );
+ const contents = await dependencies.exportFindings(
+ prepared,
+ output,
+ errorOutput,
);
- const contents = await dependencies.exportFindings(prepared, output);
- if (arguments_.output === "-") {
+ if (outputPath === "-") {
if (contents !== undefined) {
await writeCliOutput(output, Buffer.from(contents));
}
} else {
- errorOutput.write(
- `${arguments_.format.toUpperCase()}: ${arguments_.output}\n`,
- );
+ errorOutput.write(`${format.toUpperCase()}: ${outputPath}\n`);
}
exitCode = 0;
} catch (error) {
@@ -6726,41 +6738,30 @@ export async function main(
) {
return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
}
- if (
- command === "export" &&
- structuredOutput &&
- argv.some(
- (value, index) =>
- value === "--output=-" ||
- (value === "--output" && argv[index + 1] === "-"),
- ) &&
- argv.some(
- (value, index) =>
- value === "--export-format=csv" ||
- value === "--exportFormat=csv" ||
- ((value === "--export-format" || value === "--exportFormat") &&
- argv[index + 1] === "csv"),
- )
- ) {
- return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
- }
- if (
- command === "export" &&
- structuredOutput &&
- argv.some(
- (value, index) =>
- value === "--output=-" ||
- (value === "--output" && argv[index + 1] === "-"),
- ) &&
- argv.some(
- (value, index) =>
- value === "--artifact=threat-model" ||
- (value === "--artifact" && argv[index + 1] === "threat-model") ||
- value === "--export-format=md" ||
- (value === "--export-format" && argv[index + 1] === "md"),
- )
- ) {
- return "Markdown stdout cannot be combined with JSON output; write Markdown to a file or omit --json.";
+ if (command === "export" && structuredOutput) {
+ const hasValue = (flag: string, value: string) =>
+ argv.some(
+ (arg, index) =>
+ arg === `${flag}=${value}` ||
+ (arg === flag && argv[index + 1] === value),
+ );
+ if (hasValue("--output", "-")) {
+ if (
+ ["csv", "servicenow-avit"].some(
+ (format) =>
+ hasValue("--export-format", format) ||
+ hasValue("--exportFormat", format),
+ )
+ ) {
+ return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
+ }
+ if (
+ hasValue("--artifact", "threat-model") ||
+ hasValue("--export-format", "md")
+ ) {
+ return "Markdown stdout cannot be combined with JSON output; write Markdown to a file or omit --json.";
+ }
+ }
}
if (command === "scan" && !argv.includes("--schema")) {
if (
@@ -7745,7 +7746,6 @@ async function readSavedFindings(
const directory = await resolveSavedArtifactDirectory(
scanId,
"findings",
- "json",
workbench,
);
const { findings } = await loadContract(directory, {
diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.ts
index 9f0bddb9f..89168d99e 100644
--- a/sdk/typescript/tests-ts/cli-export.test.ts
+++ b/sdk/typescript/tests-ts/cli-export.test.ts
@@ -22,6 +22,7 @@ import { exportEnvironment, main } from "../src/cli.js";
import type { JsonObject } from "../src/config.js";
import {
CodexSecurityError,
+ exportArtifact,
type CoverageDocument,
type ScanManifest,
} from "../src/index.js";
@@ -188,6 +189,55 @@ describe("CLI", () => {
expect(exportedScanDir).toBe(scanDir);
});
+ test("exports the same AVIT rows through the CLI and SDK with a reusable template", async () => {
+ const directory = await temporaryDirectory("codex-security-avit-");
+ try {
+ const scan = await copyCompletedScan(directory);
+ const sample = await readFile(
+ new URL(
+ "../../../examples/servicenow-avit-template.csv",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const template = join(directory, "app template.csv");
+ await writeFile(template, sample);
+ const { runCli, stdout, stderr } = createCliTest(main);
+ expect(
+ await runCli(
+ [
+ "export",
+ scan,
+ "--export-format",
+ "servicenow-avit",
+ "--avit-template",
+ template,
+ "--output",
+ "-",
+ ],
+ undefined,
+ ),
+ ).toBe(0);
+ expect(stdout.text()).toContain("src/extract.py:41");
+ expect(stderr.text()).toContain("Rows with no recorded steps: 1");
+
+ const options = {
+ source: { directory: scan },
+ format: "servicenow-avit",
+ avitTemplate: template,
+ } as const;
+ const output = join(directory, "avit.csv");
+ await exportArtifact({ ...options, output });
+ expect(await readFile(output, "utf8")).toBe(stdout.text());
+ await expect(
+ exportArtifact({ ...options, output: template }),
+ ).rejects.toThrow("cannot overwrite the reusable template");
+ expect(await readFile(template, "utf8")).toBe(sample);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
test("reports default-source history failures once without running the exporter", async () => {
for (const lookupFails of [false, true]) {
const deps = dependencies({
@@ -277,7 +327,11 @@ describe("CLI", () => {
],
{ cwd: repository, env: environment, timeout: 30_000 },
);
- const selectors = [[], ["--scan", scanId.slice(0, 8)]];
+ const selectors = [
+ [],
+ ["--scan", "latest"],
+ ["--scan", scanId.slice(0, 8)],
+ ];
for (const selector of selectors) {
const result = await exportModel(...selector);
expect(result.stderr).toBe("");
@@ -390,8 +444,6 @@ describe("CLI", () => {
"scan-prov",
"--artifact",
"threat-model",
- "--format",
- "md",
"--validate-only",
],
]);
@@ -451,6 +503,25 @@ describe("CLI", () => {
"only support --export-format md",
],
[["saved", "--export-format", "md"], "Findings exports support"],
+ [
+ ["saved", "--export-format", "servicenow-avit"],
+ "requires --avit-template",
+ ],
+ [
+ ["saved", "--export-format", "csv", "--avit-template", "app.csv"],
+ "--avit-template is only supported",
+ ],
+ [
+ [
+ "saved",
+ "--export-format",
+ "servicenow-avit",
+ "--output",
+ "-",
+ "--json",
+ ],
+ "CSV stdout cannot",
+ ],
[
["saved", "--artifact", "threat-model", "--output", "-", "--json"],
"Markdown stdout cannot",
diff --git a/sdk/typescript/tests-ts/cli-help.test.ts b/sdk/typescript/tests-ts/cli-help.test.ts
index 12b96cbb9..6820d884f 100644
--- a/sdk/typescript/tests-ts/cli-help.test.ts
+++ b/sdk/typescript/tests-ts/cli-help.test.ts
@@ -191,6 +191,7 @@ describe("CLI help", () => {
expect(text).toContain("threatmodel.md");
expect(option(text, "--export-format")).toContain("<format>");
expect(option(text, "--export-format")).toContain("sarif");
+ expect(text).toContain("--avit-template <file>");
for (const flag of [
"--format",
"--json",
@@ -207,7 +208,9 @@ describe("CLI help", () => {
options: {
properties: {
artifact: { enum: ["findings", "threat-model"], default: "findings" },
- exportFormat: { enum: ["csv", "json", "sarif", "md"] },
+ exportFormat: {
+ enum: ["csv", "json", "sarif", "md", "servicenow-avit"],
+ },
},
},
});