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: import CSV and JSON findings as saved scans (#850)

Kyle Brown6ecb9db5180e
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 8dd2d2ba5..f12ab1062 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -439,6 +439,39 @@ Scans are report-only by default. Set `--fail-on-severity high` to exit with
`1` if a completed scan finds high or critical issues. Incomplete scans exit
with `2`, writing available results to stdout and a coverage warning to stderr.
+### Import findings as a saved scan
+
+Import an existing findings CSV or JSON file into local scan history and SQLite:
+
+```bash
+codex-security scan import --csv /path/to/findings.csv
+codex-security scan import --json /path/to/findings.json --format json
+codex-security scan import --csv /path/to/findings.csv --dry-run
+```
+
+Supply exactly one of `--csv PATH` or `--json PATH`. CSV uses the existing
+[findings CSV template](https://github.com/openai/codex-security/blob/main/examples/findings.csv),
+including the optional `candidate_id` column. JSON accepts a complete
+`codex-security.findings` document or `{ "findings": [...] }`, with each finding
+matching the existing findings schema. On `scan import`, `--json` selects the
+input file; use `--format json` for JSON output. Other commands retain their
+existing `--json` output flag. The selected input must be a regular file, and its
+path must not traverse symbolic links or directory junctions. Use the direct
+filesystem path when the file or a parent directory is linked.
+
+Each import creates one completed scan using the configured
+`CODEX_SECURITY_STATE_DIR`. The target is a retained copy of the input dataset,
+independent of the current repository. Every source occurrence remains a separate
+finding, including duplicate reports. Original identifiers are preserved in
+`extensions.import`; the original file is sealed under `artifacts/import/`.
+JSON writeup paths are retained as source metadata without reading external files.
+
+Completion means the import finished. Coverage is unknown and the report states
+that no security analysis was performed. Importing requires no model calls or
+authentication. `--dry-run` validates without saving a scan. `--output-dir` and
+`--archive-existing` control saved output, and `scans rerun SCAN_ID` reimports the
+retained input.
+
### Generate mock scan results
Use `--mock` to populate a Standard scan with synthetic test data in seconds,
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index aa7e97993..7cb1eb76d 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -185,8 +185,10 @@ const distFiles = new Set(
"deep-progress",
"errors",
"finding-catalogue",
+ "findings-import",
"github",
"index",
+ "import-scan",
"knowledge-base",
"linear",
"models",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 8e73e9c2a..5aaea2107 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -138,6 +138,7 @@ import {
type PublishScanResult,
} from "./publish.js";
import type { ScanResult } from "./result.js";
+import { importScan, type ImportScanOptions } from "./import-scan.js";
import {
bundledPluginRoot,
canonicalizeModelSafePath,
@@ -1194,6 +1195,7 @@ interface CliDependencies {
planComponents?: typeof planComponents;
linearClient?: LinearClientFactory;
importGitHubAlerts?: typeof importGitHubCodeScanningAlerts;
+ importScan?: typeof importScan;
runWorkbench(
args: readonly string[],
input?: string,
@@ -1602,7 +1604,7 @@ export async function main(
errorOutput: Writable = process.stderr,
dependencies: CliDependencies = DEFAULT_DEPENDENCIES,
): Promise<number> {
- argv = defaultListCommand(argv);
+ argv = normalizeScanImportArguments(defaultListCommand(argv));
const policyFullOutput =
argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
const positionals: string[] = [];
@@ -1638,6 +1640,8 @@ export async function main(
let renderedHistory: string | undefined;
let renderedPublication: string | undefined;
let renderedPolicy: string | undefined;
+ const runImport = (options: ImportScanOptions) =>
+ runScanImport(options, errorOutput, dependencies);
const history = async (
args: readonly string[],
select: (value: JsonObject) => JsonObject | Promise<JsonObject> = (value) =>
@@ -2049,6 +2053,44 @@ export async function main(
"--scan-id",
scanId,
]);
+ if (
+ recipe !== undefined &&
+ isJsonObject(recipe) &&
+ recipe["import"] !== undefined &&
+ isJsonObject(recipe["import"])
+ ) {
+ if (options.validationPromptFile !== undefined) {
+ throw new CodexSecurityError(
+ "--validation-prompt-file is not supported when rerunning an imported scan; imports do not perform security analysis.",
+ );
+ }
+ const imported = recipe["import"];
+ const sourcePath = imported["sourcePath"];
+ const format = imported["format"];
+ if (
+ typeof sourcePath !== "string" ||
+ sourcePath.length === 0 ||
+ (format !== "csv" && format !== "json")
+ ) {
+ throw new CodexSecurityError(
+ "The saved scan recipe contains invalid import settings.",
+ );
+ }
+ const outcome = await runImport({
+ sourcePath,
+ format,
+ parentScanId: scanId,
+ });
+ exitCode = outcome.exitCode;
+ if (outcome.error !== undefined) {
+ return incurError({
+ code: "SCAN_IMPORT_FAILED",
+ message: outcome.error,
+ exitCode,
+ });
+ }
+ return outcome.data;
+ }
scanArguments = scanArgumentsFromRecipe(
recipe,
scanId,
@@ -3096,6 +3138,11 @@ export async function main(
})
.command("scan", {
description: "Run a Codex Security scan.",
+ hint:
+ "Import existing findings without security analysis:\n" +
+ " codex-security scan import --csv findings.csv\n" +
+ " codex-security scan import --json findings.json\n" +
+ "Use ./import to scan a repository named import.",
destructive: true,
mcp: false,
args: z.object({
@@ -4873,6 +4920,92 @@ export async function main(
},
});
+ // Incur cannot mount a command with both a handler and subcommands.
+ // Select the nested import route while preserving scan [repository].
+ if (isScanImportCommand(argv)) {
+ cli.command(
+ Cli.create("scan", {
+ description: "Run or import a saved scan.",
+ }).command("import", {
+ description:
+ "Save CSV or JSON findings as a completed scan without security analysis.",
+ destructive: true,
+ mcp: false,
+ options: z
+ .object({
+ csv: optionValue("--csv")
+ .optional()
+ .describe("Findings CSV in the codex-security export format."),
+ json: optionValue("--json")
+ .optional()
+ .describe(
+ "Findings JSON document or object with a findings array.",
+ ),
+ outputDir: optionValue("--output-dir")
+ .optional()
+ .describe(
+ "Artifact directory (default: Codex Security state; CODEX_SECURITY_STATE_DIR).",
+ ),
+ archiveExisting: z
+ .boolean()
+ .default(false)
+ .describe("Archive existing results; requires --output-dir."),
+ dryRun: z
+ .boolean()
+ .default(false)
+ .describe("Validate the input without saving a scan."),
+ })
+ .refine(
+ (options) =>
+ Number(options.csv !== undefined) +
+ Number(options.json !== undefined) ===
+ 1,
+ { message: "Provide exactly one of --csv FILE or --json FILE." },
+ )
+ .refine(
+ (options) =>
+ !options.archiveExisting || options.outputDir !== undefined,
+ { message: "--archive-existing requires --output-dir." },
+ ),
+ examples: [
+ { options: { csv: "findings.csv" } },
+ { options: { json: "findings.json" } },
+ ],
+ hint: "Each input row is retained, including duplicates. --json selects the input file; use --format json for JSON output.",
+ output: z.record(z.string(), z.unknown()).optional(),
+ async run({ options, format, error: incurError }) {
+ const directory = dependencies.currentDirectory();
+ const outcome = await runImport({
+ sourcePath: resolveCliPath(directory, options.csv ?? options.json!),
+ format: options.csv === undefined ? "json" : "csv",
+ outputDir:
+ options.outputDir === undefined
+ ? undefined
+ : resolveCliPath(directory, options.outputDir),
+ archiveExisting: options.archiveExisting,
+ dryRun: options.dryRun,
+ });
+ exitCode = outcome.exitCode;
+ if (outcome.error !== undefined) {
+ return incurError({
+ code: "SCAN_IMPORT_FAILED",
+ message: outcome.error,
+ exitCode,
+ });
+ }
+ if (
+ !options.dryRun &&
+ format === "toon" &&
+ !argv.some((argument) => OUTPUT_OPTION.test(argument))
+ ) {
+ return;
+ }
+ return outcome.data;
+ },
+ }),
+ );
+ }
+
let notice: UpdateNotice | undefined;
try {
await cli.serve(
@@ -4924,6 +5057,77 @@ export async function main(
}
}
+async function runScanImport(
+ options: ImportScanOptions,
+ errorOutput: Writable,
+ dependencies: CliDependencies,
+): Promise<ScanOutcome> {
+ const controller = new AbortController();
+ const onInterrupt = () => controller.abort("SIGINT");
+ const onTerminate = () => controller.abort("SIGTERM");
+ dependencies.addSignalListener("SIGINT", onInterrupt);
+ dependencies.addSignalListener("SIGTERM", onTerminate);
+ try {
+ const result = await (dependencies.importScan ?? importScan)(
+ { ...options, signal: controller.signal },
+ { environment: dependencies.environment },
+ );
+ if ("dryRun" in result) return { exitCode: 0, data: { ...result } };
+ try {
+ errorOutput.write(
+ `Imported ${result.findings.findings.length} findings as scan ${result.manifest.scan.id}.\n` +
+ `Artifacts: ${result.scanDir}\n`,
+ );
+ } catch {}
+ return { exitCode: 0, data: result.toJSON() };
+ } catch (error) {
+ const signal = controller.signal.reason;
+ const message =
+ signal === "SIGINT" || signal === "SIGTERM"
+ ? "Scan import canceled."
+ : safeErrorMessage(error);
+ errorOutput.write(`codex-security: ${message}\n`);
+ return {
+ exitCode: signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2,
+ error: message,
+ };
+ } finally {
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
+ }
+}
+
+function isScanImportCommand(argv: readonly string[]): boolean {
+ const commandIndex = cliCommandIndex(argv);
+ return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";
+}
+
+function normalizeScanImportArguments(
+ argv: readonly string[],
+): readonly string[] {
+ if (!isScanImportCommand(argv)) return argv;
+ const normalized: string[] = [];
+ const subcommandIndex = cliCommandIndex(argv) + 1;
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]!;
+ const next = argv[index + 1];
+ // Incur reserves bare --json for output, but parses --json=FILE normally.
+ if (
+ index > subcommandIndex &&
+ argument === "--json" &&
+ next !== undefined &&
+ !next.startsWith("--") &&
+ next !== "-h"
+ ) {
+ normalized.push(`--json=${next}`);
+ index += 1;
+ } else {
+ normalized.push(argument);
+ }
+ }
+ return normalized;
+}
+
function cliCommandIndex(argv: readonly string[]): number {
return argv.findIndex((value, index) => {
if (value.startsWith("-")) return false;
@@ -5189,7 +5393,9 @@ function validateCliArguments(
return "Markdown output is not supported for scan results.";
}
}
+ const scanImport = isScanImportCommand(argv);
const nestedCommand =
+ scanImport ||
command === "scans" ||
command === "findings" ||
command === "publish" ||
@@ -5239,7 +5445,11 @@ function validateCliArguments(
}
const equals = value.indexOf("=");
const option = equals < 0 ? value : value.slice(0, equals);
- if (equals >= 0 || !VALUE_OPTIONS.has(option)) continue;
+ if (
+ equals >= 0 ||
+ (!VALUE_OPTIONS.has(option) && !(scanImport && option === "--json"))
+ )
+ continue;
const next = argv[index + 1];
if (next === undefined || next.startsWith("--") || next === "-h") {
return `Missing value for flag: ${option}`;
@@ -5262,7 +5472,10 @@ function validateCliArguments(
command !== "verify-fix" &&
command !== "patch" &&
positionals.length >
- (command === "logout" || command === "info" || command === "serve"
+ (scanImport ||
+ command === "logout" ||
+ command === "info" ||
+ command === "serve"
? 0
: subcommand === "compare" || subcommand === "match"
? 2
diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.ts
index 8f5a1b3ee..ca1be47a8 100644
--- a/sdk/typescript/src/cloud-publish.ts
+++ b/sdk/typescript/src/cloud-publish.ts
@@ -1,13 +1,17 @@
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
-import { isAbsolute, join, posix } from "node:path";
+import { join } from "node:path";
import { z } from "incur";
-import Papa from "papaparse";
import { parse as parseToml } from "smol-toml";
import { loadContract } from "./contract.js";
import { AuthenticationRequiredError, CodexSecurityError } from "./errors.js";
import type { Finding, ScanManifest } from "./models.js";
+import {
+ CSV_TARGET_ID,
+ csvRowFinding,
+ parseFindingsCsv,
+} from "./findings-import.js";
import {
bundledPluginRoot,
codexSecurityCredentialAllowsAmbientImport,
@@ -19,7 +23,6 @@ import { VERSION } from "./version.js";
const CLOUD_PUBLISH_URL =
"https://chatgpt.com/backend-api/aardvark/cli/findings";
-const CSV_TARGET_ID = "codex-security-csv-import";
const CHATGPT_LOGIN_REQUIRED =
"Cloud publication requires a ChatGPT login already available to Codex Security. Run a scan or sign in with ChatGPT using Codex file credential storage, then retry.";
@@ -53,97 +56,6 @@ interface CloudPublicationDependencies {
dryRun?: boolean;
}
-const EXPORTED_CSV_ESCAPE = /^'(?:[\t\r\n]|\s*[=+\-@=+-@])/u;
-const csvFindingRowSchema = z
- .object({
- occurrence_id: z.string().regex(/^occ_[a-f0-9]{24}$/u, {
- error: "has an invalid occurrence_id",
- }),
- finding_id: z.string().regex(/^csf_[a-f0-9]{24}$/u, {
- error: "has an invalid finding_id",
- }),
- candidate_id: z
- .string()
- .optional()
- .transform((value) =>
- value === undefined || value.trim() === "" ? undefined : value,
- ),
- title: requiredCsvText("title"),
- summary: requiredCsvText("summary"),
- severity: z.enum(["critical", "high", "medium", "low", "informational"], {
- error: "has an invalid severity",
- }),
- confidence: z.enum(["high", "medium", "low"], {
- error: "has an invalid confidence",
- }),
- status: z.enum(["open", "closed"], {
- error: "has an invalid status",
- }),
- close_reason: z
- .union(
- [
- z.literal(""),
- z.enum(["already_fixed", "wont_fix", "false_positive"]),
- ],
- { error: "has an invalid close_reason" },
- )
- .transform((value) => (value === "" ? undefined : value)),
- note: z
- .string()
- .transform((value) => (value.trim() === "" ? undefined : value)),
- remediation: requiredCsvText("remediation"),
- path: z.string().refine(safeFindingPath, {
- error: "has an invalid path",
- }),
- start_line: z
- .string()
- .refine(validCsvLine, { error: "has an invalid start_line" })
- .transform(Number),
- end_line: z
- .string()
- .refine((value) => value === "" || validCsvLine(value), {
- error: "has an invalid end_line",
- })
- .transform((value) => (value === "" ? undefined : Number(value))),
- })
- .superRefine((row, context) => {
- if (
- (row.status === "open" && row.close_reason !== undefined) ||
- (row.status === "closed" && row.close_reason === undefined)
- ) {
- context.addIssue({
- code: "custom",
- path: ["close_reason"],
- message: "has an invalid close_reason",
- });
- }
- if (
- row.status === "closed" &&
- (row.close_reason === "false_positive" ||
- row.close_reason === "wont_fix") &&
- row.note === undefined
- ) {
- context.addIssue({
- code: "custom",
- path: ["note"],
- message: "requires a note for its close_reason",
- });
- }
- if (row.end_line !== undefined && row.end_line < row.start_line) {
- context.addIssue({
- code: "custom",
- path: ["end_line"],
- message: "has end_line before start_line",
- });
- }
- });
-type CsvFindingRow = z.infer<typeof csvFindingRowSchema>;
-type CsvColumn = keyof typeof csvFindingRowSchema.shape;
-const CSV_COLUMNS = Object.keys(csvFindingRowSchema.shape) as CsvColumn[];
-const REQUIRED_CSV_COLUMNS = CSV_COLUMNS.filter(
- (column) => !csvFindingRowSchema.shape[column].isOptional(),
-);
-
export async function publishScanToCloud(
scanDirectory: string,
dependencies: CloudPublicationDependencies & {
@@ -249,161 +161,6 @@ export async function publishFindingsCsvToCloud(
return publishCloudPayload(scan, findings, dependencies);
}
-function parseFindingsCsv(source: string): CsvFindingRow[] {
- const {
- data: rows,
- errors,
- meta,
- } = Papa.parse<Record<string, string>>(source, {
- header: true,
- delimiter: ",",
- skipEmptyLines: "greedy",
- transform: decodeExportedCsvCell,
- });
- const fieldMismatch = errors.find(
- (error) => error.code === "TooFewFields" || error.code === "TooManyFields",
- );
- if (fieldMismatch?.row !== undefined) {
- throw csvRowError(fieldMismatch.row + 2, "must match the header columns");
- }
- if (errors.length > 0) {
- throw new CodexSecurityError(
- `Findings CSV could not be parsed: ${errors[0]!.message}`,
- );
- }
- const headers = meta.fields;
- const allowed = new Set<string>(CSV_COLUMNS);
- if (
- headers === undefined ||
- !REQUIRED_CSV_COLUMNS.every((name) => headers.includes(name)) ||
- headers.some((name) => !allowed.has(name)) ||
- new Set(headers).size !== headers.length
- ) {
- throw new CodexSecurityError(
- `Findings CSV must use the Codex Security export columns: ${REQUIRED_CSV_COLUMNS.join(", ")} (candidate_id is optional).`,
- );
- }
- if (rows.length === 0) {
- throw new CodexSecurityError(
- "Findings CSV must contain at least one finding.",
- );
- }
-
- const findingIds = new Set<string>();
- const occurrenceIds = new Set<string>();
- return rows.map((record, index) => {
- const rowNumber = index + 2;
- const parsed = csvFindingRowSchema.safeParse(record);
- if (!parsed.success) {
- throw csvRowError(rowNumber, parsed.error.issues[0]!.message);
- }
- const row = parsed.data;
- if (findingIds.has(row.finding_id)) {
- throw csvRowError(rowNumber, "has a duplicate finding_id");
- }
- if (occurrenceIds.has(row.occurrence_id)) {
- throw csvRowError(rowNumber, "has a duplicate occurrence_id");
- }
- findingIds.add(row.finding_id);
- occurrenceIds.add(row.occurrence_id);
- return row;
- });
-}
-
-function decodeExportedCsvCell(value: string): string {
- return EXPORTED_CSV_ESCAPE.test(value) ? value.slice(1) : value;
-}
-
-function csvRowFinding(row: CsvFindingRow, scanId: string): Finding {
- const ruleId = "import.csv";
- const anchor = row.finding_id;
- const fingerprint = `codex-security/v1:sha256:${sha256(
- ["codex-security/v1", CSV_TARGET_ID, ruleId, anchor, ""].join("\0"),
- )}`;
- const findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;
- const occurrenceId = `occ_${sha256([scanId, fingerprint].join("\0")).slice(
- 0,
- 24,
- )}`;
- return {
- findingId,
- occurrenceId,
- ruleId,
- identity: { anchor },
- fingerprints: {
- algorithm: "codex-security/v1",
- primary: fingerprint,
- },
- title: row.title,
- summary: row.summary,
- severity: { level: row.severity },
- confidence: {
- level: row.confidence,
- rationale: "Imported from a Codex Security findings CSV.",
- },
- taxonomy: { category: "imported", cwe: [] },
- locations: [
- {
- path: row.path,
- startLine: row.start_line,
- ...(row.end_line === undefined ? {} : { endLine: row.end_line }),
- },
- ],
- remediation: row.remediation,
- validation: {
- method: "Source-reported CSV import metadata",
- status: row.status,
- summary: [
- `Source finding ID: ${row.finding_id}`,
- `Source occurrence ID: ${row.occurrence_id}`,
- `Source status: ${row.status}`,
- ...(row.close_reason === undefined
- ? []
- : [`Source close reason: ${row.close_reason}`]),
- ...(row.note === undefined ? [] : [`Source note: ${row.note}`]),
- ].join("\n"),
- },
- provenance: { source: "csv_import" },
- extensions: {
- ...(row.candidate_id === undefined
- ? {}
- : { candidateId: row.candidate_id }),
- },
- };
-}
-
-function requiredCsvText(column: string) {
- return z.string().refine((value) => value.trim().length > 0, {
- error: `requires ${column}`,
- });
-}
-
-function validCsvLine(value: string): boolean {
- if (!/^[1-9]\d*$/u.test(value)) return false;
- const line = Number(value);
- return Number.isSafeInteger(line);
-}
-
-function safeFindingPath(value: string): boolean {
- if (
- value.trim().length === 0 ||
- value === "." ||
- isAbsolute(value) ||
- /^[A-Za-z]:/u.test(value) ||
- value.includes("\\") ||
- /[\u0000-\u001F]/u.test(value) ||
- value.split("/").includes("..")
- ) {
- return false;
- }
- const normalized = posix.normalize(value).replace(/\/+$/u, "");
- return normalized !== "." && !normalized.startsWith("../");
-}
-
-function csvRowError(rowNumber: number, detail: string): CodexSecurityError {
- return new CodexSecurityError(`Findings CSV row ${rowNumber} ${detail}.`);
-}
-
function sha256(value: string): string {
return createHash("sha256").update(value, "utf8").digest("hex");
}
diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.ts
index 7f75b6c5d..f88d88914 100644
--- a/sdk/typescript/src/contract.ts
+++ b/sdk/typescript/src/contract.ts
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
-import { constants, type Stats } from "node:fs";
+import { constants, type BigIntStats, type Stats } from "node:fs";
import {
lstat,
open,
@@ -1155,8 +1155,8 @@ async function openCheckedScanFile(
export async function sameCheckedFileDevice(
file: FileHandle,
- checked: CheckedScanFile,
- opened: Stats,
+ checked: { path: string; metadata: Pick<Stats | BigIntStats, "dev" | "ino"> },
+ opened: Pick<Stats | BigIntStats, "dev" | "ino">,
platform: NodeJS.Platform = process.platform,
openReference: (path: string, flags: number) => Promise<FileHandle> = open,
): Promise<boolean> {
diff --git a/sdk/typescript/src/findings-import.ts b/sdk/typescript/src/findings-import.ts
new file mode 100644
index 000000000..aa66322f9
--- /dev/null
+++ b/sdk/typescript/src/findings-import.ts
@@ -0,0 +1,372 @@
+import { createHash } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { isAbsolute, join, posix } from "node:path";
+import Ajv2020 from "ajv/dist/2020.js";
+import { z } from "incur";
+import Papa from "papaparse";
+import { CodexSecurityError } from "./errors.js";
+import type { Finding, FindingsDocument } from "./models.js";
+
+export const CSV_TARGET_ID = "codex-security-csv-import";
+export type FindingsImportFormat = "csv" | "json";
+
+const EXPORTED_CSV_ESCAPE = /^'(?:[\t\r\n]|\s*[=+\-@=+-@])/u;
+const csvFindingRowSchema = z
+ .object({
+ occurrence_id: z.string().regex(/^occ_[a-f0-9]{24}$/u, {
+ error: "has an invalid occurrence_id",
+ }),
+ finding_id: z.string().regex(/^csf_[a-f0-9]{24}$/u, {
+ error: "has an invalid finding_id",
+ }),
+ candidate_id: z
+ .string()
+ .optional()
+ .transform((value) =>
+ value === undefined || value.trim() === "" ? undefined : value,
+ ),
+ title: requiredCsvText("title"),
+ summary: requiredCsvText("summary"),
+ severity: z.enum(["critical", "high", "medium", "low", "informational"], {
+ error: "has an invalid severity",
+ }),
+ confidence: z.enum(["high", "medium", "low"], {
+ error: "has an invalid confidence",
+ }),
+ status: z.enum(["open", "closed"], {
+ error: "has an invalid status",
+ }),
+ close_reason: z
+ .union(
+ [
+ z.literal(""),
+ z.enum(["already_fixed", "wont_fix", "false_positive"]),
+ ],
+ { error: "has an invalid close_reason" },
+ )
+ .transform((value) => (value === "" ? undefined : value)),
+ note: z
+ .string()
+ .transform((value) => (value.trim() === "" ? undefined : value)),
+ remediation: requiredCsvText("remediation"),
+ path: z.string().refine(safeFindingPath, {
+ error: "has an invalid path",
+ }),
+ start_line: z
+ .string()
+ .refine(validCsvLine, { error: "has an invalid start_line" })
+ .transform(Number),
+ end_line: z
+ .string()
+ .refine((value) => value === "" || validCsvLine(value), {
+ error: "has an invalid end_line",
+ })
+ .transform((value) => (value === "" ? undefined : Number(value))),
+ })
+ .superRefine((row, context) => {
+ if (
+ (row.status === "open" && row.close_reason !== undefined) ||
+ (row.status === "closed" && row.close_reason === undefined)
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["close_reason"],
+ message: "has an invalid close_reason",
+ });
+ }
+ if (
+ row.status === "closed" &&
+ (row.close_reason === "false_positive" ||
+ row.close_reason === "wont_fix") &&
+ row.note === undefined
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["note"],
+ message: "requires a note for its close_reason",
+ });
+ }
+ if (row.end_line !== undefined && row.end_line < row.start_line) {
+ context.addIssue({
+ code: "custom",
+ path: ["end_line"],
+ message: "has end_line before start_line",
+ });
+ }
+ });
+type CsvFindingRow = z.infer<typeof csvFindingRowSchema>;
+type CsvColumn = keyof typeof csvFindingRowSchema.shape;
+const CSV_COLUMNS = Object.keys(csvFindingRowSchema.shape) as CsvColumn[];
+const REQUIRED_CSV_COLUMNS = CSV_COLUMNS.filter(
+ (column) => !csvFindingRowSchema.shape[column].isOptional(),
+);
+
+export async function parseImportedFindings(
+ source: string,
+ format: FindingsImportFormat,
+ pluginRoot: string,
+): Promise<Finding[]> {
+ if (format === "csv") {
+ return parseFindingsCsv(source).map((row) => ({
+ ...csvRowFinding(row, "import"),
+ findingId: row.finding_id,
+ occurrenceId: row.occurrence_id,
+ }));
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(source);
+ } catch (error) {
+ throw new CodexSecurityError("Findings JSON could not be parsed.", {
+ cause: error,
+ });
+ }
+ if (
+ payload === null ||
+ typeof payload !== "object" ||
+ Array.isArray(payload)
+ ) {
+ throw new CodexSecurityError(
+ "Findings JSON must contain a findings document or an object with a findings array.",
+ );
+ }
+ const hasDocumentMetadata = ["documentType", "schemaVersion", "scanId"].some(
+ (key) => Object.hasOwn(payload, key),
+ );
+ const document = hasDocumentMetadata
+ ? payload
+ : {
+ documentType: "codex-security.findings",
+ schemaVersion: "1.0",
+ scanId: "import",
+ ...payload,
+ };
+ const schema = JSON.parse(
+ await readFile(join(pluginRoot, "schemas", "findings.schema.json"), "utf8"),
+ );
+ const validate = new Ajv2020({ strict: false }).compile<FindingsDocument>(
+ schema,
+ );
+ if (!validate(document)) {
+ const error = validate.errors?.[0];
+ throw new CodexSecurityError(
+ `Findings JSON does not match the Codex Security findings schema${error ? ` at ${error.instancePath || "/"}: ${error.message}` : ""}.`,
+ );
+ }
+ const occurrenceIds = new Set<string>();
+ for (const [index, finding] of document.findings.entries()) {
+ if (occurrenceIds.has(finding.occurrenceId)) {
+ throw new CodexSecurityError(
+ `Findings JSON finding ${index + 1} has a duplicate occurrenceId.`,
+ );
+ }
+ occurrenceIds.add(finding.occurrenceId);
+ }
+ return document.findings;
+}
+
+export function bindImportedFindings(
+ findings: Finding[],
+ format: FindingsImportFormat,
+ scanId: string,
+ targetId: string,
+): Finding[] {
+ return findings.map((finding) => {
+ const ruleId = `import.${format}`;
+ const anchor = finding.occurrenceId;
+ const fingerprint = `codex-security/v1:sha256:${sha256(
+ ["codex-security/v1", targetId, ruleId, anchor, ""].join("\0"),
+ )}`;
+ // A source report path names another scan's artifact. Preserve it as
+ // provenance without treating the imported path as permission to read it.
+ const { writeup, ...content } = finding;
+ return {
+ ...content,
+ findingId: `csf_${sha256(fingerprint).slice(0, 24)}`,
+ occurrenceId: `occ_${sha256([scanId, fingerprint].join("\0")).slice(0, 24)}`,
+ ruleId,
+ identity: { anchor },
+ fingerprints: {
+ algorithm: "codex-security/v1",
+ primary: fingerprint,
+ },
+ provenance: { source: `${format}_import` },
+ extensions: {
+ ...finding.extensions,
+ import: {
+ format,
+ sourceFindingId: finding.findingId,
+ sourceOccurrenceId: finding.occurrenceId,
+ sourceRuleId: finding.ruleId,
+ sourceIdentity: finding.identity,
+ sourceFingerprints: finding.fingerprints,
+ sourceProvenance: finding.provenance,
+ ...(writeup === undefined ? {} : { sourceWriteup: writeup }),
+ ...(finding.extensions?.["import"] === undefined
+ ? {}
+ : { previousImport: finding.extensions["import"] }),
+ },
+ },
+ };
+ });
+}
+
+export function parseFindingsCsv(source: string): CsvFindingRow[] {
+ const {
+ data: rows,
+ errors,
+ meta,
+ } = Papa.parse<Record<string, string>>(source, {
+ header: true,
+ delimiter: ",",
+ skipEmptyLines: "greedy",
+ transform: decodeExportedCsvCell,
+ });
+ const fieldMismatch = errors.find(
+ (error) => error.code === "TooFewFields" || error.code === "TooManyFields",
+ );
+ if (fieldMismatch?.row !== undefined) {
+ throw csvRowError(fieldMismatch.row + 2, "must match the header columns");
+ }
+ if (errors.length > 0) {
+ throw new CodexSecurityError(
+ `Findings CSV could not be parsed: ${errors[0]!.message}`,
+ );
+ }
+ const headers = meta.fields;
+ const allowed = new Set<string>(CSV_COLUMNS);
+ if (
+ headers === undefined ||
+ !REQUIRED_CSV_COLUMNS.every((name) => headers.includes(name)) ||
+ headers.some((name) => !allowed.has(name)) ||
+ new Set(headers).size !== headers.length
+ ) {
+ throw new CodexSecurityError(
+ `Findings CSV must use the Codex Security export columns: ${REQUIRED_CSV_COLUMNS.join(", ")} (candidate_id is optional).`,
+ );
+ }
+ if (rows.length === 0) {
+ throw new CodexSecurityError(
+ "Findings CSV must contain at least one finding.",
+ );
+ }
+
+ const findingIds = new Set<string>();
+ const occurrenceIds = new Set<string>();
+ return rows.map((record, index) => {
+ const rowNumber = index + 2;
+ const parsed = csvFindingRowSchema.safeParse(record);
+ if (!parsed.success) {
+ throw csvRowError(rowNumber, parsed.error.issues[0]!.message);
+ }
+ const row = parsed.data;
+ if (findingIds.has(row.finding_id)) {
+ throw csvRowError(rowNumber, "has a duplicate finding_id");
+ }
+ if (occurrenceIds.has(row.occurrence_id)) {
+ throw csvRowError(rowNumber, "has a duplicate occurrence_id");
+ }
+ findingIds.add(row.finding_id);
+ occurrenceIds.add(row.occurrence_id);
+ return row;
+ });
+}
+
+function decodeExportedCsvCell(value: string): string {
+ return EXPORTED_CSV_ESCAPE.test(value) ? value.slice(1) : value;
+}
+
+export function csvRowFinding(row: CsvFindingRow, scanId: string): Finding {
+ const ruleId = "import.csv";
+ const anchor = row.finding_id;
+ const fingerprint = `codex-security/v1:sha256:${sha256(
+ ["codex-security/v1", CSV_TARGET_ID, ruleId, anchor, ""].join("\0"),
+ )}`;
+ const findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;
+ const occurrenceId = `occ_${sha256([scanId, fingerprint].join("\0")).slice(
+ 0,
+ 24,
+ )}`;
+ return {
+ findingId,
+ occurrenceId,
+ ruleId,
+ identity: { anchor },
+ fingerprints: {
+ algorithm: "codex-security/v1",
+ primary: fingerprint,
+ },
+ title: row.title,
+ summary: row.summary,
+ severity: { level: row.severity },
+ confidence: {
+ level: row.confidence,
+ rationale: "Imported from a Codex Security findings CSV.",
+ },
+ taxonomy: { category: "imported", cwe: [] },
+ locations: [
+ {
+ path: row.path,
+ startLine: row.start_line,
+ ...(row.end_line === undefined ? {} : { endLine: row.end_line }),
+ },
+ ],
+ remediation: row.remediation,
+ validation: {
+ method: "Source-reported CSV import metadata",
+ status: row.status,
+ summary: [
+ `Source finding ID: ${row.finding_id}`,
+ `Source occurrence ID: ${row.occurrence_id}`,
+ `Source status: ${row.status}`,
+ ...(row.close_reason === undefined
+ ? []
+ : [`Source close reason: ${row.close_reason}`]),
+ ...(row.note === undefined ? [] : [`Source note: ${row.note}`]),
+ ].join("\n"),
+ },
+ provenance: { source: "csv_import" },
+ extensions: {
+ ...(row.candidate_id === undefined
+ ? {}
+ : { candidateId: row.candidate_id }),
+ },
+ };
+}
+
+function requiredCsvText(column: string) {
+ return z.string().refine((value) => value.trim().length > 0, {
+ error: `requires ${column}`,
+ });
+}
+
+function validCsvLine(value: string): boolean {
+ if (!/^[1-9]\d*$/u.test(value)) return false;
+ const line = Number(value);
+ return Number.isSafeInteger(line);
+}
+
+function safeFindingPath(value: string): boolean {
+ if (
+ value.trim().length === 0 ||
+ value === "." ||
+ isAbsolute(value) ||
+ /^[A-Za-z]:/u.test(value) ||
+ value.includes("\\") ||
+ /[\u0000-\u001F]/u.test(value) ||
+ value.split("/").includes("..")
+ ) {
+ return false;
+ }
+ const normalized = posix.normalize(value).replace(/\/+$/u, "");
+ return normalized !== "." && !normalized.startsWith("../");
+}
+
+function csvRowError(rowNumber: number, detail: string): CodexSecurityError {
+ return new CodexSecurityError(`Findings CSV row ${rowNumber} ${detail}.`);
+}
+
+function sha256(value: string): string {
+ return createHash("sha256").update(value, "utf8").digest("hex");
+}
diff --git a/sdk/typescript/src/import-scan.ts b/sdk/typescript/src/import-scan.ts
new file mode 100644
index 000000000..2a7152a54
--- /dev/null
+++ b/sdk/typescript/src/import-scan.ts
@@ -0,0 +1,355 @@
+import { createHash } from "node:crypto";
+import { constants } from "node:fs";
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ open,
+ readFile,
+ realpath,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import type { CodexSecurityConfig } from "./config.js";
+import { loadContract, sameCheckedFileDevice } from "./contract.js";
+import {
+ CodexSecurityError,
+ ScanInterruptedError,
+ safeErrorMessage,
+} from "./errors.js";
+import {
+ bindImportedFindings,
+ parseImportedFindings,
+} from "./findings-import.js";
+import { ScanResult } from "./result.js";
+import {
+ cleanupSdkDirectory,
+ codexSecurityStateDirectory,
+ expandHome,
+ pluginMetadata,
+ prepareOutputDir,
+ preparePersistentOutputRoot,
+ requireOutputOutsideRepository,
+ requirePrivateOutputDirectory,
+ requireSecureOutputAncestry,
+ resolvePluginPath,
+ resolvePluginPython,
+ runWorkbench,
+ validateOutputDir,
+ type ProcessEnvironment,
+ type WorkbenchCommandOptions,
+} from "./runtime.js";
+
+export interface ImportScanOptions {
+ sourcePath: string;
+ format: "csv" | "json";
+ config?: CodexSecurityConfig;
+ outputDir?: string;
+ archiveExisting?: boolean;
+ dryRun?: boolean;
+ parentScanId?: string;
+ signal?: AbortSignal;
+}
+
+export interface ImportScanPreview {
+ dryRun: true;
+ inputPath: string;
+ format: "csv" | "json";
+ findingCount: number;
+}
+
+export interface ImportScanDependencies {
+ environment?: ProcessEnvironment;
+ runWorkbench?: typeof runWorkbench;
+ resolvePluginPython?: typeof resolvePluginPython;
+}
+
+const IMPORT_DESCRIPTION =
+ "Imported findings; no security analysis was performed. Coverage is unknown. Source locations describe the imported reports.";
+
+async function readImportSource(
+ inputPath: string,
+ signal?: AbortSignal,
+): Promise<Buffer> {
+ signal?.throwIfAborted();
+ const selected = await lstat(inputPath, { bigint: true });
+ if (!selected.isFile()) {
+ throw new CodexSecurityError("Import source must be a regular file.");
+ }
+ for (let parent = dirname(inputPath); ; parent = dirname(parent)) {
+ signal?.throwIfAborted();
+ if ((await lstat(parent)).isSymbolicLink()) {
+ throw new CodexSecurityError(
+ "Import source must not traverse directory links. Use the direct filesystem path.",
+ );
+ }
+ if (dirname(parent) === parent) break;
+ }
+ const path = join(await realpath(dirname(inputPath)), basename(inputPath));
+ const file = await open(
+ path,
+ constants.O_RDONLY |
+ (constants.O_NOFOLLOW ?? 0) |
+ (constants.O_NONBLOCK ?? 0),
+ );
+ try {
+ signal?.throwIfAborted();
+ const opened = await file.stat({ bigint: true });
+ const current = await lstat(path, { bigint: true });
+ if (
+ !opened.isFile() ||
+ !current.isFile() ||
+ current.dev !== selected.dev ||
+ current.ino !== selected.ino ||
+ !(await sameCheckedFileDevice(file, { path, metadata: selected }, opened))
+ ) {
+ throw new CodexSecurityError(
+ "Import source must remain the selected regular file.",
+ );
+ }
+ return await file.readFile({ signal });
+ } finally {
+ await file.close();
+ }
+}
+
+/** Save supplied findings through the normal scan completion and indexing flow. */
+export async function importScan(
+ options: ImportScanOptions,
+ dependencies: ImportScanDependencies = {},
+): Promise<ScanResult | ImportScanPreview> {
+ const { signal } = options;
+ const environment = dependencies.environment ?? process.env;
+ const inputPath = resolve(expandHome(options.sourcePath, environment));
+ const source = await readImportSource(inputPath, signal);
+ const workspace = await mkdtemp(
+ join(await realpath(tmpdir()), "codex-security-import-"),
+ );
+ const workbench = dependencies.runWorkbench ?? runWorkbench;
+ let activeScan: { id: string; options: WorkbenchCommandOptions } | undefined;
+ let scanDir = "";
+ try {
+ const pluginRoot = await resolvePluginPath(
+ options.config?.pluginPath,
+ workspace,
+ signal,
+ );
+ const findings = await parseImportedFindings(
+ source.toString("utf8"),
+ options.format,
+ pluginRoot,
+ );
+ signal?.throwIfAborted();
+ await validateOutputDir(options.outputDir, options.archiveExisting);
+ if (options.dryRun) {
+ return {
+ dryRun: true,
+ inputPath,
+ format: options.format,
+ findingCount: findings.length,
+ };
+ }
+ const plugin = await pluginMetadata(pluginRoot);
+ const stateDirectory = codexSecurityStateDirectory(environment);
+ const digest = createHash("sha256")
+ .update(options.format)
+ .update("\0")
+ .update(source)
+ .digest("hex");
+ // A retained input directory is the scan target, independent of the caller's repository.
+ const repository = await preparePersistentOutputRoot(
+ stateDirectory,
+ "imports",
+ `${options.format}-${digest}`,
+ );
+ requirePrivateOutputDirectory(await lstat(repository), repository);
+ await requireSecureOutputAncestry(repository);
+ const sourcePath = join(repository, `source.${options.format}`);
+ try {
+ await writeFile(sourcePath, source, { flag: "wx", signal });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ if (!(await readFile(sourcePath, { signal })).equals(source)) {
+ throw new CodexSecurityError("The retained import source has changed.");
+ }
+ }
+ const python = await (
+ dependencies.resolvePluginPython ?? resolvePluginPython
+ )({
+ configuredPath: options.config?.pythonPath,
+ environment,
+ protectedRoot: repository,
+ signal,
+ });
+ const outputRoot =
+ options.outputDir === undefined
+ ? await preparePersistentOutputRoot(stateDirectory, "scans", "imports")
+ : undefined;
+ let archivedScanDir: string | undefined;
+ scanDir = await prepareOutputDir(
+ options.outputDir,
+ "import",
+ outputRoot,
+ (path) => requireOutputOutsideRepository(repository, path),
+ options.archiveExisting,
+ (path) => {
+ archivedScanDir = path;
+ },
+ );
+ const workbenchOptions: WorkbenchCommandOptions = {
+ python,
+ pluginRoot,
+ environment: { ...environment, CODEX_SECURITY_STATE_DIR: stateDirectory },
+ signal,
+ failureMessage: "Could not save the imported scan",
+ };
+ const registration = await workbench(
+ workbenchOptions,
+ [
+ "register-cli-scan",
+ "--repository",
+ repository,
+ "--scan-dir",
+ scanDir,
+ "--registration-json-stdin",
+ ...(options.archiveExisting ? ["--archive-existing"] : []),
+ ...(archivedScanDir === undefined
+ ? []
+ : ["--archived-scan-dir", archivedScanDir]),
+ ...(options.parentScanId === undefined
+ ? []
+ : ["--parent-scan-id", options.parentScanId]),
+ ],
+ JSON.stringify({
+ recipe: {
+ repository,
+ target: { kind: "repository", paths: [] },
+ mode: "standard",
+ pluginVersion: plugin.version,
+ config: {},
+ import: { format: options.format, sourcePath },
+ },
+ }),
+ );
+ const scanId = registration["scanId"];
+ const targetId = registration["targetId"];
+ if (
+ typeof scanId !== "string" ||
+ typeof targetId !== "string" ||
+ registration["scanDir"] !== scanDir
+ ) {
+ throw new CodexSecurityError(
+ "The workbench returned an invalid import scan registration.",
+ );
+ }
+ activeScan = { id: scanId, options: workbenchOptions };
+ const bound = bindImportedFindings(
+ findings,
+ options.format,
+ scanId,
+ targetId,
+ );
+ const sourceRef = `artifacts/import/source.${options.format}`;
+ await mkdir(join(scanDir, "artifacts", "import"), { recursive: true });
+ await writeFile(join(scanDir, sourceRef), source, { flag: "wx", signal });
+ const documents: Record<string, unknown> = {
+ "scan-manifest.json": {
+ scan: {
+ target: { kind: "directory_snapshot" },
+ scope: {
+ summary: IMPORT_DESCRIPTION,
+ runtimeStatus: "imported",
+ limitations: [IMPORT_DESCRIPTION],
+ },
+ extensions: {
+ import: {
+ format: options.format,
+ sourceRef,
+ findingCount: findings.length,
+ },
+ },
+ },
+ },
+ "findings.json": { findings: bound },
+ "coverage.json": {
+ completeness: "unknown",
+ inventoryStrategy: "custom",
+ surfaces: [
+ {
+ id: "import",
+ label: basename(inputPath),
+ disposition: "reported",
+ receiptRefs: [sourceRef],
+ notes: IMPORT_DESCRIPTION,
+ },
+ ],
+ explicitExclusions: [],
+ deferred: [],
+ },
+ };
+ for (const [name, document] of Object.entries(documents)) {
+ await writeFile(
+ join(scanDir, name),
+ `${JSON.stringify(document, null, 2)}\n`,
+ { flag: "wx", signal },
+ );
+ }
+ await workbench(workbenchOptions, [
+ "prepare-scan-completion",
+ "--scan-id",
+ scanId,
+ ]);
+ // Finalization normally recovers partial output. An import must retain every supplied row.
+ const contract = await loadContract(scanDir, {
+ pluginRoot,
+ expectedScanId: scanId,
+ workbenchValidated: true,
+ signal,
+ });
+ const expectedIds = new Set(bound.map((finding) => finding.findingId));
+ if (
+ contract.findings.findings.length !== findings.length ||
+ contract.findings.findings.some(
+ (finding) => !expectedIds.delete(finding.findingId),
+ ) ||
+ expectedIds.size !== 0
+ ) {
+ throw new CodexSecurityError(
+ "Import finalization did not preserve every input finding; the scan was not completed.",
+ );
+ }
+ await workbench(workbenchOptions, ["complete-scan", "--scan-id", scanId]);
+ activeScan = undefined;
+ return new ScanResult({
+ ...contract,
+ scanDir,
+ threadId: "",
+ turnResult: {
+ status: "completed",
+ imported: true,
+ finalResponse: IMPORT_DESCRIPTION,
+ },
+ });
+ } catch (error) {
+ if (activeScan !== undefined) {
+ await workbench({ ...activeScan.options, signal: undefined }, [
+ "fail-scan",
+ "--scan-id",
+ activeScan.id,
+ "--message",
+ safeErrorMessage(error).slice(0, 2400),
+ ]).catch(() => undefined);
+ }
+ if (signal?.aborted) {
+ throw new ScanInterruptedError(
+ "Codex Security import was interrupted.",
+ scanDir,
+ { cause: error },
+ );
+ }
+ throw error;
+ } finally {
+ await cleanupSdkDirectory(workspace);
+ }
+}
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 3d14482ea..36c8f15c9 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1538,7 +1538,7 @@ export function requireOutputOutsideRepositories(
export async function preparePersistentOutputRoot(
stateDirectory: string,
- category: "scans" | "policies" | "validations",
+ category: "scans" | "policies" | "validations" | "imports",
repositoryName: string,
): Promise<string> {
requireModelSafeOutputDir(stateDirectory);
@@ -1549,7 +1549,7 @@ export async function preparePersistentOutputRoot(
await mkdir(root, { recursive: true, mode: 0o700 });
if (!(await lstat(root)).isDirectory()) {
throw new OutputDirectoryError(
- `Persistent ${category === "scans" ? "scan" : category === "policies" ? "policy" : "validation"} output must use real directories: ${root}`,
+ `Persistent ${category === "scans" ? "scan" : category === "policies" ? "policy" : category === "imports" ? "import" : "validation"} output must use real directories: ${root}`,
);
}
}
diff --git a/sdk/typescript/tests-ts/cli-scan-import.test.ts b/sdk/typescript/tests-ts/cli-scan-import.test.ts
new file mode 100644
index 000000000..db5d8c171
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-scan-import.test.ts
@@ -0,0 +1,353 @@
+import { resolve } from "node:path";
+import { describe, expect, test } from "bun:test";
+import { main } from "../src/cli.js";
+import {
+ capture,
+ dependencies,
+ fakeResult,
+ FakeSignals,
+} from "./cli-fixtures.js";
+
+function importDependencies() {
+ const deps = dependencies({
+ currentDirectory: resolve("workspace"),
+ onConfig: () => {
+ throw new Error("Import must not create a model client");
+ },
+ });
+ const calls: Parameters<NonNullable<typeof deps.importScan>>[0][] = [];
+ deps.importScan = async (options, settings) => {
+ expect(settings?.environment).toBe(deps.environment);
+ calls.push(options);
+ return options.dryRun
+ ? {
+ dryRun: true,
+ inputPath: options.sourcePath,
+ format: options.format,
+ findingCount: 2,
+ }
+ : fakeResult(["high", "high"]);
+ };
+ return { deps, calls };
+}
+
+describe("scan import", () => {
+ test.each(["csv", "json"] as const)(
+ "imports --%s while --format json controls output",
+ async (format) => {
+ const { deps, calls } = importDependencies();
+ const stdout = capture();
+ const stderr = capture();
+ expect(
+ await main(
+ [
+ "scan",
+ "import",
+ `--${format}`,
+ `inputs/findings.${format}`,
+ "--output-dir",
+ "saved scan",
+ "--archive-existing",
+ "--format",
+ "json",
+ ],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ sourcePath: resolve("workspace", `inputs/findings.${format}`),
+ format,
+ outputDir: resolve("workspace", "saved scan"),
+ archiveExisting: true,
+ dryRun: false,
+ signal: expect.any(AbortSignal),
+ });
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ manifest: { scan: { id: "scan" } },
+ findings: {
+ findings: [
+ { severity: { level: "high" } },
+ { severity: { level: "high" } },
+ ],
+ },
+ });
+ expect(stderr.text()).toContain("Imported 2 findings as scan scan.");
+ },
+ );
+
+ test("accepts equals input syntax and validates without saving", async () => {
+ const { deps, calls } = importDependencies();
+ const stdout = capture();
+ const stderr = capture();
+ expect(
+ await main(
+ [
+ "scan",
+ "import",
+ "--json=inputs/findings with spaces.json",
+ "--dry-run",
+ "--format=json",
+ ],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls[0]).toMatchObject({ dryRun: true, format: "json" });
+ expect(JSON.parse(stdout.text())).toEqual({
+ dryRun: true,
+ inputPath: resolve("workspace", "inputs/findings with spaces.json"),
+ format: "json",
+ findingCount: 2,
+ });
+ expect(stderr.text()).toBe("");
+ });
+
+ test("uses a concise summary for default output", async () => {
+ const { deps } = importDependencies();
+ const stdout = capture();
+ const stderr = capture();
+ expect(
+ await main(
+ ["scan", "import", "--json", "findings.json"],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(stdout.text()).toBe("");
+ expect(stderr.text()).toContain("Imported 2 findings as scan scan.");
+ });
+
+ test.each([
+ [[], "exactly one"],
+ [["--csv", "findings.csv", "--json", "findings.json"], "exactly one"],
+ [["--json"], "Missing value for flag: --json"],
+ [["--json", "--dry-run"], "Missing value for flag: --json"],
+ [["--csv"], "Missing value for flag: --csv"],
+ [["--json="], "--json must not be empty"],
+ [
+ ["--csv", "findings.csv", "extra"],
+ "Unexpected positional argument for scan import",
+ ],
+ [
+ ["--csv", "findings.csv", "--archive-existing"],
+ "--archive-existing requires --output-dir",
+ ],
+ ])("rejects invalid import arguments %j", async (args, message) => {
+ const { deps, calls } = importDependencies();
+ const stderr = capture();
+ expect(
+ await main(
+ ["scan", "import", ...args],
+ capture().stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(2);
+ expect(calls).toHaveLength(0);
+ expect(stderr.text()).toContain(message);
+ });
+
+ test("exposes both source flags in help and schemas", async () => {
+ const { deps, calls } = importDependencies();
+ const help = capture();
+ expect(
+ await main(
+ ["scan", "import", "--help"],
+ help.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(help.text()).toContain("--csv <string>");
+ expect(help.text()).toContain("--json <string>");
+ expect(help.text()).toContain("--format json");
+ const schema = capture();
+ expect(
+ await main(
+ ["scan", "import", "--schema", "--format", "json"],
+ schema.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(JSON.parse(schema.text())).toMatchObject({
+ options: {
+ properties: { csv: { type: "string" }, json: { type: "string" } },
+ },
+ });
+ expect(calls).toHaveLength(0);
+ });
+
+ test("ordinary scan retains repository arguments and the --json output shortcut", async () => {
+ const stdout = capture();
+ const stderr = capture();
+ let scans = 0;
+ const deps = dependencies({
+ onRun: () => {
+ scans += 1;
+ },
+ });
+ expect(
+ await main(
+ ["scan", "./import", "--json"],
+ stdout.stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(scans).toBe(1);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ manifest: { scan: { id: "scan" } },
+ });
+ });
+
+ test("preserves the global JSON shortcut before the scan command", async () => {
+ const { deps, calls } = importDependencies();
+ const stdout = capture();
+ expect(
+ await main(
+ ["--json", "scan", "import", "--csv", "findings.csv"],
+ stdout.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls[0]?.format).toBe("csv");
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ manifest: { scan: { id: "scan" } },
+ });
+ });
+
+ test("keeps a completed import successful if its summary cannot be written", async () => {
+ const { deps, calls } = importDependencies();
+ const stdout = capture();
+ expect(
+ await main(
+ ["scan", "import", "--csv", "findings.csv", "--format", "json"],
+ stdout.stream,
+ {
+ write() {
+ throw new Error("closed progress stream");
+ },
+ },
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls).toHaveLength(1);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ manifest: { scan: { id: "scan" } },
+ });
+ });
+
+ test("reruns an imported scan from its retained source", async () => {
+ const { deps, calls } = importDependencies();
+ deps.runWorkbench = async (args) => {
+ expect(args).toEqual(["get-scan-recipe", "--scan-id", "previous-scan"]);
+ return {
+ recipe: {
+ import: {
+ format: "csv",
+ sourcePath: resolve("retained", "source.csv"),
+ },
+ },
+ };
+ };
+ const stdout = capture();
+ expect(
+ await main(
+ ["scans", "rerun", "previous-scan", "--json"],
+ stdout.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls[0]).toMatchObject({
+ sourcePath: resolve("retained", "source.csv"),
+ format: "csv",
+ parentScanId: "previous-scan",
+ });
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ manifest: { scan: { id: "scan" } },
+ });
+ });
+
+ test("rejects custom validation when rerunning an imported scan", async () => {
+ const { deps, calls } = importDependencies();
+ deps.runWorkbench = async () => ({
+ recipe: {
+ import: {
+ format: "csv",
+ sourcePath: resolve("retained", "source.csv"),
+ },
+ },
+ });
+ const stderr = capture();
+ expect(
+ await main(
+ [
+ "scans",
+ "rerun",
+ "previous-scan",
+ "--validation-prompt-file",
+ "workflow.md",
+ ],
+ capture().stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "--validation-prompt-file is not supported when rerunning an imported scan",
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ test("reports import errors without leaving signal handlers", async () => {
+ const signals = new FakeSignals();
+ const deps = dependencies({ signals });
+ deps.importScan = async () => {
+ throw new Error("Input JSON is not a findings document.");
+ };
+ const stderr = capture();
+ expect(
+ await main(
+ ["scan", "import", "--json", "findings.json"],
+ capture().stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain("Input JSON is not a findings document.");
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ });
+
+ test.each([
+ ["SIGINT", 130],
+ ["SIGTERM", 143],
+ ] as const)("cancels imports on %s", async (signal, status) => {
+ const signals = new FakeSignals();
+ const deps = dependencies({ signals });
+ deps.importScan = async (options) => {
+ signals.emit(signal);
+ options.signal!.throwIfAborted();
+ throw new Error("unreachable");
+ };
+ const stderr = capture();
+ expect(
+ await main(
+ ["scan", "import", "--csv", "findings.csv"],
+ capture().stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(status);
+ expect(stderr.text()).toContain("Scan import canceled.");
+ expect(signals.listeners.get(signal)?.size).toBe(0);
+ });
+});
diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.ts
index 515df46ab..e7e95fb23 100644
--- a/sdk/typescript/tests-ts/contract.test.ts
+++ b/sdk/typescript/tests-ts/contract.test.ts
@@ -316,6 +316,28 @@ describe("canonical scan contract", () => {
sameCheckedFileDevice(file, checked, opened, "linux", openReference),
).resolves.toBe(false);
expect(inspected).toBe(windowsInspections);
+
+ device = referenceDevice = highDevice;
+ inode = referenceInode = identity.ino;
+ regular = referenceRegular = true;
+ await expect(
+ sameCheckedFileDevice(
+ file,
+ { path, metadata: identity },
+ { dev: highDevice, ino: identity.ino },
+ "win32",
+ openReference,
+ ),
+ ).resolves.toBe(true);
+ const largeInode = 2n ** 60n;
+ expect(Number(largeInode)).toBe(Number(largeInode + 1n));
+ await expect(
+ sameCheckedFileDevice(
+ file,
+ { path, metadata: { dev: identity.dev, ino: largeInode } },
+ { dev: identity.dev, ino: largeInode + 1n },
+ ),
+ ).resolves.toBe(false);
});
test("loads the unchanged plugin example with typed canonical names", async () => {
diff --git a/sdk/typescript/tests-ts/findings-import.test.ts b/sdk/typescript/tests-ts/findings-import.test.ts
new file mode 100644
index 000000000..4fd96f461
--- /dev/null
+++ b/sdk/typescript/tests-ts/findings-import.test.ts
@@ -0,0 +1,122 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import {
+ bindImportedFindings,
+ parseImportedFindings,
+} from "../src/findings-import.js";
+import type { Finding, FindingsDocument } from "../src/models.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
+
+async function sourceDocument(): Promise<FindingsDocument> {
+ return JSON.parse(
+ await readFile(
+ join(PLUGIN_ROOT, "examples", "completed-scan", "findings.json"),
+ "utf8",
+ ),
+ );
+}
+
+describe("findings import formats", () => {
+ test("accepts full findings documents and findings-service payloads", async () => {
+ const document = await sourceDocument();
+ document.findings[0]!.summary =
+ 'Full description\nwith "quotes", commas, and unicode: λ.';
+ const payloads = [document, { findings: document.findings }];
+ for (const payload of payloads) {
+ expect(
+ await parseImportedFindings(
+ JSON.stringify(payload),
+ "json",
+ PLUGIN_ROOT,
+ ),
+ ).toEqual(document.findings);
+ }
+ expect(
+ await parseImportedFindings('{"findings":[]}', "json", PLUGIN_ROOT),
+ ).toEqual([]);
+ });
+
+ test("binds separate source occurrences and retains source metadata without following report paths", async () => {
+ const document = await sourceDocument();
+ const finding = document.findings[0]!;
+ finding.writeup = { reportPath: "findings/source-report/source-report.md" };
+ finding.extensions = {
+ candidateId: "ISSUE-42",
+ import: { sourceSystem: "synthetic" },
+ };
+ const sibling: Finding = {
+ ...structuredClone(finding),
+ occurrenceId: "occ_111111111111111111111111",
+ };
+ const source = JSON.stringify({ findings: [finding, sibling] });
+ const parsed = await parseImportedFindings(source, "json", PLUGIN_ROOT);
+ const bound = bindImportedFindings(parsed, "json", "scan_first", "dataset");
+ const rerun = bindImportedFindings(
+ parsed,
+ "json",
+ "scan_second",
+ "dataset",
+ );
+ expect(new Set(bound.map((row) => row.findingId)).size).toBe(2);
+ expect(new Set(bound.map((row) => row.occurrenceId)).size).toBe(2);
+ expect(bound.map((row) => row.findingId)).toEqual(
+ rerun.map((row) => row.findingId),
+ );
+ expect(bound[0]!.occurrenceId).not.toBe(rerun[0]!.occurrenceId);
+ expect(bound[0]).toMatchObject({
+ ruleId: "import.json",
+ identity: { anchor: finding.occurrenceId },
+ title: finding.title,
+ summary: finding.summary,
+ locations: finding.locations,
+ provenance: { source: "json_import" },
+ extensions: {
+ candidateId: "ISSUE-42",
+ import: {
+ format: "json",
+ sourceFindingId: finding.findingId,
+ sourceOccurrenceId: finding.occurrenceId,
+ sourceRuleId: finding.ruleId,
+ sourceIdentity: finding.identity,
+ sourceFingerprints: finding.fingerprints,
+ sourceProvenance: finding.provenance,
+ sourceWriteup: finding.writeup,
+ previousImport: { sourceSystem: "synthetic" },
+ },
+ },
+ });
+ expect(bound[0]).not.toHaveProperty("writeup");
+ expect(parsed[0]!.writeup).toEqual(finding.writeup);
+ expect(JSON.stringify({ findings: parsed })).toBe(source);
+ });
+
+ test("rejects malformed JSON, noncanonical finding shapes, and repeated source occurrences", async () => {
+ const document = await sourceDocument();
+ const invalidPayloads = [
+ { ...document, schemaVersion: "2.0" },
+ { findings: [{ title: "Missing finding fields" }] },
+ document.findings,
+ {
+ findings: [{ ...document.findings[0], severity: { level: "urgent" } }],
+ },
+ ];
+ for (const payload of invalidPayloads) {
+ await expect(
+ parseImportedFindings(JSON.stringify(payload), "json", PLUGIN_ROOT),
+ ).rejects.toThrow("Findings JSON");
+ }
+ await expect(
+ parseImportedFindings("{", "json", PLUGIN_ROOT),
+ ).rejects.toThrow("could not be parsed");
+ await expect(
+ parseImportedFindings(
+ JSON.stringify({
+ findings: [document.findings[0], document.findings[0]],
+ }),
+ "json",
+ PLUGIN_ROOT,
+ ),
+ ).rejects.toThrow("duplicate occurrenceId");
+ });
+});
diff --git a/sdk/typescript/tests-ts/import-scan.test.ts b/sdk/typescript/tests-ts/import-scan.test.ts
new file mode 100644
index 000000000..28e13b808
--- /dev/null
+++ b/sdk/typescript/tests-ts/import-scan.test.ts
@@ -0,0 +1,539 @@
+import { execFileSync } from "node:child_process";
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import * as filesystem from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, spyOn, test } from "bun:test";
+import { loadContract } from "../src/contract.js";
+import { ScanInterruptedError } from "../src/errors.js";
+import { importScan, type ImportScanOptions } from "../src/import-scan.js";
+import type { FindingsDocument } from "../src/models.js";
+import { ScanResult } from "../src/result.js";
+import { runWorkbench } from "../src/runtime.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
+import { runCommand } from "./support/shell.js";
+import { runTestInSubprocess } from "./support/test-subprocess.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
+const description =
+ 'An imported report with a comma, a "quoted value", and Unicode: café.\n\n' +
+ "The full second paragraph must survive importing and indexing.\n" +
+ "A final line describes the reported impact.";
+const sourceOccurrenceIds = [
+ "occ_000000000000000000000001",
+ "occ_000000000000000000000002",
+];
+const csvColumns = [
+ "occurrence_id",
+ "finding_id",
+ "title",
+ "summary",
+ "severity",
+ "confidence",
+ "status",
+ "close_reason",
+ "note",
+ "remediation",
+ "path",
+ "start_line",
+ "end_line",
+];
+
+function csvSource(): string {
+ const rows = sourceOccurrenceIds.map((occurrenceId, index) => [
+ occurrenceId,
+ `csf_00000000000000000000000${index + 1}`,
+ "Reported archive extraction issue",
+ description,
+ "high",
+ "high",
+ "open",
+ "",
+ "",
+ "Validate archive entry destinations.",
+ "src/extract.ts",
+ "41",
+ "44",
+ ]);
+ return (
+ [csvColumns, ...rows]
+ .map((row) =>
+ row.map((value) => `"${value.replaceAll('"', '""')}"`).join(","),
+ )
+ .join("\r\n") + "\r\n"
+ );
+}
+
+async function fixture(format: "csv" | "json" = "csv") {
+ const root = await mkdtemp(
+ join(await realpath(tmpdir()), "import-scan-test-"),
+ );
+ roots.push(root);
+ const python = Bun.which("python3") ?? Bun.which("python");
+ expect(python).not.toBeNull();
+ const stateDirectory = join(root, "state");
+ const environment = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: join(root, "codex-home"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ };
+ let source = csvSource();
+ if (format === "json") {
+ const example = JSON.parse(
+ await readFile(
+ join(PLUGIN_ROOT, "examples", "completed-scan", "findings.json"),
+ "utf8",
+ ),
+ ) as FindingsDocument;
+ const finding = example.findings[0]!;
+ source = JSON.stringify({
+ ...example,
+ findings: sourceOccurrenceIds.map((occurrenceId) => ({
+ ...finding,
+ occurrenceId,
+ summary: description,
+ })),
+ });
+ }
+ const sourcePath = join(root, `findings.${format}`);
+ await writeFile(sourcePath, source);
+ const options: ImportScanOptions = {
+ sourcePath,
+ format,
+ config: { pluginPath: PLUGIN_ROOT, pythonPath: python! },
+ };
+ return {
+ root,
+ stateDirectory,
+ environment,
+ python: python!,
+ source,
+ options,
+ workbenchOptions: { python: python!, pluginRoot: PLUGIN_ROOT, environment },
+ };
+}
+
+function completed(result: Awaited<ReturnType<typeof importScan>>): ScanResult {
+ expect(result).toBeInstanceOf(ScanResult);
+ if (!(result instanceof ScanResult)) throw new Error("Expected a saved scan");
+ return result;
+}
+
+async function storedScans(context: Awaited<ReturnType<typeof fixture>>) {
+ const result = await runCommand(
+ context.python,
+ [
+ "-c",
+ [
+ "import json, sqlite3, sys",
+ "connection = sqlite3.connect(sys.argv[1])",
+ "connection.row_factory = sqlite3.Row",
+ 'rows = connection.execute("SELECT id, status, target_path, scan_dir, (SELECT COUNT(*) FROM finding_occurrences WHERE scan_id = scans.id) AS occurrence_count FROM scans ORDER BY created_at, id")',
+ 'print(json.dumps([dict(row, summaries=[summary for (summary,) in connection.execute("SELECT summary FROM finding_occurrences WHERE scan_id = ?", (row["id"],))]) for row in rows]))',
+ ].join("\n"),
+ join(context.stateDirectory, "workbench.sqlite3"),
+ ],
+ { timeout: 30_000 },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ return JSON.parse(result.stdout) as Array<{
+ id: string;
+ status: string;
+ target_path: string;
+ scan_dir: string;
+ occurrence_count: number;
+ summaries: string[];
+ }>;
+}
+
+test.each(["csv", "json"] as const)(
+ "%s import seals every source occurrence and indexes a separate dataset scan",
+ async (format) => {
+ const context = await fixture(format);
+ const result = completed(
+ await importScan(context.options, { environment: context.environment }),
+ );
+ expect(result.findings.findings).toHaveLength(2);
+ expect(
+ new Set(result.findings.findings.map((finding) => finding.findingId))
+ .size,
+ ).toBe(2);
+ expect(
+ new Set(result.findings.findings.map((finding) => finding.occurrenceId))
+ .size,
+ ).toBe(2);
+ for (const finding of result.findings.findings) {
+ expect(finding.summary).toBe(description);
+ expect(finding.locations[0]).toMatchObject({
+ startLine: 41,
+ endLine: 44,
+ });
+ expect(finding.extensions?.["import"]).toMatchObject({ format });
+ }
+ const expectedFindingIds =
+ format === "csv"
+ ? ["csf_000000000000000000000001", "csf_000000000000000000000002"]
+ : (JSON.parse(context.source) as FindingsDocument).findings.map(
+ (finding) => finding.findingId,
+ );
+ expect(
+ result.findings.findings
+ .map(
+ (finding) =>
+ (finding.extensions?.["import"] as { sourceFindingId: string })
+ .sourceFindingId,
+ )
+ .sort(),
+ ).toEqual(expectedFindingIds.sort());
+ expect(
+ result.findings.findings
+ .map(
+ (finding) =>
+ (finding.extensions?.["import"] as { sourceOccurrenceId: string })
+ .sourceOccurrenceId,
+ )
+ .sort(),
+ ).toEqual(sourceOccurrenceIds);
+ expect(result.findings.findings[0]!.locations).toEqual(
+ result.findings.findings[1]!.locations,
+ );
+ expect(result.manifest.scan.status).toBe("completed");
+ expect(result.manifest.scan.sealedAt).toBeTruthy();
+ expect(result.manifest.scan.target.kind).toBe("directory_snapshot");
+ expect(result.manifest.scan.scope.runtimeStatus).toBe("imported");
+ expect(result.coverage.completeness).toBe("unknown");
+ expect(result.turnResult["imported"]).toBe(true);
+ expect(result.threadId).toBe("");
+ expect(await readFile(result.reportPath, "utf8")).toContain(
+ "no security analysis was performed",
+ );
+ expect(
+ await loadContract(result.scanDir, { pluginRoot: PLUGIN_ROOT }),
+ ).toEqual({
+ manifest: result.manifest,
+ findings: result.findings,
+ coverage: result.coverage,
+ });
+ const sourceRef = `artifacts/import/source.${format}`;
+ expect(result.manifest.scan["extensions"]).toMatchObject({
+ import: { format, sourceRef, findingCount: 2 },
+ });
+ expect(
+ result.manifest.scan.artifacts.some(
+ (artifact) => artifact.path === sourceRef,
+ ),
+ ).toBe(true);
+ expect(await readFile(join(result.scanDir, sourceRef), "utf8")).toBe(
+ context.source,
+ );
+ expect(await readFile(context.options.sourcePath, "utf8")).toBe(
+ context.source,
+ );
+ const [stored] = await storedScans(context);
+ expect(stored).toMatchObject({
+ id: result.manifest.scan.id,
+ status: "complete",
+ occurrence_count: 2,
+ summaries: [description, description],
+ });
+ expect(stored!.target_path).not.toBe(process.cwd());
+ expect(stored!.target_path).not.toBe(context.root);
+ const recipe = await runWorkbench(context.workbenchOptions, [
+ "get-scan-recipe",
+ "--scan-id",
+ result.manifest.scan.id,
+ ]);
+ const imported = (
+ recipe["recipe"] as { import: { format: string; sourcePath: string } }
+ ).import;
+ expect(imported.format).toBe(format);
+ expect(imported.sourcePath).not.toBe(context.options.sourcePath);
+ expect(await readFile(imported.sourcePath, "utf8")).toBe(context.source);
+ },
+);
+
+test.each(["csv", "json"] as const)(
+ "%s import rejects a symlinked source before persistence",
+ async (format) => {
+ const context = await fixture(format);
+ const linked = join(context.root, `linked.${format}`);
+ await symlink(context.options.sourcePath, linked, "file");
+ for (const dryRun of [false, true]) {
+ await expect(
+ importScan(
+ { ...context.options, sourcePath: linked, dryRun },
+ { environment: context.environment },
+ ),
+ ).rejects.toThrow("Import source must be a regular file");
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ }
+ },
+);
+
+test.each(["csv", "json"] as const)(
+ "%s import rejects directory links before persistence",
+ async (format) => {
+ const context = await fixture(format);
+ const repository = join(context.root, "repository");
+ await mkdir(repository);
+ const linked = join(repository, "reports");
+ await symlink(
+ context.root,
+ linked,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ for (const dryRun of [false, true]) {
+ await expect(
+ importScan(
+ {
+ ...context.options,
+ sourcePath: join(linked, `findings.${format}`),
+ dryRun,
+ },
+ { environment: context.environment },
+ ),
+ ).rejects.toThrow("Import source must not traverse directory links");
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ }
+ },
+);
+
+test.each(process.platform === "win32" ? ["directory"] : ["directory", "FIFO"])(
+ "import rejects a %s source before persistence",
+ async (kind) => {
+ const context = await fixture();
+ await rm(context.options.sourcePath);
+ if (kind === "directory") await mkdir(context.options.sourcePath);
+ else execFileSync("mkfifo", [context.options.sourcePath]);
+ await expect(
+ importScan(context.options, { environment: context.environment }),
+ ).rejects.toThrow("Import source must be a regular file");
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ },
+);
+
+test.each(["regular file", "symbolic link"])(
+ "import rejects a source replaced with a %s before reading",
+ async (replacement) => {
+ if (
+ runTestInSubprocess(
+ import.meta.path,
+ `import rejects a source replaced with a ${replacement} before reading`,
+ )
+ )
+ return;
+ const context = await fixture("json");
+ const originalOpen = filesystem.open;
+ let replaced = false;
+ let read = false;
+ let restoreRead: (() => void) | undefined;
+ const opening = spyOn(filesystem, "open").mockImplementation(
+ async (...args: Parameters<typeof filesystem.open>) => {
+ if (String(args[0]) !== context.options.sourcePath) {
+ return await originalOpen(...args);
+ }
+ opening.mockRestore();
+ const previous = join(context.root, "previous.json");
+ await rename(context.options.sourcePath, previous);
+ if (replacement === "symbolic link") {
+ await symlink(previous, context.options.sourcePath, "file");
+ } else {
+ await writeFile(context.options.sourcePath, context.source);
+ }
+ replaced = true;
+ const file = await originalOpen(...args);
+ const reading = spyOn(file, "readFile").mockImplementation(async () => {
+ read = true;
+ throw new Error("Read a replaced source");
+ });
+ restoreRead = () => reading.mockRestore();
+ return file;
+ },
+ );
+ try {
+ await expect(
+ importScan(context.options, { environment: context.environment }),
+ ).rejects.toThrow();
+ expect(replaced).toBe(true);
+ expect(read).toBe(false);
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ } finally {
+ restoreRead?.();
+ opening.mockRestore();
+ }
+ },
+);
+
+test("reimporting the retained source preserves finding identities with new scan occurrences", async () => {
+ const context = await fixture();
+ const first = completed(
+ await importScan(context.options, { environment: context.environment }),
+ );
+ const recipe = await runWorkbench(context.workbenchOptions, [
+ "get-scan-recipe",
+ "--scan-id",
+ first.manifest.scan.id,
+ ]);
+ const imported = (recipe["recipe"] as { import: { sourcePath: string } })
+ .import;
+ await rm(context.options.sourcePath);
+ const second = completed(
+ await importScan(
+ {
+ ...context.options,
+ sourcePath: imported.sourcePath,
+ parentScanId: first.manifest.scan.id,
+ },
+ { environment: context.environment },
+ ),
+ );
+ expect(second.manifest.scan.id).not.toBe(first.manifest.scan.id);
+ expect(second.manifest.scan.target.targetId).toBe(
+ first.manifest.scan.target.targetId,
+ );
+ expect(second.findings.findings.map((finding) => finding.findingId)).toEqual(
+ first.findings.findings.map((finding) => finding.findingId),
+ );
+ const previousOccurrences = new Set(
+ first.findings.findings.map((finding) => finding.occurrenceId),
+ );
+ expect(
+ second.findings.findings.every(
+ (finding) => !previousOccurrences.has(finding.occurrenceId),
+ ),
+ ).toBe(true);
+ expect(
+ (await storedScans(context)).map((scan) => scan.occurrence_count),
+ ).toEqual([2, 2]);
+});
+
+test("dry run validates source rows without creating database state or invoking the workbench", async () => {
+ const context = await fixture();
+ const unexpected = async () => {
+ throw new Error("Dry run invoked scan persistence");
+ };
+ const result = await importScan(
+ { ...context.options, dryRun: true },
+ {
+ environment: context.environment,
+ runWorkbench: unexpected,
+ resolvePluginPython: unexpected,
+ },
+ );
+ expect(result).toEqual({
+ dryRun: true,
+ inputPath: context.options.sourcePath,
+ format: "csv",
+ findingCount: 2,
+ });
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ await writeFile(context.options.sourcePath, "not,a,findings,header\n");
+ await expect(
+ importScan(
+ { ...context.options, dryRun: true },
+ {
+ environment: context.environment,
+ runWorkbench: unexpected,
+ },
+ ),
+ ).rejects.toThrow();
+ await expect(stat(context.stateDirectory)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+});
+
+test("imports archive prior output without replacing its saved findings", async () => {
+ const context = await fixture();
+ const options = {
+ ...context.options,
+ outputDir: join(context.root, "results"),
+ };
+ const first = completed(
+ await importScan(options, { environment: context.environment }),
+ );
+ const originalManifest = await readFile(first.manifestPath, "utf8");
+ await expect(
+ importScan(options, { environment: context.environment }),
+ ).rejects.toThrow();
+ expect(await readFile(first.manifestPath, "utf8")).toBe(originalManifest);
+ const second = completed(
+ await importScan(
+ { ...options, archiveExisting: true },
+ {
+ environment: context.environment,
+ },
+ ),
+ );
+ const scans = await storedScans(context);
+ expect(scans).toHaveLength(2);
+ const archived = scans.find((scan) => scan.id === first.manifest.scan.id)!;
+ expect(archived.scan_dir).not.toBe(second.scanDir);
+ expect(archived.occurrence_count).toBe(2);
+ expect(
+ await readFile(join(archived.scan_dir, "scan-manifest.json"), "utf8"),
+ ).toBe(originalManifest);
+ expect(
+ (await loadContract(archived.scan_dir, { pluginRoot: PLUGIN_ROOT }))
+ .findings.findings,
+ ).toHaveLength(2);
+});
+
+test.each(["failure", "abort"] as const)(
+ "an import %s after registration leaves a terminal saved scan",
+ async (mode) => {
+ const context = await fixture();
+ const controller = new AbortController();
+ const run: typeof runWorkbench = async (options, args, input) => {
+ if (args[0] === "prepare-scan-completion" && mode === "failure") {
+ throw new Error("Synthetic import completion failure");
+ }
+ const result = await runWorkbench(options, args, input);
+ if (args[0] === "register-cli-scan" && mode === "abort")
+ controller.abort();
+ return result;
+ };
+ const operation = importScan(
+ { ...context.options, signal: controller.signal },
+ {
+ environment: context.environment,
+ runWorkbench: run,
+ },
+ );
+ if (mode === "abort")
+ await expect(operation).rejects.toBeInstanceOf(ScanInterruptedError);
+ else
+ await expect(operation).rejects.toThrow(
+ "Synthetic import completion failure",
+ );
+ const scans = await storedScans(context);
+ expect(scans).toHaveLength(1);
+ expect(scans[0]!.status).toBe("failed");
+ },
+);