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

fix(imports): distinguish empty reports from failed scanners and exclusions (#2082)

Michael D'Angelo0888d52b81dc
diff --git a/docs/scanner-imports/opengrep.md b/docs/scanner-imports/opengrep.md
index d07922991..b3112526a 100644
--- a/docs/scanner-imports/opengrep.md
+++ b/docs/scanner-imports/opengrep.md
@@ -36,7 +36,7 @@ codex-security publish findings "$opengrep_report" --to local --repository . \
```
Check the findings, exclusions and `report.errors`, even if the findings list
-is empty. Cloud requires at least one supported finding. Keep `--provider opengrep`
+is empty. A zero-result report with scanner errors fails the import. Keep `--provider opengrep`
when you [save locally or publish to Cloud](README.md#save-or-publish-and-verify).
## Provider identity and evidence
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 046b07428..10ac7a2a8 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -25,7 +25,7 @@ codex-security publish findings /path/to/selected-wiz-findings.json \
--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`. Keep approval when the user already approved this preview and the input and destination are unchanged.
+Show the repository, source namespace, normalized evidence, and exclusions. For a zero-record preview, report whether the input is empty or failed and stop. After confirmation, repeat without `--dry-run`, adding `--yes`. Keep approval when the user already approved this preview and the input and destination are unchanged.
Read the stored evidence with `codex-security findings imported /path/to/project --format json`; the repository defaults to the current directory. Report created, updated, unchanged, and excluded counts, including exclusion reasons when the command exits 1.
@@ -143,7 +143,7 @@ Code-scanning identities include the ref; repository alerts and advisories must
## Publish to Cloud
-Resolve the user's destination to a connected GitHub or GitHub Enterprise repository URL or Cloud repository ID, including custom Enterprise hosts. Confirm the intended Cloud account and an authorized repository environment. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
+Resolve the user's destination to a connected GitHub or GitHub Enterprise repository URL or Cloud repository ID, including custom Enterprise hosts. Confirm the intended Cloud account and authorized repository environment before running a preview that can contact Cloud. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
For staging or another Cloud deployment, configure the [deployment settings](#deployment-settings) before previewing. Keep the selected deployment and login throughout the upload.
@@ -155,7 +155,7 @@ codex-security publish findings /path/to/selected-wiz-findings.json \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
-Show the Cloud API endpoint, account, repository, environments, source namespace, severity counts, and exclusions. Identify the evidence file and make the complete JSON preview available for inspection without pasting a large report into the conversation. Explain that vendor evidence is not a Codex assessment.
+When the preview returns `status: "empty"`, report that there is nothing to upload, then stop. For a nonempty preview, show the Cloud API endpoint, account, repository, environments, source namespace, severity counts, and exclusions. Identify the evidence file and make the complete JSON preview available for inspection without pasting a large report into the conversation. Explain that vendor evidence is not a Codex assessment.
Obtain explicit confirmation for this concrete upload, including skipped records. Then run the same command without `--dry-run`, adding `--yes`. Authorization to inspect or assess findings alone does not authorize sending them to Cloud. Keep approval when the user already approved this preview and the input and destination are unchanged.
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 2fa7af84f..5652a2193 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -733,6 +733,12 @@ 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.
+When a parsed selection has no publishable findings, preparation throws
+`NoPublishableFindingsError`. Inspect its `selection` for the read count,
+exclusions and scanner diagnostics. A clean empty report needs no upload;
+failed scans and excluded records need attention. Previously imported findings
+remain open.
+
To inspect dependency vulnerabilities in a saved Trivy schema-v2 repository or filesystem
report, call `readTrivyFindings` with the JSON or gzip path. Use `normalizeTrivyFindings`
for an already parsed report. Supply the scanned directory relative to the checkout
@@ -757,7 +763,9 @@ 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.
+records remain stored, and unknown evidence fields are not inferred. A local
+SDK import with only excluded records returns the exclusions and zero write
+counts. The CLI exits 2 for that result so automation can detect it.
File imports forward repository references from the reader automatically. With
`prepareNormalizedLocalImport()`, supply additional known references in the
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 1a67ddd4c..722a99f1a 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1493,11 +1493,23 @@ review the new submission before confirming.
| Status | Exit code | Meaning |
| ------------- | --------- | -------------------------------------------------------------------------------------- |
+| `empty` | 0 | No records were available to upload. |
| `complete` | 0 | The inbox job processed every record successfully, or the publisher verified each one. |
| `partial` | 1 | The import had exclusions or record errors, or the inbox job failed or was cancelled. |
| `interrupted` | 2 | The CLI stopped while uploading, checking the result or saving a receipt. |
| `failed` | 2 | Preparation failed before upload. |
+A clean empty report needs no confirmation. Self-contained file imports can
+finish before Cloud sign-in; Semgrep Platform and Snyk REST captures use the
+Cloud catalog to verify their repository. Local imports still validate the
+checkout and create no workbench database. Explicit scanner errors
+and selections containing only excluded records fail; JSON output retains their
+diagnostics and exclusion reasons. Existing findings stay open.
+
+For automation, check the scanner's exit status as well as the import's. SARIF
+can contain no runs or omit results in a rules-only export. `empty` describes
+the selected report, not whether a scan completed successfully.
+
For a partial or interrupted import, check `excluded` and any `error` before
retrying. Some records may already have reached Cloud.
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index f7be8d886..c92a6a391 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -131,8 +131,15 @@ import {
import { listLocalExternalFindings } from "./external-findings-local.js";
import type { collectSonarIssues } from "./sonar-collector.js";
import { prepareSonarImport } from "./sonar-import.js";
-import { EXTERNAL_FINDINGS_READERS } from "./external-findings-read.js";
-import type { ExternalFindings } from "./external-findings.js";
+import {
+ EXTERNAL_FINDINGS_PROVIDERS,
+ EXTERNAL_FINDINGS_READERS,
+} from "./external-findings-read.js";
+import {
+ externalImportDisposition,
+ NoPublishableFindingsError,
+ type ExternalFindings,
+} from "./external-findings.js";
import {
publishPatchReview,
resolvePatchReviewPublisher,
@@ -424,7 +431,6 @@ const FRAMEWORK_VALUE_OPTIONS = new Set([
"--token-limit",
"--token-offset",
]);
-const TOKEN_OUTPUT_OPTION = /^--token-(?:count|limit|offset)(?:=|$)/u;
const OUTPUT_OPTION =
/^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
const HIDE_CURSOR = "\u001B[?25l";
@@ -2143,7 +2149,7 @@ export async function main(
let frameworkExit: number | undefined;
const frameworkCapture = captureOutput();
let rawExportOutput = false;
- let escapeHostedOutput = false;
+ let escapeFrameworkOutput = false;
let batchedVerification = false;
let deferredVerificationDiagnostic: string | undefined;
let streamedLogs: Awaited<ReturnType<typeof readSavedScanLogs>> | undefined;
@@ -2178,8 +2184,7 @@ export async function main(
const message = errorMessage(outcome.error);
if (!argv.includes("--full-output")) {
const data = { status: "failed", code, message };
- if (argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument)))
- filteredScanFailure = { format, data };
+ if (frameworkFlags.filterOutput) filteredScanFailure = { format, data };
return data;
}
// Incur would wrap returned data in an ok: true envelope.
@@ -3725,6 +3730,7 @@ export async function main(
const writeDiagnostic = (message: string): void =>
notify(() => errorOutput.write(message));
const machineFormat = format === "json" || format === "jsonl";
+ escapeFrameworkOutput = !machineFormat;
if (argv.includes("--full-output") && !machineFormat) {
structuredError = true;
exitCode = 2;
@@ -3742,6 +3748,17 @@ export async function main(
format === "toon" &&
!formatExplicit &&
!argv.some((argument) => OUTPUT_OPTION.test(argument));
+ const showExclusions = (excluded: ExternalFindings["excluded"]) => {
+ const sample = excluded.slice(0, 5);
+ for (const item of sample)
+ writeDiagnostic(
+ `Excluded item ${item.position}: ${diagnosticValue(item.reason)}\n`,
+ );
+ if (sample.length < excluded.length)
+ writeDiagnostic(
+ `Showing ${sample.length} of ${excluded.length} exclusions. Use --format json for every position and reason.\n`,
+ );
+ };
const confirmImport = async (
preview: ExternalFindings,
showPreview: () => void,
@@ -3841,10 +3858,7 @@ export async function main(
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`,
- );
+ showExclusions(preview.excluded);
for (const finding of preview.findings.slice(0, 5))
writeDiagnostic(
` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,
@@ -3853,19 +3867,28 @@ export async function main(
`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`,
);
};
+ const disposition = externalImportDisposition(preview);
+ if (disposition === "excluded" || disposition === "failed")
+ throw new NoPublishableFindingsError(preview);
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 (
+ disposition === "ready" &&
+ !(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`;
+ const summary =
+ disposition === "empty"
+ ? "The report contains no findings. Nothing was stored.\n"
+ : `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 };
@@ -3890,10 +3913,7 @@ export async function main(
writeDiagnostic(
`Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`,
);
- for (const excluded of preview.excluded)
- writeDiagnostic(
- `Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,
- );
+ showExclusions(preview.excluded);
writeDiagnostic(
`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`,
);
@@ -3936,14 +3956,40 @@ export async function main(
writeDiagnostic(renderExternalPublicationSummary(result));
return { ...result };
} catch (error) {
+ const noFindings =
+ error instanceof NoPublishableFindingsError ? error : undefined;
+ const selection = noFindings?.selection;
+ if (
+ selection &&
+ externalImportDisposition(selection) === "empty" &&
+ !controller.signal.aborted
+ ) {
+ const message =
+ "The report contains no findings. Nothing was uploaded.\n";
+ if (humanSummary) renderedOutput = message;
+ else if (!structured) writeDiagnostic(message);
+ return {
+ ...selection,
+ status: "empty",
+ published: false,
+ ready: 0,
+ repository: options.repository,
+ source: {
+ provider: EXTERNAL_FINDINGS_PROVIDERS[options.provider],
+ source_key: options.sourceKey,
+ },
+ ...(options.dryRun ? { dryRun: true } : {}),
+ };
+ }
+ const message = diagnosticValue(noFindings?.summary ?? error);
if (argv.includes("--full-output") && machineFormat)
failedResultOutput = {
format,
code: "IMPORT_FAILED",
- message: diagnosticValue(error),
+ message,
};
reportPublicationError(
- diagnosticValue(error),
+ message,
controller.signal.aborted ? controller.signal.reason : undefined,
);
if (error instanceof ExternalPublicationError) {
@@ -3951,11 +3997,22 @@ export async function main(
renderedOutput = renderExternalPublicationSummary(error.result);
return { ...error.result };
}
- const failure = { status: "failed", error: diagnosticValue(error) };
+ if (selection && !machineFormat) showExclusions(selection.excluded);
+ const failure = {
+ status: "failed",
+ error: message,
+ ...(machineFormat &&
+ selection && {
+ read: selection.read,
+ ready: 0,
+ excluded: selection.excluded,
+ report: selection.report,
+ }),
+ };
if (
machineFormat &&
- !argv.includes("--full-output") &&
- argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument))
+ (!argv.includes("--full-output") || selection !== undefined) &&
+ frameworkFlags.filterOutput
)
filteredScanFailure = { format, data: failure };
return structured ? failure : undefined;
@@ -4200,7 +4257,7 @@ export async function main(
fetch: dependencies.hostedScannerFetch,
};
function setHostedOutputFormat(format?: string) {
- escapeHostedOutput =
+ escapeFrameworkOutput =
format === "md" || (format === "toon" && output.isTTY === true);
}
const semgrepReport = z
@@ -6363,7 +6420,7 @@ export async function main(
const structured = format === "json" || format === "jsonl";
const reportDiagnostic = async (chunk: string): Promise<void> => {
if (structured) {
- if (!batchedVerification || frameworkFlags.tokenOutput)
+ if (!batchedVerification || frameworkFlags.tokenArguments.length)
deferredVerificationDiagnostic = chunk;
} else {
await writeCliOutput(errorOutput, chunk).catch(() => {});
@@ -7595,25 +7652,18 @@ export async function main(
} finally {
updateController.abort();
}
+ let frameworkOutput = frameworkCapture.text();
if (filteredScanFailure !== undefined) {
// Success-field filters do not apply to diagnostics. Reuse Incur's format
// and token controls without running the saved scan a second time.
const failureOutput = captureOutput();
- const failureArguments = ["render", "--format", filteredScanFailure.format];
- for (let index = 0; index < argv.length; index += 1) {
- const argument = argv[index]!;
- if (!TOKEN_OUTPUT_OPTION.test(argument)) continue;
- const separator = argument.indexOf("=");
- if (separator !== -1)
- failureArguments.push(
- argument.slice(0, separator),
- argument.slice(separator + 1),
- );
- else {
- failureArguments.push(argument);
- if (argument !== "--token-count") failureArguments.push(argv[++index]!);
- }
- }
+ const failureArguments = [
+ "render",
+ "--format",
+ filteredScanFailure.format,
+ ...frameworkFlags.tokenArguments,
+ ];
+ if (failedResultOutput) failureArguments.push("--full-output");
const failure = filteredScanFailure.data;
await Cli.create("codex-security-scan-error")
.command("render", { run: () => failure })
@@ -7621,10 +7671,10 @@ export async function main(
stdout: failureOutput.stream.write,
exit: () => undefined,
});
- renderedOutput = failureOutput.text();
+ if (failedResultOutput) frameworkOutput = failureOutput.text();
+ else renderedOutput = failureOutput.text();
}
- let frameworkOutput = frameworkCapture.text();
- if (escapeHostedOutput)
+ if (escapeFrameworkOutput)
frameworkOutput = escapeTerminalText(frameworkOutput, true);
const writeUpdateNotice = () => {
if (notice === undefined || batchedVerification) return;
@@ -7669,9 +7719,19 @@ export async function main(
const envelope: JsonValue = JSON.parse(frameworkOutput);
// Token-count output is a number, not a full-output envelope.
if (isJsonObject(envelope) && envelope["ok"] === true) {
+ // Re-rendered failures carry the unfiltered page, but the command's
+ // original metadata describes the actual invocation.
+ const meta =
+ filteredScanFailure && isJsonObject(envelope["meta"])
+ ? {
+ ...JSON.parse(frameworkCapture.text()).meta,
+ nextOffset: envelope["meta"]["nextOffset"],
+ }
+ : envelope["meta"];
frameworkOutput = `${JSON.stringify(
{
...envelope,
+ meta,
ok: false,
error: {
code: failedResultOutput.code ?? "SCAN_FAILED",
@@ -7697,7 +7757,7 @@ export async function main(
if (deferredVerificationDiagnostic !== undefined) {
// Token output can omit the diagnostic. Otherwise a buffered stderr
// write is optional once the complete structured failure is on stdout.
- if (frameworkFlags.tokenOutput) {
+ if (frameworkFlags.tokenArguments.length) {
await writeCliOutput(errorOutput, deferredVerificationDiagnostic).catch(
() => {},
);
@@ -8001,7 +8061,8 @@ function frameworkOutputFlags(argv: readonly string[]) {
let hideDisabledRoute = false;
let fullOutput = false;
let rawCollector = false;
- let tokenOutput = false;
+ const tokenArguments: string[] = [];
+ let filterOutput = false;
for (let index = 0; index < argv.length; index++) {
const value = argv[index]!;
if (
@@ -8013,9 +8074,15 @@ function frameworkOutputFlags(argv: readonly string[]) {
hideDisabledRoute = true;
if (value === "--full-output") fullOutput = true;
if (value === "--json") rawCollector = true;
- if (TOKEN_OUTPUT_OPTION.test(value)) tokenOutput = true;
+ if (value === "--token-count") tokenArguments.push(value);
if (FRAMEWORK_VALUE_OPTIONS.has(value)) {
const operand = argv[++index];
+ if (value === "--filter-output") filterOutput = true;
+ if (
+ (value === "--token-limit" || value === "--token-offset") &&
+ operand !== undefined
+ )
+ tokenArguments.push(value, operand);
if (value === "--format")
rawCollector =
operand === "json" || operand === "jsonl" || operand === "yaml";
@@ -8024,7 +8091,8 @@ function frameworkOutputFlags(argv: readonly string[]) {
return {
hideDisabledRoute,
rawCollector: rawCollector && !fullOutput,
- tokenOutput,
+ filterOutput,
+ tokenArguments,
};
}
diff --git a/sdk/typescript/src/endor-findings.ts b/sdk/typescript/src/endor-findings.ts
index cb207e955..c1c638161 100644
--- a/sdk/typescript/src/endor-findings.ts
+++ b/sdk/typescript/src/endor-findings.ts
@@ -4,14 +4,15 @@ import type { ExternalFindings } from "./external-findings.js";
import { asRecord } from "./record.js";
import {
array,
- hasSarifExternalPropertyReferences,
normalizeRecords,
readScannerJson,
record,
relativePath,
requiredText,
+ sarifRunRepositories,
sarifRunResults,
strings,
+ readSarifRuns,
text,
validateSarifRuleReference,
} from "./scanner-import.js";
@@ -31,15 +32,68 @@ export function endorRepositoryUrls(
.map((entry) => asRecord(entry)?.["repositoryUri"])
.filter((url) => typeof url === "string");
}
- return array(
- record(run, "Endor run context")["versionControlProvenance"] ?? [],
- "Endor version control provenance",
- ).map((entry) =>
- requiredText(
- record(entry, "Endor repository provenance")["repositoryUri"],
- "Endor repository URI",
- ),
+ return sarifRunRepositories(run, "Endor").map((ref) => ref.url);
+}
+
+function positiveCount(value: unknown): boolean {
+ return (
+ (typeof value === "number" || typeof value === "string") &&
+ Number(value) > 0
+ );
+}
+
+function endorListObjects(root: Record<string, unknown>): unknown[] {
+ const list = record(root["list"], "Endor list");
+ const response = record(list["response"] ?? {}, "Endor list response");
+ const {
+ next_page_id: nextId,
+ next_page_token: token,
+ total_size: total,
+ } = response;
+ if (nextId != null && typeof nextId !== "string")
+ throw new Error("Endor next_page_id must be a string.");
+ if (
+ text(nextId) ||
+ (token != null && token !== 0 && token !== "0" && token !== "")
+ )
+ throw new Error(
+ "The Endor list response has another page. Supply a complete export or an explicitly selected array.",
+ );
+ const values = array(list["objects"] ?? [], "Endor list.objects");
+ if (values.length) return values;
+
+ // Protobuf can omit an empty repeated field. Recognize only its known
+ // pagination envelope; don't mistake an unrecognized payload for no matches.
+ if (
+ positiveCount(total) ||
+ (list["objects"] == null &&
+ (Object.keys(list).some(
+ (key) => key !== "response" && key !== "objects",
+ ) ||
+ Object.keys(response).some(
+ (key) =>
+ !["next_page_token", "next_page_id"].includes(key) &&
+ !(key === "total_size" && (total === 0 || total === "0")),
+ )))
+ )
+ throw new Error("Expected Endor list.objects in the finding export.");
+
+ const { count } = record(
+ root["count_response"] ?? {},
+ "Endor count response",
+ );
+ const { groups } = record(
+ root["group_response"] ?? {},
+ "Endor group response",
);
+ if (
+ positiveCount(count) ||
+ (groups != null && Object.keys(record(groups, "Endor groups")).length)
+ )
+ throw new Error(
+ "The Endor report contains a summary without finding objects. Supply the complete finding export.",
+ );
+ return values;
}
/** Saved Endor Finding objects, an array, or an unmasked ListFindingsResponse. */
@@ -50,25 +104,12 @@ export function normalizeEndorFindings(
const root = Array.isArray(input) ? null : record(input, "Endor report");
if (root?.["version"] === "2.1.0" && root["runs"] !== undefined)
return normalizeEndorSarif(root, target);
- const list =
- root?.["list"] === undefined ? null : record(root["list"], "Endor list");
- if (list) {
- const response = record(list["response"] ?? {}, "Endor list response");
- const token = response["next_page_token"];
- if (
- text(response["next_page_id"]) ||
- (token != null && token !== 0 && token !== "0" && token !== "")
- ) {
- throw new Error(
- "The Endor list response has another page. Supply a complete export or an explicitly selected array.",
- );
- }
- }
- const values = list
- ? array(list["objects"] ?? [], "Endor list.objects")
- : Array.isArray(input)
- ? input
- : [input];
+ const values =
+ root?.["list"] !== undefined
+ ? endorListObjects(root)
+ : Array.isArray(input)
+ ? input
+ : [input];
return normalizeRecords(
values,
(value) => {
@@ -195,20 +236,10 @@ export function normalizeEndorSarif(
input: unknown,
target: ExternalImportTarget = "cloud",
): ExternalFindings {
- const document = record(input, "Endor SARIF");
- if (document["version"] !== "2.1.0")
- throw new Error("Expected Endor SARIF 2.1.0.");
- const entries = array(document["runs"], "SARIF runs").flatMap((value) => {
- const run = record(value, "SARIF run");
- const tool = record(run["tool"], "SARIF tool");
- const driver = record(tool["driver"], "SARIF driver");
- if (driver["name"] !== "endorctl")
+ const entries = readSarifRuns(input, "Endor", (context) => {
+ if (context.driver["name"] !== "endorctl")
throw new Error("Expected the endorctl SARIF producer.");
- if (
- hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])
- )
- throw new Error("Use a self-contained Endor SARIF report.");
- return sarifRunResults(document, run, tool, driver, "Endor");
+ return sarifRunResults(context, "Endor");
});
return normalizeRecords(
entries,
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index 89f417f6a..f82e6a93e 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -18,6 +18,8 @@ import {
requireExternalImports,
} from "./external-imports-feature.js";
import {
+ externalImportDisposition,
+ NoPublishableFindingsError,
cloneImportPreview,
snapshotImportOptions,
snapshotNormalizedFindings,
@@ -1317,6 +1319,25 @@ export async function prepareLocalImport(
preview,
async import() {
dependencies.signal?.throwIfAborted();
+ const disposition = externalImportDisposition(current);
+ if (disposition === "failed")
+ throw new NoPublishableFindingsError(cloneImportPreview(current));
+ const summary = {
+ repository,
+ read: current.read,
+ ...(current.report === undefined
+ ? {}
+ : snapshotNormalizedFindings({ report: current.report })),
+ ready: current.findings.length,
+ excluded: structuredClone(current.excluded),
+ };
+ if (disposition !== "ready") {
+ return {
+ ...summary,
+ findings: [],
+ counts: { created: 0, updated: 0, unchanged: 0 },
+ };
+ }
const protectedRoot = [
...new Set([
...workbenchOptions.protectedRoot,
@@ -1351,13 +1372,7 @@ export async function prepareLocalImport(
);
}, dependencies.signal);
return {
- repository,
- read: current.read,
- ...(current.report === undefined
- ? {}
- : snapshotNormalizedFindings({ report: current.report })),
- ready: current.findings.length,
- excluded: structuredClone(current.excluded),
+ ...summary,
findings: result["findings"] as unknown as StoredExternalFinding[],
counts: result["counts"] as LocalExternalImportResult["counts"],
};
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index 2a3435652..58faed86e 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -105,6 +105,8 @@ import { veracodeReportRepositories } from "./veracode-findings.js";
import { inspectorReportRepository } from "./inspector-findings.js";
import { sonarRepositoryUrls } from "./sonar-findings.js";
import {
+ NoPublishableFindingsError,
+ reportForJson,
snapshotSourceRepositories,
type ExternalSourceRepository,
snapshotImportOptions,
@@ -370,15 +372,6 @@ async function readOptionalFile(path: string): Promise<string | undefined> {
});
}
-function reportForJson(report: ExternalFindings["report"]) {
- const errors = report?.["errors"];
- if (!Array.isArray(errors)) return report;
- const json = JSON.stringify(errors, (_key, entry: unknown) =>
- entry instanceof Error ? { ...entry, message: entry.message } : entry,
- );
- return { ...report, errors: JSON.parse(json) as unknown[] };
-}
-
export function externalPublicationStateDirectory(
environment: NodeJS.ProcessEnv,
): string {
@@ -1401,13 +1394,10 @@ async function preparePublicationInput(
"The source key must contain 1–512 UTF-8 bytes and no NUL characters. Use a stable scanner organization/project/branch namespace across imports.",
);
}
+ const environment = dependencies.environment ?? process.env;
+ dependencies.signal?.throwIfAborted();
+ requireExternalImports(environment);
progress({ phase: "reading", completed: 0 });
- function noFindings(parsed: ExternalFindings): never {
- const diagnostics = reportForJson(parsed.report)?.["errors"];
- throw new CodexSecurityError(
- `No supported findings are ready to publish. ${parsed.excluded.map((item) => `Item ${item.position}: ${item.reason}`).join(" ")}${Array.isArray(diagnostics) && diagnostics.length ? ` Scanner diagnostics: ${JSON.stringify(diagnostics)}` : ""}`,
- );
- }
function checkSelection(input: PublicationSelection) {
const parsed = input.current;
if (
@@ -1419,12 +1409,10 @@ async function preparePublicationInput(
!input.unprovenOccurrenceCount &&
!input.unprovenIdPrefixes?.length
)
- noFindings(parsed);
+ throw new NoPublishableFindingsError(parsed);
}
if (typeof supplied !== "function") checkSelection(supplied);
progress({ phase: "discovering", completed: 0 });
- const environment = dependencies.environment ?? process.env;
- requireExternalImports(environment);
const apiBaseUrl = cloudBaseUrl(environment);
const cloudApiUrl = `${apiBaseUrl}/external`;
// Validate the configured return destination before authentication or uploads.
@@ -2587,7 +2575,7 @@ async function preparePublicationInput(
}
const saved = selected?.content ?? recovered;
if (historicalOnly && !saved) throw unmatchedPreviousNumbers();
- if (!parsed.findings.length) noFindings(parsed);
+ if (!parsed.findings.length) throw new NoPublishableFindingsError(parsed);
if (saved) {
await retireIfReset(saved, () =>
underLocks(lockKeys, async () => {
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index 5f53c2f24..7ddf93610 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -4,17 +4,28 @@ import type {
ExternalPublicationInput,
ExternalSourceRepository,
} from "./external-findings.js";
+import { hasNoExternalRecords } from "./external-findings.js";
+import { readScannerJson, sarifRunRepositories } from "./scanner-import.js";
import type { Provider } from "./external-import-models.js";
import type { ExternalImportTarget } from "./external-import-contract.js";
-import { readSnykFindings, snykRepositoryUrls } from "./snyk-findings.js";
+import { dependabotRepository } from "./github-dependabot-findings.js";
+import {
+ normalizeSnykFile,
+ readSnykReport,
+ emptySnykReportRepositories,
+ snykRepositoryUrls,
+} from "./snyk-findings.js";
import {
isSemgrepSarifDriver,
- readSemgrepFindings,
+ normalizeSemgrepFindings,
+ readSemgrepReport,
} from "./semgrep-findings.js";
import { semgrepPlatformReportRepository } from "./semgrep-platform-findings.js";
import { readOpenGrepFindings } from "./opengrep-findings.js";
-import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";
-import { dependabotRepository } from "./github-dependabot-findings.js";
+import {
+ normalizeEndorFindings,
+ endorRepositoryUrls,
+} from "./endor-findings.js";
import { readGitHubFindings } from "./github-findings.js";
import { readSonarFindings } from "./sonar-findings.js";
import { readVeracodeFindings } from "./veracode-findings.js";
@@ -130,6 +141,19 @@ export function semgrepSarifRepositories(
: [];
}
+/** A run may name a repository even when it produces no findings. */
+function sarifFileRepositories(
+ input: unknown,
+ producer: "Endor" | "Semgrep" | "Snyk",
+) {
+ if (
+ isRecord(input) &&
+ input["version"] === "2.1.0" &&
+ Array.isArray(input["runs"])
+ )
+ return input["runs"].flatMap((run) => sarifRunRepositories(run, producer));
+}
+
/** @internal Read vendor evidence for the local and Cloud import entrypoints. */
export async function readExternalFindings(
path: string,
@@ -137,7 +161,8 @@ export async function readExternalFindings(
target: ExternalImportTarget = "cloud",
references: readonly ExternalSourceRepository[] = [],
): Promise<ReadExternalFindings> {
- if (options.provider === "sonar") {
+ const { provider } = options;
+ if (provider === "sonar") {
const url = options.sourceRepositoryUrl;
const findings = await readSonarFindings(path, url ?? "", target);
const binding = findings.report?.["repositoryUrl"];
@@ -146,7 +171,7 @@ export async function readExternalFindings(
sourceRepositories: typeof binding === "string" ? [{ url: binding }] : [],
};
}
- if (options.provider === "opengrep") {
+ if (provider === "opengrep") {
const sourceRepositoryUrl = options.sourceRepositoryUrl ?? "";
return {
findings: await readOpenGrepFindings(
@@ -157,22 +182,26 @@ export async function readExternalFindings(
sourceRepositories: [{ url: sourceRepositoryUrl }],
};
}
- if (options.provider === "snyk" || options.provider === "endor") {
- const provider = options.provider;
- const findings =
- provider === "snyk"
- ? await readSnykFindings(path, target, references)
- : await readEndorFindings(path, target);
- return {
- findings,
- sourceRepositories: findings.findings.flatMap((finding) =>
- localFindingRepositories(provider, finding),
- ),
- };
+ if (provider === "snyk" || provider === "endor") {
+ const snyk = provider === "snyk";
+ const input = await (snyk ? readSnykReport : readScannerJson)(path);
+ const findings = snyk
+ ? await normalizeSnykFile(input, target, references)
+ : normalizeEndorFindings(input, target);
+ const header = sarifFileRepositories(input, snyk ? "Snyk" : "Endor");
+ const sourceRepositories =
+ header ??
+ (snyk && hasNoExternalRecords(findings)
+ ? emptySnykReportRepositories(input)
+ : findings.findings.flatMap((row) =>
+ localFindingRepositories(provider, row),
+ ));
+ return { findings, sourceRepositories };
}
- if (options.provider === "semgrep") {
- const findings = await readSemgrepFindings(
- path,
+ if (provider === "semgrep") {
+ const input = await readSemgrepReport(path);
+ const findings = normalizeSemgrepFindings(
+ input,
{
sourceRepositoryUrl: options.sourceRepositoryUrl,
sourceRepositories: references,
@@ -180,19 +209,19 @@ export async function readExternalFindings(
target,
);
if (semgrepPlatformReportRepository(findings)) return { findings };
- const sourceRepositories = findings.findings.flatMap((finding) =>
- semgrepSarifRepositories(finding),
- );
+ const sourceRepositories = sarifFileRepositories(input, "Semgrep") ?? [];
+ if (!sourceRepositories.length && options.sourceRepositoryUrl)
+ sourceRepositories.push({ url: options.sourceRepositoryUrl });
return { findings, sourceRepositories };
}
- if (options.provider === "github")
+ if (provider === "github")
return { findings: await readGitHubFindings(path, target) };
if (
- options.provider === "inspector" ||
- options.provider === "continuum" ||
- options.provider === "checkmarx" ||
- options.provider === "blackduck" ||
- options.provider === "veracode"
+ provider === "inspector" ||
+ provider === "continuum" ||
+ provider === "checkmarx" ||
+ provider === "blackduck" ||
+ provider === "veracode"
) {
const url = options.sourceRepositoryUrl ?? "";
const read = {
@@ -201,14 +230,14 @@ export async function readExternalFindings(
checkmarx: readCheckmarxFindings,
blackduck: readBlackDuckFindings,
veracode: readVeracodeFindings,
- }[options.provider];
+ }[provider];
return {
findings: await read(path, url, target, options.inspectorProjectMap),
sourceRepositories: [{ url }],
};
}
// A new reader must choose its parser before reaching the Wiz replay path.
- options.provider satisfies "wiz";
+ provider satisfies "wiz";
const wiz =
target === "local"
? await readLocalWizFindings(path)
diff --git a/sdk/typescript/src/external-findings.ts b/sdk/typescript/src/external-findings.ts
index 44cd66702..57b67167d 100644
--- a/sdk/typescript/src/external-findings.ts
+++ b/sdk/typescript/src/external-findings.ts
@@ -40,6 +40,48 @@ export interface ExternalFindings {
}[];
}
+export function hasNoExternalRecords(input: ExternalFindings): boolean {
+ return input.read === 0 && !input.findings.length && !input.excluded.length;
+}
+
+/** Classify a reader selection before deciding whether to store, publish, or report it. */
+export function externalImportDisposition(
+ input: ExternalFindings,
+): "ready" | "empty" | "excluded" | "failed" {
+ if (input.findings.length) return "ready";
+ const errors = input.report?.["errors"];
+ if (Array.isArray(errors) && errors.length) return "failed";
+ if (hasNoExternalRecords(input)) return "empty";
+ return input.read === input.excluded.length ? "excluded" : "failed";
+}
+
+/** No findings can be imported. The selection retains every reader exclusion and diagnostic. */
+export class NoPublishableFindingsError extends CodexSecurityError {
+ readonly summary: string;
+
+ constructor(public readonly selection: ExternalFindings) {
+ const diagnostics = reportForJson(selection.report)?.["errors"];
+ const summary =
+ externalImportDisposition(selection) === "empty"
+ ? "No supported findings are ready to publish: the report is empty."
+ : `No supported findings are ready to publish (${selection.read} read, ${selection.excluded.length} excluded).${Array.isArray(diagnostics) && diagnostics.length ? ` Scanner diagnostics: ${JSON.stringify(diagnostics)}` : ""}`;
+ const reasons = selection.excluded.map(
+ (item) => `Item ${item.position}: ${item.reason}`,
+ );
+ super([summary, ...reasons].join(" "));
+ this.summary = summary;
+ }
+}
+
+export function reportForJson(report: ExternalFindings["report"]) {
+ const errors = report?.["errors"];
+ if (!Array.isArray(errors)) return report;
+ const json = JSON.stringify(errors, (_key, entry: unknown) =>
+ entry instanceof Error ? { ...entry, message: entry.message } : entry,
+ );
+ return { ...report, errors: JSON.parse(json) as unknown[] };
+}
+
const isScannerError = Error.isError ?? isNativeError;
export const nativeErrorStackGetter = Object.getOwnPropertyDescriptor(
new Error(),
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 57e1c25fa..cea990f49 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -233,10 +233,11 @@ export type {
LocalExternalImportResult,
PreparedLocalExternalImport,
} from "./external-findings-local.js";
-export type {
- ExternalFinding,
- ExternalFindings,
- ExternalSourceRepository,
+export {
+ NoPublishableFindingsError,
+ type ExternalFinding,
+ type ExternalFindings,
+ type ExternalSourceRepository,
} from "./external-findings.js";
export type {
ExternalFindingEvidence,
diff --git a/sdk/typescript/src/scanner-import.ts b/sdk/typescript/src/scanner-import.ts
index 82e69d9c9..f3b5a90c0 100644
--- a/sdk/typescript/src/scanner-import.ts
+++ b/sdk/typescript/src/scanner-import.ts
@@ -6,7 +6,7 @@ import { gunzip } from "node:zlib";
import { CodexSecurityError, errorMessage } from "./errors.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import { SCAN_SEVERITIES } from "./scan-settings.js";
-import { isRecord } from "./record.js";
+import { asRecord, isRecord } from "./record.js";
import { previousAdmission } from "./external-import-contract.js";
import { rememberPreviousSelection } from "./reader-selection.js";
@@ -21,6 +21,128 @@ export function array(value: unknown, label: string): unknown[] {
return value;
}
+export function optionalArray(value: unknown, label: string): unknown[] {
+ return value === undefined ? [] : array(value, label);
+}
+
+// SARIF uses the same index/GUID/ID references for components and descriptors.
+function sarifReferences<T>(
+ entries: unknown[],
+ select: (entry: Record<string, unknown>) => T,
+ first = 0,
+) {
+ const refs = new Map<string | number, T>();
+ entries.forEach((entry, index) => {
+ if (!isRecord(entry)) return;
+ const item = select(entry);
+ refs.set(index + first, item);
+ if (typeof entry["guid"] === "string")
+ refs.set("guid:" + entry["guid"].toLowerCase(), item);
+ if (typeof entry["id"] === "string") refs.set("id:" + entry["id"], item);
+ });
+ return (ref: unknown) => {
+ const { index, guid, id } = asRecord(ref) ?? {};
+ if (typeof index === "number" && index >= 0) return refs.get(index);
+ if (typeof guid === "string") return refs.get("guid:" + guid.toLowerCase());
+ return typeof id === "string" ? refs.get("id:" + id) : refs.get(-1);
+ };
+}
+
+function notificationDescriptors(value: unknown) {
+ const tool = asRecord(value);
+ // The driver is the default component (-1); extension indexes start at 0.
+ const component = sarifReferences(
+ [
+ tool?.["driver"],
+ ...optionalArray(tool?.["extensions"], "SARIF tool extensions"),
+ ],
+ (owner) =>
+ sarifReferences(
+ optionalArray(owner["notifications"], "SARIF notification descriptors"),
+ (entry) => entry,
+ ),
+ -1,
+ );
+ return (ref: unknown) => component(asRecord(ref)?.["toolComponent"])?.(ref);
+}
+
+export function validateSarifRun(
+ run: Record<string, unknown>,
+ producer: string,
+): void {
+ if (hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"]))
+ throw new Error(`Use a self-contained ${producer} SARIF report.`);
+ function validate(
+ values: unknown[],
+ tool: unknown,
+ strictExecution: boolean,
+ ) {
+ let descriptors: ReturnType<typeof notificationDescriptors> | undefined;
+ const resolve = (ref: unknown) =>
+ isRecord(ref)
+ ? (descriptors ??= notificationDescriptors(tool))(ref)
+ : undefined;
+ for (const value of values) {
+ const invocation = record(value, `${producer} invocation`);
+ const successful = invocation["executionSuccessful"];
+ if (typeof successful !== "boolean")
+ throw new Error(
+ `${producer} SARIF executionSuccessful must be a boolean.`,
+ );
+ const list = (key: string) =>
+ optionalArray(invocation[key], `${producer} ${key}`);
+ const execution = list("toolExecutionNotifications");
+ const notices = execution.concat(list("toolConfigurationNotifications"));
+ if (!successful) {
+ const details = [
+ invocation["processStartFailureMessage"],
+ invocation["exitCodeDescription"],
+ invocation["exitCode"],
+ invocation["exitSignalName"],
+ ...notices,
+ ].filter((value) => value !== undefined);
+ throw new Error(
+ `${producer} SARIF contains an unsuccessful invocation.${details.length ? " " + JSON.stringify(details) : ""}`,
+ );
+ }
+ if (strictExecution && execution.length)
+ throw new Error(
+ `${producer} SARIF contains scan error notifications: ${JSON.stringify(execution)}`,
+ );
+ const levels = new Map<Record<string, unknown>, unknown>();
+ for (const value of list("notificationConfigurationOverrides")) {
+ const override = asRecord(value);
+ const descriptor = resolve(override?.["descriptor"]);
+ const level = asRecord(override?.["configuration"])?.["level"];
+ if (descriptor && level !== undefined) levels.set(descriptor, level);
+ }
+ for (const value of notices) {
+ const notice = record(value, `${producer} notification`);
+ const descriptor = resolve(notice["descriptor"]);
+ const level =
+ notice["level"] ??
+ (descriptor && levels.get(descriptor)) ??
+ asRecord(descriptor?.["defaultConfiguration"])?.["level"];
+ if (level === "error")
+ throw new Error(
+ `${producer} SARIF contains scan error notifications: ${JSON.stringify(notice)}`,
+ );
+ }
+ }
+ }
+ // Semgrep reports scanner errors as execution notices even below error level.
+ validate(
+ optionalArray(run["invocations"], `${producer} invocations`),
+ run["tool"],
+ producer === "Semgrep",
+ );
+ if (run["conversion"] !== undefined) {
+ const conversion = record(run["conversion"], `${producer} conversion`);
+ if (conversion["invocation"] !== undefined)
+ validate([conversion["invocation"]], conversion["tool"], false);
+ }
+}
+
export function text(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value : null;
}
@@ -31,6 +153,32 @@ export function requiredText(value: unknown, label: string): string {
return result;
}
+/** SARIF repository claims must be checked even when a run has no results. */
+export function sarifRunRepositories(
+ run: unknown,
+ producer: string,
+): { url: string; branch?: string }[] {
+ if (run == null) return [];
+ return array(
+ record(run, `${producer} run context`)["versionControlProvenance"] ?? [],
+ `${producer} version control provenance`,
+ ).flatMap((entry) => {
+ const ref = record(entry, `${producer} repository provenance`);
+ const url =
+ producer === "Semgrep"
+ ? text(ref["repositoryUri"])
+ : requiredText(ref["repositoryUri"], `${producer} repository URI`);
+ if (url === null) return [];
+ const branch = ref["branch"];
+ return [
+ {
+ url,
+ ...(producer === "Semgrep" && typeof branch === "string" && { branch }),
+ },
+ ];
+ });
+}
+
export function scannerSeverity(value: string | null | undefined) {
return SCAN_SEVERITIES.find((severity) => severity === value) ?? "unknown";
}
@@ -80,15 +228,29 @@ export function stableId(prefix: string, fields: unknown[]): string {
const strictUtf8 = new TextDecoder("utf-8", { fatal: true });
const gunzipAsync = promisify(gunzip);
+async function readScannerInput(path: string | FileHandle) {
+ const bytes = await readFile(path);
+ const gzip = bytes[0] === 0x1f && bytes[1] === 0x8b;
+ return { gzip, bytes: gzip ? await gunzipAsync(bytes) : bytes };
+}
+
export async function readScannerBytes(
path: string | FileHandle,
): Promise<Buffer> {
- const bytes = await readFile(path);
- return bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipAsync(bytes) : bytes;
+ return (await readScannerInput(path)).bytes;
}
export async function readScannerText(path: string): Promise<string> {
- return strictUtf8.decode(await readScannerBytes(path));
+ const { bytes, gzip } = await readScannerInput(path);
+ const contents = strictUtf8.decode(bytes);
+ // Empty JSONL is a valid stream of zero records; a blank JSON or CSV document isn't.
+ if (!contents.trim()) {
+ if (!gzip && /\.gz$/iu.test(path))
+ throw new Error("The report is blank and contains no gzip stream.");
+ if (/\.(?:json|csv)(?:\.gz)?$/iu.test(path))
+ throw new Error("The report is blank.");
+ }
+ return contents;
}
export function parseJsonOrJsonl(contents: string): unknown {
@@ -242,14 +404,34 @@ export function indexSarifRules(
return byId;
}
+type SarifRun = Record<
+ "document" | "run" | "tool" | "driver",
+ Record<string, unknown>
+>;
+
+/** Unpack the common SARIF envelope; each reader qualifies its own producer. */
+export function readSarifRuns<T>(
+ input: unknown,
+ producer: "Semgrep" | "Snyk" | "Endor",
+ read: (context: SarifRun) => T[],
+): T[] {
+ const document = record(input, `${producer} SARIF`);
+ if (document["version"] !== "2.1.0")
+ throw new Error(`Expected ${producer} SARIF 2.1.0.`);
+ return array(document["runs"], "SARIF runs").flatMap((value) => {
+ const run = record(value, "SARIF run");
+ const tool = record(run["tool"], "SARIF tool");
+ const driver = record(tool["driver"], "SARIF driver");
+ return read({ document, run, tool, driver });
+ });
+}
+
/** Pair each result with its shared run context and original evidence. */
export function sarifRunResults(
- document: Record<string, unknown>,
- run: Record<string, unknown>,
- tool: Record<string, unknown>,
- driver: Record<string, unknown>,
+ { document, run, tool, driver }: SarifRun,
producer: "Endor" | "Semgrep",
) {
+ validateSarifRun(run, producer);
const rules = array(driver["rules"] ?? [], `${producer} rules`).map((rule) =>
record(rule, `${producer} rule`),
);
@@ -281,7 +463,7 @@ export function sarifRunResults(
});
},
};
- return array(run["results"] ?? [], `${producer} results`).map((result) => ({
+ return optionalArray(run["results"], `${producer} results`).map((result) => ({
result,
context,
}));
diff --git a/sdk/typescript/src/semgrep-findings.ts b/sdk/typescript/src/semgrep-findings.ts
index 202cc5d5f..adad3579b 100644
--- a/sdk/typescript/src/semgrep-findings.ts
+++ b/sdk/typescript/src/semgrep-findings.ts
@@ -30,14 +30,16 @@ import {
} from "./native-json-findings.js";
import {
array,
- hasSarifExternalPropertyReferences,
normalizeRecords,
+ optionalArray,
readScannerJson,
record,
relativePath,
requiredText,
+ sarifRunRepositories,
sarifRunResults,
stableId,
+ readSarifRuns,
text,
validateSarifRuleReference,
} from "./scanner-import.js";
@@ -196,13 +198,16 @@ export function normalizeSemgrepFindings(
);
const repositoryUrl = sourceRepository(options);
requiredText(document["version"], "Semgrep version");
- if (array(document["errors"] ?? [], "Semgrep errors").length)
+ const { results, paths: _paths, time: _time, ...context } = document;
+ const rows = array(results, "Semgrep results");
+ if (!rows.length && document["errors"] === undefined)
+ throw new Error("An empty Semgrep report must include its errors array.");
+ if (optionalArray(document["errors"], "Semgrep errors").length)
throw new Error(
"The Semgrep report contains scan errors; supply a successful report before importing findings.",
);
- const { results, paths: _paths, time: _time, ...context } = document;
return normalizeRecords(
- array(results, "Semgrep results"),
+ rows,
(value) =>
projectNativeJsonResult(parseNativeJsonResult(value, "Semgrep"), {
origin: "Semgrep",
@@ -226,51 +231,27 @@ export function normalizeSemgrepSarif(
target: ExternalImportTarget = "cloud",
): ExternalFindings {
const repositoryUrl = sourceRepository(options);
- const document = record(input, "Semgrep SARIF");
- if (document["version"] !== "2.1.0")
- throw new Error("Expected Semgrep SARIF 2.1.0.");
const repositoryKey = cloudRepositoryUrlKey(repositoryUrl);
const verifiedUrls = new Set([repositoryUrl]);
- const entries = array(document["runs"], "SARIF runs").flatMap((value) => {
- const run = record(value, "SARIF run");
- for (const entry of array(
- run["versionControlProvenance"] ?? [],
- "Version control provenance",
+ const entries = readSarifRuns(input, "Semgrep", (context) => {
+ for (const { url: declared } of sarifRunRepositories(
+ context.run,
+ "Semgrep",
)) {
- const declared = text(
- record(entry, "Repository provenance")["repositoryUri"],
- );
- if (!declared || verifiedUrls.has(declared)) continue;
+ if (verifiedUrls.has(declared)) continue;
if (cloudRepositoryUrlKey(declared) !== repositoryKey)
throw new Error(
"SARIF source repository does not match the declared source repository URL.",
);
verifiedUrls.add(declared);
}
- const tool = record(run["tool"], "SARIF tool");
- const driver = record(tool["driver"], "SARIF driver");
- if (!isSemgrepSarifDriver(requiredText(driver["name"], "SARIF producer")))
- throw new Error("Expected a Semgrep SARIF producer.");
if (
- hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])
- )
- throw new Error("Use a self-contained Semgrep SARIF report.");
- for (const invocation of array(
- run["invocations"] ?? [],
- "Semgrep invocations",
- )) {
- const details = record(invocation, "Semgrep invocation");
- if (details["executionSuccessful"] === false)
- throw new Error("Semgrep SARIF contains an unsuccessful invocation.");
- if (
- array(
- details["toolExecutionNotifications"] ?? [],
- "Semgrep scan notifications",
- ).length
+ !isSemgrepSarifDriver(
+ requiredText(context.driver["name"], "SARIF producer"),
)
- throw new Error("Semgrep SARIF contains scan error notifications.");
- }
- return sarifRunResults(document, run, tool, driver, "Semgrep");
+ )
+ throw new Error("Expected a Semgrep SARIF producer.");
+ return sarifRunResults(context, "Semgrep");
});
return normalizeRecords(
entries,
diff --git a/sdk/typescript/src/snyk-findings.ts b/sdk/typescript/src/snyk-findings.ts
index 9f237c5b9..ee940e47d 100644
--- a/sdk/typescript/src/snyk-findings.ts
+++ b/sdk/typescript/src/snyk-findings.ts
@@ -14,16 +14,19 @@ import type { SnykIssuesFindings } from "./snyk-rest-findings.js";
import { isRecord } from "./record.js";
import {
array,
- hasSarifExternalPropertyReferences,
indexSarifRules,
normalizeRecords,
+ optionalArray,
readScannerJson,
record,
requiredText,
+ sarifRunRepositories,
sarifRunContextSelector,
stableId,
strings,
+ readSarifRuns,
text,
+ validateSarifRun,
validateSarifRuleReference,
} from "./scanner-import.js";
@@ -71,6 +74,13 @@ function pluginIdentity(value: unknown): string {
]);
}
+function requireEmptyIssueCount(value: unknown, label: string): void {
+ if (value === undefined || value === 0) return;
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
+ throw new Error(`${label} must be a nonnegative integer.`);
+ throw new Error(`${label} reported issues but the findings array is empty.`);
+}
+
/** Import the official Snyk Codex plugin's documented local SCA bundle. */
export function normalizeSnykFindingsExport(
input: unknown,
@@ -84,9 +94,9 @@ export function normalizeSnykFindingsExport(
throw new Error("Expected a snyk-findings-export/v1 bundle from Snyk.");
const collection = record(document["collection"], "Snyk collection");
const sourceTarget = record(collection["target"], "Snyk target");
- const { findings: _findings, ...context } = document;
- return normalizeRecords(
- array(document["findings"], "Snyk findings"),
+ const { findings, ...context } = document;
+ const parsed = normalizeRecords(
+ array(findings, "Snyk findings"),
(value) => {
const finding = record(value, "Snyk plugin finding");
const observation = record(finding["observation"], "Snyk observation");
@@ -151,6 +161,35 @@ export function normalizeSnykFindingsExport(
pluginIdentity,
target,
);
+ let successfulSca = false;
+ for (const entry of optionalArray(
+ collection["scans"],
+ "Snyk collection scans",
+ )) {
+ const scan = record(entry, "Snyk collection scan");
+ if (!parsed.read && scan["outcome"] === "succeeded")
+ requireEmptyIssueCount(scan["issueCount"], "Snyk plugin issueCount");
+ if (scan["category"] !== "sca") continue;
+ if (scan["outcome"] !== "succeeded") {
+ const failure = `Snyk plugin SCA scan did not succeed (outcome: ${String(scan["outcome"])}).${scan["error"] ? " " + JSON.stringify(scan["error"]) : ""}`;
+ if (parsed.read && !parsed.findings.length)
+ return {
+ ...parsed,
+ report: {
+ collection: structuredClone(collection),
+ errors: [failure],
+ },
+ };
+ throw new Error(failure);
+ }
+ successfulSca = true;
+ }
+ if (parsed.read) return parsed;
+ if (!successfulSca)
+ throw new Error(
+ "An empty Snyk plugin bundle must identify a successful SCA scan.",
+ );
+ return { ...parsed, report: { collection: structuredClone(collection) } };
}
function normalizeGitRepositoryUrl(
@@ -192,6 +231,33 @@ function normalizeGitRepositoryUrl(
return repository;
}
+function snykJsonProjectRepository(
+ project: Record<string, unknown>,
+): string | undefined {
+ // A remote Snyk test puts its GitHub URL and optional ref in the same
+ // path field that local scans use for a directory or npm package name.
+ const repository = text(project["path"])?.split("#", 1)[0];
+ if (
+ repository &&
+ /^https?:\/\/github\.com(?::\d+)?\/[^/?#\\\s]+\/[^/?#\\\s]+\/?$/iu.test(
+ repository,
+ )
+ )
+ return repository;
+}
+
+/** Empty plugin and CLI JSON exports have no rows to carry their repository. */
+export function emptySnykReportRepositories(input: unknown): { url: string }[] {
+ if (isRecord(input) && input["format"] === "snyk-findings-export/v1")
+ return snykRepositoryUrls(input, { normalizeGitRemote: false }).map(
+ (url) => ({ url }),
+ );
+ return (Array.isArray(input) ? input : [input]).flatMap((project) => {
+ const url = isRecord(project) && snykJsonProjectRepository(project);
+ return url ? [{ url }] : [];
+ });
+}
+
/** @internal Repository claims retained in original Snyk evidence. */
export function snykRepositoryUrls(
sourceData: unknown,
@@ -229,16 +295,8 @@ export function snykRepositoryUrls(
text(project["packageManager"]) &&
isRecord(source["vulnerability"])
) {
- // A remote Snyk test puts its GitHub URL and optional ref in the same
- // path field that local scans use for a directory or npm package name.
- const repository = text(project["path"])?.split("#", 1)[0];
- if (
- repository &&
- /^https?:\/\/github\.com(?::\d+)?\/[^/?#\\\s]+\/[^/?#\\\s]+\/?$/iu.test(
- repository,
- )
- )
- return [repository];
+ const repository = snykJsonProjectRepository(project);
+ if (repository) return [repository];
}
// Generic normalized evidence may use these field names for opaque metadata.
const document = source["document"];
@@ -250,20 +308,12 @@ export function snykRepositoryUrls(
driver["name"] !== "Snyk Open Source"
)
return [];
- const run = source["run"];
- if (run == null) return [];
- return array(
- record(run, "Snyk run context")["versionControlProvenance"] ?? [],
- "Snyk version control provenance",
- ).map((entry) => {
- const repository = requiredText(
- record(entry, "Snyk repository provenance")["repositoryUri"],
- "Snyk repository URI",
- );
- return normalizeGitRemote
- ? normalizeGitRepositoryUrl(repository, cloudRepositoryUrl)
- : repository;
- });
+ const urls = sarifRunRepositories(source["run"], "Snyk").map(
+ (ref) => ref.url,
+ );
+ return normalizeGitRemote
+ ? urls.map((url) => normalizeGitRepositoryUrl(url, cloudRepositoryUrl))
+ : urls;
}
/** Snyk Open Source's formatter groups all dependency paths for an advisory in a project. */
@@ -271,51 +321,39 @@ export function normalizeSnykSarif(
input: unknown,
target: ExternalImportTarget = "cloud",
): ExternalFindings {
- const document = record(input, "Snyk SARIF");
- if (document["version"] !== "2.1.0")
- throw new Error("Expected Snyk Open Source SARIF 2.1.0.");
- const entries = array(document["runs"], "SARIF runs").flatMap((value) => {
- const run = record(value, "SARIF run");
- const driver = record(
- record(run["tool"], "SARIF tool")["driver"],
- "SARIF driver",
- );
- if (driver["name"] !== "Snyk Open Source")
- throw new Error(
- "Only Snyk Open Source SARIF is supported; Code, Container, and IaC need separate mappings.",
+ const entries = readSarifRuns(
+ input,
+ "Snyk",
+ ({ document, run, tool, driver }) => {
+ if (driver["name"] !== "Snyk Open Source")
+ throw new Error(
+ "Only Snyk Open Source SARIF is supported; Code, Container, and IaC need separate mappings.",
+ );
+ validateSarifRun(run, "Snyk");
+ const rules = array(driver["rules"], "SARIF rules").map((rule) =>
+ record(rule, "SARIF rule"),
);
- if (
- hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])
- )
- throw new Error(
- "External SARIF property files are unsupported; use a self-contained report.",
+ // SDK inputs can leave descriptor slots empty. Keep the original rule indexes.
+ const rulesById = indexSarifRules(
+ rules.entries().filter(([index]) => index in rules),
);
- const rules = array(driver["rules"], "SARIF rules").map((rule) =>
- record(rule, "SARIF rule"),
- );
- // SDK inputs can leave descriptor slots empty. Keep the original rule indexes.
- const rulesById = indexSarifRules(
- rules.entries().filter(([index]) => index in rules),
- );
- const project = snykSarifProject(run);
- const { results: _results, tool: _tool, ...runContext } = run;
- const { rules: _rules, ...driverContext } = driver;
- const { driver: _driver, ...toolContext } = record(
- run["tool"],
- "SARIF tool",
- );
- runContext["tool"] = toolContext;
- const { runs: _runs, ...documentContext } = document;
- const selectRunContext = sarifRunContextSelector(runContext);
- return array(run["results"], "SARIF results").map((result) => ({
- result,
- rulesById,
- project,
- selectRunContext,
- driverContext,
- documentContext,
- }));
- });
+ const project = snykSarifProject(run);
+ const { results: _results, tool: _tool, ...runContext } = run;
+ const { rules: _rules, ...driverContext } = driver;
+ const { driver: _driver, ...toolContext } = tool;
+ runContext["tool"] = toolContext;
+ const { runs: _runs, ...documentContext } = document;
+ const selectRunContext = sarifRunContextSelector(runContext);
+ return optionalArray(run["results"], "SARIF results").map((result) => ({
+ result,
+ rulesById,
+ project,
+ selectRunContext,
+ driverContext,
+ documentContext,
+ }));
+ },
+ );
return normalizeRecords(
entries,
({
@@ -427,6 +465,8 @@ export function normalizeSnykJson(
target: ExternalImportTarget = "cloud",
): ExternalFindings {
const projects = Array.isArray(input) ? input : [input];
+ if (!projects.length)
+ throw new Error("The Snyk report contains no scanned projects.");
const entries = projects.flatMap((value) => {
const project = record(value, "Snyk Open Source project");
if (project["error"])
@@ -444,7 +484,15 @@ export function normalizeSnykJson(
const manifest =
text(project["displayTargetFile"]) ?? text(project["targetFile"]);
const { vulnerabilities, ...context } = project;
- return array(vulnerabilities, "Snyk vulnerabilities").map((value) => ({
+ const records = array(vulnerabilities, "Snyk vulnerabilities");
+ if (!records.length) {
+ if (!project["ok"])
+ throw new Error(
+ "Snyk reported issues but the findings array is empty.",
+ );
+ requireEmptyIssueCount(project["uniqueCount"], "Snyk native uniqueCount");
+ }
+ return records.map((value) => ({
value,
context,
manager,
diff --git a/sdk/typescript/src/wiz-findings.ts b/sdk/typescript/src/wiz-findings.ts
index aa43169dc..825a8f366 100644
--- a/sdk/typescript/src/wiz-findings.ts
+++ b/sdk/typescript/src/wiz-findings.ts
@@ -423,9 +423,12 @@ function records(payload: unknown): FindingInput {
} as const;
const selected: InputRecord[] = [];
let found = false;
+ let countedCollection: string | undefined;
for (const [root, kind] of Object.entries(collections)) {
+ if (!(root in data)) continue;
const collection = asRecord(data[root]);
- if (!collection) continue;
+ if (!collection)
+ throw new Error(`Wiz ${root} must be an object with a nodes array.`);
found = true;
if (!Array.isArray(collection["nodes"]))
throw new Error(`Wiz ${root}.nodes must be an array.`);
@@ -433,8 +436,14 @@ function records(payload: unknown): FindingInput {
throw new Error(
"Wiz response has another page. Complete the requested pages or save the explicitly selected records in their named collection before publishing.",
);
+ const total = collection["totalCount"];
+ if (typeof total === "number" && total > 0) countedCollection = root;
for (const value of collection["nodes"]) selected.push({ value, kind });
}
+ if (!selected.length && countedCollection)
+ throw new Error(
+ `Wiz ${countedCollection}.totalCount reports findings, but the export contains no finding nodes.`,
+ );
if (found)
return {
records: selected,
diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.ts
index bcca60e46..1ebc0fe98 100644
--- a/sdk/typescript/tests-ts/cli-local-import.test.ts
+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts
@@ -114,6 +114,55 @@ async function fixture() {
return { root, repository, file, record, state, deps, command };
}
+test.each(["local", "cloud"])(
+ "zero-record OpenGrep imports to %s preserve scanner diagnostics",
+ async (destination) => {
+ const f = await fixture();
+ const command = [
+ ...f.command,
+ "--source-repository-url",
+ "https://github.com/example/project",
+ ];
+ command[command.indexOf("--provider") + 1] = "opengrep";
+ command[command.indexOf("--to") + 1] = destination;
+ if (destination === "cloud")
+ command[command.indexOf("--repository") + 1] = "example/project";
+ const input = { ...opengrepJson(), results: [] };
+ await writeFile(f.file, JSON.stringify(input));
+ const failed = createCliTest(main);
+ expect(await failed.runCli([...command, "--dry-run"], f.deps)).toBe(2);
+ expect(JSON.parse(failed.stdout.text())).toMatchObject({
+ error: expect.stringContaining(input.errors[0]!.message),
+ report: { errors: input.errors, paths: input.paths },
+ });
+
+ const paths = { scanned: ["src/example\u001b[2J\u009b.ts"] };
+ await writeFile(f.file, JSON.stringify({ ...input, errors: [], paths }));
+ const clean = createCliTest(main);
+ expect(await clean.runCli(command, f.deps)).toBe(0);
+ expect(JSON.parse(clean.stdout.text())).toMatchObject({
+ read: 0,
+ ready: 0,
+ findings: [],
+ excluded: [],
+ report: { errors: [], paths },
+ ...(destination === "local" && {
+ counts: { created: 0, updated: 0, unchanged: 0 },
+ }),
+ });
+ const terminal = createCliTest(main);
+ expect(
+ await terminal.runCli(
+ command.map((arg) => (arg === "json" ? "md" : arg)),
+ f.deps,
+ ),
+ ).toBe(0);
+ expect(terminal.stdout.text()).toContain("src/example");
+ expect(terminal.stdout.text()).not.toMatch(/[\u001b\u009b]/u);
+ await expect(readdir(f.state)).rejects.toThrow("ENOENT");
+ },
+);
+
test("local preview and declined confirmation do not create database state or use Cloud", async () => {
const f = await fixture();
const preview = createCliTest(main);
@@ -332,6 +381,24 @@ test("CLI imports OpenGrep evidence locally without assessing it", async () => {
});
});
+test("local dry runs and imports reject an entirely excluded report before opening the workbench", async () => {
+ const f = await fixture();
+ await writeFile(
+ f.file,
+ JSON.stringify([{ ...f.record, vendorSeverity: "unsupported" }]),
+ );
+ for (const flags of [["--dry-run"], ["--yes"]]) {
+ const cli = createCliTest(main);
+ expect(await cli.runCli([...f.command, ...flags], f.deps)).toBe(2);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ read: 1,
+ ready: 0,
+ excluded: [{ position: 1, reason: expect.any(String) }],
+ });
+ await expect(readdir(f.state)).rejects.toThrow("ENOENT");
+ }
+});
+
test("local import confirms exclusions and returns partial status after storing ready records", async () => {
const f = await fixture();
await writeFile(
diff --git a/sdk/typescript/tests-ts/endor-findings.test.ts b/sdk/typescript/tests-ts/endor-findings.test.ts
index ae614cb34..2dc2ed1b1 100644
--- a/sdk/typescript/tests-ts/endor-findings.test.ts
+++ b/sdk/typescript/tests-ts/endor-findings.test.ts
@@ -44,6 +44,57 @@ test("arrays and ListFindingsResponse use the same identities and empty lists ar
findings: [],
excluded: [],
});
+ for (const list of [
+ {},
+ { objects: null, response: null },
+ { response: { next_page_token: 0 } },
+ { response: { total_size: 0 } },
+ { objects: null, response: { total_size: "0" } },
+ ]) {
+ expect(normalizeEndorFindings({ list })).toEqual(
+ normalizeEndorFindings([]),
+ );
+ }
+});
+
+test("an Endor response with no objects and unrecognized list data is not an empty export", () => {
+ expect(() =>
+ normalizeEndorFindings({ list: { response: { next_page_id: 2 } } }),
+ ).toThrow("next_page_id");
+ for (const list of [
+ { items: [endorFinding()] },
+ { response: { total_size: 13 } },
+ { objects: [], response: { total_size: 13 } },
+ { objects: null, response: { total_size: 13 } },
+ ]) {
+ expect(() => normalizeEndorFindings({ list })).toThrow(
+ "Endor list.objects",
+ );
+ }
+});
+
+test("an Endor summary reporting matches cannot substitute for finding objects", () => {
+ for (const summary of [
+ { count_response: { count: 13 } },
+ { count_response: { count: "13" } },
+ {
+ group_response: {
+ groups: { example: { aggregation_count: { count: 2 } } },
+ },
+ },
+ ]) {
+ for (const list of [{}, { objects: [] }])
+ expect(() => normalizeEndorFindings({ list, ...summary })).toThrow(
+ "summary",
+ );
+ }
+ expect(
+ normalizeEndorFindings({
+ list: {},
+ count_response: { count: "0" },
+ group_response: { groups: {} },
+ }),
+ ).toEqual(normalizeEndorFindings([]));
});
test.each(["sast_data", "ai_sast_data"])(
diff --git a/sdk/typescript/tests-ts/external-findings-local.test.ts b/sdk/typescript/tests-ts/external-findings-local.test.ts
index a701a2c23..0ae70f616 100644
--- a/sdk/typescript/tests-ts/external-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-local.test.ts
@@ -72,6 +72,47 @@ function input(): ExternalFindings {
const source = { provider: "snyk" as const, sourceKey: "example-project/main" };
describe("local normalized scanner findings", () => {
+ test("reports empty and excluded selections without storage and preserves failed scanner diagnostics", async () => {
+ const { repository, stateDirectory, environment } = await fixture();
+ const options = { repository, ...source };
+ const empty = { read: 0, findings: [], excluded: [] };
+ const failed = {
+ ...empty,
+ report: { errors: [{ message: "Scanner timed out" }] },
+ };
+ const excluded = {
+ ...empty,
+ read: 1,
+ excluded: [
+ {
+ position: 1,
+ source_finding_id: null,
+ reason: "Unsupported severity",
+ },
+ ],
+ };
+ for (const [selection, shouldFail] of [
+ [empty, false],
+ [excluded, false],
+ [failed, true],
+ [{ ...excluded, report: failed.report }, true],
+ [{ ...empty, read: 1 }, true],
+ ] as const) {
+ const prepared = await prepareNormalizedLocalImport(selection, options, {
+ environment,
+ });
+ expect(prepared.preview).toMatchObject(selection);
+ if (shouldFail)
+ await expect(prepared.import()).rejects.toMatchObject({ selection });
+ else
+ expect(await prepared.import()).toMatchObject({
+ ...selection,
+ counts: { created: 0, updated: 0, unchanged: 0 },
+ });
+ expect(existsSync(stateDirectory)).toBe(false);
+ }
+ });
+
test("requires opt-in before resolving repositories or accessing the workbench", async () => {
const { root, stateDirectory, environment } = await fixture();
const disabledEnvironment: NodeJS.ProcessEnv = { ...environment };
@@ -801,7 +842,7 @@ describe("local normalized scanner findings", () => {
},
}),
};
- const input = { read: 0, findings: [], excluded: [] };
+ const input = ${JSON.stringify(input())};
const options = { repository, provider: "snyk", sourceKey: "synthetic-project" };
const prepared = operation === "import"
? await prepareNormalizedLocalImport(input, options, dependencies)
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index b073b691b..296cf20b3 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -42,6 +42,7 @@ import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { gzipSync } from "node:zlib";
import { Database } from "bun:sqlite";
+import { NoPublishableFindingsError } from "../src/index.js";
import { afterEach, expect, spyOn, test } from "bun:test";
import {
ExternalPublicationError,
@@ -886,6 +887,156 @@ async function fixture(
};
}
+test("a zero-record report needs no Cloud account, destination lookup, confirmation, or submission", async () => {
+ const f = await fixture([]);
+ await rm(f.environment.CODEX_HOME, { recursive: true });
+ const fetch = spyOn(f.cliDeps, "cloudFetch");
+ const cli = createCliTest(main);
+ const code = await cli.runCli(
+ [...f.command, "--full-output", "--dry-run"],
+ f.cliDeps,
+ );
+ expect(code, cli.stderr.text()).toBe(0);
+ expect(fetch).not.toHaveBeenCalled();
+ const { ok, data } = JSON.parse(cli.stdout.text());
+ expect(ok).toBe(true);
+ expect(data).toMatchObject({
+ status: "empty",
+ published: false,
+ dryRun: true,
+ read: 0,
+ ready: 0,
+ findings: [],
+ excluded: [],
+ });
+ expect(data).not.toHaveProperty("destination");
+ expect(data).not.toHaveProperty("accountId");
+ await expect(readdir(f.environment.CODEX_SECURITY_STATE_DIR)).rejects.toThrow(
+ "ENOENT",
+ );
+});
+
+test("an empty monitored Snyk capture finishes without an upload after catalog lookup", async () => {
+ const report = snykRestFixture("open-source");
+ report.pages = [{ startingAfter: null, responseJson: '{"data":[]}' }];
+ const f = await fixture(report, report.sourceRepositoryUrl);
+ const cli = createCliTest(main);
+ const args = f.command.map((arg) => (arg === "wiz" ? "snyk" : arg));
+ expect(await cli.runCli(args, f.cliDeps)).toBe(0);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ status: "empty",
+ published: false,
+ });
+ expect(f.posts).toHaveLength(0);
+});
+
+test("an entirely excluded report fails with all positions intact and a short diagnostic", async () => {
+ const f = await fixture(
+ Array.from({ length: 500 }, (_, index) =>
+ normalized(`id-\x1b[2J${index}`, "unsupported"),
+ ),
+ );
+ await rm(f.environment.CODEX_HOME, { recursive: true });
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli([...f.command, "--dry-run", "--full-output"], f.cliDeps),
+ ).toBe(2);
+ const output = JSON.parse(cli.stdout.text());
+ expect(output).toMatchObject({
+ ok: false,
+ error: { code: "IMPORT_FAILED" },
+ data: { status: "failed", read: 500, ready: 0 },
+ });
+ expect(
+ output.data.excluded.map((row: { position: number }) => row.position),
+ ).toEqual(Array.from({ length: 500 }, (_, index) => index + 1));
+ expect(output.data.excluded.at(-1)).toMatchObject({
+ source_finding_id: "id-\x1b[2J499",
+ reason: expect.any(String),
+ });
+ expect(cli.stderr.text()).not.toContain("Item 500");
+ expect(output.error.message).not.toContain("Item 500");
+ const terminal = createCliTest(main);
+ expect(
+ await terminal.runCli([...f.command.slice(0, -2), "--yes"], f.cliDeps),
+ ).toBe(2);
+ expect(terminal.stderr.text()).toContain("Excluded item 1:");
+ expect(terminal.stderr.text()).toContain("Showing 5 of 500 exclusions");
+ expect(terminal.stderr.text()).not.toContain("Excluded item 6:");
+ expect(terminal.stderr.text()).not.toContain("\x1b");
+ const flags = [
+ ...f.command.slice(0, -1),
+ "jsonl",
+ "--full-output",
+ "--filter-output=findings",
+ ];
+ const filtered = createCliTest(main);
+ expect(await filtered.runCli(flags, f.cliDeps)).toBe(2);
+ const failure = JSON.parse(filtered.stdout.text());
+ expect(failure.data.excluded).toEqual(output.data.excluded);
+ expect(failure.meta.command).toBe("publish findings");
+ const limited = createCliTest(main);
+ expect(await limited.runCli([...flags, "--token-limit=5"], f.cliDeps)).toBe(
+ 2,
+ );
+ expect(JSON.parse(limited.stdout.text())).toMatchObject({
+ ok: false,
+ data: expect.any(String),
+ meta: { nextOffset: 5 },
+ });
+ expect(f.posts).toHaveLength(0);
+});
+
+test("normalized SDK callers can distinguish an empty report from exclusions without authenticating", async () => {
+ for (const selection of [
+ { read: 0, findings: [], excluded: [] },
+ {
+ read: 1,
+ findings: [],
+ excluded: [
+ { position: 1, source_finding_id: null, reason: "Not an occurrence" },
+ ],
+ },
+ ]) {
+ const prepared = prepareNormalizedExternalPublication(selection, options, {
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ credentials: async () => {
+ throw new Error("Unexpected credential read");
+ },
+ });
+ await expect(prepared).rejects.toBeInstanceOf(NoPublishableFindingsError);
+ await expect(prepared).rejects.toMatchObject({ selection });
+ }
+});
+
+test("a failed scanner run is not an empty successful import", async () => {
+ const f = await fixture({
+ version: "1.100.0",
+ results: [],
+ errors: [{ message: "example scan error" }],
+ });
+ const command = f.command.map((argument) =>
+ argument === "wiz" ? "semgrep" : argument,
+ );
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(
+ [
+ ...command,
+ "--source-repository-url",
+ "https://github.com/example/project",
+ "--yes",
+ ],
+ f.cliDeps,
+ ),
+ ).toBe(2);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ status: "failed",
+ error: expect.stringContaining("scan errors"),
+ });
+ expect(f.posts).toHaveLength(0);
+});
+
async function hostedFixture(
provider: "semgrep" | "snyk",
records: unknown,
diff --git a/sdk/typescript/tests-ts/opengrep-findings-local.test.ts b/sdk/typescript/tests-ts/opengrep-findings-local.test.ts
index 89e28394c..fc0d00d85 100644
--- a/sdk/typescript/tests-ts/opengrep-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/opengrep-findings-local.test.ts
@@ -84,7 +84,7 @@ test("OpenGrep grouped traces survive SQLite import, replay, and evidence update
);
});
-test("empty OpenGrep local imports retain scanner diagnostics without creating findings", async () => {
+test("empty OpenGrep local imports reject scanner errors and accept clean reports", async () => {
await using fixture = await localReportFixture(
"opengrep.json",
{
@@ -110,11 +110,16 @@ test("empty OpenGrep local imports retain scanner diagnostics without creating f
excluded: [],
report,
});
- expect(await prepared.import()).toMatchObject({
+ await expect(prepared.import()).rejects.toMatchObject({
+ selection: { report },
+ message: expect.stringContaining(input.errors[0]!.message),
+ });
+ await fixture.writeJson({ ...input, errors: [] });
+ expect(await (await fixture.prepare()).import()).toMatchObject({
read: 0,
ready: 0,
findings: [],
- report,
+ report: { ...report, errors: [] },
counts: { created: 0, updated: 0, unchanged: 0 },
});
expect(await fixture.read()).toEqual([]);
diff --git a/sdk/typescript/tests-ts/scanner-import-contract.test.ts b/sdk/typescript/tests-ts/scanner-import-contract.test.ts
index 5c771d292..1954aa4fd 100644
--- a/sdk/typescript/tests-ts/scanner-import-contract.test.ts
+++ b/sdk/typescript/tests-ts/scanner-import-contract.test.ts
@@ -1,5 +1,6 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
+import { gzipSync } from "node:zlib";
import { expect, test } from "bun:test";
import { prepareLocalExternalImport } from "../src/external-findings-import.js";
import { listLocalExternalFindings } from "../src/external-findings-local.js";
@@ -12,7 +13,10 @@ import {
semgrepJson,
semgrepSarif,
} from "./support/semgrep-import-fixtures.js";
-import { snykJson } from "./support/snyk-import-fixtures.js";
+import { normalizeEndorSarif } from "../src/endor-findings.js";
+import { normalizeSemgrepSarif } from "../src/semgrep-findings.js";
+import { normalizeSnykSarif } from "../src/snyk-findings.js";
+import { snykSarif, snykJson } from "./support/snyk-import-fixtures.js";
import {
removeTemporaryDirectory,
temporaryDirectory,
@@ -139,6 +143,36 @@ test.each(cases)(
},
);
+test.each(["github", "wiz"] as const)(
+ "%s distinguishes a missing report from an empty JSON Lines export",
+ async (provider) => {
+ const root = await temporaryDirectory("scanner-import-contract-");
+ try {
+ for (const [name, data] of [
+ ["report.json", ""],
+ ["report.csv.gz", gzipSync(" \n")],
+ ["report.jsonl.gz", ""],
+ ["report.jsonl.gz", " \n"],
+ ] as const) {
+ const path = join(root, name);
+ await writeFile(path, data);
+ await expect(
+ readExternalFindings(path, { provider }),
+ ).rejects.toThrow();
+ }
+ for (const name of ["selection", "selection.jsonl.gz"]) {
+ const path = join(root, name);
+ await writeFile(path, name.endsWith(".gz") ? gzipSync("") : "");
+ expect(
+ (await readExternalFindings(path, { provider })).findings,
+ ).toEqual({ read: 0, findings: [], excluded: [] });
+ }
+ } finally {
+ await removeTemporaryDirectory(root);
+ }
+ },
+);
+
test("overlapping vendor IDs and advisories stay distinct on SQLite replay", async () => {
await using fixture = await localFindingsFixture({ remote: repositoryUrl });
const { repository, environment } = fixture;
@@ -237,3 +271,103 @@ test("overlapping vendor IDs and advisories stay distinct on SQLite replay", asy
stored.find((record) => record.provider === "wiz"),
);
});
+
+const sarifCases = [
+ ["endor", endorSarif, normalizeEndorSarif],
+ [
+ "semgrep",
+ semgrepSarif,
+ (input: unknown) =>
+ normalizeSemgrepSarif(input, { sourceRepositoryUrl: repositoryUrl }),
+ ],
+ ["snyk", snykSarif, normalizeSnykSarif],
+] as const;
+const emptySelection = { read: 0, findings: [], excluded: [] };
+
+test.each(sarifCases)(
+ "%s SARIF accepts no-data exports and rejects failed or malformed reports",
+ (_provider, fixture, normalize) => {
+ const report = fixture();
+ const { results: _results, ...emptyRun } = report.runs[0]!;
+ const normalizeRun = (run: unknown) =>
+ normalize({ ...report, runs: [run] });
+ expect(normalize({ ...report, runs: [] })).toMatchObject(emptySelection);
+ for (const run of [emptyRun, { ...emptyRun, results: [] }])
+ expect(normalizeRun(run)).toMatchObject(emptySelection);
+ for (const invalid of [null, {}, "invalid"]) {
+ expect(() => normalizeRun({ ...emptyRun, results: invalid })).toThrow(
+ "must be an array",
+ );
+ expect(() => normalize({ ...report, runs: invalid })).toThrow(
+ "must be an array",
+ );
+ }
+ for (const [invocation, message] of [
+ [{ executionSuccessful: false }, "unsuccessful invocation"],
+ [
+ {
+ executionSuccessful: true,
+ toolExecutionNotifications: [
+ { level: "error", message: { text: "Synthetic scan failure" } },
+ ],
+ },
+ "Synthetic scan failure",
+ ],
+ ] as const)
+ expect(() =>
+ normalizeRun({ ...emptyRun, invocations: [invocation] }),
+ ).toThrow(message);
+ expect(() =>
+ normalizeRun({
+ ...emptyRun,
+ conversion: {
+ invocation: {
+ executionSuccessful: false,
+ processStartFailureMessage: "Synthetic converter failure",
+ },
+ },
+ }),
+ ).toThrow("Synthetic converter failure");
+ },
+);
+
+test.each(sarifCases)(
+ "%s SARIF validates provenance even in empty runs",
+ async (provider, fixture) => {
+ const root = await temporaryDirectory("scanner-import-contract-");
+ try {
+ const path = join(root, "report.sarif");
+ const report = fixture();
+ const run = report.runs[0]!;
+ const read = async (runs: unknown) => {
+ await writeFile(path, JSON.stringify({ ...report, runs }));
+ return readExternalFindings(path, readerOptions(provider), "local");
+ };
+ const repository = { repositoryUri: repositoryUrl };
+ for (const results of [run.results, []])
+ await expect(
+ read([{ ...run, results, versionControlProvenance: repository }]),
+ ).rejects.toThrow("version control provenance must be an array");
+ const foreignUrl = "https://github.com/example/other";
+ const foreignRun = {
+ ...run,
+ results: [],
+ versionControlProvenance: [{ repositoryUri: foreignUrl }],
+ };
+ for (const runs of [
+ [foreignRun],
+ [{ ...run, versionControlProvenance: [repository] }, foreignRun],
+ ]) {
+ const parsed = read(runs);
+ if (provider === "semgrep")
+ await expect(parsed).rejects.toThrow("does not match");
+ else
+ expect((await parsed).sourceRepositories).toContainEqual({
+ url: foreignUrl,
+ });
+ }
+ } finally {
+ await removeTemporaryDirectory(root);
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/scanner-import.test.ts b/sdk/typescript/tests-ts/scanner-import.test.ts
index 56650d17b..bfaa5b6d2 100644
--- a/sdk/typescript/tests-ts/scanner-import.test.ts
+++ b/sdk/typescript/tests-ts/scanner-import.test.ts
@@ -8,6 +8,7 @@ import {
readScannerText,
relativePath,
sarifRunContextSelector,
+ validateSarifRun,
} from "../src/scanner-import.js";
import { createTemporaryDirectories } from "./support/temporary-directories.js";
@@ -79,6 +80,103 @@ test("scanner readers preserve UTF-8 and JSON parse diagnostics", async () => {
});
});
+test.each(["toolExecutionNotifications", "toolConfigurationNotifications"])(
+ "SARIF %s warnings preserve a successful invocation",
+ (property) => {
+ const invocation = {
+ executionSuccessful: true,
+ [property]: [
+ { level: "warning", message: { text: "Synthetic scan warning" } },
+ { level: "note", message: { text: "Synthetic scan note" } },
+ ],
+ };
+ const run = { invocations: [invocation], conversion: { invocation } };
+ expect(() => validateSarifRun(run, "Example")).not.toThrow();
+ },
+);
+
+test("SARIF extension descriptors retain error severity across index, ID and GUID references", () => {
+ const guid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
+ const componentGuid = "bbbbbbbb-cccc-dddd-eeee-ffffffffffff";
+ const tool = {
+ extensions: [
+ {
+ guid: componentGuid,
+ notifications: [
+ { id: "coverage", guid, defaultConfiguration: { level: "error" } },
+ ],
+ },
+ ],
+ };
+ for (const reference of [
+ { index: 0 },
+ { id: "coverage" },
+ { guid: guid.toUpperCase() },
+ ]) {
+ const notification = {
+ descriptor: {
+ ...reference,
+ toolComponent: { guid: componentGuid.toUpperCase() },
+ },
+ message: { text: "Synthetic descriptor failure" },
+ };
+ const invocation = {
+ executionSuccessful: true,
+ toolConfigurationNotifications: [notification],
+ };
+ const validate = (overrides = {}) =>
+ validateSarifRun(
+ {
+ tool,
+ invocations: [{ ...invocation, ...overrides }],
+ },
+ "Example",
+ );
+ expect(() => validate()).toThrow("Synthetic descriptor failure");
+ expect(() =>
+ validate({
+ notificationConfigurationOverrides: [
+ {
+ descriptor: notification.descriptor,
+ configuration: { level: "warning" },
+ },
+ ],
+ }),
+ ).not.toThrow();
+ }
+});
+
+test("malformed SARIF notifications cannot hide a scanner error", () => {
+ for (const [notifications, message] of [
+ [{ level: "error" }, "must be an array"],
+ [[null], "must be an object"],
+ ] as const) {
+ const invocation = {
+ executionSuccessful: true,
+ toolConfigurationNotifications: notifications,
+ };
+ const run = { invocations: [invocation] };
+ expect(() => validateSarifRun(run, "Example")).toThrow(message);
+ }
+});
+
+test("SARIF validates converter failures separately from scanner invocations", () => {
+ const converted = (invocation: unknown) =>
+ validateSarifRun({ conversion: { invocation } }, "Example");
+ expect(() => converted({ executionSuccessful: false })).toThrow(
+ "unsuccessful invocation",
+ );
+ const failedConversion = {
+ toolExecutionNotifications: [
+ { level: "error", message: { text: "Synthetic conversion failure" } },
+ ],
+ };
+ for (const executionSuccessful of [true, false])
+ expect(() =>
+ converted({ ...failedConversion, executionSuccessful }),
+ ).toThrow("Synthetic conversion failure");
+});
+
test("scanner repository paths retain colons outside Windows drive prefixes", () => {
expect(relativePath("schema:prod.json")).toBe("schema:prod.json");
expect(relativePath("src/schema:prod.ts")).toBe("src/schema:prod.ts");
diff --git a/sdk/typescript/tests-ts/semgrep-findings-local.test.ts b/sdk/typescript/tests-ts/semgrep-findings-local.test.ts
index 72fedbe10..f14166358 100644
--- a/sdk/typescript/tests-ts/semgrep-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/semgrep-findings-local.test.ts
@@ -282,8 +282,20 @@ test.each(formats)(
},
{ remote: repositoryUrl },
);
- await fixture.writeJson(report(format));
+ const input = report(format);
+ await fixture.writeJson(input);
await expect(fixture.prepare()).rejects.toThrow("does not match");
+ if ("runs" in input) input.runs[0]!.results.length = 0;
+ else input.results.length = 0;
+ await fixture.writeJson(input);
+ await expect(fixture.prepare()).rejects.toThrow("does not match");
+ const empty = await fixture.prepare({ sourceRepositoryUrl: repositoryUrl });
+ expect((await empty.import()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 0,
+ });
+ await expect(access(fixture.stateDirectory)).rejects.toThrow();
expect(await fixture.read()).toEqual([]);
},
);
@@ -352,6 +364,12 @@ test.each([
}
await writeReport(originalUrl, true);
if (platform === "unknown host") {
+ await expect(
+ prepareLocalExternalImport(file, options, dependencies),
+ ).rejects.toThrow("does not match");
+ const empty = sarifWithRepositories([sourceRepositoryUrl, originalUrl]);
+ empty.runs[0]!.results.length = 0;
+ await writeFile(file, JSON.stringify(empty));
await expect(
prepareLocalExternalImport(file, options, dependencies),
).rejects.toThrow("does not match");
diff --git a/sdk/typescript/tests-ts/semgrep-findings.test.ts b/sdk/typescript/tests-ts/semgrep-findings.test.ts
index 805eea856..0fa0c80b6 100644
--- a/sdk/typescript/tests-ts/semgrep-findings.test.ts
+++ b/sdk/typescript/tests-ts/semgrep-findings.test.ts
@@ -122,6 +122,17 @@ test.each([
},
);
+test("a zero-result Semgrep report must retain its errors array", () => {
+ const { errors, ...input } = semgrepJson();
+ expect(normalizeSemgrepFindings(input).findings).toHaveLength(1);
+ expect(() => normalizeSemgrepFindings({ ...input, results: [] })).toThrow(
+ "errors array",
+ );
+ expect(normalizeSemgrepFindings({ ...input, results: [], errors }).read).toBe(
+ 0,
+ );
+});
+
test("failed scans and unrelated SARIF producers fail before publishing partial results", () => {
const input: any = semgrepJson();
input.errors = [{ message: "Scan incomplete" }];
diff --git a/sdk/typescript/tests-ts/snyk-findings-local.test.ts b/sdk/typescript/tests-ts/snyk-findings-local.test.ts
index 5a56ad116..3425a8317 100644
--- a/sdk/typescript/tests-ts/snyk-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/snyk-findings-local.test.ts
@@ -94,6 +94,15 @@ test.each(["plugin", "JSON", "SARIF"] as const)(
};
await fixture.writeJson(input);
await expect(fixture.prepare()).rejects.toThrow(/repository/iu);
+ if ("findings" in input) {
+ input.findings.length = 0;
+ input.collection.scans[0]!.issueCount = 0;
+ } else if ("vulnerabilities" in input) {
+ input.vulnerabilities.length = 0;
+ input.ok = true;
+ } else input.runs[0]!.results.length = 0;
+ await fixture.writeJson(input);
+ await expect(fixture.prepare()).rejects.toThrow(/does not match.*remote/iu);
expect(await fixture.read()).toEqual([]);
},
);
diff --git a/sdk/typescript/tests-ts/snyk-findings.test.ts b/sdk/typescript/tests-ts/snyk-findings.test.ts
index be7de2e61..e05c3aecd 100644
--- a/sdk/typescript/tests-ts/snyk-findings.test.ts
+++ b/sdk/typescript/tests-ts/snyk-findings.test.ts
@@ -433,6 +433,46 @@ test("plugin finding identity ignores scan timestamps and preserves separate occ
expect(duplicate.excluded).toHaveLength(2);
});
+test("empty plugin reports require a successful zero-issue SCA scan", () => {
+ const input: any = snykPluginExport();
+ input.findings = [];
+ const scan = input.collection.scans[0];
+ scan.issueCount = 0;
+ expect(normalizeSnykFindingsExport(input)).toMatchObject({
+ read: 0,
+ findings: [],
+ excluded: [],
+ });
+ for (const outcome of ["failed", "denied", "unavailable", "not_requested"]) {
+ scan.outcome = outcome;
+ expect(() => normalizeSnykFindingsExport(input)).toThrow("did not succeed");
+ }
+ scan.outcome = "succeeded";
+ for (const issueCount of [1, "1", -1]) {
+ scan.issueCount = issueCount;
+ expect(() => normalizeSnykFindingsExport(input)).toThrow();
+ }
+ scan.issueCount = 0;
+ input.collection.completeness = {
+ collection: "partial",
+ reason: "Other products were not selected",
+ };
+ expect(normalizeSnykFindingsExport(input).report).toMatchObject({
+ collection: input.collection,
+ });
+ input.collection.scans.push({
+ category: "code",
+ tool: "snyk_code_scan",
+ outcome: "succeeded",
+ issueCount: 2,
+ });
+ expect(() => normalizeSnykFindingsExport(input)).toThrow("reported issues");
+ input.collection.scans = [];
+ expect(() => normalizeSnykFindingsExport(input)).toThrow(
+ "successful SCA scan",
+ );
+});
+
test("mixed plugin bundles explicitly exclude other products and licenses", () => {
const input = snykPluginExport();
for (const [scanner, category, scan] of [
@@ -605,6 +645,16 @@ test("native project errors stop import, including partial all-projects output",
error: "Synthetic dependency resolution failed",
path: "/work/example/worker",
};
+ for (const uniqueCount of [undefined, 0, 1]) {
+ expect(() =>
+ normalizeSnykJson({
+ ...snykJson(),
+ ok: false,
+ vulnerabilities: [],
+ uniqueCount,
+ }),
+ ).toThrow("reported issues");
+ }
for (const input of [failed, [snykJson(), failed]]) {
expect(() => normalizeSnykJson(input)).toThrow(
"Synthetic dependency resolution failed",
@@ -617,6 +667,7 @@ test("native project errors stop import, including partial all-projects output",
{ infrastructureAsCodeIssues: [], ok: true },
{ version: "2.1.0", runs: [] },
{ data: [] },
+ [],
]) {
expect(() => normalizeSnykJson(input)).toThrow();
}
@@ -870,3 +921,19 @@ test.each(snykRepositoryContexts)(
});
},
);
+
+test("failed SCA scans reject valid rows and retain diagnostics for excluded rows", () => {
+ const input = snykPluginExport();
+ Object.assign(input.collection.scans[0]!, {
+ outcome: "failed",
+ error: "SCA timed out",
+ });
+ expect(() => normalizeSnykFindingsExport(input)).toThrow("SCA timed out");
+ input.findings[0]!.originatingScanner = "snyk-code";
+ expect(normalizeSnykFindingsExport(input)).toMatchObject({
+ read: 1,
+ findings: [],
+ excluded: [{ position: 1 }],
+ report: { errors: [expect.stringContaining("SCA timed out")] },
+ });
+});
diff --git a/sdk/typescript/tests-ts/wiz-findings.test.ts b/sdk/typescript/tests-ts/wiz-findings.test.ts
index 59952b182..e50d5ef04 100644
--- a/sdk/typescript/tests-ts/wiz-findings.test.ts
+++ b/sdk/typescript/tests-ts/wiz-findings.test.ts
@@ -415,6 +415,23 @@ test("workload secrets and cloud configuration remain visible exclusions in a mi
]);
});
+test("an empty Wiz export cannot report a positive finding count", async () => {
+ const page = { nodes: [], totalCount: 20, pageInfo: { hasNextPage: false } };
+ await expect(parse({ data: { sastFindings: page } })).rejects.toThrow(
+ "sastFindings.totalCount",
+ );
+ expect(
+ (await parse({ data: { sastFindings: { ...page, totalCount: 0 } } })).read,
+ ).toBe(0);
+ expect(
+ (
+ await parse({
+ data: { sastFindings: page, iacFindings: { nodes: [iac] } },
+ })
+ ).read,
+ ).toBe(1);
+});
+
test("GraphQL errors, unfinished finding pages, and unfinished inventory stop parsing", async () => {
await expect(
parse({