Skip to content

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

feat(imports): read native Trivy dependency reports in the SDK (#2087)

Michael D'Angelob6d1e0ddb79f
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 8dbd5c147..6dd52146b 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -729,6 +729,21 @@ 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.
+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
+(`.` for the whole checkout) unless the report's remote target and Git metadata establish it.
+
+```ts
+import { readTrivyFindings } from "@openai/codex-security";
+
+const { findings, excluded, report } = await readTrivyFindings(
+ "trivy.json.gz",
+ "local",
+ ".",
+);
+```
+
For CLI examples and supported input formats, see the
[scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md).
diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.ts
index 94b194534..a41ffb558 100644
--- a/sdk/typescript/scripts/fixtures/package-consumer.ts
+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts
@@ -11,6 +11,7 @@ import {
type NormalizedLocalImportOptions,
type StoredExternalFinding,
normalizeSnykFindingsExport,
+ normalizeTrivyFindings,
prepareNormalizedExternalPublication,
type ExternalFindings,
type FindingImportRequest,
@@ -437,3 +438,7 @@ export async function importLocalFile(
export function snykPluginFindings(bundle: unknown): ExternalFindings {
return normalizeSnykFindingsExport(bundle);
}
+
+export function trivyFindings(report: unknown): ExternalFindings {
+ return normalizeTrivyFindings(report, "local", ".");
+}
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index c6daf912f..a2021072d 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -56,6 +56,7 @@ const distModules = [
"sonar-import",
"native-json-findings",
"opengrep-findings",
+ "trivy-findings",
"external-findings-publish",
"private-finding-import",
"external-import-contract",
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index cd9edf7dd..57e1c25fa 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -342,6 +342,7 @@ export {
normalizeVeracodeFindings,
readVeracodeFindings,
} from "./veracode-findings.js";
+export { normalizeTrivyFindings, readTrivyFindings } from "./trivy-findings.js";
export {
normalizeBlackDuckFindings,
readBlackDuckFindings,
diff --git a/sdk/typescript/src/trivy-findings.ts b/sdk/typescript/src/trivy-findings.ts
new file mode 100644
index 000000000..02d35b308
--- /dev/null
+++ b/sdk/typescript/src/trivy-findings.ts
@@ -0,0 +1,516 @@
+import { posix, sep } from "node:path";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import { validateExternalEvidence } from "./external-import-contract.js";
+import type { ExternalFindings } from "./external-findings.js";
+import { isGitHubCloudHost, isGitSsh, parseGitRemote } from "./git-remote.js";
+import {
+ hostedRepositoryUrlKey,
+ normalizeHostedGitRepositoryUrl,
+} from "./hosted-git-repository.js";
+import { isRecord } from "./record.js";
+import { REPORTABLE_SEVERITIES } from "./scan-settings.js";
+import {
+ array,
+ normalizeRecords,
+ readScannerJson,
+ record,
+ relativePath,
+ requiredText,
+ stableId,
+ strings,
+ text,
+} from "./scanner-import.js";
+
+type NativeRecord = Record<string, unknown>;
+
+const urlScheme = /^[a-z][a-z\d+.-]*:\/\//iu;
+const javaArchiveAncestor = /\.(?:jar|war|ear|par)\//iu;
+
+const curlUrlPrefix = /^(?:(?:https?|ftps?)::)?(?:https?|ftps?):\/{1,3}/iu;
+const unsafeRepositoryUrl =
+ "Use a Trivy repository URL without credentials, a query, or a fragment.";
+
+function hasHttpUserinfo(
+ value: string | null,
+ allowImplicitHttps: boolean,
+): boolean {
+ if (!value) return false;
+ const prefix = curlUrlPrefix.exec(value)?.[0];
+ if (!prefix && (!allowImplicitHttps || /^[a-z]:[\\/]/iu.test(value)))
+ return false;
+ // Git's HTTP transport treats backslashes before @ as part of userinfo.
+ const authority = value.slice(prefix?.length ?? 0).split(/[/?#]/u, 1)[0]!;
+ const at = authority.lastIndexOf("@");
+ const colon = authority.indexOf(":");
+ const scp = colon > authority.indexOf("@");
+ // A bare user@host:path is Git's SSH form. Trivy reads user@host/path as HTTPS.
+ return at > 0 && (!!prefix || (!scp && !authority.includes("\\", at + 1)));
+}
+
+function networkRepository(value: unknown): string | null {
+ const source = text(value);
+ if (!source || /^(?:[a-z]:|[./\\])/iu.test(source)) return null;
+ const remote = parseGitRemote(source);
+ if (!remote) return null;
+ const { url } = remote;
+ const ssh = isGitSsh(url.protocol);
+ if (url.password || (!ssh && url.username) || /[?#\t\r\n]/u.test(source))
+ throw new Error(unsafeRepositoryUrl);
+ if (url.protocol === "file:") return null;
+ if (
+ !url.hostname ||
+ !remote.path ||
+ (!ssh &&
+ !["http:", "https:", "git:", "ftp:", "ftps:"].includes(url.protocol))
+ )
+ throw new Error("Unsupported Trivy repository URL.");
+ return source;
+}
+
+function comparableGitHubRemote(remote: string): string | undefined {
+ const parsed = parseGitRemote(remote);
+ if (!parsed) return undefined;
+ const prefix = `${parsed.url.protocol}//`;
+ // Git dispatches mixed-case schemes to distinct remote helpers.
+ if (!parsed.scpStyle && !remote.startsWith(prefix)) return undefined;
+ const host = parsed.url.hostname.toLowerCase();
+ if (!isGitHubCloudHost(host)) return undefined;
+ const normalized = normalizeHostedGitRepositoryUrl(
+ remote,
+ `https://${host}`,
+ true,
+ );
+ return /^https?:\/\//iu.test(normalized) ? normalized : undefined;
+}
+
+function trivyRemoteKey(remote: string): string {
+ const normalized = comparableGitHubRemote(remote);
+ return normalized
+ ? hostedRepositoryUrlKey(normalized, true, false, "local")
+ : remote;
+}
+
+const sshScheme = /^(?:ssh|git\+ssh|ssh\+git):\/\//u;
+
+function userlessSsh(url: string): boolean {
+ return sshScheme.test(url) && !new URL(url).username;
+}
+
+const headerFields = [
+ "SchemaVersion",
+ "ArtifactType",
+ "ArtifactID",
+ "ReportID",
+ "CreatedAt",
+];
+
+// Go may rewrite escaped separators or unreserved bytes in mixed Unicode paths.
+// Only escape spaces and non-ASCII bytes when existing escapes are unambiguous.
+function escapedHttpTarget(target: string): string {
+ return target.replace(
+ /^(https?:\/\/[^/]+)(\/(?:[^%]|%(?:2[05]|[89A-F][\dA-F]))*)$/u,
+ (_, authority: string, path: string) =>
+ authority + path.replace(/[ \P{ASCII}]+/gu, encodeURIComponent),
+ );
+}
+
+function trivyReportRemotes(report: NativeRecord): string[] {
+ const metadata = report["Metadata"];
+ const repoUrl = text(isRecord(metadata) && metadata["RepoURL"]);
+ const name = text(report["ArtifactName"]);
+ if (
+ hasHttpUserinfo(repoUrl, true) ||
+ hasHttpUserinfo(name, report["ArtifactType"] !== "filesystem")
+ )
+ throw new Error(unsafeRepositoryUrl);
+ const repository = networkRepository(repoUrl);
+ let artifact = name && urlScheme.test(name) ? networkRepository(name) : null;
+ // A filesystem display label is validated but never identifies the repository.
+ if (report["ArtifactType"] === "filesystem")
+ return repository ? [repository] : [];
+ // Trivy accepts scheme-less HTTPS targets and relative checkout paths.
+ // A scheme-less name identifies a remote only when Git metadata corroborates it.
+ const target =
+ artifact ??
+ (name && /^[^./:\\][^/:\\]*\//u.test(name) ? `https://${name}` : null);
+ if (
+ target &&
+ repository &&
+ report["ArtifactType"] === "repository" &&
+ (target === repository || escapedHttpTarget(target) === repository)
+ )
+ artifact = repository;
+ // A checkout-supplied label cannot restore an omitted SSH user. Keep any
+ // other difference visible when validating the report's repository claims.
+ if (
+ repository &&
+ userlessSsh(repository) &&
+ artifact?.replace(/^([^:]+:\/\/)[^/@]+@/u, "$1") === repository
+ )
+ return [repository];
+ return [repository, artifact].filter((url) => url !== null);
+}
+
+function matchingTrivyRemotes([
+ repository,
+ artifact,
+]: readonly string[]): boolean {
+ return (
+ !!repository &&
+ !!artifact &&
+ trivyRemoteKey(repository) === trivyRemoteKey(artifact)
+ );
+}
+
+function repositoryPath(value: unknown, directory = false): string | null {
+ const raw = text(value);
+ if (!raw || !relativePath(raw)) return null;
+ // Check the emitted spelling across platforms while retaining literal POSIX backslashes.
+ const path = posix.normalize(raw);
+ const portable = posix.normalize(path.replaceAll("\\", "/"));
+ const firstComponent = portable.split("/", 1)[0]!;
+ const at = firstComponent.indexOf("@", 1);
+ const scpStyle = at !== -1 && firstComponent.indexOf(":", at + 2) !== -1;
+ return relativePath(portable) &&
+ (directory || (portable !== "." && !portable.endsWith("/"))) &&
+ !scpStyle &&
+ !/^[a-z][a-z\d+.-]*:\//iu.test(portable)
+ ? path
+ : null;
+}
+
+const aggregateTargets = new Map([
+ ["python-pkg", "Python"],
+ ["conda-pkg", "Conda"],
+ ["gemspec", "Ruby"],
+ ["node-pkg", "Node.js"],
+ ["jar", "Java"],
+ ["kubernetes", "Kubernetes"],
+]);
+const nonManifestTypes = new Set([
+ "gobinary",
+ "rustbinary",
+ "jar",
+ "javascript",
+]);
+
+function resolveScanRoot(
+ scanRoot: string | undefined,
+ remoteRepository: boolean,
+): string {
+ if (scanRoot === undefined) {
+ if (remoteRepository) return ".";
+ throw new Error(
+ "Specify scanRoot relative to the repository; use . for a whole-checkout scan.",
+ );
+ }
+ const root = repositoryPath(scanRoot.split(sep).join("/"), true)?.replace(
+ /\/$/u,
+ "",
+ );
+ if (!root)
+ throw new Error(
+ "scanRoot must be a repository-relative directory without traversal.",
+ );
+ if (remoteRepository && root !== ".")
+ throw new Error(
+ "A remote Trivy repository scan starts at the checkout root; scanRoot must be .",
+ );
+ return root;
+}
+
+function scopedPath(root: string, value: unknown): string | null {
+ const path = repositoryPath(value);
+ return path === null ? null : posix.join(root, path);
+}
+
+function pick(source: NativeRecord, fields: string[]): NativeRecord {
+ return Object.fromEntries(
+ fields
+ .filter((field) => Object.hasOwn(source, field))
+ .map((field) => [field, source[field]]),
+ );
+}
+
+function packageKeys(row: NativeRecord, inventory: boolean) {
+ const path = row[inventory ? "FilePath" : "PkgPath"];
+ const identifier = row[inventory ? "Identifier" : "PkgIdentifier"];
+ const name = row[inventory ? "Name" : "PkgName"];
+ const version = row[inventory ? "Version" : "InstalledVersion"];
+ const file = repositoryPath(path) ?? text(path);
+ const key = (kind: string, value: unknown) =>
+ text(value) && JSON.stringify([kind, value, file]);
+ const native = isRecord(identifier) ? identifier : {};
+ return {
+ id: key("id", row[inventory ? "ID" : "PkgID"]),
+ uid: key("uid", native["UID"]),
+ purl: key("purl", native["PURL"]),
+ bomRef: key("bomRef", native["BOMRef"]),
+ nameVersion:
+ text(name) &&
+ text(version) &&
+ JSON.stringify(["name-version", name, version, file]),
+ };
+}
+
+type PackageIndex = Map<
+ string,
+ { pkg: NativeRecord; keys: ReturnType<typeof packageKeys> } | null
+>;
+
+function indexPackages(packages: unknown): PackageIndex {
+ const index: PackageIndex = new Map();
+ for (const value of array(packages ?? [], "Trivy Packages")) {
+ const pkg = record(value, "Trivy package");
+ const keys = packageKeys(pkg, true);
+ const match = { pkg, keys };
+ for (const key of Object.values(keys))
+ if (key) index.set(key, index.has(key) ? null : match);
+ }
+ return index;
+}
+
+function matchingPackage(vulnerability: NativeRecord, index: PackageIndex) {
+ const keys = packageKeys(vulnerability, false);
+ const supplied = (["uid", "id", "purl", "bomRef"] as const).filter(
+ (field) => keys[field],
+ );
+ for (const field of supplied.length ? supplied : (["nameVersion"] as const)) {
+ const key = keys[field];
+ const match = key && index.get(key);
+ if (
+ match &&
+ agreesWhenPresent(vulnerability["PkgName"], match.pkg["Name"]) &&
+ agreesWhenPresent(
+ vulnerability["InstalledVersion"],
+ match.pkg["Version"],
+ ) &&
+ supplied.every((id) => !match.keys[id] || keys[id] === match.keys[id])
+ )
+ return match.pkg;
+ }
+ return null;
+}
+
+function agreesWhenPresent(detected: unknown, inventoried: unknown): boolean {
+ return !text(detected) || !text(inventoried) || detected === inventoried;
+}
+
+interface Entry {
+ result: { Target?: string; Type: string; Class: string };
+ packages: PackageIndex;
+ value: unknown;
+}
+
+function occurrence(entry: Entry | string, root: string) {
+ if (typeof entry === "string") throw new Error(entry);
+ const vulnerability = record(entry.value, "Trivy vulnerability");
+ const { Target, Type } = entry.result;
+ return {
+ ...entry,
+ vulnerability,
+ advisory: requiredText(
+ vulnerability["VulnerabilityID"],
+ "Trivy VulnerabilityID",
+ ),
+ name: requiredText(vulnerability["PkgName"], "Trivy PkgName"),
+ pkgPath: text(vulnerability["PkgPath"]),
+ targetPath:
+ aggregateTargets.get(Type) === Target ? null : scopedPath(root, Target),
+ packagePath: scopedPath(root, vulnerability["PkgPath"]),
+ };
+}
+
+/** Import native Trivy dependency occurrences. Local scans require their checkout-relative
+ * scan root. The package ecosystem is the PURL type when supplied, otherwise the analyzer. */
+export function normalizeTrivyFindings(
+ input: unknown,
+ target: ExternalImportTarget = "cloud",
+ scanRoot?: string,
+): ExternalFindings {
+ const document = record(input, "Trivy report");
+ if (document["SchemaVersion"] !== 2)
+ throw new Error(
+ "Expected a native Trivy JSON report with SchemaVersion 2.",
+ );
+ if (
+ document["ArtifactType"] !== "repository" &&
+ document["ArtifactType"] !== "filesystem"
+ )
+ throw new Error(
+ "Only Trivy repository and filesystem reports are supported.",
+ );
+ const metadata = record(document["Metadata"] ?? {}, "Trivy Metadata");
+ const urls = trivyReportRemotes(document);
+ const report = {
+ ...pick(document, headerFields),
+ ...(isRecord(document["Trivy"])
+ ? { Trivy: pick(document["Trivy"], ["Version"]) }
+ : {}),
+ ...(typeof document["ArtifactName"] === "string"
+ ? { ArtifactName: document["ArtifactName"] }
+ : {}),
+ Metadata: pick(metadata, ["RepoURL", "Branch", "Commit"]),
+ };
+ // A scan root requires corroboration. Explicit-root readers can inspect a report
+ // whose declarations still have to agree with the destination at import.
+ const root = resolveScanRoot(scanRoot, matchingTrivyRemotes(urls));
+
+ const entries: (Entry | string)[] = [];
+ for (const group of array(document["Results"] ?? [], "Trivy Results")) {
+ const result = record(group, "Trivy result");
+ if (result["Class"] !== "lang-pkgs") {
+ entries.push(
+ `Unsupported Trivy result class: ${text(result["Class"]) ?? "(missing)"}. Only lang-pkgs vulnerabilities are imported.`,
+ );
+ continue;
+ }
+ for (const field of [
+ "Misconfigurations",
+ "Secrets",
+ "Licenses",
+ "CryptoAssets",
+ "CustomResources",
+ "ExperimentalModifiedFindings",
+ ])
+ if (array(result[field] ?? [], `Trivy ${field}`).length)
+ entries.push(`Unsupported Trivy ${field} in lang-pkgs result.`);
+
+ const vulnerabilities = array(
+ result["Vulnerabilities"] ?? [],
+ "Trivy Vulnerabilities",
+ );
+ if (!vulnerabilities.length) continue;
+ const reportedTarget = result["Target"];
+ if (reportedTarget != null && typeof reportedTarget !== "string")
+ throw new Error("Trivy result Target must be text.");
+ const context = {
+ ...(reportedTarget == null ? {} : { Target: reportedTarget }),
+ Type: requiredText(result["Type"], "Trivy result Type"),
+ Class: result["Class"],
+ };
+ const packages = indexPackages(result["Packages"]);
+ for (const value of vulnerabilities)
+ entries.push({ result: context, packages, value });
+ }
+
+ const findings = normalizeRecords(
+ entries,
+ (entry) => {
+ const row = occurrence(entry, root);
+ const { result, packages, vulnerability, advisory, name, targetPath } =
+ row;
+ const identifier = vulnerability["PkgIdentifier"];
+ const purl = isRecord(identifier) ? text(identifier["PURL"]) : null;
+ const ecosystem =
+ purl?.match(/^pkg:([a-z][a-z\d.+-]*)\//iu)?.[1]?.toLowerCase() ??
+ result.Type;
+ const pkg = matchingPackage(vulnerability, packages);
+ const manifest = nonManifestTypes.has(result.Type) ? null : targetPath;
+ // Trivy uses the same spelling for archive members and files in exploded archives.
+ let declaration = row.pkgPath ? row.packagePath : manifest;
+ if (
+ result.Type === "jar" &&
+ row.pkgPath !== null &&
+ javaArchiveAncestor.test(row.pkgPath) &&
+ /\.(?:jar|ear|war)$/u.test(row.pkgPath)
+ )
+ declaration = null;
+ const locations: { path: string; line: number | null }[] = [];
+ if (targetPath && targetPath !== declaration)
+ locations.push({ path: targetPath, line: null });
+ if (declaration) {
+ const lines = new Set<number>();
+ for (const range of array(
+ pkg?.["Locations"] ?? [],
+ "Trivy package Locations",
+ )) {
+ const start = isRecord(range) && range["StartLine"];
+ if (
+ typeof start === "number" &&
+ Number.isSafeInteger(start) &&
+ start > 0
+ )
+ lines.add(start);
+ }
+ if (!lines.size) locations.push({ path: declaration, line: null });
+ for (const line of lines) locations.push({ path: declaration, line });
+ }
+ const severity = text(vulnerability["Severity"])?.toLowerCase();
+ return validateExternalEvidence(
+ {
+ title: text(vulnerability["Title"]) ?? `${advisory} in ${name}`,
+ severity:
+ REPORTABLE_SEVERITIES.find((level) => level === severity) ??
+ "unknown",
+ description: text(vulnerability["Description"]),
+ url: text(vulnerability["PrimaryURL"]),
+ advisory_ids: [
+ ...new Set([advisory, ...strings(vulnerability["VendorIDs"])]),
+ ],
+ packages: [
+ {
+ name,
+ ecosystem,
+ manifest_path: manifest,
+ installed_version: text(vulnerability["InstalledVersion"]),
+ fixed_versions:
+ text(vulnerability["FixedVersion"])
+ ?.split(",")
+ .map((version) => version.trim())
+ .filter(Boolean) ?? [],
+ },
+ ],
+ locations,
+ branch: text(metadata["Branch"]),
+ source_scan_id: text(document["ReportID"]),
+ source_data: structuredClone({
+ scanRoot: root,
+ report,
+ result,
+ vulnerability,
+ ...(pkg
+ ? {
+ package: pick(pkg, [
+ "ID",
+ "Name",
+ "Version",
+ "Identifier",
+ "FilePath",
+ "Relationship",
+ "Locations",
+ ]),
+ }
+ : {}),
+ }),
+ },
+ target,
+ );
+ },
+ (entry) => {
+ const { result, advisory, name, pkgPath, targetPath, packagePath } =
+ occurrence(entry, root);
+ const manifest = targetPath ?? text(result.Target);
+ const concretePath = packagePath ?? pkgPath;
+ return stableId("trivy", [
+ result.Type,
+ manifest,
+ advisory,
+ name,
+ concretePath === manifest ? null : concretePath,
+ ...(!targetPath && !packagePath && root !== "." ? [root] : []),
+ ]);
+ },
+ target,
+ );
+ if (!findings.findings.length) findings.report = report;
+ return findings;
+}
+
+export async function readTrivyFindings(
+ path: string,
+ target: ExternalImportTarget = "cloud",
+ scanRoot?: string,
+): Promise<ExternalFindings> {
+ return normalizeTrivyFindings(await readScannerJson(path), target, scanRoot);
+}
diff --git a/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts b/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts
new file mode 100644
index 000000000..1789d4237
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts
@@ -0,0 +1,61 @@
+export function trivyReport() {
+ const name = "@example/package";
+ const version = "1.0.0";
+ const id = `${name}@${version}`;
+ const identifier = {
+ PURL: "pkg:npm/%40example/[email protected]",
+ UID: "123456789abcdef0",
+ };
+ return {
+ SchemaVersion: 2,
+ Trivy: { Version: "0.76.1" },
+ ReportID: "00000000-0000-7000-8000-000000000001",
+ CreatedAt: "2026-01-01T00:00:00Z",
+ ArtifactName: ".",
+ ArtifactType: "repository",
+ Metadata: {
+ RepoURL: "https://github.com/example/project",
+ Branch: "main",
+ Commit: "a".repeat(40),
+ },
+ Results: [
+ {
+ Target: "package-lock.json",
+ Class: "lang-pkgs",
+ Type: "npm",
+ Packages: [
+ {
+ ID: id,
+ Name: name,
+ Version: version,
+ Identifier: { ...identifier },
+ Relationship: "indirect",
+ Locations: [{ StartLine: 12, EndLine: 17 }],
+ },
+ ],
+ Vulnerabilities: [
+ {
+ VulnerabilityID: "CVE-2099-0001",
+ VendorIDs: ["GHSA-2345-6789-cfgh"],
+ PkgName: name,
+ PkgID: id,
+ PkgIdentifier: { ...identifier },
+ InstalledVersion: version,
+ FixedVersion: "1.0.1, 2.0.3",
+ Status: "fixed",
+ Fingerprint: `sha256:${"b".repeat(64)}`,
+ Title: "Synthetic dependency vulnerability",
+ Description: "A vulnerable version was detected.",
+ Severity: "HIGH",
+ SeveritySource: "ghsa",
+ PrimaryURL: "https://example.invalid/advisories/CVE-2099-0001",
+ References: [
+ "https://example.invalid/advisories/GHSA-2345-6789-cfgh",
+ ],
+ CweIDs: ["CWE-79"],
+ },
+ ],
+ },
+ ],
+ };
+}
diff --git a/sdk/typescript/tests-ts/trivy-findings.test.ts b/sdk/typescript/tests-ts/trivy-findings.test.ts
new file mode 100644
index 000000000..beb733a90
--- /dev/null
+++ b/sdk/typescript/tests-ts/trivy-findings.test.ts
@@ -0,0 +1,757 @@
+import { expect, test } from "bun:test";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { gzipSync } from "node:zlib";
+import {
+ normalizeTrivyFindings,
+ readTrivyFindings,
+} from "../src/trivy-findings.js";
+import { trivyReport } from "./support/trivy-import-fixtures.js";
+
+function normalizeAtRoot(input: unknown) {
+ return normalizeTrivyFindings(input, "cloud", ".");
+}
+
+const origin = trivyReport().Metadata.RepoURL;
+const schemeLess = origin.replace("https://", "");
+
+function repositoryReport(ArtifactName: string, RepoURL?: string) {
+ return { ...trivyReport(), ArtifactName, Metadata: { RepoURL } };
+}
+
+test("filesystem labels and uncorroborated repository targets require a scan root", () => {
+ for (const report of [
+ ...[".", "apps/web", "/checkout/apps/web", "apps:web", undefined].map(
+ (ArtifactName) => ({ ...trivyReport(), ArtifactName }),
+ ),
+ repositoryReport(".", "r:org/repo"),
+ repositoryReport(origin),
+ repositoryReport(schemeLess),
+ repositoryReport(schemeLess, origin.replace("https:", "http:")),
+ repositoryReport("./" + schemeLess, origin),
+ repositoryReport(schemeLess + "-other", origin),
+ { ...repositoryReport(origin, origin), ArtifactType: "filesystem" },
+ { ...repositoryReport(schemeLess, origin), ArtifactType: "filesystem" },
+ ])
+ expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+});
+
+test.each([
+ [origin, "apps/web"],
+ ["arbitrary filesystem display label", "."],
+ ["apps:web", "packages@v2/apps:web"],
+ ["apps:web", "apps:web"],
+ [schemeLess, "."],
+] as const)("retains artifact %s inside explicit root %s", (target, root) => {
+ const { evidence } = normalizeTrivyFindings(
+ repositoryReport(target),
+ "local",
+ root,
+ ).findings[0]!;
+ expect(evidence.packages![0]!.manifest_path).toBe(
+ root === "." ? "package-lock.json" : root + "/package-lock.json",
+ );
+ const retained = evidence.source_data!["report"];
+ expect(retained).toMatchObject({ ArtifactName: target });
+});
+
+test.each([
+ [origin, origin],
+ [schemeLess, origin],
+ ["ssh://[email protected]/org/project", "ssh://[email protected]/org/project"],
+ [
+ "https://github.com/example/%E2%84%AAit",
+ "ssh://[email protected]/example/Kit.git",
+ ],
+])(
+ "infers the whole checkout for corroborated target %s and remote %s",
+ (artifact, remote) => {
+ const report = repositoryReport(artifact, remote);
+ expect(normalizeTrivyFindings(report)).toEqual(normalizeAtRoot(report));
+ expect(() => normalizeTrivyFindings(report, "local", "nested")).toThrow(
+ "must be .",
+ );
+ },
+);
+
+test.each([
+ ["é/repo", "%C3%A9/repo", true],
+ ["team name/répo", "team%20name/r%C3%A9po", true],
+ ["Team%20Name/répo", "Team%20Name/r%C3%A9po", true],
+ ["a%2520b/x é", "a%2520b/x%20%C3%A9", true],
+ ["a%FF/répo", "a%FF/r%C3%A9po", true],
+ ["%72epo/café", "repo/caf%C3%A9", false],
+ ["a%2f b/repo", "a/%20b/repo", false],
+ ["other/../repo name", "repo%20name", false],
+ ["repo name", "Repo%20name", false],
+] as const)(
+ "retains the scanner target %s when the cloned path is %s",
+ (target, cloned, matches) => {
+ for (const [prefix, clonedBase] of [
+ ["https://git.example.test:08443/", "https://git.example.test:08443/"],
+ ["git.example.test/", "https://git.example.test/"],
+ ] as const) {
+ const report = {
+ ...trivyReport(),
+ ArtifactName: prefix + target,
+ Metadata: { RepoURL: clonedBase + cloned },
+ };
+ const input = normalizeAtRoot(report);
+ if (matches) {
+ expect(normalizeTrivyFindings(report)).toEqual(input);
+ expect(() => normalizeTrivyFindings(report, "local", "nested")).toThrow(
+ "must be .",
+ );
+ } else expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ const saved = input.findings[0]!.evidence.source_data!["report"];
+ expect(saved).toMatchObject({
+ ArtifactName: report.ArtifactName,
+ Metadata: report.Metadata,
+ });
+ }
+ },
+);
+
+const enterpriseTarget = "https://git.example.test/org/project";
+
+test.each([
+ [origin.replace("https:", "HTTPS:"), origin],
+ ["ssh://[email protected]/org/project", "[email protected]:org/project"],
+ ["https://github.com/example/Kit", "ssh://[email protected]/example/Kit.git"],
+ [enterpriseTarget, "[email protected]:org/project.git"],
+ [enterpriseTarget, "https://git.example.test/org/Project"],
+ [enterpriseTarget, "https://git.example.test/org/other"],
+ [enterpriseTarget, "https://other.example.test/org/project"],
+ [enterpriseTarget, "https://git.example.test:8443/org/project"],
+ ["http://git.example.test/org/project", "http://git.example.test/ORG/other"],
+])(
+ "conflicting artifact %s and origin %s require explicit inspection",
+ (artifact, remote) => {
+ const report = repositoryReport(artifact, remote);
+ expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ const retained = normalizeTrivyFindings(report, "local", "apps/web")
+ .findings[0]!.evidence.source_data!["report"];
+ expect(retained).toMatchObject({
+ ArtifactName: artifact,
+ Metadata: { RepoURL: remote },
+ });
+ },
+);
+
+test("a repository display label cannot supply an SSH account omitted from Git metadata", () => {
+ const report = {
+ ...trivyReport(),
+ ArtifactName: "ssh://[email protected]:2222/org/project",
+ Metadata: { RepoURL: "ssh://git.example.test:2222/org/project" },
+ };
+ expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ const retained =
+ normalizeAtRoot(report).findings[0]!.evidence.source_data!["report"];
+
+ expect(retained).toMatchObject({
+ ArtifactName: report.ArtifactName,
+ Metadata: report.Metadata,
+ });
+});
+
+test("rejects unsafe scan directories before importing even a clean local report", () => {
+ const report = { ...trivyReport(), Results: [] };
+ for (const root of [
+ "",
+ "../web",
+ "apps\\..\\web",
+ "/apps/web",
+ "C:\\apps",
+ "C:apps",
+ "\\\\host\\share",
+ "https://example.invalid/repo",
+ "a\0b",
+ ])
+ expect(() => normalizeTrivyFindings(report, "local", root)).toThrow(
+ "scanRoot",
+ );
+});
+
+test("whole-checkout and scoped scans resolve the same manifest and package occurrence", () => {
+ const report = trivyReport();
+ const result = report.Results[0]!;
+ const run = (prefix: string, root: string) => {
+ const path = prefix + "vendor/package.json";
+ return normalizeTrivyFindings(
+ {
+ ...report,
+ Results: [
+ {
+ ...result,
+ Target: prefix + result.Target,
+ Packages: [{ ...result.Packages[0]!, FilePath: path }],
+ Vulnerabilities: [{ ...result.Vulnerabilities[0]!, PkgPath: path }],
+ },
+ ],
+ },
+ "local",
+ root,
+ ).findings[0]!;
+ };
+ const directory = process.platform === "win32" ? "apps/web" : "apps\\web";
+ const full = run(directory + "/", ".");
+ const scoped = run("", "./apps\\web/");
+ expect(scoped.source_finding_id).toBe(full.source_finding_id);
+ expect(scoped.source_finding_id).not.toBe(
+ run("", directory === "apps/web" ? "apps/api" : "apps/web")
+ .source_finding_id,
+ );
+ expect(scoped.evidence.locations).toEqual(full.evidence.locations);
+ expect(scoped.evidence).toMatchObject({
+ packages: [{ manifest_path: `${directory}/package-lock.json` }],
+ locations: [
+ { path: `${directory}/package-lock.json`, line: null },
+ { path: `${directory}/vendor/package.json`, line: 12 },
+ ],
+ source_data: {
+ scanRoot: directory,
+ result: { Target: "package-lock.json" },
+ vulnerability: { PkgPath: "vendor/package.json" },
+ package: { FilePath: "vendor/package.json" },
+ },
+ });
+});
+
+test.each([
+ ["node-pkg", "Node.js"],
+ ["npm", "../manifest"],
+ ["npm", ""],
+ ["npm", undefined],
+] as const)(
+ "scopes %s target %s without inventing a manifest",
+ (Type, Target) => {
+ const report = trivyReport();
+ const result = report.Results[0]!;
+ const run = (root: string, PkgPath?: string) =>
+ normalizeTrivyFindings(
+ {
+ ...report,
+ Results: [
+ {
+ ...result,
+ Target,
+ Type,
+ Packages: [{ ...result.Packages[0]!, FilePath: PkgPath }],
+ Vulnerabilities: [{ ...result.Vulnerabilities[0]!, PkgPath }],
+ },
+ ],
+ },
+ "cloud",
+ root,
+ ).findings[0]!;
+ const scoped = run("apps/web", "vendor/package.json");
+ expect(scoped.source_finding_id).toBe(
+ run(".", "apps/web/vendor/package.json").source_finding_id,
+ );
+ expect(scoped.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(scoped.evidence.locations).toEqual([
+ { path: "apps/web/vendor/package.json", line: 12 },
+ ]);
+ for (const path of [undefined, "/outside/package.json"]) {
+ const web = run("apps/web", path);
+ expect(web.evidence.locations).toEqual([]);
+ expect(web.source_finding_id).not.toBe(
+ run("apps/api", path).source_finding_id,
+ );
+ }
+ },
+);
+
+test("retains the detected vulnerability and only its package declarations and scan context", () => {
+ const report = trivyReport();
+ report.ArtifactName = report.Metadata.RepoURL;
+ const result = report.Results[0]!;
+ const pkg = result.Packages[0]!;
+ pkg.Locations.push({ StartLine: 42, EndLine: 45 });
+ result.Packages.unshift({
+ ...pkg,
+ Name: "unrelated-inventory",
+ Identifier: { PURL: "pkg:npm/unrelated-inventory", UID: "another-uid" },
+ Locations: [{ StartLine: 2, EndLine: 6 }],
+ });
+ Object.assign(pkg, { DependsOn: ["unrelated-inventory"] });
+ Object.assign(report.Metadata, {
+ CommitMsg: "unrelated-metadata",
+ Author: "unrelated-metadata",
+ });
+ const original = structuredClone(report);
+ const output = normalizeAtRoot(report);
+ expect(report).toEqual(original);
+ expect(output).toMatchObject({ read: 1, excluded: [] });
+ const { evidence } = output.findings[0]!;
+ expect(evidence).toMatchObject({
+ title: result.Vulnerabilities[0]!.Title,
+ severity: "high",
+ url: result.Vulnerabilities[0]!.PrimaryURL,
+ advisory_ids: ["CVE-2099-0001", "GHSA-2345-6789-cfgh"],
+ packages: [
+ {
+ name: pkg.Name,
+ ecosystem: "npm",
+ manifest_path: result.Target,
+ installed_version: "1.0.0",
+ fixed_versions: ["1.0.1", "2.0.3"],
+ },
+ ],
+ locations: [
+ { path: result.Target, line: 12 },
+ { path: result.Target, line: 42 },
+ ],
+ branch: "main",
+ code_revision: null,
+ source_scan_id: report.ReportID,
+ source_data: {
+ report: { Metadata: { Commit: report.Metadata.Commit } },
+ result: { Type: "npm", Target: result.Target },
+ package: { ID: pkg.ID, Locations: pkg.Locations },
+ },
+ });
+ expect(evidence.details).toBeUndefined();
+ result.Vulnerabilities[0]!.Status = "affected";
+ expect(evidence.source_data?.["vulnerability"]).toEqual(
+ original.Results[0]!.Vulnerabilities[0],
+ );
+ expect(JSON.stringify(evidence.source_data)).not.toContain("unrelated-");
+});
+
+test("filesystem scans without inventory or Git metadata do not invent lines, versions or revisions", () => {
+ const report = {
+ SchemaVersion: 2,
+ ArtifactType: "filesystem",
+ ArtifactName: "scan-root",
+ Results: [
+ {
+ Class: "lang-pkgs",
+ Type: "npm",
+ Target: "app\\package-lock.json",
+ Vulnerabilities: [
+ { VulnerabilityID: "CVE-2099-0001", PkgName: "example" },
+ ],
+ },
+ ],
+ };
+ const { evidence } = normalizeAtRoot(report).findings[0]!;
+ expect(evidence).toMatchObject({
+ severity: "unknown",
+ source_data: { report: { ArtifactName: report.ArtifactName } },
+ branch: null,
+ code_revision: null,
+ source_scan_id: null,
+ packages: [
+ {
+ installed_version: null,
+ fixed_versions: [],
+ manifest_path: "app\\package-lock.json",
+ },
+ ],
+ locations: [{ path: "app\\package-lock.json", line: null }],
+ });
+});
+
+function normalizeResult(result: unknown) {
+ return normalizeAtRoot({ ...trivyReport(), Results: [result] });
+}
+
+test("a later PURL enriches the ecosystem without changing a Poetry occurrence's identity", () => {
+ const result = trivyReport().Results[0]!;
+ const run = (PkgIdentifier?: { PURL: string }) =>
+ normalizeResult({
+ ...result,
+ Type: "poetry",
+ Target: "poetry.lock",
+ Vulnerabilities: [
+ {
+ VulnerabilityID: "CVE-2099-0001",
+ PkgName: "example",
+ PkgIdentifier,
+ },
+ ],
+ }).findings[0]!;
+ const before = run();
+ const after = run({ PURL: "pkg:pypi/[email protected]" });
+ expect(before.evidence.packages![0]!.ecosystem).toBe("poetry");
+ expect(after.evidence.packages![0]!.ecosystem).toBe("pypi");
+ expect(after.source_finding_id).toBe(before.source_finding_id);
+ expect(after.evidence.source_data?.["result"]).toMatchObject({
+ Type: "poetry",
+ });
+});
+
+test("new scan, commit, fingerprint, versions, severity and declaration range update the same occurrence", () => {
+ const report = trivyReport();
+ const first = normalizeAtRoot(report).findings[0]!;
+ const result = report.Results[0]!;
+ const vulnerability = result.Vulnerabilities[0]!;
+ report.Metadata.Commit = "c".repeat(40);
+ report.ReportID = "next-scan";
+ Object.assign(vulnerability, {
+ Severity: "LOW",
+ InstalledVersion: "1.0.2",
+ FixedVersion: "1.0.3",
+ PkgID: "[email protected]",
+ PkgIdentifier: { UID: "changed", PURL: "pkg:npm/%40example/[email protected]" },
+ Fingerprint: "changed",
+ });
+ Object.assign(result.Packages[0]!, {
+ ID: vulnerability.PkgID,
+ Version: vulnerability.InstalledVersion,
+ Identifier: vulnerability.PkgIdentifier,
+ Locations: [{ StartLine: 81, EndLine: 90 }],
+ });
+ const next = normalizeAtRoot(report).findings[0]!;
+ expect(next.source_finding_id).toBe(first.source_finding_id);
+ expect(next.evidence).toMatchObject({
+ severity: "low",
+ locations: [{ line: 81 }],
+ });
+});
+
+test("manifests, analyzers, names, advisories and concrete package paths distinguish occurrences regardless of order", () => {
+ const report = trivyReport();
+ const result = report.Results[0]!;
+ const vuln = result.Vulnerabilities[0]!;
+ const results = [
+ { ...result, Target: "apps/web/package-lock.json" },
+ { ...result, Target: "apps\\web/package-lock.json" },
+ { ...result, Type: "yarn" },
+ {
+ ...result,
+ Vulnerabilities: [
+ vuln,
+ { ...vuln, PkgName: "other" },
+ { ...vuln, VulnerabilityID: "CVE-2099-0002" },
+ { ...vuln, PkgPath: "a/package.json" },
+ { ...vuln, PkgPath: "a\\package.json" },
+ ],
+ },
+ ];
+ const run = () => normalizeAtRoot({ ...report, Results: results });
+ const first = run();
+ expect(first.excluded).toEqual([]);
+ const ids = first.findings.map((finding) => finding.source_finding_id).sort();
+ expect(new Set(ids).size).toBe(8);
+ expect(first.findings[1]!.evidence).toMatchObject({
+ packages: [{ manifest_path: "apps\\web/package-lock.json" }],
+ locations: [{ path: "apps\\web/package-lock.json", line: 12 }],
+ source_data: { result: { Target: "apps\\web/package-lock.json" } },
+ });
+ results.reverse();
+ for (const group of results) group.Vulnerabilities.reverse();
+ expect(
+ run()
+ .findings.map((finding) => finding.source_finding_id)
+ .sort(),
+ ).toEqual(ids);
+});
+
+test("different installed versions alone cannot disambiguate two detections in a manifest", () => {
+ const result = trivyReport().Results[0]!;
+ const vuln = result.Vulnerabilities[0]!;
+ const output = normalizeResult({
+ ...result,
+ Vulnerabilities: [
+ vuln,
+ {
+ ...vuln,
+ PkgID: "other-version",
+ InstalledVersion: "2.0.0",
+ PkgPath: result.Target,
+ },
+ { ...vuln, VulnerabilityID: "another-advisory" },
+ ],
+ });
+ expect(output.read).toBe(3);
+ expect(output.findings).toHaveLength(1);
+ expect(output.excluded.map(({ position }) => position)).toEqual([1, 2]);
+ expect(output.excluded[0]!.source_finding_id).toBe(
+ output.excluded[1]!.source_finding_id,
+ );
+ expect(output.excluded[0]!.reason).toMatch(/ambiguous duplicate/i);
+});
+
+test.each([
+ ["node-pkg", "Node.js"],
+ ["python-pkg", "Python"],
+ ["conda-pkg", "Conda"],
+ ["gemspec", "Ruby"],
+ ["jar", "Java"],
+ ["kubernetes", "Kubernetes"],
+])(
+ "%s aggregate target %s is not a manifest or file location",
+ (type, label) => {
+ const result = trivyReport().Results[0]!;
+ const vuln = result.Vulnerabilities[0]!;
+ const path = "app/installed/package.json";
+ const output = normalizeResult({
+ ...result,
+ Type: type,
+ Target: label,
+ Vulnerabilities: [vuln, { ...vuln, PkgPath: path }],
+ });
+ expect(output.excluded).toEqual([]);
+ expect(output.findings[0]!.evidence.locations).toEqual([]);
+ expect(output.findings[1]!.evidence.locations).toEqual([
+ { path, line: null },
+ ]);
+ expect(output.findings[1]!.evidence.packages![0]!.manifest_path).toBeNull();
+ },
+);
+
+test("keeps ambiguous Java package paths in the original evidence", () => {
+ const result = trivyReport().Results[0]!;
+ const paths = [
+ "service.war/lib/dep.jar",
+ "lib/dep.jar",
+ "service.war/lib/dep.par",
+ "service.war/lib/dep.JAR",
+ ];
+ const { findings, excluded } = normalizeResult({
+ ...result,
+ Type: "jar",
+ Target: "Java",
+ Vulnerabilities: paths.map((PkgPath) => ({
+ ...result.Vulnerabilities[0]!,
+ PkgPath,
+ })),
+ });
+ expect(excluded).toEqual([]);
+ expect(findings.map(({ evidence }) => evidence.locations)).toEqual([
+ [],
+ ...paths.slice(1).map((path) => [{ path, line: null }]),
+ ]);
+ expect(findings[0]!.evidence.source_data?.["vulnerability"]).toMatchObject({
+ PkgPath: paths[0],
+ });
+});
+
+test("declaration ranges come from an unambiguous package at the reported path", () => {
+ const result = trivyReport().Results[0]!;
+ const vuln = result.Vulnerabilities[0]!;
+ const pkg = result.Packages[0]!;
+ const selected = { ...pkg, FilePath: "a/package.json" };
+ const other = {
+ ...pkg,
+ FilePath: "a\\package.json",
+ Locations: [{ StartLine: 24, EndLine: 28 }],
+ };
+ const group = {
+ ...result,
+ Packages: [other, selected],
+ Vulnerabilities: [{ ...vuln, PkgPath: selected.FilePath }],
+ };
+ const run = () => normalizeResult(group).findings[0]!.evidence;
+ expect(run().locations).toEqual([
+ { path: result.Target, line: null },
+ { path: selected.FilePath, line: 12 },
+ ]);
+ group.Packages.push({ ...other, FilePath: selected.FilePath });
+ expect(run().locations![1]!.line).toBeNull();
+ expect(run().source_data?.["package"]).toBeUndefined();
+});
+
+test("only ID-less detections use a unique name/version match from inventory", () => {
+ const result = trivyReport().Results[0]!;
+ const pkg = result.Packages[0]!;
+ const vuln = result.Vulnerabilities[0]!;
+ const sparse = {
+ VulnerabilityID: vuln.VulnerabilityID,
+ PkgName: pkg.Name,
+ InstalledVersion: pkg.Version,
+ };
+ const line = (value: unknown, packages = [pkg]) =>
+ normalizeResult({ ...result, Packages: packages, Vulnerabilities: [value] })
+ .findings[0]!.evidence.locations![0]!.line;
+ expect(line(sparse)).toBe(12);
+ expect(
+ line(sparse, [
+ pkg,
+ { ...pkg, ID: "other", Identifier: { ...pkg.Identifier, UID: "other" } },
+ ]),
+ ).toBeNull();
+ expect(line({ ...sparse, PkgID: "unknown-id" })).toBeNull();
+ expect(
+ line({ ...sparse, PkgIdentifier: { PURL: pkg.Identifier.PURL } }),
+ ).toBe(12);
+ expect(
+ line({ ...sparse, PkgIdentifier: { PURL: "pkg:npm/[email protected]" } }),
+ ).toBeNull();
+ expect(
+ line({ ...vuln, PkgIdentifier: { UID: "conflicting-uid" } }),
+ ).toBeNull();
+ expect(line({ ...vuln, PkgID: "conflicting-id" })).toBeNull();
+});
+
+test("conflicting package names or installed versions suppress enrichment even with matching IDs", () => {
+ const result = trivyReport().Results[0]!;
+ const pkg = result.Packages[0]!;
+ for (const mismatch of [{ Name: "unrelated" }, { Version: "9.0.0" }]) {
+ const output = normalizeResult({
+ ...result,
+ Packages: [{ ...pkg, ...mismatch }],
+ });
+ expect(output.excluded).toEqual([]);
+ const { evidence } = output.findings[0]!;
+ expect(evidence.locations).toEqual([{ path: result.Target, line: null }]);
+ expect(evidence.source_data?.["package"]).toBeUndefined();
+ expect(evidence.packages![0]!.installed_version).toBe(pkg.Version);
+ }
+});
+
+test.each([
+ "/work/manifest",
+ "C:\\work\\manifest",
+ "\\\\host\\share\\manifest",
+ "../manifest",
+ "https://example.invalid/file",
+])("keeps %s out of repository paths", (path) => {
+ const result = trivyReport().Results[0]!;
+ const output = normalizeResult({
+ ...result,
+ Target: path,
+ Vulnerabilities: [{ ...result.Vulnerabilities[0]!, PkgPath: path }],
+ });
+ const { evidence } = output.findings[0]!;
+ expect(evidence.locations).toEqual([]);
+ expect(evidence.packages![0]!.manifest_path).toBeNull();
+ expect(evidence.source_data?.["result"]).toMatchObject({ Target: path });
+});
+
+test("clean native reports differ from unsupported, mixed and malformed findings", () => {
+ const report = trivyReport();
+ const { Results: groups, ...header } = report;
+ const result = groups[0]!;
+ for (const Results of [
+ undefined,
+ [],
+ [{ ...result, Vulnerabilities: undefined }],
+ ])
+ expect(normalizeAtRoot({ ...report, Results })).toEqual({
+ read: 0,
+ report: header,
+ excluded: [],
+ findings: [],
+ });
+ const secret = {
+ Class: "secret",
+ Secrets: [{ Match: "excluded-secret-evidence" }],
+ };
+ const mixed = normalizeAtRoot({
+ ...report,
+ Results: [
+ secret,
+ result,
+ { Class: "os-pkgs", Vulnerabilities: result.Vulnerabilities },
+ { Class: "config" },
+ { Class: "license" },
+ {
+ ...result,
+ Vulnerabilities: [{}],
+ ExperimentalModifiedFindings: [{ Finding: "excluded-modification" }],
+ },
+ ],
+ });
+ expect(mixed.read).toBe(7);
+ expect(mixed.findings).toHaveLength(1);
+ expect(mixed.excluded.map(({ position }) => position)).toEqual([
+ 1, 3, 4, 5, 6, 7,
+ ]);
+ expect(JSON.stringify(mixed)).not.toContain("excluded-secret-evidence");
+ expect(JSON.stringify(mixed)).not.toContain("excluded-modification");
+ expect(
+ normalizeAtRoot({ ...report, Results: [secret] }).excluded,
+ ).toHaveLength(1);
+ expect(() =>
+ normalizeAtRoot({ ...report, ArtifactType: "container_image" }),
+ ).toThrow(/repository and filesystem/);
+ expect(() => normalizeAtRoot({ ...report, SchemaVersion: 1 })).toThrow(
+ /SchemaVersion 2/,
+ );
+ expect(() => normalizeAtRoot({ version: "2.1.0", runs: [] })).toThrow(
+ /SchemaVersion 2/,
+ );
+});
+
+test("clean reports reject unsafe remote URLs", () => {
+ const report = { ...trivyReport(), Results: [] };
+
+ for (const source of [
+ "https://[email protected]/repo",
+ "https://example\\scanner:[email protected]/repo",
+ "http:///example\\scanner:[email protected]/repo",
+ "ssh://git:[email protected]/repo",
+ "git://[email protected]/repo",
+ "https://example.invalid/repo?token=fixture",
+ "ssh://[email protected]/example/project?",
+ ]) {
+ expect(() =>
+ normalizeTrivyFindings(
+ { ...report, Metadata: { RepoURL: source } },
+ "cloud",
+ ".",
+ ),
+ ).toThrow(/without credentials/);
+ expect(() =>
+ normalizeTrivyFindings({ ...report, ArtifactName: source }, "cloud", "."),
+ ).toThrow(/without credentials/);
+ }
+});
+
+test("a repository target can carry an HTTPS account without an explicit scheme", () => {
+ const report = trivyReport();
+ for (const ArtifactName of [
+ "example:[email protected]/repo",
+ "example:[email protected]:443/repo",
+ "\\[email protected]/repo",
+ ]) {
+ const header = { ArtifactName, Metadata: {} };
+ expect(() =>
+ normalizeAtRoot({ ...report, ...header, Results: [] }),
+ ).toThrow(/without credentials/);
+ }
+ for (const ArtifactName of [
+ "/checkout/team@local/repo",
+ "apps/team@local/repo",
+ "\\\\server\\builds@nightly\\checkout",
+ "[email protected]:group/repo",
+ ]) {
+ expect(
+ normalizeAtRoot({ ...report, ArtifactName, Results: [] }).report,
+ ).toHaveProperty("ArtifactName", ArtifactName);
+ }
+});
+
+test("reads native JSON and gzip by content, applying the destination's evidence limits", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "trivy-import-"));
+ try {
+ const path = join(directory, "report.json");
+ const report = trivyReport();
+ await writeFile(path, JSON.stringify(report));
+ await expect(readTrivyFindings(path)).rejects.toThrow("scanRoot");
+ expect(await readTrivyFindings(path, "cloud", "apps/web")).toEqual(
+ normalizeTrivyFindings(report, "cloud", "apps/web"),
+ );
+ const custom = "x".repeat(256 * 1024);
+ Object.assign(report.Results[0]!.Vulnerabilities[0]!, { Custom: custom });
+ await writeFile(path, gzipSync(JSON.stringify(report)));
+ const cloud = await readTrivyFindings(path, "cloud", ".");
+ expect(cloud.findings).toEqual([]);
+ expect(cloud.excluded[0]!.reason).toContain("256 KiB");
+ const local = await readTrivyFindings(path, "local", ".");
+ expect(local.excluded).toEqual([]);
+ expect(
+ local.findings[0]!.evidence.source_data?.["vulnerability"],
+ ).toMatchObject({ Custom: custom });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});