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(imports): add local report import and readback (#1848)

Michael D'Angelod79cbf6c419d
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 73595107c..397c1736f 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -1,13 +1,33 @@
---
name: publish-findings
-description: Import selected Wiz package vulnerabilities, SAST, repository secrets, and IaC findings to Codex Security Cloud after previewing the destination and evidence. Supports plain or gzip-compressed JSON and normalized JSONL; does not import workload secrets or cloud configuration, run a scan, or assess findings.
+description: Import selected Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Supports plain or gzip-compressed JSON and normalized JSONL; does not import workload secrets or cloud configuration, run a scan, or assess findings.
---
# Publish external findings
-Use the installed `codex-security publish findings` command for both preview and upload. It owns source mapping, Cloud authentication, source versions, and saved request retries. Do not implement another HTTP uploader or put credentials in a command argument.
+Use the installed `codex-security publish findings` command for preview and import. It owns source mapping and local persistence or Cloud publication. Select `--to local` for the local workbench SQLite database or `--to cloud` for Cloud. Do not implement another store or uploader or put credentials in a command argument.
-Cloud destinations currently support connected GitHub and GitHub Enterprise repositories, including custom Enterprise hostnames. Resolve the user's destination to its repository URL or Cloud repository ID; the command accepts either. Confirm that the repository is connected in the intended Cloud account and has an authorized environment. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
+For `--to cloud`, destinations currently support connected GitHub and GitHub Enterprise repositories, including custom Enterprise hostnames. Resolve the user's destination to its repository URL or Cloud repository ID; the command accepts either. Confirm that the repository is connected in the intended Cloud account and has an authorized environment. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
+
+## Choose the source report
+
+Prefer the provider's supported native JSON from its authenticated CLI, plugin, or API. Keep the original records and complete the requested pagination. A JSON summary or a different product's API response is not interchangeable with the documented report. Use SARIF or CSV only when the installed provider reader supports that profile and native JSON is unavailable or the user supplies that format. Do not convert a richer JSON report to SARIF for import.
+
+Use the same acquisition format for repeated imports. Check the provider's identity rules before switching formats: another format can create a separate record or replace a richer snapshot with less detail. Importing findings does not reconcile equivalent vulnerabilities across formats. `--format json` controls command output, not the input report format; readers detect their supported inputs.
+
+## Local imports
+
+For local storage, use a repository path with `--repository`. No Cloud login is required. Preview the same selected evidence before importing:
+
+```sh
+codex-security publish findings /path/to/selected-wiz-findings.json \
+ --to local --repository /path/to/project --provider wiz \
+ --source-key TENANT_ID/vulnerability-finding --dry-run --format json
+```
+
+Show the repository, source namespace, normalized evidence, and exclusions. After confirmation, repeat without `--dry-run`, adding `--yes`. Read the persisted result with `codex-security findings imported /path/to/project --format json`. The readback repository defaults to the current directory.
+
+Local records remain unassessed source evidence, separate from `findings list` and completed scans. Retain unknown metadata without inventing scanner revisions, assessment fields, or patch results. Report the created, updated, unchanged, and excluded counts. Repeated imports use the same repository/provider/source-key/source-ID identity; omitted records remain stored. When a source repository URL and local Git remotes are available, the source URL must match one of those remotes. Local import does not publish to Cloud or automatically investigate or patch findings.
## Wiz findings
@@ -23,7 +43,7 @@ For SAST, repository secrets, and IaC, retain the explicit `data.sastFindings.no
Keep raw source records unchanged in `source_data`. New raw occurrence IDs are prefixed `sast:`, `secret:`, or `iac:`; existing package IDs are unchanged. For CSV report conversion, use a reviewed mapping of the actual header names into the documented normalized JSONL profile, set `evidence.details.kind` and the verified `details.repository.url`, and use the same prefixed occurrence ID. The command does not parse CSV directly. Select source paths and line numbers explicitly in secret reports; the standard metadata query lacks them. Preserve rule/CWE, range/snippet, detector validation, and IaC comparison fields in the typed details described in the CLI docs. Preserve empty comparison strings. Do not invent missing IDs, severity, revisions, or locations, retrieve credential values, test credentials, or apply suggested fixes. Vendor status, AI verdict, secret validation, introduced commits, and logical IaC resources are evidence, not Codex assessment or proof of runtime deployment.
-For staging or another Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its API root before both preview and upload. If the Cloud page or user supplies its app URL, also set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL so the command can return a repository link. The UI setting does not change API routing or authentication. Use that deployment's login and an isolated state directory for tests. Verify `cloudApiUrl` and any `cloudUrl` in the preview against the intended deployment; the former is the API endpoint and the latter is the UI link. Saved retries are separated by deployment. The native scan setting `CODEX_SECURITY_CLOUD_PUBLISH_URL` does not route vendor imports. Never fall back to production when staging is unavailable.
+When publishing to staging or another Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its API root before both preview and upload. If the Cloud page or user supplies its app URL, also set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL so the command can return a repository link. The UI setting does not change API routing or authentication. Use that deployment's login and an isolated state directory for tests. Verify `cloudApiUrl` and any `cloudUrl` in the preview against the intended deployment; the former is the API endpoint and the latter is the UI link. Saved retries are separated by deployment. The native scan setting `CODEX_SECURITY_CLOUD_PUBLISH_URL` does not route vendor imports. Never fall back to production when staging is unavailable.
```sh
codex-security publish findings /path/to/selected-wiz-findings.json \
@@ -35,4 +55,4 @@ Show a concise preview of the Cloud API endpoint, account, repository, environme
After a lost response or retryable failure, repeat the same command with unchanged input and destination. The publisher resends only unacknowledged requests, using their saved IDs and bodies. Existing findings keep their original Cloud environment even if the repository’s default changes. After a repository reset, stop and show the error; require fresh discovery and confirmation before a new publication. Report partial failures and retain their explanations. Successful receipts and source-record readback confirm stored vendor evidence. They do not establish a Codex assessment or visibility in the shared Cloud Findings view. Include the returned `cloudUrl` as a clickable repository link when available; do not derive a UI URL from the API endpoint or invent a link.
-Read the result even when the process exits nonzero. `complete` exits 0, `partial` exits 1 for local exclusions or final item failures, and `interrupted` exits 2 while preserving acknowledged counts and receipts. Report `failures` by vendor source ID, distinguish `verified` from `unacknowledged`, and retain `savedSubmission` and the recovery error. A lost response does not mean that no findings reached Cloud. Preparation failures use `failed`; cancellation keeps the normal signal exit code. Terminal progress goes to stderr and does not replace the JSON result.
+Read the result even when the process exits nonzero. Local imports exit 1 when records were excluded; report their exclusion reasons alongside the stored counts. For Cloud publication, `complete` exits 0, `partial` exits 1 for exclusions or final item failures, and `interrupted` exits 2 while preserving acknowledged counts and receipts. Report `failures` by vendor source ID, distinguish `verified` from `unacknowledged`, and retain `savedSubmission` and the recovery error. A lost response does not mean that no findings reached Cloud. Preparation failures use `failed`; cancellation keeps the normal signal exit code. Terminal progress goes to stderr and does not replace the JSON result.
diff --git a/plugins/codex-security/skills/publish-findings/agents/openai.yaml b/plugins/codex-security/skills/publish-findings/agents/openai.yaml
index 56d284a1d..0bce48a54 100644
--- a/plugins/codex-security/skills/publish-findings/agents/openai.yaml
+++ b/plugins/codex-security/skills/publish-findings/agents/openai.yaml
@@ -1,6 +1,6 @@
interface:
display_name: "Publish Findings"
- short_description: "Preview and publish vendor findings to Cloud"
- default_prompt: "Use $publish-findings to preview selected vendor findings for my Cloud repository."
+ short_description: "Import vendor findings locally or to Cloud"
+ default_prompt: "Use $publish-findings to preview selected vendor findings for my repository and import them to my chosen destination."
policy:
allow_implicit_invocation: true
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index e19014efb..55561d768 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -659,6 +659,37 @@ use `ExternalPublicationOptions` for their supported formats. Both resolve the C
calling `publish()`. Imported evidence remains not assessed by Codex, and saved
requests and receipts support retries after interruption.
+Prefer each provider's supported native JSON for local and Cloud imports. Keep
+the same acquisition format for repeat imports: SARIF and CSV are compatibility
+options where supported, and changing formats can change record identities or
+replace richer evidence with less detail. See the
+[import guide](docs/cli.md#import-vendor-findings-locally) for format selection.
+
+Use `publish findings FILE --to local --repository PATH --provider wiz
+--source-key KEY` to store the same vendor evidence in the local workbench SQLite
+database. Preview with `--dry-run --format json`, then confirm interactively or
+use `--yes`. Read it with `findings imported [REPOSITORY] --format json`; the
+repository defaults to the current directory. No Cloud login or model call is
+needed. See [local imports](docs/cli.md#import-vendor-findings-locally).
+
+The SDK's `prepareLocalExternalImport(file, options)` returns a `preview` and a
+separate `import()` operation. `prepareNormalizedLocalImport(findings,
+options)` accepts already normalized evidence, and
+`listLocalExternalFindings({ repository })` reads the stored records. Imports
+remain unassessed source evidence, separate from native scan findings. Repeated
+imports update the same repository/provider/source-key/source-ID record; omitted
+records remain stored, and unknown evidence fields are not inferred.
+
+File imports forward repository references from the reader automatically. Direct
+normalized callers should provide additional known references in the third
+argument's `sourceRepositories` when they are absent from
+`evidence.details.repository.url`. For a known GitHub custom host, include
+`platform: "github"`, for example `{ sourceRepositories: [{ url:
+"https://git.example.test/example/project", platform: "github" }] }`. Named Wiz
+reports carry this platform in their repository inventory. If you export only the
+normalized finding rows to JSONL, supply that metadata separately; the original
+finding evidence does not include the surrounding inventory.
+
## Findings storage and deduplication
Saved-scan deduplication uses local SQLite directly:
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 43037ef6e..cac89b806 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -607,6 +607,9 @@ Import needs no model calls or authentication. `--dry-run` validates without
saving; `--output-dir` and `--archive-existing` control output. `scans rerun`
reimports the retained input.
+For vendor exports, use [local vendor import](#import-vendor-findings-locally)
+instead. That flow retains unassessed source evidence without creating a scan.
+
### Generate mock scan results
```bash
@@ -1192,6 +1195,60 @@ failure or incomplete/invalid output fails the scan. Deferred candidates remain
follow-up notes and do not fail the scan. An incompatible plugin stops the scan.
Supply the validation prompt again when rerunning.
+## Import vendor findings locally
+
+Prefer the provider's supported native JSON from its CLI, plugin, or API. Native
+reports can retain details omitted by SARIF. Use SARIF or CSV as compatibility
+inputs only for providers and report profiles that support them. A JSON API
+summary is not automatically a supported report; follow the provider's acquisition
+instructions and retain the original records. The readers detect supported input
+formats; `--format json` selects command output, not the input format.
+
+Keep the acquisition format consistent across imports. Depending on the provider,
+switching formats can create separate records for the same vulnerability or
+replace a richer evidence snapshot with less detail. The importer does not merge
+evidence or deduplicate equivalent vulnerabilities across different source IDs.
+
+Use the same vendor input and parser as Cloud publication, selecting a local
+repository path instead of a Cloud repository ID or URL:
+
+```bash
+codex-security publish findings selected-wiz.json \
+ --to local --repository ./project --provider wiz \
+ --source-key TENANT_ID/vulnerability-finding --dry-run --format json
+```
+
+Review the normalized evidence, repository, source namespace, and exclusions.
+Run the same command without `--dry-run` to confirm interactively, or add `--yes`
+after reviewing the preview. `--to` is required; there is no default destination.
+Local import uses the workbench SQLite database and requires no Cloud login,
+network connection, or model call. `--dry-run` does not write findings.
+
+Read the saved evidence with:
+
+```bash
+codex-security findings imported ./project --format json
+```
+
+The repository argument defaults to the current directory. Local imports are
+separate from the assessed findings shown by `findings list`: they remain
+`not_assessed`, retain the original vendor evidence, and do not create a completed
+scan or automatically validate or patch findings. Missing revisions, locations,
+and assessment fields stay unknown. When the source includes a repository URL and the local checkout has configured
+Git remotes, the URL must match one of those remotes; the importer does not
+substitute the checkout's current commit for an unknown scanner revision.
+
+Repeated imports update the same record by repository, provider, source key, and
+source finding ID. The result reports created, updated, and unchanged counts.
+Keep the source key stable across exports. Records omitted from a later selection
+remain stored; omission does not resolve or delete a finding. Excluded records
+are reported, and an import with exclusions exits with status 1. The same
+supported vendor formats and evidence requirements apply locally and in Cloud.
+
+`scan import --json` and `scan import --csv` remain separate commands for importing
+Codex Security's findings schema as a saved scan; they do not accept vendor
+exports.
+
## Publish findings to Cloud
### Import Wiz findings
@@ -1797,6 +1854,7 @@ least eight characters.
| `scans match --all` | Match completed scans across worktrees/clones. |
| `scans compare [BEFORE] [AFTER]` | Compare scans; defaults to latest two completed. |
| `findings list [REPOSITORY]` | List open findings. |
+| `findings imported [REPOSITORY]` | Read locally imported, unassessed vendor evidence. |
| `findings false-positive OCCURRENCE_ID --reason TEXT` | Dismiss a finding while the reason applies. |
Without an ID, `scans show` selects the latest completed scan, while `scans logs`
diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.ts
index 1b96af1c9..403a902be 100644
--- a/sdk/typescript/scripts/fixtures/package-consumer.ts
+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts
@@ -1,6 +1,7 @@
import {
CodexSecurity,
prepareExternalPublication,
+ prepareLocalExternalImport,
prepareNormalizedLocalImport,
listLocalExternalFindings,
type NormalizedLocalImportOptions,
@@ -383,3 +384,11 @@ export async function importLocalEvidence(
await prepared.import();
return listLocalExternalFindings({ repository: options.repository });
}
+
+export async function importLocalFile(
+ file: string,
+ options: ExternalPublicationOptions,
+): Promise<StoredExternalFinding[]> {
+ const prepared = await prepareLocalExternalImport(file, options);
+ return (await prepared.import()).findings;
+}
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 252a25d97..957509fdb 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -25,6 +25,8 @@ const distModules = [
"cloud-publish",
"external-findings",
"external-findings-local",
+ "external-findings-import",
+ "external-findings-read",
"scanner-import",
"external-findings-publish",
"external-import-contract",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 82a3eae02..6d4b3fb8b 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -110,6 +110,9 @@ import {
type ExternalPublicationProgress,
type ExternalPublicationResult,
} from "./external-findings-publish.js";
+import { prepareLocalExternalImport } from "./external-findings-import.js";
+import { listLocalExternalFindings } from "./external-findings-local.js";
+import type { ExternalFindings } from "./external-findings.js";
import {
publishPatchReview,
resolvePatchReviewPublisher,
@@ -1188,6 +1191,8 @@ interface CliDependencies {
publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select"> &
Partial<Pick<BulkScanPrompt, "checkbox">>;
externalPublicationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "confirm">;
+ prepareLocalExternalImport?: typeof prepareLocalExternalImport;
+ listLocalExternalFindings?: typeof listLocalExternalFindings;
checkScanPublication?: typeof checkScanPublication;
publishScan?: typeof publishScan;
deduplicateScan?: typeof deduplicateScanInternal;
@@ -2335,6 +2340,53 @@ export async function main(
);
},
});
+ findingFeedback.command("imported", {
+ description: "List imported vendor evidence for a local repository.",
+ mcp: false,
+ args: z.object({
+ repository: z
+ .string()
+ .optional()
+ .describe("Local repository to inspect (default: current directory)."),
+ }),
+ output: z.record(z.string(), z.unknown()).optional(),
+ async run({ args, format, error: incurError }) {
+ const controller = new AbortController();
+ const removeSignals = listenForAbort(dependencies, controller);
+ try {
+ const repository = resolveCliPath(
+ dependencies.currentDirectory(),
+ args.repository ?? ".",
+ );
+ const findings = await (
+ dependencies.listLocalExternalFindings ?? listLocalExternalFindings
+ )(
+ { repository },
+ { environment: dependencies.environment, signal: controller.signal },
+ );
+ return { repository, findings };
+ } catch (error) {
+ if (controller.signal.aborted) {
+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
+ if (
+ argv.includes("--full-output") &&
+ (format === "json" || format === "jsonl")
+ ) {
+ structuredError = true;
+ return incurError({
+ code: "FINDINGS_READ_FAILED",
+ message: diagnosticValue(error),
+ exitCode,
+ });
+ }
+ return;
+ }
+ throw error;
+ } finally {
+ removeSignals();
+ }
+ },
+ });
const scanHistory = Cli.create("scans", {
description: "Review saved scans (default: list).",
})
@@ -3479,8 +3531,8 @@ export async function main(
});
publication.command("findings", {
description:
- "Preview and import selected Wiz repository findings to Cloud.",
- hint: "Supply a package vulnerability JSON report, named SAST/repository-secret/IaC JSON collections with repository metadata, or normalized JSONL. Gzip is supported; CSV, scan events, workload secrets, and cloud configuration exports are not. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to cloud --repository https://github.com/example/project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
+ "Preview and import selected Wiz repository findings locally or to Cloud.",
+ hint: "Supply a package vulnerability JSON report, named SAST/repository-secret/IaC JSON collections with repository metadata, or normalized JSONL. Gzip is supported; CSV, scan events, workload secrets, and cloud configuration exports are not. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
destructive: true,
mcp: false,
args: z.object({
@@ -3491,9 +3543,9 @@ export async function main(
),
}),
options: z.object({
- to: z.literal("cloud").describe("Publication destination."),
+ to: z.enum(["cloud", "local"]).describe("Import destination (required)."),
repository: optionValue("--repository").describe(
- "Authorized Cloud repository ID or repository URL copied from Cloud.",
+ "Local repository path for --to local; authorized repository ID or URL for --to cloud.",
),
provider: z
.literal("wiz")
@@ -3505,7 +3557,7 @@ export async function main(
.boolean()
.default(false)
.describe(
- "Read and preview the destination and findings without uploading.",
+ "Read and preview the destination and findings without storing them.",
),
yes: z
.boolean()
@@ -3540,6 +3592,29 @@ export async function main(
format === "toon" &&
!formatExplicit &&
!argv.some((argument) => OUTPUT_OPTION.test(argument));
+ const confirmImport = async (
+ preview: ExternalFindings,
+ showPreview: () => void,
+ ): Promise<boolean> => {
+ if (options.yes) return true;
+ const prompt =
+ dependencies.externalPublicationPrompt ??
+ createTerminalPrompt(errorOutput);
+ const local = options.to === "local";
+ if (!prompt.isInteractive())
+ throw new CodexSecurityError(
+ `${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`,
+ );
+ if (structured) showPreview();
+ const action = local
+ ? `Store these ${preview.findings.length} findings locally`
+ : `Publish these ${preview.findings.length} findings`;
+ return prompt.confirm(
+ `${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`,
+ false,
+ controller.signal,
+ );
+ };
let lastProgress = "";
const onProgress = (event: ExternalPublicationProgress) => {
if (errorOutput.isTTY !== true) return;
@@ -3562,6 +3637,58 @@ export async function main(
);
};
try {
+ if (options.to === "local") {
+ const prepared = await (
+ dependencies.prepareLocalExternalImport ??
+ prepareLocalExternalImport
+ )(
+ resolveCliPath(dependencies.currentDirectory(), args.file),
+ {
+ ...options,
+ repository: resolveCliPath(
+ dependencies.currentDirectory(),
+ options.repository,
+ ),
+ },
+ {
+ environment: dependencies.environment,
+ signal: controller.signal,
+ },
+ );
+ const { preview } = prepared;
+ const showPreview = () => {
+ writeDiagnostic(
+ `Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`,
+ );
+ for (const excluded of preview.excluded)
+ writeDiagnostic(
+ `Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,
+ );
+ for (const finding of preview.findings.slice(0, 5))
+ writeDiagnostic(
+ ` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,
+ );
+ writeDiagnostic(
+ `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`,
+ );
+ };
+ if (!structured) showPreview();
+ if (options.dryRun) {
+ if (humanSummary)
+ renderedOutput = "Dry run complete. No findings stored.\n";
+ return { ...preview, dryRun: true };
+ }
+ if (!(await confirmImport(preview, showPreview))) {
+ if (humanSummary) renderedOutput = "No findings stored.\n";
+ return { imported: false, preview };
+ }
+ const result = await prepared.import();
+ if (result.excluded.length > 0) exitCode = 1;
+ const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
+ if (humanSummary) renderedOutput = summary;
+ else if (!structured) writeDiagnostic(summary);
+ return { ...result };
+ }
const prepared = await prepareExternalPublication(
resolveCliPath(dependencies.currentDirectory(), args.file),
options,
@@ -3615,25 +3742,9 @@ export async function main(
renderedOutput = "Dry run complete. No findings uploaded.\n";
return { ...preview, dryRun: true };
}
- if (!options.yes) {
- const prompt =
- dependencies.externalPublicationPrompt ??
- createTerminalPrompt(errorOutput);
- if (!prompt.isInteractive())
- throw new CodexSecurityError(
- "Publication needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.",
- );
- if (structured) showPreview();
- if (
- !(await prompt.confirm(
- `Publish these ${preview.findings.length} findings${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`,
- false,
- controller.signal,
- ))
- ) {
- if (humanSummary) renderedOutput = "No findings published.\n";
- return { published: false, preview };
- }
+ if (!(await confirmImport(preview, showPreview))) {
+ if (humanSummary) renderedOutput = "No findings published.\n";
+ return { published: false, preview };
}
const result = await prepared.publish();
if (result.status === "partial") exitCode = 1;
diff --git a/sdk/typescript/src/external-findings-import.ts b/sdk/typescript/src/external-findings-import.ts
new file mode 100644
index 000000000..8fe8cc8ad
--- /dev/null
+++ b/sdk/typescript/src/external-findings-import.ts
@@ -0,0 +1,27 @@
+import type { ExternalPublicationOptions } from "./external-findings-publish.js";
+import { readExternalFindings } from "./external-findings-read.js";
+import {
+ prepareNormalizedLocalImport,
+ type LocalExternalImportDependencies,
+} from "./external-findings-local.js";
+import { abortable } from "./targets.js";
+
+/** Read an installed vendor format and prepare it for the local workbench. */
+export async function prepareLocalExternalImport(
+ path: string,
+ options: ExternalPublicationOptions,
+ dependencies: LocalExternalImportDependencies = {},
+) {
+ dependencies.signal?.throwIfAborted();
+ const parsed = await abortable(
+ () => readExternalFindings(path, options),
+ dependencies.signal,
+ );
+ return prepareNormalizedLocalImport(parsed.findings, options, {
+ ...dependencies,
+ sourceRepositories: [
+ ...(dependencies.sourceRepositories ?? []),
+ ...(parsed.sourceRepositories ?? []),
+ ],
+ });
+}
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index ce64a0f52..a7ad767ab 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -24,7 +24,10 @@ import {
createWindowsOutputDirectory,
validatePreparedOutputDir,
} from "./runtime.js";
-import { readVendorFindingsForPublication } from "./wiz-findings.js";
+import {
+ readExternalFindings,
+ type ExternalFindingsReaderOptions,
+} from "./external-findings-read.js";
import type {
ExternalFindings,
ExternalPublicationInput,
@@ -56,7 +59,7 @@ export interface NormalizedExternalPublicationOptions {
/** File readers accept the vendor formats installed in this SDK. */
export interface ExternalPublicationOptions extends NormalizedExternalPublicationOptions {
- provider: "wiz";
+ provider: ExternalFindingsReaderOptions["provider"];
}
/** Optional transport, account, cancellation, and progress hooks. */
@@ -339,8 +342,14 @@ export async function prepareExternalPublication(
options: ExternalPublicationOptions,
dependencies: ExternalPublicationDependencies = {},
): Promise<PreparedExternalPublication> {
- const input = await readVendorFindingsForPublication(path);
- return preparePublicationInput(input, options, dependencies);
+ const parsed = await readExternalFindings(path, options);
+ return parsed.publication
+ ? preparePublicationInput(parsed.publication, options, dependencies)
+ : prepareNormalizedExternalPublication(
+ parsed.findings,
+ options,
+ dependencies,
+ );
}
/** Prepare normalized provider evidence without reading a vendor export. */
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
new file mode 100644
index 000000000..774fed4e0
--- /dev/null
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -0,0 +1,64 @@
+import type {
+ ExternalFindings,
+ ExternalPublicationInput,
+ ExternalSourceRepository,
+} from "./external-findings.js";
+import { isGitHubCloudHost } from "./git-remote.js";
+import { isRecord } from "./record.js";
+import { readVendorFindingsForPublication } from "./wiz-findings.js";
+
+/** File readers available in this SDK, shared by local and Cloud imports. */
+export interface ExternalFindingsReaderOptions {
+ provider: "wiz";
+}
+
+/** @internal Shared parser output, including immutable Cloud retry projections. */
+export interface ReadExternalFindings {
+ findings: ExternalFindings;
+ /** Preserve previous Wiz projections when resuming immutable Cloud requests. */
+ publication?: ExternalPublicationInput;
+ sourceRepositories?: ExternalSourceRepository[];
+}
+
+/** @internal Read vendor evidence for the local and Cloud import entrypoints. */
+export async function readExternalFindings(
+ path: string,
+ _options: ExternalFindingsReaderOptions,
+): Promise<ReadExternalFindings> {
+ const publication = await readVendorFindingsForPublication(path);
+ // Raw package exports keep repository-branch URLs in retained source data.
+ const sourceRepositories = publication.current.findings.flatMap(
+ ({ evidence }) => {
+ const asset = evidence.source_data?.["vulnerableAsset"];
+ if (!isRecord(asset) || typeof asset["cloudProviderURL"] !== "string")
+ return [];
+ const url = URL.parse(asset["cloudProviderURL"]);
+ if (!url) return [];
+ const github =
+ asset["nativeType"] === "github#repositoryBranch" ||
+ (asset["type"] === "REPOSITORY_BRANCH" &&
+ isGitHubCloudHost(url.hostname));
+ if (!github)
+ return asset["type"] === "REPOSITORY_BRANCH"
+ ? [{ url: asset["cloudProviderURL"] }]
+ : [];
+ const [, owner, repository] = url.pathname.split("/");
+ return owner && repository
+ ? [
+ {
+ url: `${url.origin}/${owner}/${repository}`,
+ platform: "github" as const,
+ },
+ ]
+ : [];
+ },
+ );
+ return {
+ findings: publication.current,
+ publication,
+ sourceRepositories: [
+ ...publication.sourceRepositories,
+ ...sourceRepositories,
+ ],
+ };
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 9fd0f8bbe..077042a27 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -310,3 +310,5 @@ export type {
ValidateRecordsOptions,
ValidationReviewRequest,
} from "./validation-records.js";
+
+export { prepareLocalExternalImport } from "./external-findings-import.js";
diff --git a/sdk/typescript/src/scanner-import.ts b/sdk/typescript/src/scanner-import.ts
index 28db27f41..9fd7d9fd1 100644
--- a/sdk/typescript/src/scanner-import.ts
+++ b/sdk/typescript/src/scanner-import.ts
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
import { gunzip } from "node:zlib";
import { CodexSecurityError, errorMessage } from "./errors.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
+import { isRecord } from "./record.js";
export function record(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value))
@@ -90,6 +91,86 @@ export async function readScannerJson(path: string): Promise<unknown> {
}
}
+/** Empty reference containers and property-bag metadata do not externalize data. */
+export function hasSarifExternalPropertyReferences(value: unknown): boolean {
+ if (value == null) return false;
+ return Object.entries(
+ record(value, "SARIF external property references"),
+ ).some(
+ ([key, references]) =>
+ key !== "properties" &&
+ (!Array.isArray(references) || references.length > 0),
+ );
+}
+
+const sarifArtifactLocationFields = new Set([
+ "artifactLocation",
+ "analysisTarget",
+ "executableLocation",
+ "workingDirectory",
+ "stdin",
+ "stdout",
+ "stderr",
+ "stdoutStderr",
+ "mappedTo",
+ "displayBase",
+]);
+
+/** Keep original artifact indexes; omit only inventory unrelated to this finding. */
+export function sarifRunContextForResult(
+ runContext: Record<string, unknown>,
+ ...selectedEvidence: unknown[]
+): Record<string, unknown> {
+ const { artifacts, ...context } = runContext;
+ if (!Array.isArray(artifacts) || artifacts.length === 0) return runContext;
+ const locations: Record<string, unknown>[] = [];
+ let hasArtifactLink = false;
+ function visit(value: unknown): void {
+ if (typeof value === "string") {
+ // SARIF message links can refer to an artifact without an artifactLocation.
+ if (/sarif:/iu.test(value)) hasArtifactLink = true;
+ } else if (Array.isArray(value)) value.forEach(visit);
+ else if (isRecord(value))
+ for (const [key, child] of Object.entries(value)) {
+ if (key === "properties") continue;
+ if (sarifArtifactLocationFields.has(key) && isRecord(child))
+ locations.push(child);
+ if (
+ ["locations", "responseFiles", "analysisToolLogFiles"].includes(
+ key,
+ ) &&
+ Array.isArray(child)
+ )
+ locations.push(...child.filter(isRecord));
+ if (key === "originalUriBaseIds" && isRecord(child))
+ locations.push(...Object.values(child).filter(isRecord));
+ visit(child);
+ }
+ }
+ visit([context, ...selectedEvidence]);
+ if (hasArtifactLink) return runContext;
+ const unresolvedUri = /[%:\\]|(?:^|\/)\.\.?(?:\/|$)/u;
+ for (const location of locations) {
+ if (typeof location["index"] === "number" && location["index"] >= 0)
+ return runContext;
+ if (typeof location["uri"] !== "string") continue;
+ for (const artifact of artifacts) {
+ if (!isRecord(artifact) || !isRecord(artifact["location"])) continue;
+ const candidate = artifact["location"];
+ // Keep URI spellings that need resolution; evidence is never rewritten.
+ if (
+ location["uriBaseId"] !== candidate["uriBaseId"] ||
+ unresolvedUri.test(location["uri"]) ||
+ (typeof candidate["uri"] === "string" &&
+ unresolvedUri.test(candidate["uri"])) ||
+ location["uri"] === candidate["uri"]
+ )
+ return runContext;
+ }
+ }
+ return context;
+}
+
/** Exclude every colliding record: choosing the first could overwrite another occurrence. */
export function normalizeRecords<T>(
records: T[],
diff --git a/sdk/typescript/src/wiz-findings.ts b/sdk/typescript/src/wiz-findings.ts
index 0fd16fd1a..177c81ec7 100644
--- a/sdk/typescript/src/wiz-findings.ts
+++ b/sdk/typescript/src/wiz-findings.ts
@@ -7,6 +7,7 @@ import { parseJsonOrJsonl, readScannerText } from "./scanner-import.js";
import type {
ExternalFinding as VendorFinding,
ExternalFindings as VendorFindings,
+ ExternalSourceRepository,
} from "./external-findings.js";
export type {
@@ -451,6 +452,7 @@ export async function readVendorFindingsForPublication(path: string): Promise<{
legacy: VendorFindings;
currentIdentity: unknown[];
legacyIdentity: unknown[];
+ sourceRepositories: ExternalSourceRepository[];
}> {
const input = await readFindingInput(path);
const normalized = new WeakSet<VendorFinding>();
@@ -486,6 +488,18 @@ export async function readVendorFindingsForPublication(path: string): Promise<{
legacy,
currentIdentity: identity(current),
legacyIdentity: identity(legacy),
+ sourceRepositories: current.findings.flatMap(({ evidence }) => {
+ const repository = evidence.details?.repository;
+ const inventory = input.repositories.get(repository?.id ?? "");
+ // Forward provenance only for selected findings that match the inventory.
+ // Use the emitted spelling so typed evidence and reader hints share it.
+ return repository &&
+ inventory?.platform === "GITHUB" &&
+ inventoryRepositoryUrlKey(repository.url, inventory.platform) ===
+ inventoryRepositoryUrlKey(inventory.url, inventory.platform)
+ ? [{ url: repository.url, platform: "github" as const }]
+ : [];
+ }),
};
}
diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.ts
new file mode 100644
index 000000000..87dd448e1
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts
@@ -0,0 +1,347 @@
+import { execFileSync } from "node:child_process";
+import {
+ mkdir,
+ mkdtemp,
+ readdir,
+ realpath,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, expect, test } from "bun:test";
+import { main } from "../src/cli.js";
+import { dependencies, FakeSignals } from "./cli-fixtures.js";
+import { createCliTest } from "./support/cli-run.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
+async function fixture() {
+ const root = await realpath(
+ await mkdtemp(join(tmpdir(), "local-import-cli-")),
+ );
+ roots.push(root);
+ const repository = join(root, "example project");
+ await mkdir(repository);
+ execFileSync("git", ["init", "--quiet", repository]);
+ execFileSync("git", [
+ "-C",
+ repository,
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/example/project.git",
+ ]);
+ const file = join(root, "selected.json");
+ const record = {
+ id: "vendor-finding-1",
+ name: "CVE-2026-0001",
+ detailedName: "example-package",
+ vendorSeverity: "HIGH",
+ version: "1.2.3",
+ fixedVersion: "1.2.4",
+ locationPath: "/package-lock.json",
+ vulnerableAsset: {
+ id: "repository-branch-1",
+ nativeType: "github#repositoryBranch",
+ name: "example/project/main",
+ cloudProviderURL: "https://github.com/example/project/tree/main",
+ },
+ };
+ await writeFile(file, JSON.stringify([record]));
+ const state = join(root, "state");
+ const deps = {
+ ...dependencies({
+ currentDirectory: root,
+ environment: {
+ ...process.env,
+ HOME: join(root, "home"),
+ USERPROFILE: join(root, "home"),
+ CODEX_HOME: join(root, "codex"),
+ CODEX_SECURITY_STATE_DIR: state,
+ CODEX_SECURITY_CLOUD_BASE_URL: "invalid-cloud-url",
+ },
+ onConfig: () => {
+ throw new Error("Local imports must not initialize a model client");
+ },
+ onCodex: () => {
+ throw new Error("Local imports must not invoke Codex or sign in");
+ },
+ }),
+ cloudFetch: async () => {
+ throw new Error("Local imports must not call Cloud");
+ },
+ };
+ const command = [
+ "publish",
+ "findings",
+ "selected.json",
+ "--to",
+ "local",
+ "--repository",
+ "example project",
+ "--provider",
+ "wiz",
+ "--source-key",
+ "tenant-example/vulnerability-finding",
+ "--format",
+ "json",
+ ];
+ return { root, repository, file, record, state, deps, command };
+}
+
+test("local preview and declined confirmation do not create database state or use Cloud", async () => {
+ const f = await fixture();
+ const preview = createCliTest(main);
+ expect(await preview.runCli([...f.command, "--dry-run"], f.deps)).toBe(0);
+ expect(preview.stderr.text()).toBe("");
+ expect(JSON.parse(preview.stdout.text())).toMatchObject({
+ dryRun: true,
+ repository: f.repository,
+ source: {
+ provider: "wiz",
+ source_key: "tenant-example/vulnerability-finding",
+ },
+ read: 1,
+ findings: [
+ { source_finding_id: f.record.id, evidence: { source_data: f.record } },
+ ],
+ });
+ const declined = createCliTest(main);
+ expect(
+ await declined.runCli(f.command, {
+ ...f.deps,
+ externalPublicationPrompt: {
+ isInteractive: () => true,
+ confirm: async (question, defaultValue) => {
+ expect(question).toContain("Store these 1 findings locally");
+ expect(defaultValue).toBe(false);
+ expect(declined.stderr.text()).toContain(f.repository);
+ expect(declined.stderr.text()).toContain(f.record.id);
+ expect(declined.stderr.text()).toContain("not assessed by Codex");
+ return false;
+ },
+ },
+ }),
+ ).toBe(0);
+ expect(JSON.parse(declined.stdout.text()).imported).toBe(false);
+ const headless = createCliTest(main);
+ expect(await headless.runCli(f.command, f.deps)).toBe(2);
+ expect(headless.stderr.text()).toContain("needs confirmation");
+ expect(await readdir(f.state).catch(() => [])).toEqual([]);
+});
+
+test("CLI imports a vendor report, reads local evidence, and updates the same source record", async () => {
+ const f = await fixture();
+ const first = createCliTest(main);
+ expect(await first.runCli([...f.command, "--yes"], f.deps)).toBe(0);
+ const imported = JSON.parse(first.stdout.text());
+ expect(imported.counts).toEqual({ created: 1, updated: 0, unchanged: 0 });
+ expect(imported.findings[0]).toMatchObject({
+ repository: f.repository,
+ provider: "wiz",
+ sourceFindingId: f.record.id,
+ version: 1,
+ assessment: { state: "not_assessed" },
+ evidence: { severity: "high", source_data: f.record },
+ });
+ const repeated = createCliTest(main);
+ expect(await repeated.runCli([...f.command, "--yes"], f.deps)).toBe(0);
+ expect(JSON.parse(repeated.stdout.text()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 1,
+ });
+ await writeFile(
+ f.file,
+ JSON.stringify([{ ...f.record, vendorSeverity: "CRITICAL" }]),
+ );
+ const updated = createCliTest(main);
+ expect(await updated.runCli([...f.command, "--yes"], f.deps)).toBe(0);
+ expect(JSON.parse(updated.stdout.text()).counts).toEqual({
+ created: 0,
+ updated: 1,
+ unchanged: 0,
+ });
+ const readback = createCliTest(main);
+ expect(
+ await readback.runCli(["findings", "imported", "--format", "json"], {
+ ...f.deps,
+ currentDirectory: () => f.repository,
+ }),
+ ).toBe(0);
+ const result = JSON.parse(readback.stdout.text());
+ expect(result.repository).toBe(f.repository);
+ expect(result.findings).toHaveLength(1);
+ expect(result.findings[0]).toMatchObject({
+ id: imported.findings[0].id,
+ version: 2,
+ assessment: { state: "not_assessed" },
+ evidence: { severity: "critical" },
+ });
+ expect(result.findings[0].evidence.code_revision).toBeNull();
+ expect(result.findings[0].evidence.confidence).toBeUndefined();
+});
+
+test("local import confirms exclusions and returns partial status after storing ready records", async () => {
+ const f = await fixture();
+ await writeFile(
+ f.file,
+ JSON.stringify([
+ f.record,
+ { ...f.record, id: "unsupported", vendorSeverity: "not-a-severity" },
+ ]),
+ );
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(f.command, {
+ ...f.deps,
+ externalPublicationPrompt: {
+ isInteractive: () => true,
+ confirm: async (question) => {
+ expect(question).toContain("skip 1 excluded records");
+ expect(cli.stderr.text()).toContain("Excluded: 1");
+ return true;
+ },
+ },
+ }),
+ ).toBe(1);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ read: 2,
+ ready: 1,
+ counts: { created: 1 },
+ });
+});
+
+test.each(["SIGINT", "SIGTERM"] as const)(
+ "local import forwards %s cancellation without storing findings",
+ async (signalName) => {
+ const signals = new FakeSignals();
+ const deps = dependencies({
+ signals,
+ currentDirectory: resolve("workspace"),
+ });
+ const cli = createCliTest(main);
+ let imports = 0;
+ deps.prepareLocalExternalImport = async (file, options, settings) => {
+ expect(file).toBe(resolve("workspace", "selected.json"));
+ expect(options.repository).toBe(resolve("workspace", "project"));
+ expect(settings?.environment).toBe(deps.environment);
+ signals.emit(signalName);
+ settings?.signal?.throwIfAborted();
+ imports += 1;
+ throw new Error("Import should have been canceled");
+ };
+ expect(
+ await cli.runCli(
+ [
+ "publish",
+ "findings",
+ "selected.json",
+ "--to",
+ "local",
+ "--repository",
+ "project",
+ "--provider",
+ "wiz",
+ "--source-key",
+ "tenant-example/findings",
+ "--yes",
+ "--format",
+ "json",
+ ],
+ deps,
+ ),
+ ).toBe(signalName === "SIGINT" ? 130 : 143);
+ expect(imports).toBe(0);
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ },
+);
+
+test("imported readback resolves its repository argument and supports structured output", async () => {
+ const deps = dependencies({ currentDirectory: resolve("workspace") });
+ deps.listLocalExternalFindings = async ({ repository }, settings) => {
+ expect(repository).toBe(resolve("workspace", "project"));
+ expect(settings?.environment).toBe(deps.environment);
+ expect(settings?.signal?.aborted).toBe(false);
+ return [];
+ };
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(
+ ["findings", "imported", "project", "--format", "json"],
+ deps,
+ ),
+ ).toBe(0);
+ expect(JSON.parse(cli.stdout.text())).toEqual({
+ repository: resolve("workspace", "project"),
+ findings: [],
+ });
+});
+
+for (const format of ["json", "jsonl"] as const) {
+ test.each(["SIGINT", "SIGTERM"] as const)(
+ `imported readback reports %s cancellation in ${format} full output`,
+ async (signalName) => {
+ const signals = new FakeSignals();
+ const deps = dependencies({
+ signals,
+ currentDirectory: resolve("workspace"),
+ });
+ deps.listLocalExternalFindings = async (_selection, settings) => {
+ expect(settings?.signal).toBeDefined();
+ signals.emit(signalName);
+ settings!.signal!.throwIfAborted();
+ throw new Error("Readback should have been canceled");
+ };
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(
+ ["findings", "imported", "--format", format, "--full-output"],
+ deps,
+ ),
+ ).toBe(signalName === "SIGINT" ? 130 : 143);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ ok: false,
+ error: { code: "FINDINGS_READ_FAILED", message: signalName },
+ });
+ expect(cli.stderr.text()).toBe("");
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ },
+ );
+}
+
+test("finding import requires an explicit destination and advertises local repository paths", async () => {
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(["publish", "findings", "--help"], dependencies()),
+ ).toBe(0);
+ expect(cli.stdout.text()).toContain("local");
+ expect(cli.stdout.text()).toContain("Local repository path");
+ const missing = createCliTest(main);
+ expect(
+ await missing.runCli(
+ [
+ "publish",
+ "findings",
+ "selected.json",
+ "--repository",
+ "project",
+ "--provider",
+ "wiz",
+ "--source-key",
+ "tenant-example/findings",
+ "--dry-run",
+ ],
+ dependencies(),
+ ),
+ ).not.toBe(0);
+ expect(missing.stderr.text()).toContain("to");
+});
diff --git a/sdk/typescript/tests-ts/external-findings-import.test.ts b/sdk/typescript/tests-ts/external-findings-import.test.ts
new file mode 100644
index 000000000..4218cfa88
--- /dev/null
+++ b/sdk/typescript/tests-ts/external-findings-import.test.ts
@@ -0,0 +1,491 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { gzipSync } from "node:zlib";
+import { access, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, test } from "bun:test";
+import { prepareLocalExternalImport } from "../src/external-findings-import.js";
+import { listLocalExternalFindings } from "../src/external-findings-local.js";
+import { readVendorFindings } from "../src/wiz-findings.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+
+test("cancels preparation while the source file read is pending", async () => {
+ const fixture = await localFindingsFixture();
+ try {
+ const file = join(fixture.root, "wiz.json");
+ const module = new URL(
+ "../src/external-findings-import.ts",
+ import.meta.url,
+ ).href;
+ const mocks = new URL("./support/module-mocks.ts", import.meta.url).href;
+ const script = `
+ import { strictEqual } from "node:assert/strict";
+ import * as fs from "node:fs/promises";
+ import { setImmediate } from "node:timers/promises";
+ import { mockFs } from ${JSON.stringify(mocks)};
+ const file = ${JSON.stringify(file)};
+ const originalReadFile = fs.readFile;
+ let enteredRead, releaseRead;
+ const entered = new Promise((resolve) => { enteredRead = resolve; });
+ const read = new Promise((resolve) => { releaseRead = resolve; });
+ mockFs(() => ({
+ readFile: (path, ...args) => {
+ if (path !== file) return originalReadFile(path, ...args);
+ enteredRead();
+ return read;
+ },
+ }));
+ const { prepareLocalExternalImport } = await import(${JSON.stringify(module)});
+ const controller = new AbortController();
+ const reason = new Error("Synthetic import cancellation");
+ let outcome;
+ const preparing = prepareLocalExternalImport(
+ file,
+ ${JSON.stringify({ repository: fixture.repository, provider: "wiz", sourceKey: "example-project/main" })},
+ { signal: controller.signal },
+ ).then(
+ () => { outcome = "fulfilled"; },
+ (error) => { outcome = error; },
+ );
+ await entered;
+ controller.abort(reason);
+ await setImmediate();
+ try {
+ strictEqual(outcome, reason);
+ } finally {
+ releaseRead(Buffer.from("[]"));
+ await preparing;
+ }
+ console.log("CANCELLED");
+ `;
+ const result = spawnSync(process.execPath, ["-e", script], {
+ encoding: "utf8",
+ env: fixture.environment,
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout.trim()).toBe("CANCELLED");
+ await expect(access(fixture.stateDirectory)).rejects.toThrow();
+ } finally {
+ await fixture.dispose();
+ }
+});
+
+test("Wiz JSON imports retain parsed evidence through SQLite readback and updates", async () => {
+ const fixture = await localFindingsFixture();
+ try {
+ const file = join(fixture.root, "wiz.json");
+ const record = {
+ id: "package-occurrence",
+ name: "CVE-2026-0001",
+ detailedName: "example-package",
+ version: "1.0.0",
+ severity: "UNKNOWN",
+ vulnerableAsset: { id: "source-branch", type: "REPOSITORY_BRANCH" },
+ sourceMetadata: { retained: true },
+ };
+ await writeFile(file, JSON.stringify([record]));
+ const options = {
+ repository: fixture.repository,
+ provider: "wiz" as const,
+ sourceKey: "example-project/main",
+ };
+ const dependencies = { environment: fixture.environment };
+ const parsed = await readVendorFindings(file);
+ const prepared = await prepareLocalExternalImport(
+ file,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview.findings).toEqual(parsed.findings);
+ await expect(
+ access(join(fixture.stateDirectory, "workbench.sqlite3")),
+ ).rejects.toThrow();
+ const first = await prepared.import();
+ expect(first.counts).toEqual({ created: 1, updated: 0, unchanged: 0 });
+ const stored = await listLocalExternalFindings(
+ { repository: fixture.repository },
+ dependencies,
+ );
+ expect(stored).toEqual(first.findings);
+ expect(stored[0]).toMatchObject({
+ sourceFindingId: "package-occurrence",
+ assessment: { state: "not_assessed" },
+ version: 1,
+ evidence: {
+ severity: "unknown",
+ locations: [],
+ code_revision: null,
+ source_data: record,
+ },
+ });
+ expect(stored[0]!.evidence).toEqual(parsed.findings[0]!.evidence);
+ expect(
+ (
+ await (
+ await prepareLocalExternalImport(file, options, dependencies)
+ ).import()
+ ).counts,
+ ).toEqual({ created: 0, updated: 0, unchanged: 1 });
+ await writeFile(
+ file,
+ JSON.stringify([{ ...record, fixedVersion: "1.0.1" }]),
+ );
+ const changed = await (
+ await prepareLocalExternalImport(file, options, dependencies)
+ ).import();
+ expect(changed.counts).toEqual({ created: 0, updated: 1, unchanged: 0 });
+ expect(changed.findings[0]).toMatchObject({
+ id: stored[0]!.id,
+ version: 2,
+ });
+ expect(
+ await listLocalExternalFindings(
+ { repository: fixture.repository },
+ dependencies,
+ ),
+ ).toEqual(changed.findings);
+ } finally {
+ await fixture.dispose();
+ }
+});
+
+test.each([
+ ["raw JSON", "github#repositoryBranch", "github.com"],
+ ["normalized JSONL", "github#repositoryBranch", "github.com"],
+ ["raw JSON", "REPOSITORY_BRANCH", "github.com"],
+ ["normalized JSONL", "REPOSITORY_BRANCH", "github.com"],
+ ["raw JSON", "github#repositoryBranch", "git.example.test"],
+ ["normalized JSONL", "github#repositoryBranch", "git.example.test"],
+ ["gzip JSON", "github#repositoryBranch", "git.example.test"],
+ ["gzip normalized JSONL", "github#repositoryBranch", "git.example.test"],
+ ["named GraphQL JSON", "github#repositoryBranch", "git.example.test"],
+] as const)(
+ "Wiz package %s (%s on %s) binds repository-branch URLs before storing evidence",
+ async (format, assetType, host) => {
+ const fixture = await localFindingsFixture({
+ remote: `git@${host}:example/project.git`,
+ });
+ try {
+ const file = join(fixture.root, "wiz.json");
+ const record = {
+ id: "package-occurrence",
+ name: "CVE-2026-0001",
+ detailedName: "example-package",
+ severity: "HIGH",
+ vulnerableAsset: {
+ id: "source-branch",
+ ...(assetType === "github#repositoryBranch"
+ ? { nativeType: assetType }
+ : { type: assetType }),
+ cloudProviderURL: `https://${host}/example/other/tree/main`,
+ },
+ };
+ const options = {
+ repository: fixture.repository,
+ provider: "wiz" as const,
+ sourceKey: "example-project/main",
+ };
+ const dependencies = { environment: fixture.environment };
+ async function writeSelection() {
+ const contents = JSON.stringify(
+ format === "named GraphQL JSON"
+ ? { data: { vulnerabilityFindings: { nodes: [record] } } }
+ : [record],
+ );
+ await writeFile(
+ file,
+ format === "gzip JSON" ? gzipSync(contents) : contents,
+ );
+ const parsed = await readVendorFindings(file);
+ if (format.includes("normalized JSONL")) {
+ const normalized = parsed.findings
+ .map((finding) => JSON.stringify(finding))
+ .join("\n");
+ await writeFile(
+ file,
+ format.startsWith("gzip") ? gzipSync(normalized) : normalized,
+ );
+ }
+ return parsed;
+ }
+ await writeSelection();
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ await expect(
+ access(join(fixture.stateDirectory, "workbench.sqlite3")),
+ ).rejects.toThrow();
+
+ record.vulnerableAsset.cloudProviderURL = `https://${host}/Example/Project/tree/feature/imports`;
+ const parsed = await writeSelection();
+ const prepared = await prepareLocalExternalImport(
+ file,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview.findings).toEqual(parsed.findings);
+ const imported = await prepared.import();
+ expect(imported.counts.created).toBe(1);
+ const [stored] = await listLocalExternalFindings(options, dependencies);
+ expect(stored!.evidence).toEqual(parsed.findings[0]!.evidence);
+ expect(stored!.evidence.source_data).toEqual(record);
+ expect(stored!.evidence.code_revision).toBeNull();
+ } finally {
+ await fixture.dispose();
+ }
+ },
+);
+
+test.each(["raw JSON", "normalized JSONL"])(
+ "Wiz package %s retains generic repository URLs without guessing their platform",
+ async (format) => {
+ const fixture = await localFindingsFixture({
+ remote: "[email protected]:example/group/project.git",
+ });
+ try {
+ const file = join(fixture.root, "wiz.json");
+ const record = {
+ id: "package-occurrence",
+ name: "CVE-2026-0001",
+ detailedName: "example-package",
+ severity: "HIGH",
+ vulnerableAsset: {
+ id: "source-branch",
+ type: "REPOSITORY_BRANCH",
+ cloudProviderURL: "",
+ },
+ };
+ const options = {
+ repository: fixture.repository,
+ provider: "wiz" as const,
+ sourceKey: "example-project/main",
+ };
+ const dependencies = { environment: fixture.environment };
+ async function writeSelection(url: string) {
+ record.vulnerableAsset.cloudProviderURL = url;
+ await writeFile(file, JSON.stringify([record]));
+ const parsed = await readVendorFindings(file);
+ if (format === "normalized JSONL")
+ await writeFile(
+ file,
+ parsed.findings
+ .map((finding) => JSON.stringify(finding))
+ .join("\n"),
+ );
+ return parsed;
+ }
+ for (const path of [
+ "example/group/other",
+ "Example/Group/Project",
+ "example/group/project/tree/main",
+ ]) {
+ await writeSelection(`https://git.example.test/${path}`);
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ await expect(
+ access(join(fixture.stateDirectory, "workbench.sqlite3")),
+ ).rejects.toThrow();
+ }
+ const parsed = await writeSelection(
+ "https://git.example.test/example/group/project",
+ );
+ const prepared = await prepareLocalExternalImport(
+ file,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview.findings).toEqual(parsed.findings);
+ expect((await prepared.import()).counts.created).toBe(1);
+ const [stored] = await listLocalExternalFindings(options, dependencies);
+ expect(stored!.evidence.source_data).toEqual(record);
+ } finally {
+ await fixture.dispose();
+ }
+ },
+);
+
+for (const kind of [
+ "sastFindings",
+ "secretInstances",
+ "iacFindings",
+] as const) {
+ test.each(["JSON with supplied URL", "gzip with inventory URL"])(
+ `Wiz ${kind} %s retains selected GitHub inventory provenance locally`,
+ async (format) => {
+ const fixture = await localFindingsFixture({
+ remote: "[email protected]:example/project.git",
+ });
+ try {
+ const repository = {
+ id: "source-repository",
+ ...(format.startsWith("JSON")
+ ? { url: "https://git.example.test/Example/Project" }
+ : {}),
+ };
+ const record = {
+ id: "named-occurrence",
+ name: "Example finding",
+ severity: "HIGH",
+ ...(kind === "secretInstances"
+ ? {
+ resource: {
+ type: "REPOSITORY_BRANCH",
+ typedProperties: { repository },
+ name: "feature/imports",
+ },
+ }
+ : { repository, filePath: "src/example.ts", startLine: 4 }),
+ };
+ const inventory = {
+ nodes: [
+ {
+ repository: {
+ id: repository.id,
+ url: "https://git.example.test/EXAMPLE/PROJECT",
+ },
+ },
+ {
+ platform: "GITHUB",
+ repository: {
+ id: repository.id,
+ url: "https://git.example.test/example/project",
+ },
+ },
+ {
+ platform: "GITHUB",
+ repository: {
+ id: "unselected-repository",
+ url: "https://other.example.test/example/other",
+ },
+ },
+ ],
+ };
+ const file = join(fixture.root, "named-wiz.json");
+ async function writeReport(nodes: unknown[]) {
+ const contents = JSON.stringify({
+ data: {
+ versionControlResources: inventory,
+ [kind]: { nodes },
+ },
+ });
+ await writeFile(
+ file,
+ format.startsWith("gzip") ? gzipSync(contents) : contents,
+ );
+ }
+ await writeReport([record, { ...record, id: "" }]);
+ const options = {
+ repository: fixture.repository,
+ provider: "wiz" as const,
+ sourceKey: "named-project/main",
+ };
+ const dependencies = { environment: fixture.environment };
+ const parsed = await readVendorFindings(file);
+ expect(parsed.findings).toHaveLength(1);
+ expect(parsed.excluded).toHaveLength(1);
+ execFileSync(
+ "git",
+ [
+ "remote",
+ "set-url",
+ "origin",
+ "[email protected]:example/other.git",
+ ],
+ { cwd: fixture.repository },
+ );
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ await expect(
+ access(join(fixture.stateDirectory, "workbench.sqlite3")),
+ ).rejects.toThrow();
+ execFileSync(
+ "git",
+ [
+ "remote",
+ "set-url",
+ "origin",
+ "[email protected]:example/project.git",
+ ],
+ { cwd: fixture.repository },
+ );
+ const prepared = await prepareLocalExternalImport(
+ file,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview).toMatchObject(parsed);
+ await expect(
+ access(join(fixture.stateDirectory, "workbench.sqlite3")),
+ ).rejects.toThrow();
+ const created = await prepared.import();
+ expect(created.counts.created).toBe(1);
+ expect(created.findings[0]!.evidence).toEqual(
+ parsed.findings[0]!.evidence,
+ );
+ expect(created.findings[0]!.evidence.source_data).toEqual(record);
+
+ // Normalized rows may retain their inventory in a supported named envelope.
+ await writeReport(parsed.findings);
+ expect(
+ (
+ await (
+ await prepareLocalExternalImport(file, options, dependencies)
+ ).import()
+ ).counts.unchanged,
+ ).toBe(1);
+ for (const remote of [
+ "[email protected]:example/other.git",
+ "[email protected]:example/project.git",
+ ]) {
+ execFileSync("git", [
+ "-C",
+ fixture.repository,
+ "remote",
+ "set-url",
+ "origin",
+ remote,
+ ]);
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ }
+ execFileSync("git", [
+ "-C",
+ fixture.repository,
+ "remote",
+ "set-url",
+ "origin",
+ "[email protected]:example/project.git",
+ ]);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ created.findings,
+ );
+
+ // Findings-only JSONL does not contain the discarded envelope's platform.
+ await writeFile(
+ file,
+ parsed.findings.map((finding) => JSON.stringify(finding)).join("\n"),
+ );
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ const withMetadata = await prepareLocalExternalImport(file, options, {
+ ...dependencies,
+ sourceRepositories: [
+ {
+ url: parsed.findings[0]!.evidence.details!.repository!.url,
+ platform: "github",
+ },
+ ],
+ });
+ expect((await withMetadata.import()).counts.unchanged).toBe(1);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ created.findings,
+ );
+ } finally {
+ await fixture.dispose();
+ }
+ },
+ );
+}
diff --git a/sdk/typescript/tests-ts/scanner-import.test.ts b/sdk/typescript/tests-ts/scanner-import.test.ts
index 88c78f1c8..d5ea4b2a4 100644
--- a/sdk/typescript/tests-ts/scanner-import.test.ts
+++ b/sdk/typescript/tests-ts/scanner-import.test.ts
@@ -1,5 +1,9 @@
import { expect, test } from "bun:test";
-import { relativePath } from "../src/scanner-import.js";
+import {
+ hasSarifExternalPropertyReferences,
+ relativePath,
+ sarifRunContextForResult,
+} from "../src/scanner-import.js";
test("scanner repository paths retain colons outside Windows drive prefixes", () => {
expect(relativePath("schema:prod.json")).toBe("schema:prod.json");
@@ -12,3 +16,144 @@ test("scanner repository paths retain colons outside Windows drive prefixes", ()
])
expect(relativePath(path)).toBeNull();
});
+
+test.each([
+ undefined,
+ {},
+ { artifacts: [], results: [] },
+ { properties: { producer: "example" } },
+])(
+ "SARIF external reference metadata %p keeps the report self-contained",
+ (references) => {
+ expect(hasSarifExternalPropertyReferences(references)).toBe(false);
+ },
+);
+
+test.each([
+ { artifacts: [{ location: { uri: "artifacts.sarif" } }] },
+ { results: [{ guid: "external-result-file" }] },
+ { externalizedProperties: { location: { uri: "properties.sarif" } } },
+])("SARIF external reference %p requires external data", (references) => {
+ expect(hasSarifExternalPropertyReferences(references)).toBe(true);
+});
+
+test("SARIF findings omit unrelated inventory without mutating shared run context", () => {
+ const artifacts = Array.from({ length: 5000 }, (_, index) => ({
+ location: { uri: `unrelated/file-${index}.ts` },
+ contents: { text: "unrelated source content".repeat(10) },
+ }));
+ const provenance = [{ repositoryUri: "https://github.com/example/project" }];
+ const context = { artifacts, versionControlProvenance: provenance };
+ const direct = {
+ locations: [
+ { physicalLocation: { artifactLocation: { uri: "src/main.ts" } } },
+ ],
+ };
+ expect(sarifRunContextForResult(context, direct)).toEqual({
+ versionControlProvenance: provenance,
+ });
+ expect(context.artifacts).toBe(artifacts);
+ const indexed = {
+ ...direct,
+ fixes: [
+ {
+ artifactChanges: [
+ { artifactLocation: { index: 42 }, replacements: [] },
+ ],
+ },
+ ],
+ };
+ const before = structuredClone(indexed);
+ expect(sarifRunContextForResult(context, indexed)["artifacts"]).toBe(
+ artifacts,
+ );
+ expect(indexed).toEqual(before);
+});
+
+test.each([
+ { locations: [{ physicalLocation: { artifactLocation: { index: 0 } } }] },
+ {
+ relatedLocations: [
+ { physicalLocation: { artifactLocation: { index: 0 } } },
+ ],
+ },
+ { analysisTarget: { index: 0 } },
+ {
+ codeFlows: [
+ {
+ threadFlows: [
+ {
+ locations: [
+ {
+ location: {
+ physicalLocation: { artifactLocation: { index: 0 } },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ { invocations: [{ executableLocation: { index: 0 } }] },
+ { originalUriBaseIds: { SOURCE: { index: 0 } } },
+ { name: "example-tool", locations: [{ index: 0 }] },
+ { message: { text: "See [artifact](sarif:/runs/0/artifacts/0)." } },
+ { message: { markdown: "See [artifact](SARIF:/runs/0/artifacts/0)." } },
+])(
+ "SARIF retained context %p preserves artifact indexes and links",
+ (selected) => {
+ const artifacts = [
+ {
+ location: { uri: "generated.ts" },
+ hashes: { sha256: "synthetic-digest" },
+ },
+ ];
+ const context = { artifacts };
+ expect(sarifRunContextForResult(context, selected)["artifacts"]).toBe(
+ artifacts,
+ );
+ },
+);
+
+test.each([
+ [{ uri: "src/main.ts" }, { uri: "src/main.ts" }],
+ [{ uri: "src/%6dain.ts" }, { uri: "src/main.ts" }],
+ [{ uri: "src/main.ts" }, { uri: "./src/main.ts" }],
+ [{ uri: "src/main.ts" }, { uri: "src/../src/main.ts" }],
+ [{ uri: "file:///source/main.ts" }, { uri: "main.ts" }],
+ [
+ { uri: "src/main.ts", uriBaseId: "SOURCE" },
+ { uri: "src/main.ts", uriBaseId: "SOURCE" },
+ ],
+ [{ uri: "main.ts", uriBaseId: "SOURCE" }, { uri: "src/main.ts" }],
+])(
+ "SARIF direct URI context %p preserves artifact metadata from %p",
+ (location, inventoryLocation) => {
+ const artifacts = [
+ {
+ location: inventoryLocation,
+ hashes: { sha256: "synthetic-digest" },
+ contents: { text: "source evidence" },
+ },
+ ];
+ const context = { artifacts };
+ const result = {
+ locations: [{ physicalLocation: { artifactLocation: location } }],
+ };
+ expect(sarifRunContextForResult(context, result)["artifacts"]).toBe(
+ artifacts,
+ );
+ },
+);
+
+test("unrelated SARIF property-bag indexes do not require artifact inventory", () => {
+ const context = { artifacts: [{ location: { uri: "other.ts" } }] };
+ const result = {
+ properties: { artifactLocation: { index: 0 } },
+ locations: [
+ { physicalLocation: { artifactLocation: { uri: "src/main.ts" } } },
+ ],
+ };
+ expect(sarifRunContextForResult(context, result)).toEqual({});
+});