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): import Trivy findings locally and to Cloud (#2276)

Michael D'Angelo5283c84ba7fa
diff --git a/docs/scanner-imports/README.md b/docs/scanner-imports/README.md
index 604b0d01a..d030cbebe 100644
--- a/docs/scanner-imports/README.md
+++ b/docs/scanner-imports/README.md
@@ -50,6 +50,7 @@ Cloud private inbox imports came after [version 0.8.2](https://github.com/openai
| [Semgrep](semgrep.md) | CLI/CI JSON, SARIF, selected Guardian findings, or Platform Web API reports |
| [Snyk](snyk.md) | CLI JSON, plugin exports, SARIF, or monitored Code and Open Source issues |
| [SonarQube Cloud](sonar.md) | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |
+| [Trivy](trivy.md) | Native schema-v2 repository or filesystem JSON, optionally gzip-compressed |
| [Veracode Static Analysis](veracode.md) | Findings API pages for one application's policy flaws |
| [Wiz](wiz.md) | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.md
index 5932b6fdc..3d700943e 100644
--- a/docs/scanner-imports/schema-guide.md
+++ b/docs/scanner-imports/schema-guide.md
@@ -31,6 +31,7 @@ changes.
| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |
| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |
| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |
+| [Trivy](trivy.md) | Analyzer, advisory, package name, target and package path when available. Use the same source key for a repository, project and branch. |
| [Snyk Open Source](snyk.md) | Native CLI JSON distinguishes manifest, package manager, advisory, package name and version, and dependency path. Plugin and SARIF reports use different identities. |
| [Black Duck SCA](blackduck.md), [Veracode Static Analysis](veracode.md) | Black Duck combines project version, component version, origin and advisory identity. Veracode scopes a native issue ID to its API origin, application and context. |
| [Semgrep CLI or CI reports](semgrep.md), [OpenGrep](opengrep.md) | Semgrep prefers a fingerprint and falls back to rule, path and range. OpenGrep groups traces by rule, path and range. Both store provider `semgrep`. Use a separate OpenGrep source key. |
diff --git a/docs/scanner-imports/trivy.md b/docs/scanner-imports/trivy.md
new file mode 100644
index 000000000..e3bfe1a97
--- /dev/null
+++ b/docs/scanner-imports/trivy.md
@@ -0,0 +1,32 @@
+# Import Trivy dependency findings
+
+Use a saved Trivy schema-v2 JSON or gzip report from a repository or filesystem scan. The importer reads language-package vulnerabilities and lists excluded sections, including OS packages, secrets and misconfigurations. The reader works offline without installing Trivy.
+
+## Preview the report
+
+Enable external imports and select the checkout that Trivy scanned. Set `--trivy-scan-root` to the scanned directory relative to the checkout, for example `.` for the whole checkout or `apps/web` for a subtree.
+
+```sh
+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
+codex-security publish findings trivy.json.gz --to local --repository /path/to/checkout \
+ --provider trivy --trivy-scan-root . --source-key example/project/main --dry-run --format json
+```
+
+Check the repository, manifest paths, versions and exclusions in the preview. Keep the same source key across scans of the same project and branch. [Save locally, publish to Cloud and verify the import](README.md#save-or-publish-and-verify). Cloud requires a deployment that accepts the `trivy` provider.
+
+## Match the report to its checkout
+
+A repository scan can omit `--trivy-scan-root` when its remote target and Git metadata corroborate a whole-checkout scan. A filesystem scan always needs the scan root. A filesystem artifact name is a display label. Trivy's Git metadata is the source of its repository claim. When the report or local checkout has no comparable remote, verify the source independently.
+
+Use credential-free repository URLs. If the importer reports ambiguous or conflicting repository claims, check the remote that supplied `Metadata.RepoURL` (Trivy v0.76.1 prefers `upstream` to `origin`). Regenerate the report with a verified HTTPS URL or an unambiguous SSH remote, preserving its account, host, port and path. An artifact label cannot restore an SSH account that Trivy omitted. Unknown Git hosts may require the same remote spelling. For older Windows reports, regenerate with Trivy v0.36.0 or later so path separators are recorded as `/`.
+
+## Read the evidence and repeat an import
+
+- Each finding retains its native vulnerability, exact `FixedVersion` expression and, when available, the matched package and declaration lines. Ambiguous archive paths stay in the raw evidence.
+- Trivy can scan uncommitted files. Its reported commit stays in `source_data.report.Metadata.Commit`. Imported findings start as `not_assessed`, including when Trivy reports an upstream fix.
+- Changes to severity, installed version or declaration line update the same occurrence. A different manifest or package path identifies a separate occurrence. Duplicate identities are excluded as a group. Omitted findings stay open.
+- With the SDK, use `readTrivyFindings` for a file or `normalizeTrivyFindings` for parsed JSON. When selecting rows from a repository-bound report, retain its native header and each row’s `source_data.report` or `details.repository.url`, and import with provider `trivy`. Empty and fully excluded reports also retain their native header.
+
+If a private-inbox upload is interrupted and the connected repository is renamed, check the existing job before retrying. The new catalog URL can fail the original report’s source check.
+
+If an earlier development build left a pending Cloud upload, verify the destination and finish it with that build. A change to finding IDs or evidence can prevent the newer build from recognizing the pending request.
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 10ac7a2a8..16f34db43 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -31,6 +31,10 @@ Read the stored evidence with `codex-security findings imported /path/to/project
Local records remain unassessed source evidence, separate from `findings list` and completed scans. Repeated imports use the same repository/provider/source-key/source-ID identity; omitted records remain stored. When a source repository URL and local Git remotes are available, the URL must match a remote. Local import does not publish to Cloud or automatically investigate or patch findings.
+## Trivy dependency vulnerabilities
+
+Use `--provider trivy` with a saved schema-v2 repository or filesystem report (JSON or gzip). Preview with a stable project/branch source key and `--trivy-scan-root` relative to the checkout (`.` for the whole checkout). Omit the root only when the report's Git metadata corroborates a remote repository scan. Check the source, package paths and exclusions before importing. Trivy's `fixed` status identifies an available upstream fix. [Trivy import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/trivy.md)
+
## Amazon Inspector repository findings
Use `--provider inspector` and `--source-repository-url` with a complete Inspector2 ListFindings export for one Code Security repository. If it contains only a project ARN and name, pass the full `--inspector-project-arn ARN` verified for that Git URL in the SCM integration. Supply the same ARN when resuming a pending Cloud submission. Self-managed GitLab is supported locally.
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index cfa22d142..b825b725a 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1427,6 +1427,10 @@ For completed scans exported in the Codex Security JSON or CSV format, use
For Checkmarx One CLI JSON or CxSAST XML, use `--provider checkmarx` and pass the
verified Git URL with `--source-repository-url`. See the [Checkmarx SAST guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md).
+## Import Trivy dependency findings
+
+Use `--provider trivy` to read a schema-v2 repository or filesystem report (JSON or gzip). Pass `--trivy-scan-root .` for a whole checkout or a checkout-relative path for a subtree. A corroborated remote repository scan can infer the root. See the [Trivy import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/trivy.md) for a preview command, repository matching, and how to save or publish the results.
+
## Import Endor Labs findings
Use `--provider endor` for one Endor project and context. The
diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.json
index c79c9a22c..5fb9905e8 100644
--- a/sdk/typescript/schemas/external-findings.schema.json
+++ b/sdk/typescript/schemas/external-findings.schema.json
@@ -389,7 +389,8 @@
"veracode",
"sonar",
"continuum",
- "checkmarx"
+ "checkmarx",
+ "trivy"
],
"title": "Provider",
"type": "string"
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index cee75e582..09fb42d8d 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -57,6 +57,7 @@ const distModules = [
"native-json-findings",
"opengrep-findings",
"trivy-findings",
+ "trivy-import",
"external-findings-publish",
"private-finding-import",
"external-import-contract",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 6f6162373..4bdc6b970 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -3708,6 +3708,11 @@ export async function main(
.describe(
"Full Inspector project ARN independently verified for --source-repository-url. Required when the report does not identify its repository by URL.",
),
+ trivyScanRoot: optionValue("--trivy-scan-root")
+ .optional()
+ .describe(
+ "Repository-relative directory scanned by Trivy. Use . for the repository root. Required unless Git metadata confirms a whole-checkout scan.",
+ ),
sourceKey: optionValue("--source-key").describe(
"Stable vendor tenant and finding namespace; not a project selection filter.",
),
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index f82e6a93e..9cfb7d188 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -11,6 +11,11 @@ import {
gitTransportBytes,
hostedRepositoryMatches,
} from "./hosted-git-repository.js";
+import {
+ checkRetainedTrivyProvider,
+ checkTrivyReportProvider,
+ matchTrivyCheckout,
+} from "./trivy-import.js";
import { readHostedGitRemotes } from "./hosted-git-remotes.js";
import { CodexSecurityError } from "./errors.js";
import {
@@ -767,6 +772,7 @@ export async function prepareLocalImport(
requireIdentity(options.sourceKey, "Source key");
const parsedSources = distinctSourceRepositories(parsedInput);
const current = snapshotNormalizedFindings(input, checkStoredNumber);
+ checkTrivyReportProvider(options.provider, current.report);
// The JSON snapshot omits inherited or non-enumerable SDK reader properties.
if (!("snykRestContext" in current) && "snykRestContext" in input)
current.snykRestContext = structuredClone(input.snykRestContext);
@@ -789,6 +795,7 @@ export async function prepareLocalImport(
identities.add(finding.source_finding_id);
if (!isRecord(finding.evidence))
throw new CodexSecurityError("Imported evidence must be an object.");
+ checkRetainedTrivyProvider(options.provider, finding, "local");
if (options.provider !== "github") continue;
const native = dependabotRepository(finding);
if (!native) continue;
@@ -1282,23 +1289,32 @@ export async function prepareLocalImport(
false,
);
const selected = manualSource ? new URL(manualSource) : undefined;
- const matchesRepositoryRemote = await requireMatchingRepository(
- repository,
- options.provider,
- ordinarySources,
- strictSources,
- hosted,
- (source, bound) => (bound ? platformFor(source) : loosePlatformFor(source)),
- snyk,
- workbenchOptions.protectedRoot,
- workbenchOptions.environment,
- dependencies.signal,
- selected?.protocol === "https:" ? selected.hostname : undefined,
- fetchRemotes,
- checkmarx.projections.size
- ? (url) => checkmarxKeys.has(identify(url).key)
- : undefined,
- );
+ const matchesRepositoryRemote =
+ options.provider === "trivy"
+ ? await matchTrivyCheckout(
+ repository,
+ current,
+ references,
+ workbenchOptions,
+ )
+ : await requireMatchingRepository(
+ repository,
+ options.provider,
+ ordinarySources,
+ strictSources,
+ hosted,
+ (source, bound) =>
+ bound ? platformFor(source) : loosePlatformFor(source),
+ snyk,
+ workbenchOptions.protectedRoot,
+ workbenchOptions.environment,
+ dependencies.signal,
+ selected?.protocol === "https:" ? selected.hostname : undefined,
+ fetchRemotes,
+ checkmarx.projections.size
+ ? (url) => checkmarxKeys.has(identify(url).key)
+ : undefined,
+ );
dependencies.signal?.throwIfAborted();
const preview = {
...cloneImportPreview(current),
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index 58faed86e..08b3d6f4a 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -93,6 +93,7 @@ import {
hostedRepositoryUrlKey,
normalizeHostedGitRepositoryUrl,
} from "./hosted-git-repository.js";
+import { trivyRemoteKey, trivyRepositoryUrl } from "./trivy-findings.js";
import { hostedRepositoryUrl } from "./hosted-scanner-http.js";
import { endorRepositoryUrls } from "./endor-findings.js";
import {
@@ -104,6 +105,14 @@ import { continuumReportRepositories } from "./continuum-findings.js";
import { veracodeReportRepositories } from "./veracode-findings.js";
import { inspectorReportRepository } from "./inspector-findings.js";
import { sonarRepositoryUrls } from "./sonar-findings.js";
+import {
+ checkRetainedTrivyProvider,
+ checkTrivyReportProvider,
+ isTrivyReportHeader,
+ retainedTrivyReport,
+ trivyBatchSourceUrls,
+ validateTrivyRepositoryUrl,
+} from "./trivy-import.js";
import {
NoPublishableFindingsError,
reportForJson,
@@ -149,13 +158,10 @@ export interface NormalizedExternalPublicationOptions {
}
/** File readers accept the vendor formats installed in this SDK. */
-export interface ExternalPublicationOptions extends Omit<
- NormalizedExternalPublicationOptions,
- "provider"
-> {
- provider: ExternalFindingsReaderOptions["provider"];
- sourceRepositoryUrl?: string;
-}
+export interface ExternalPublicationOptions
+ extends
+ Omit<NormalizedExternalPublicationOptions, "provider">,
+ ExternalFindingsReaderOptions {}
/** Optional transport, account, cancellation, and progress hooks. */
export interface ExternalPublicationDependencies {
@@ -213,6 +219,7 @@ export class ExternalPublicationError extends CodexSecurityError {
interface SavedSubmission {
accountId: string;
+ trivyRepositoryUrl?: string;
requests: FindingImportRequest[];
receipts?: FindingImportReceipt[];
inputProjection?: {
@@ -291,6 +298,7 @@ function sameSubmission(
): boolean {
return (
left.accountId === right.accountId &&
+ left.trivyRepositoryUrl === right.trivyRepositoryUrl &&
left.inspectorProjectMapRequired === right.inspectorProjectMapRequired &&
wireJson(left.requests) === wireJson(right.requests)
);
@@ -687,7 +695,6 @@ export async function prepareNormalizedExternalPublication(
): Promise<PreparedExternalPublication> {
requireExternalImports(dependencies.environment);
const settings = snapshotImportOptions(options);
- rejectGuardianSelection(input);
return preparePublicationInput(
normalizedPublicationInput(input, settings.provider),
settings,
@@ -1194,7 +1201,14 @@ function normalizedPublicationInput(
current = { read: original.parsed.read, findings: [], excluded: [] };
}
rejectGuardianSelection(current);
- const identity = publicationIdentity(current);
+ // A Trivy header provides repository provenance for its findings. Either entrypoint
+ // can resume the same immutable request when the independently checked rows agree.
+ const identity =
+ provider === "trivy" &&
+ current.report &&
+ isTrivyReportHeader(current.report)
+ ? current.findings
+ : publicationIdentity(current);
return {
current,
legacy: current,
@@ -1398,8 +1412,22 @@ async function preparePublicationInput(
dependencies.signal?.throwIfAborted();
requireExternalImports(environment);
progress({ phase: "reading", completed: 0 });
+ const trivyReportUrls =
+ options.provider === "trivy" && typeof supplied !== "function"
+ ? trivyBatchSourceUrls(
+ supplied.current,
+ supplied.current.findings.length > 0,
+ )
+ : undefined;
+ if (trivyReportUrls) validateTrivyRepositoryUrl(options.repository);
+ const catalogKey = trivyReportUrls
+ ? (url: string) => cloudSourceKey(url, "github")
+ : cloudRepositoryUrlKey;
function checkSelection(input: PublicationSelection) {
const parsed = input.current;
+ checkTrivyReportProvider(options.provider, parsed.report);
+ for (const finding of parsed.findings)
+ checkRetainedTrivyProvider(options.provider, finding);
if (
!parsed.findings.length &&
!input.original?.parsed.findings.length &&
@@ -1480,8 +1508,7 @@ async function preparePublicationInput(
...result.data.filter(
(item) =>
item.id === options.repository ||
- cloudRepositoryUrlKey(item.url) ===
- cloudRepositoryUrlKey(options.repository),
+ catalogKey(item.url) === catalogKey(options.repository),
),
);
page = result.next;
@@ -1500,7 +1527,9 @@ async function preparePublicationInput(
? "The repository matches multiple connectors. Select an unambiguous Cloud repository."
: "The destination repository is not available to this Cloud account. Copy its repository URL or ID from Codex Security Cloud and check that you are signed into the intended account.",
);
- return destinations[0]!;
+ const destination = destinations[0]!;
+ if (trivyReportUrls) validateTrivyRepositoryUrl(destination.url);
+ return destination;
}
const destination = await discoverDestination();
const deferred = typeof supplied === "function";
@@ -1884,8 +1913,14 @@ async function preparePublicationInput(
)
throw new Error("Saved import account or requests do not match.");
content.requests = content.requests.map(validateImportRequest);
+ for (const finding of submissionFindings(content.requests))
+ checkRetainedTrivyProvider(options.provider, finding);
if (!matchesSavedDestination(content.requests))
throw new Error("Saved import destination does not match.");
+ if (source.provider === "trivy" && !content.trivyRepositoryUrl)
+ throw new CodexSecurityError(
+ "This build cannot verify the original repository for this pending Trivy import. Check its destination before resuming with the build that created it.",
+ );
return content;
}
@@ -2696,17 +2731,39 @@ async function preparePublicationInput(
requireApprovedSource(approvedUrl);
if (legacyTypedUrl) requireApprovedSource(legacyTypedUrl);
+ const trivyTarget = saved?.trivyRepositoryUrl ?? destination.url;
+ function requireTrivyRemote(url: string, id?: string) {
+ if (trivyRemoteKey(url, trivyTarget) !== catalogKey(trivyTarget)) {
+ const label =
+ id === undefined ? "Source report" : `Finding ${JSON.stringify(id)}`;
+ throw new CodexSecurityError(
+ `${label} belongs to ${JSON.stringify(url)}, which does not match the selected Cloud repository ${JSON.stringify(trivyTarget)}. Verify the source repository mapping before publishing.`,
+ );
+ }
+ }
+ if (trivyReportUrls) {
+ for (const url of trivyReportUrls) requireTrivyRemote(url);
+ if (parsed !== resolved.current)
+ for (const url of trivyBatchSourceUrls(parsed, true))
+ requireTrivyRemote(url);
+ }
+
function checkRepositories(
{ findings, report }: Pick<ExternalFindings, "findings" | "report">,
historicalCheckmarx = Boolean(saved),
) {
+ checkTrivyReportProvider(options.provider, report);
// A catalog casing or spelling change keeps the original source comparison target.
const approved = hosted ? saved?.approvedRepositoryUrl : undefined;
const sameCatalog =
approved !== undefined &&
cloudSourceKey(approved, "github") ===
cloudSourceKey(destination.url, "github");
- const comparisonUrl = sameCatalog ? approved : destination.url;
+ const comparisonUrl = trivyReportUrls
+ ? trivyTarget
+ : sameCatalog
+ ? approved
+ : destination.url;
const key = sameCatalog
? (url: string) =>
cloudSourceKey(
@@ -2715,7 +2772,7 @@ async function preparePublicationInput(
? undefined
: "github",
)
- : cloudRepositoryUrlKey;
+ : catalogKey;
function requireDestination(id: string, url: string | null | undefined) {
if (
url &&
@@ -2730,8 +2787,9 @@ async function preparePublicationInput(
}
// Historical checkpoints already fixed the provider and request bytes.
// Recheck any projected source against the destination discovered for this retry.
- const replay = saved && options.provider !== "blackduck";
- if (!saved || options.provider === "sonar") {
+ const replay =
+ saved && options.provider !== "blackduck" && !trivyReportUrls;
+ if (!saved || options.provider === "sonar" || trivyReportUrls) {
for (const url of sonarRepositoryUrls(
options.provider,
findings,
@@ -2756,7 +2814,7 @@ async function preparePublicationInput(
["veracode", veracodeReportRepositories],
["continuum", continuumReportRepositories],
] as const) {
- if (saved && options.provider !== provider) continue;
+ if (saved && options.provider !== provider && !trivyReportUrls) continue;
for (const [id, source] of repositories(
options.provider,
findings,
@@ -2779,6 +2837,14 @@ async function preparePublicationInput(
}
for (const finding of findings) {
const { source_finding_id: id, evidence } = finding;
+ checkRetainedTrivyProvider(options.provider, finding);
+ if (trivyReportUrls) {
+ const remote = trivyRepositoryUrl(
+ retainedTrivyReport(finding),
+ trivyTarget,
+ );
+ if (remote) requireTrivyRemote(remote, id);
+ }
const blackDuckUrl = repositories
? repositories.get(id)?.url
: projectedBlackDuckRepositoryUrl(finding, "cloud");
@@ -3183,6 +3249,7 @@ async function preparePublicationInput(
);
const submission: SavedSubmission = {
accountId: credentials.account_id,
+ ...(trivyReportUrls && { trivyRepositoryUrl: trivyTarget }),
requests,
receipts: saved?.receipts,
legacyApproval: saved?.legacyApproval,
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index 7ddf93610..e993f0eb0 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -21,6 +21,7 @@ import {
readSemgrepReport,
} from "./semgrep-findings.js";
import { semgrepPlatformReportRepository } from "./semgrep-platform-findings.js";
+import { readTrivyFindings } from "./trivy-findings.js";
import { readOpenGrepFindings } from "./opengrep-findings.js";
import {
normalizeEndorFindings,
@@ -45,6 +46,7 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {
wiz: "wiz",
snyk: "snyk",
semgrep: "semgrep",
+ trivy: "trivy",
// OpenGrep uses the existing SAST contract; evidence retains its scanner origin.
opengrep: "semgrep",
endor: "endor",
@@ -68,6 +70,7 @@ export interface ExternalFindingsReaderOptions {
provider: ExternalFindingsReader;
sourceRepositoryUrl?: string;
inspectorProjectMap?: ReadonlyMap<string, string>;
+ trivyScanRoot?: string;
}
/** @internal Shared parser output, including immutable Cloud retry projections. */
@@ -162,6 +165,10 @@ export async function readExternalFindings(
references: readonly ExternalSourceRepository[] = [],
): Promise<ReadExternalFindings> {
const { provider } = options;
+ if (provider === "trivy")
+ return {
+ findings: await readTrivyFindings(path, target, options.trivyScanRoot),
+ };
if (provider === "sonar") {
const url = options.sourceRepositoryUrl;
const findings = await readSonarFindings(path, url ?? "", target);
diff --git a/sdk/typescript/src/external-findings.ts b/sdk/typescript/src/external-findings.ts
index 57b67167d..8ad933ab3 100644
--- a/sdk/typescript/src/external-findings.ts
+++ b/sdk/typescript/src/external-findings.ts
@@ -223,8 +223,17 @@ export function snapshotImportOptions<
provider,
sourceKey,
sourceRepositoryUrl,
+ trivyScanRoot,
inspectorProjectMap,
}: ExternalPublicationOptions & { provider: P }) {
+ if (provider === "trivy" && sourceRepositoryUrl !== undefined)
+ throw new CodexSecurityError(
+ "Trivy reads repository provenance from the report; do not supply --source-repository-url.",
+ );
+ if (trivyScanRoot !== undefined && provider !== "trivy")
+ throw new CodexSecurityError(
+ "--trivy-scan-root applies only to --provider trivy.",
+ );
if (inspectorProjectMap !== undefined && provider !== "inspector")
throw new CodexSecurityError(
"An Inspector project map requires the inspector provider.",
@@ -234,6 +243,7 @@ export function snapshotImportOptions<
provider,
sourceKey,
sourceRepositoryUrl,
+ trivyScanRoot,
inspectorProjectMap: inspectorProjectMap && new Map(inspectorProjectMap),
};
}
diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.ts
index e5dd99c81..d19314b29 100644
--- a/sdk/typescript/src/external-import-models.ts
+++ b/sdk/typescript/src/external-import-models.ts
@@ -16,7 +16,8 @@ export type Provider =
| "veracode"
| "sonar"
| "continuum"
- | "checkmarx";
+ | "checkmarx"
+ | "trivy";
export type SourceKey = string;
export type ClientId = string;
export type SourceFindingId = string;
diff --git a/sdk/typescript/src/hosted-git-remotes.ts b/sdk/typescript/src/hosted-git-remotes.ts
index 1dace6433..c5a288efd 100644
--- a/sdk/typescript/src/hosted-git-remotes.ts
+++ b/sdk/typescript/src/hosted-git-remotes.ts
@@ -94,6 +94,7 @@ export async function readHostedGitRemotes(
protectedRoots: string[],
environment?: NodeJS.ProcessEnv,
signal?: AbortSignal,
+ literalTrivySources?: ReadonlySet<string>,
): Promise<string[] | undefined> {
const readGit = (args: readonly string[]) => {
const overrides: NodeJS.ProcessEnv = { LC_ALL: "C" };
@@ -268,6 +269,22 @@ export async function readHostedGitRemotes(
const curl = curlHelper.test(transport.toLowerCase());
// Git uses the scheme spelling in the implicit git-remote-<scheme> executable name.
const effectiveHelper = helper ?? transport;
+ // libcurl rejects raw ASCII control characters and spaces that URL() may discard.
+ if (curl && /[\x00-\x20\x7f]/u.test(url)) {
+ hasUnverifiedRemote = true;
+ continue;
+ }
+ // A mixed-case scheme may invoke a custom Git helper. The native Trivy
+ // report can still match the checkout by its exact transport spelling.
+ if (
+ curl &&
+ helper === undefined &&
+ transport !== transport.toLowerCase() &&
+ literalTrivySources?.has(url)
+ ) {
+ remotes.push(url);
+ continue;
+ }
const recognized = curl
? await recognizedCurlHelper(
effectiveHelper,
@@ -287,8 +304,7 @@ export async function readHostedGitRemotes(
: helper === undefined &&
(!url.includes("://") ||
/^(?:ssh|git\+ssh|ssh\+git|git)$/u.test(transport));
- // libcurl rejects raw ASCII control characters and spaces that URL() may discard.
- if (!recognized || (curl && /[\x00-\x20\x7f]/u.test(url))) {
+ if (!recognized) {
hasUnverifiedRemote = true;
continue;
}
@@ -313,7 +329,11 @@ export async function readHostedGitRemotes(
throw error;
}
}
- remotes.push(url);
+ remotes.push(
+ literalTrivySources && helper !== undefined && curl
+ ? transport.toLowerCase() + url.slice(transport.length)
+ : url,
+ );
}
return hasUnverifiedRemote || remotes.length ? remotes : undefined;
}
diff --git a/sdk/typescript/src/trivy-findings.ts b/sdk/typescript/src/trivy-findings.ts
index 02d35b308..63fb9859a 100644
--- a/sdk/typescript/src/trivy-findings.ts
+++ b/sdk/typescript/src/trivy-findings.ts
@@ -67,36 +67,67 @@ function networkRepository(value: unknown): string | null {
return source;
}
-function comparableGitHubRemote(remote: string): string | undefined {
- const parsed = parseGitRemote(remote);
+function comparableGitHubRemote(
+ remote: string,
+ cloudRepositoryUrl?: string,
+): string | undefined {
+ if (/[?#\t\r\n]/u.test(remote)) return undefined;
+ let parsed;
+ try {
+ parsed = parseGitRemote(remote);
+ } catch {
+ // A checkout can have unrelated remotes with no comparable URL.
+ return undefined;
+ }
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 githubUrl =
+ cloudRepositoryUrl ??
+ (isGitHubCloudHost(host) ? `https://${host}` : undefined);
const normalized = normalizeHostedGitRepositoryUrl(
remote,
- `https://${host}`,
- true,
+ githubUrl,
+ githubUrl !== undefined,
);
- return /^https?:\/\//iu.test(normalized) ? normalized : undefined;
+ if (!/^https?:\/\//iu.test(normalized)) return undefined;
+ if (
+ !isGitHubCloudHost(new URL(normalized).hostname) &&
+ (!cloudRepositoryUrl || new URL(cloudRepositoryUrl).hostname !== host)
+ )
+ return undefined;
+ return normalized;
}
-function trivyRemoteKey(remote: string): string {
- const normalized = comparableGitHubRemote(remote);
- return normalized
- ? hostedRepositoryUrlKey(normalized, true, false, "local")
- : remote;
+export function trivyRemoteKey(
+ remote: string,
+ cloudRepositoryUrl?: string,
+ checkout = false,
+): string {
+ const normalized = comparableGitHubRemote(remote, cloudRepositoryUrl);
+ if (!normalized) return remote;
+ // GitHub identifies an HTTPS repository by host and path. Other Git servers
+ // may use the HTTP username to select the repository.
+ const url = checkout
+ ? normalized.replace(/^(https?:\/\/)[^/\\?#]*@/iu, "$1")
+ : normalized;
+ return hostedRepositoryUrlKey(
+ url,
+ true,
+ false,
+ cloudRepositoryUrl ? "cloud" : "local",
+ );
}
const sshScheme = /^(?:ssh|git\+ssh|ssh\+git):\/\//u;
-function userlessSsh(url: string): boolean {
+export function trivyRemoteOmitsSshUser(url: string): boolean {
return sshScheme.test(url) && !new URL(url).username;
}
-const headerFields = [
+export const trivyHeaderFields = [
"SchemaVersion",
"ArtifactType",
"ArtifactID",
@@ -114,7 +145,8 @@ function escapedHttpTarget(target: string): string {
);
}
-function trivyReportRemotes(report: NativeRecord): string[] {
+export function trivyReportRemotes(report: unknown) {
+ if (!isRecord(report)) return { urls: [] };
const metadata = report["Metadata"];
const repoUrl = text(isRecord(metadata) && metadata["RepoURL"]);
const name = text(report["ArtifactName"]);
@@ -125,9 +157,10 @@ function trivyReportRemotes(report: NativeRecord): string[] {
throw new Error(unsafeRepositoryUrl);
const repository = networkRepository(repoUrl);
let artifact = name && urlScheme.test(name) ? networkRepository(name) : null;
+ if (report["SchemaVersion"] !== 2) return { urls: [] };
// A filesystem display label is validated but never identifies the repository.
if (report["ArtifactType"] === "filesystem")
- return repository ? [repository] : [];
+ return { urls: 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 =
@@ -144,24 +177,42 @@ function trivyReportRemotes(report: NativeRecord): string[] {
// other difference visible when validating the report's repository claims.
if (
repository &&
- userlessSsh(repository) &&
+ trivyRemoteOmitsSshUser(repository) &&
artifact?.replace(/^([^:]+:\/\/)[^/@]+@/u, "$1") === repository
)
- return [repository];
- return [repository, artifact].filter((url) => url !== null);
+ return { urls: [repository] };
+ return {
+ urls: [repository, artifact].filter((url) => url !== null),
+ uncorroboratedTarget: repository ? null : artifact,
+ };
}
-function matchingTrivyRemotes([
- repository,
- artifact,
-]: readonly string[]): boolean {
+function matchingTrivyRemotes(
+ [repository, artifact]: readonly string[],
+ githubUrl?: string,
+): boolean {
return (
!!repository &&
!!artifact &&
- trivyRemoteKey(repository) === trivyRemoteKey(artifact)
+ trivyRemoteKey(repository, githubUrl) ===
+ trivyRemoteKey(artifact, githubUrl)
);
}
+/** Compare the report's claims using the authenticated host when available. */
+export function trivyRepositoryUrl(
+ report: unknown,
+ cloudRepositoryUrl?: string,
+): string | null {
+ const { urls } = trivyReportRemotes(report);
+ if (urls.length > 1 && !matchingTrivyRemotes(urls, cloudRepositoryUrl))
+ throw new Error("Trivy source URLs identify different repositories.");
+ const remote = urls[0];
+ return remote && cloudRepositoryUrl
+ ? (comparableGitHubRemote(remote, cloudRepositoryUrl) ?? remote)
+ : (remote ?? null);
+}
+
function repositoryPath(value: unknown, directory = false): string | null {
const raw = text(value);
if (!raw || !relativePath(raw)) return null;
@@ -201,7 +252,7 @@ function resolveScanRoot(
if (scanRoot === undefined) {
if (remoteRepository) return ".";
throw new Error(
- "Specify scanRoot relative to the repository; use . for a whole-checkout scan.",
+ "Specify --trivy-scan-root relative to the repository; use . for a whole-checkout scan.",
);
}
const root = repositoryPath(scanRoot.split(sep).join("/"), true)?.replace(
@@ -210,11 +261,11 @@ function resolveScanRoot(
);
if (!root)
throw new Error(
- "scanRoot must be a repository-relative directory without traversal.",
+ "--trivy-scan-root 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 .",
+ "A remote Trivy repository scan starts at the checkout root; --trivy-scan-root must be .",
);
return root;
}
@@ -341,9 +392,9 @@ export function normalizeTrivyFindings(
"Only Trivy repository and filesystem reports are supported.",
);
const metadata = record(document["Metadata"] ?? {}, "Trivy Metadata");
- const urls = trivyReportRemotes(document);
+ const { urls } = trivyReportRemotes(document);
const report = {
- ...pick(document, headerFields),
+ ...pick(document, trivyHeaderFields),
...(isRecord(document["Trivy"])
? { Trivy: pick(document["Trivy"], ["Version"]) }
: {}),
diff --git a/sdk/typescript/src/trivy-import.ts b/sdk/typescript/src/trivy-import.ts
new file mode 100644
index 000000000..94c18df5f
--- /dev/null
+++ b/sdk/typescript/src/trivy-import.ts
@@ -0,0 +1,268 @@
+import { resolve } from "node:path";
+import { CodexSecurityError } from "./errors.js";
+import type {
+ ExternalFinding,
+ ExternalFindings,
+ ExternalSourceRepository,
+} from "./external-findings.js";
+import type { ExternalImportTarget } from "./external-import-contract.js";
+import type { Provider } from "./external-import-models.js";
+import { readHostedGitRemotes } from "./hosted-git-remotes.js";
+import { hasGitMetadata } from "./local-git-metadata.js";
+import { isRecord } from "./record.js";
+import { canonicalConfigPath, sameFile } from "./runtime.js";
+import { abortable, gitOutput } from "./targets.js";
+import { ambiguousHostedHttpPath } from "./hosted-git-repository.js";
+import {
+ trivyHeaderFields,
+ trivyRemoteKey,
+ trivyRemoteOmitsSshUser,
+ trivyReportRemotes,
+} from "./trivy-findings.js";
+import { isWizOccurrence } from "./wiz-findings.js";
+
+export function validateTrivyRepositoryUrl(value: string): void {
+ if (
+ /[\x00-\x20\x7f]/u.test(value) &&
+ (/^https?:\/\//iu.test(value) ||
+ /^https?:$/u.test(URL.parse(value)?.protocol ?? ""))
+ )
+ throw new CodexSecurityError(
+ "HTTP(S) repository URLs must percent-encode spaces and control characters.",
+ );
+ if (ambiguousHostedHttpPath(value))
+ throw new CodexSecurityError(
+ "The repository URL has an HTTP path that does not match its Git path.",
+ );
+}
+
+/** A canonical occurrence ID can identify a projected native repository declaration. */
+export function retainedTrivyReport({
+ source_finding_id: id,
+ evidence,
+}: ExternalFinding): unknown {
+ const report = evidence.source_data?.["report"];
+ if (
+ !isRecord(report) ||
+ report["SchemaVersion"] !== undefined ||
+ !/^trivy:[a-f0-9]{64}$/u.test(id)
+ )
+ return report;
+ const metadata = report["Metadata"];
+ return isRecord(metadata) && typeof metadata["RepoURL"] === "string"
+ ? { ...report, SchemaVersion: 2 }
+ : report;
+}
+
+function identifiesTrivyReport(report: unknown): boolean {
+ if (!isRecord(report) || report["SchemaVersion"] !== 2) return false;
+ const scanner = report["Trivy"];
+ const metadata = report["Metadata"];
+ return (
+ (isRecord(scanner) && typeof scanner["Version"] === "string") ||
+ ((report["ArtifactType"] === "repository" ||
+ report["ArtifactType"] === "filesystem") &&
+ isRecord(metadata) &&
+ typeof metadata["RepoURL"] === "string")
+ );
+}
+
+/** Each selected finding must retain the repository asserted by a native batch header. */
+export function trivyBatchSourceUrls(
+ input: ExternalFindings,
+ bind: boolean,
+): string[] {
+ const batch = trivyReportRemotes(input.report);
+ if (bind) requireTrivyBinding(batch);
+ for (const finding of input.findings) {
+ const typedUrl = finding.evidence.details?.repository?.url;
+ const row = trivyReportRemotes(retainedTrivyReport(finding));
+ if (typedUrl && (bind || batch.urls.length || row.urls.length))
+ validateTrivyRepositoryUrl(typedUrl);
+ if (bind) requireTrivyBinding(row);
+ if (batch.urls.length && !typedUrl && !row.urls.length)
+ throw new Error(
+ "For a repository-bound Trivy report, retain the source repository in each finding's source_data.report or details.repository.url.",
+ );
+ }
+ return batch.urls;
+}
+
+/** A native header supplies provenance for the selected rows, not independent run metadata. */
+export function isTrivyReportHeader(report: Record<string, unknown>): boolean {
+ return (
+ report["SchemaVersion"] === 2 &&
+ (report["ArtifactType"] === "repository" ||
+ report["ArtifactType"] === "filesystem") &&
+ Object.keys(report).every(
+ (field) =>
+ trivyHeaderFields.includes(field) ||
+ ["ArtifactName", "Trivy", "Metadata", "Results"].includes(field),
+ )
+ );
+}
+
+function requireTrivyBinding({
+ urls,
+ uncorroboratedTarget,
+}: ReturnType<typeof trivyReportRemotes>): void {
+ if (urls.some(trivyRemoteOmitsSshUser))
+ throw new Error(
+ "Trivy omitted the SSH user, so this report cannot identify its source repository. Verify the recorded remote’s SSH account, host, port and path, or use a verified HTTPS remote, then regenerate the report.",
+ );
+ if (
+ uncorroboratedTarget &&
+ /^https?:\/\//iu.test(uncorroboratedTarget) &&
+ !/^https?:\/\//u.test(uncorroboratedTarget)
+ )
+ throw new Error(
+ "Trivy's mixed-case HTTP target cannot identify the Git transport. Verify the source remote and regenerate the report.",
+ );
+}
+
+function isRetainedTrivyFinding(finding: ExternalFinding) {
+ const data = finding.evidence.source_data;
+ if (!data) return false;
+ const report = retainedTrivyReport(finding);
+ if (identifiesTrivyReport(report)) return true;
+ const metadata = isRecord(report) ? report["Metadata"] : undefined;
+ const nativeReport =
+ isRecord(report) &&
+ report["SchemaVersion"] === 2 &&
+ (isTrivyReportHeader(report) ||
+ (isRecord(metadata) && typeof metadata["RepoURL"] === "string"));
+ const result = data["result"];
+ const vulnerability = data["vulnerability"];
+ const nativeRow =
+ isRecord(result) &&
+ result["Class"] === "lang-pkgs" &&
+ isRecord(vulnerability) &&
+ typeof vulnerability["VulnerabilityID"] === "string" &&
+ typeof vulnerability["PkgName"] === "string";
+ return (
+ (nativeReport && finding.source_finding_id.startsWith("trivy:")) ||
+ (nativeRow && (nativeReport || typeof data["scanRoot"] === "string"))
+ );
+}
+
+/** Retained rows keep their scanner identity even if the report header is projected out. */
+export function checkRetainedTrivyProvider(
+ provider: Provider,
+ finding: ExternalFinding,
+ target: ExternalImportTarget = "cloud",
+): void {
+ if (
+ provider !== "trivy" &&
+ isRetainedTrivyFinding(finding) &&
+ !(provider === "wiz" && isWizOccurrence(finding, target))
+ )
+ throw new CodexSecurityError(
+ "Retained Trivy evidence requires the trivy provider.",
+ );
+}
+
+export function checkTrivyReportProvider(
+ provider: Provider,
+ report: unknown,
+): void {
+ if (provider !== "trivy" && identifiesTrivyReport(report))
+ throw new CodexSecurityError(
+ "Retained Trivy evidence requires the trivy provider.",
+ );
+}
+
+// Typed web links and explicit curl helper arguments use a case-insensitive URL scheme.
+function trivyUrlArgument(url: string) {
+ return url.replace(/^(?:https?|ftps?):\/\//iu, (scheme) =>
+ scheme.toLowerCase(),
+ );
+}
+
+function localTrivySources(
+ input: ExternalFindings,
+ references: readonly ExternalSourceRepository[],
+) {
+ const urls = new Set(trivyBatchSourceUrls(input, false));
+ for (const finding of input.findings) {
+ const typedUrl = finding.evidence.details?.repository?.url;
+ if (typedUrl) urls.add(trivyUrlArgument(typedUrl));
+ for (const url of trivyReportRemotes(retainedTrivyReport(finding)).urls)
+ urls.add(url);
+ }
+ for (const { platform, url } of references)
+ urls.add(platform === "github" ? trivyUrlArgument(url) : url);
+ return [...urls];
+}
+
+export async function matchTrivyCheckout(
+ repository: string,
+ trivy: ExternalFindings,
+ references: readonly ExternalSourceRepository[],
+ {
+ protectedRoot,
+ environment,
+ signal,
+ }: {
+ protectedRoot: string[];
+ environment: NodeJS.ProcessEnv;
+ signal?: AbortSignal | undefined;
+ },
+): Promise<boolean> {
+ const sources = localTrivySources(trivy, references);
+ const trivyKeys = new Set(sources.map((url) => trivyRemoteKey(url)));
+ let remotes: string[] | undefined;
+ if (await hasGitMetadata(repository, signal)) {
+ const gitProtectedRoots = [
+ ...protectedRoot,
+ await abortable(() => canonicalConfigPath(process.cwd()), signal),
+ ];
+ const root = resolve(
+ await abortable(
+ () =>
+ gitOutput(
+ repository,
+ ["rev-parse", "--show-toplevel"],
+ signal,
+ { LC_ALL: "C" },
+ undefined,
+ "utf8",
+ gitProtectedRoots,
+ environment,
+ ),
+ signal,
+ ),
+ );
+ if (
+ root !== repository &&
+ !(await abortable(() => sameFile(root, repository), signal))
+ )
+ throw new CodexSecurityError(
+ `Trivy finding paths are checkout-relative. Git found the checkout at ${JSON.stringify(root)}. Select it with --repository and set --trivy-scan-root relative to it.`,
+ );
+ if (sources.length)
+ remotes = await readHostedGitRemotes(
+ repository,
+ gitProtectedRoots,
+ environment,
+ signal,
+ trivyKeys,
+ );
+ }
+ if (remotes) trivyBatchSourceUrls(trivy, true);
+ if (trivyKeys.size > 1)
+ throw new CodexSecurityError(
+ "Trivy source URLs identify different repositories.",
+ );
+ if (
+ remotes &&
+ !remotes.some(
+ (url) =>
+ !/^(?:https?|ftps?):\/\/[^/?#@]*@[^/?#@]*@/iu.test(url) &&
+ trivyKeys.has(trivyRemoteKey(url, undefined, true)),
+ )
+ )
+ throw new CodexSecurityError(
+ `Imported repository ${JSON.stringify(sources[0])} does not match a configured remote of ${repository}. Select the matching local repository.`,
+ );
+ return remotes !== undefined;
+}
diff --git a/sdk/typescript/src/wiz-findings.ts b/sdk/typescript/src/wiz-findings.ts
index 825a8f366..006fc3eaf 100644
--- a/sdk/typescript/src/wiz-findings.ts
+++ b/sdk/typescript/src/wiz-findings.ts
@@ -4,7 +4,7 @@ import {
validateExternalEvidence,
type ExternalImportTarget,
} from "./external-import-contract.js";
-import { asRecord } from "./record.js";
+import { asRecord, canonicalJson } from "./record.js";
import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
import { isGitHubCloudHost } from "./git-remote.js";
import { readWizCsv, wizCsvFinding, wizCsvRepositoryUrl } from "./wiz-csv.js";
@@ -598,6 +598,48 @@ async function readFindingInput(path: string): Promise<FindingInput> {
}
}
+/** Apply Wiz's own reader to an occurrence that also retains another scanner's fields. */
+export function isWizOccurrence(
+ finding: VendorFinding,
+ target: ExternalImportTarget,
+): boolean {
+ const { source_data: data, details } = finding.evidence;
+ if (!data || typeof data["id"] !== "string") return false;
+ const kind = details?.kind;
+ const scoped = kind === "sast" || kind === "iac" || kind === "secret";
+ if (
+ finding.source_finding_id !==
+ (scoped ? `${kind}:${data["id"]}` : data["id"])
+ )
+ return false;
+ const input: FindingInput = {
+ records: [{ value: data, kind: scoped ? kind : "sca" }],
+ repositories: new Map(),
+ };
+ const repository = details?.repository;
+ if (scoped && repository?.id)
+ input.repositories.set(repository.id, {
+ id: repository.id,
+ name: repository.name ?? null,
+ url: repository.url,
+ platform: null,
+ });
+ // The raw record is the same. Check that Wiz produced the selected evidence,
+ // including its own repository binding, before treating upstream fields as opaque.
+ const selected = canonicalJson({
+ ...validateExternalEvidence(finding.evidence, target),
+ source_data: undefined,
+ });
+ const matches = (legacy: boolean) => {
+ const [row] = normalizeFindings(input, target, undefined, legacy).findings;
+ return (
+ row !== undefined &&
+ canonicalJson({ ...row.evidence, source_data: undefined }) === selected
+ );
+ };
+ return matches(false) || (scoped && matches(true));
+}
+
function normalizeFindings(
input: FindingInput,
target: ExternalImportTarget,
diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
index dacd1bc3c..f7790143d 100644
--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts
+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
@@ -34,6 +34,9 @@ const { workerRuntimeSettings } = (await import(workerExecutorUrl)) as {
}>;
};
+const nativeTestTimeoutMs = Number(
+ process.env["CODEX_SECURITY_TEST_TIMEOUT_MS"] ?? 30_000,
+);
const { temporaryDirectory, cleanup } = createApiTestFixtures();
afterEach(cleanup);
@@ -57,7 +60,13 @@ async function nativeRequest(
const lines = createInterface({ input: child.stdout });
let stderr = "";
child.stderr.on("data", (chunk) => (stderr += chunk));
- const timer = setTimeout(() => child.kill(), 15_000);
+ // Keep the child deadline inside the CI runner's per-test budget.
+ const probeTimeoutMs = nativeTestTimeoutMs / 2;
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill();
+ }, probeTimeoutMs);
const send = (message: unknown) =>
child.stdin.write(JSON.stringify(message) + "\n");
try {
@@ -78,7 +87,10 @@ async function nativeRequest(
}
if (response.id === 2) return response.result;
}
- throw new Error(`Native ${method} probe did not finish: ${stderr}`);
+ const reason = timedOut
+ ? `timed out after ${probeTimeoutMs}ms`
+ : "closed before replying";
+ throw new Error(`Native ${method} probe ${reason}: ${stderr}`);
} finally {
clearTimeout(timer);
lines.close();
@@ -725,7 +737,7 @@ test.each(["openrouter", "fireworks"] as const)(
);
expect(selected).toMatchObject({ env_key: "SYNTHETIC_CUSTOM_API_KEY" });
},
- 30_000,
+ nativeTestTimeoutMs,
);
for (const mode of ["standard", "deep"] as const) {
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 296cf20b3..3bb644b80 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -101,7 +101,16 @@ import {
importedAdvisory,
} from "./support/github-import-fixtures.js";
import { createCliTest } from "./support/cli-run.js";
+import { normalizeTrivyFindings } from "../src/trivy-findings.js";
+import { normalizeInspectorFindings } from "../src/inspector-findings.js";
import {
+ trivyReport,
+ trivyRepositoryHeader,
+} from "./support/trivy-import-fixtures.js";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+import {
+ inspectorReport,
inspectorPackageFinding,
inspectorRepositoryUrl,
} from "./support/inspector-import-fixtures.js";
@@ -1598,6 +1607,41 @@ test("a saved selection with Guardian evidence cannot resume a Cloud upload", as
expect(await readFile(path, "utf8")).toBe(bytes);
});
+test("Trivy Cloud preparation reads the serialized batch and rows", async () => {
+ const report = normalizeTrivyFindings(trivyReport(), "cloud", ".");
+ const row = report.findings[0]!;
+ for (const input of [
+ {
+ ...report,
+ get findings(): never {
+ throw new Error("Unused batch getter");
+ },
+ toJSON: () => report,
+ },
+ {
+ ...report,
+ findings: [
+ {
+ ...row,
+ get evidence(): never {
+ throw new Error("Unused row getter");
+ },
+ toJSON: () => row,
+ },
+ ],
+ },
+ ]) {
+ await expect(
+ prepareNormalizedExternalPublication(input, trivyOptions, {
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ credentials: async () => {
+ throw new Error("Reached credential lookup");
+ },
+ }),
+ ).rejects.toThrow("Reached credential lookup");
+ }
+});
+
test("a normalized Semgrep report checks the provider before Cloud credentials", async () => {
const url = "https://github.com/example/project";
const report = normalizeSemgrepFindings(
@@ -4322,43 +4366,60 @@ test("Inspector publication checks its source and reuses the finding ARN", async
expect(f.posts).toHaveLength(2);
});
-test("Wiz can import, resume and update its own occurrence with upstream Inspector evidence", async () => {
- const record = {
- id: "wiz-vulnerability-1",
- name: "CVE-2099-1234",
- detailedName: "example-package",
- vendorSeverity: "HIGH",
- vulnerableAsset: { id: "example-asset" },
- finding: inspectorPackageFinding(),
- };
- const f = await fixture([record]);
- const prepare = () => prepareExternalPublication(f.file, options, f.deps);
- const first = await prepare();
- f.state.loseResponse = true;
- const error = await first.publish().catch((error: unknown) => error);
- if (!(error instanceof ExternalPublicationError)) throw error;
- expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);
+test.each(["Inspector", "Trivy"] as const)(
+ "Wiz can import, resume and update its own occurrence with upstream %s evidence",
+ async (upstream) => {
+ const trivy = selectedTrivyRows().findings[0]!;
+ const record = {
+ id:
+ upstream === "Trivy" ? trivy.source_finding_id : "wiz-vulnerability-1",
+ name: "CVE-2099-1234",
+ detailedName: "example-package",
+ vendorSeverity: "HIGH",
+ vulnerableAsset: { id: "example-asset" },
+ ...(upstream === "Trivy"
+ ? trivy.evidence.source_data
+ : { finding: inspectorPackageFinding() }),
+ };
+ const f = await fixture([record]);
+ await using local = await localFindingsFixture({
+ remote: foreignArtifactUrl,
+ });
+ const prepared = await prepareNormalizedLocalImport(
+ await readVendorFindings(f.file),
+ { ...options, repository: local.repository },
+ { environment: local.environment },
+ );
+ expect((await prepared.import()).counts.created).toBe(1);
- // A pre-Inspector checkpoint can contain the original requests without their input projection.
- const path = error.result.savedSubmission!;
- const saved = JSON.parse(await readFile(path, "utf8"));
- delete saved.inputProjection;
- await writeFile(path, JSON.stringify(saved));
- const retry = await prepare();
- expect(retry.preview.resumed).toBe(true);
- expect((await retry.publish()).verified).toBe(1);
- expect(f.posts).toEqual([f.posts[0]!, f.posts[0]!]);
+ const prepare = () => prepareExternalPublication(f.file, options, f.deps);
+ const first = await prepare();
+ f.state.loseResponse = true;
+ const error = await first.publish().catch((error: unknown) => error);
+ if (!(error instanceof ExternalPublicationError)) throw error;
+ expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);
- record.vendorSeverity = "MEDIUM";
- await writeFile(f.file, JSON.stringify([record]));
- const updated = await prepareNormalizedExternalPublication(
- await readVendorFindings(f.file),
- options,
- f.deps,
- );
- expect((await updated.publish()).counts.updated).toBe(1);
- expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);
-});
+ // Older checkpoints can contain the original requests without their input projection.
+ const path = error.result.savedSubmission!;
+ const saved = JSON.parse(await readFile(path, "utf8"));
+ delete saved.inputProjection;
+ await writeFile(path, JSON.stringify(saved));
+ const retry = await prepare();
+ expect(retry.preview.resumed).toBe(true);
+ expect((await retry.publish()).verified).toBe(1);
+ expect(f.posts).toEqual([f.posts[0]!, f.posts[0]!]);
+
+ record.vendorSeverity = "MEDIUM";
+ await writeFile(f.file, JSON.stringify([record]));
+ const updated = await prepareNormalizedExternalPublication(
+ await readVendorFindings(f.file),
+ options,
+ f.deps,
+ );
+ expect((await updated.publish()).counts.updated).toBe(1);
+ expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);
+ },
+);
test.each(["example/project", inspectorRepositoryUrl])(
"pending Inspector requests for %s recheck their project mapping and destination host",
@@ -9211,6 +9272,462 @@ async function snykRepositoryEvidence(
const gitHubProject = "https://github.com/example/project";
const connectedProject = "https://git.example.test/example/project";
+const foreignArtifactUrl = "https://github.com/example/other";
+
+const trivyOptions = {
+ ...options,
+ provider: "trivy" as const,
+ trivyScanRoot: ".",
+};
+
+async function trivyCloud(
+ report: unknown = trivyReport(),
+ destination = gitHubProject,
+) {
+ const f = await fixture(report, destination);
+ return {
+ ...f,
+ fileImport: () => prepareExternalPublication(f.file, trivyOptions, f.deps),
+ selected: (rows: ExternalFindings, settings = trivyOptions) =>
+ prepareNormalizedExternalPublication(rows, settings, f.deps),
+ };
+}
+
+test.each([
+ [
+ "http://git.example.test/Example/Project",
+ "http://git.example.test/example/project.git",
+ true,
+ ],
+ [connectedProject, "[email protected]:example/project.git", true],
+ [
+ "ssh://[email protected]/example/project",
+ "ssh://git.example.test/example/project",
+ false,
+ ],
+] as const)(
+ "Trivy CLI binds artifact %s and origin %s before publication",
+ async (ArtifactName, RepoURL, matches) => {
+ const cloud = await trivyCloud(
+ { ...trivyReport(), ArtifactName, Metadata: { RepoURL } },
+ RepoURL.startsWith("http:")
+ ? connectedProject.replace("https:", "http:")
+ : connectedProject,
+ );
+ const args = [...cloud.command, "--trivy-scan-root", "."];
+ args[args.indexOf("--provider") + 1] = "trivy";
+ const cli = createCliTest(main);
+ for (const mode of ["--dry-run", "--yes"]) {
+ expect(await cli.runCli([...args, mode], cloud.cliDeps)).toBe(
+ matches ? 0 : 2,
+ );
+ if (!matches)
+ expect(cli.stderr.text()).toContain("Trivy omitted the SSH user");
+ expect(cloud.posts).toHaveLength(matches && mode === "--yes" ? 1 : 0);
+ }
+ if (matches)
+ expect([...cloud.reports.values()]).toMatchObject([
+ {
+ source: { provider: "trivy" },
+ assessment: { state: "not_assessed" },
+ evidence: { source_data: { report: { Metadata: { RepoURL } } } },
+ },
+ ]);
+ },
+);
+
+test.each([
+ ["HTTPS://github.com/example/project", gitHubProject],
+ ["Git+SSH://[email protected]/example/project", gitHubProject],
+ ["http://git.example.test/example/project.git", connectedProject],
+ [gitHubProject, foreignArtifactUrl],
+ ["[email protected]:example/project.git.git", gitHubProject],
+ ["ssh://[email protected]/other/../example/project.git", connectedProject],
+ ["https://0177.1./org/project", "https://127.0.0.1/org/project"],
+])(
+ "Trivy file and selected row preserve origin %s at destination %s",
+ async (RepoURL, destination) => {
+ const report = { ...trivyReport(), Metadata: { RepoURL } };
+ const cloud = await trivyCloud(report, destination);
+ await expect(cloud.fileImport()).rejects.toThrow("does not match");
+ await expect(cloud.selected(selectedTrivyRows(report))).rejects.toThrow(
+ "does not match",
+ );
+ expect(cloud.posts).toHaveLength(0);
+ },
+);
+
+// A selected row can be imported without the original batch header.
+function selectedTrivyRows(report: unknown = trivyReport()) {
+ const { findings, read, excluded } = normalizeTrivyFindings(
+ report,
+ "cloud",
+ ".",
+ );
+ return { findings, read, excluded };
+}
+
+test.each(["complete", "projected", "header only", "URL only"] as const)(
+ "selected Trivy %s evidence keeps its provider and repository",
+ async (shape) => {
+ const rows = selectedTrivyRows();
+ const row = rows.findings[0]!;
+ const header = row.evidence.source_data!["report"] as Record<
+ string,
+ unknown
+ >;
+ if (shape === "projected") delete header["ArtifactType"];
+ if (shape === "header only") row.evidence.source_data = { report: header };
+ if (shape === "URL only")
+ row.evidence.source_data = {
+ report: { Metadata: { RepoURL: gitHubProject } },
+ };
+ else row.source_finding_id = "selected-occurrence";
+ await expectTrivyReplay(rows);
+ await expectTrivyReplay(rows, /does not match/, foreignArtifactUrl);
+ await expectTrivyReplay(
+ rows,
+ /requires the trivy provider/,
+ foreignArtifactUrl,
+ "wiz",
+ );
+ },
+);
+
+test.each(["batch header", "SAST fields", "package fields"])(
+ "Trivy ownership survives projection as Wiz %s",
+ async (shape) => {
+ const rows: ExternalFindings = selectedTrivyRows();
+ const row = rows.findings[0]!;
+ const data = row.evidence.source_data!;
+ const id = "selected-occurrence";
+ row.source_finding_id = id;
+ if (shape === "batch header") {
+ rows.report = data["report"] as Record<string, unknown>;
+ delete row.evidence.source_data;
+ } else if (shape === "SAST fields") {
+ data["id"] = id;
+ row.source_finding_id = `sast:${id}`;
+ row.evidence.details = {
+ kind: "sast",
+ repository: { id: "wiz-repository", url: foreignArtifactUrl },
+ };
+ } else
+ Object.assign(data, {
+ id,
+ name: "CVE-2099-0001",
+ detailedName: "example-package",
+ vendorSeverity: "HIGH",
+ vulnerableAsset: { id: "example-asset" },
+ });
+ await expectTrivyReplay(
+ rows,
+ /requires the trivy provider/,
+ foreignArtifactUrl,
+ "wiz",
+ );
+ },
+);
+
+test("Wiz SAST can carry upstream Trivy evidence while binding its own repository through inventory", async () => {
+ const record = {
+ ...selectedTrivyRows().findings[0]!.evidence.source_data,
+ id: "example-occurrence",
+ name: "Synthetic finding",
+ severity: "HIGH",
+ repository: { id: "wiz-repository" },
+ };
+ const cloud = await fixture(
+ {
+ data: {
+ sastFindings: { nodes: [record] },
+ versionControlResources: {
+ nodes: [
+ {
+ platform: "GITHUB",
+ repository: { ...record.repository, url: foreignArtifactUrl },
+ },
+ ],
+ },
+ },
+ },
+ foreignArtifactUrl,
+ );
+ const rows = await readVendorFindings(cloud.file);
+ expect(rows.findings[0]).toMatchObject({
+ source_finding_id: `sast:${record.id}`,
+ evidence: {
+ details: { repository: { url: foreignArtifactUrl } },
+ source_data: record,
+ },
+ });
+ await using local = await localFindingsFixture({
+ remote: foreignArtifactUrl,
+ });
+ const prepared = await prepareNormalizedLocalImport(
+ rows,
+ { ...options, repository: local.repository },
+ { environment: local.environment },
+ );
+ expect((await prepared.import()).counts.created).toBe(1);
+ const publication = await prepareExternalPublication(
+ cloud.file,
+ options,
+ cloud.deps,
+ );
+ expect((await publication.publish()).counts.created).toBe(1);
+});
+
+async function expectTrivyReplay(
+ rows: ExternalFindings,
+ error?: string | RegExp,
+ remote = gitHubProject,
+ provider: "trivy" | "wiz" = "trivy",
+) {
+ await using local = await localFindingsFixture({ remote });
+ const cloud = await fixture(undefined, remote);
+ const settings = { ...options, provider };
+ for (const prepare of [
+ () =>
+ prepareNormalizedLocalImport(
+ rows,
+ { ...settings, repository: local.repository },
+ { environment: local.environment },
+ ),
+ () => prepareNormalizedExternalPublication(rows, settings, cloud.deps),
+ ]) {
+ if (error) await expect(prepare()).rejects.toThrow(error);
+ else expect((await prepare()).preview.findings).toHaveLength(1);
+ }
+}
+
+const uppercaseWebUrl = "HTTPS://github.com/Example/Project";
+const userlessSsh = "ssh://github.com/example/project";
+const explicitSsh = "ssh://[email protected]/example/project";
+test.each([
+ [gitHubProject, uppercaseWebUrl, undefined],
+ [gitHubProject, foreignArtifactUrl, /does not match|different repositories/],
+ [uppercaseWebUrl, gitHubProject, /does not match|different repositories/],
+ [userlessSsh, gitHubProject, /omitted the SSH user/],
+ [explicitSsh, gitHubProject, undefined],
+] as const)(
+ "Trivy compares the raw origin %s independently of the typed repository %s",
+ async (raw, typed, error) => {
+ const rows = selectedTrivyRows();
+ const evidence = rows.findings[0]!.evidence;
+ evidence.source_data!["report"] = trivyRepositoryHeader(raw);
+ evidence.details = { kind: "sast", repository: { url: typed } };
+ await expectTrivyReplay(
+ { ...rows, report: trivyRepositoryHeader(gitHubProject) },
+ error,
+ );
+ },
+);
+
+test("each normalized Trivy finding must retain its report's repository", async () => {
+ const report = trivyReport();
+ report.Results.push({
+ ...report.Results[0]!,
+ Target: "nested/package-lock.json",
+ });
+ const input = normalizeTrivyFindings(report, "cloud", ".");
+ delete input.findings[1]!.evidence.source_data;
+ input.report = trivyRepositoryHeader(report.Metadata.RepoURL);
+ await expectTrivyReplay(input, /retain/i);
+});
+
+test.each([
+ [`${gitHubProject}/Kit`, `${gitHubProject}/Kit`, false],
+ [`${gitHubProject}/Kit`, `${gitHubProject}/%E2%84%AAit`, true],
+ ["https://0177.1./org/project", "https://127.0.0.1/org/project", false],
+] as const)(
+ "Trivy compares typed and catalog URLs %s and %s",
+ async (source, target, matches) => {
+ const cloud = await trivyCloud(undefined, target);
+ const rows = selectedTrivyRows({ ...trivyReport(), Metadata: {} });
+ const catalog = cloud.selected(rows, {
+ ...trivyOptions,
+ repository: source,
+ });
+ if (matches) expect((await catalog).preview.destination.url).toBe(target);
+ else
+ await expect(catalog).rejects.toThrow(
+ "destination repository is not available",
+ );
+
+ for (const kind of ["typed", "native"]) {
+ const report = {
+ ...trivyReport(),
+ Metadata: { RepoURL: kind === "native" ? source : target },
+ };
+ const rows = selectedTrivyRows(report);
+ if (kind === "typed")
+ rows.findings[0]!.evidence.details = {
+ kind: "sast",
+ repository: { url: source },
+ };
+ const prepared = cloud.selected(rows);
+ if (matches) expect((await prepared).preview.findings).toHaveLength(1);
+ else await expect(prepared).rejects.toThrow("does not match");
+ }
+ },
+);
+
+test("Trivy preparation rejects retained Inspector findings", async () => {
+ const input = normalizeInspectorFindings(inspectorReport(), gitHubProject);
+ const cloud = await fixture();
+ await expect(
+ prepareNormalizedExternalPublication(input, trivyOptions, cloud.deps),
+ ).rejects.toThrow(
+ "Retained Inspector evidence requires the inspector provider.",
+ );
+});
+
+test("Trivy typed repository links and catalog URLs must identify the same HTTP and Git path", async () => {
+ const ambiguous = "https://github.com/example/%2e%2e/../project";
+ const error = /HTTP path that does not match its Git path/u;
+ const input = selectedTrivyRows({ ...trivyReport(), Metadata: {} });
+ input.findings[0]!.evidence.details = {
+ kind: "sast",
+ repository: { url: ambiguous },
+ };
+ await expectTrivyReplay(input, error);
+
+ const rows = selectedTrivyRows();
+ const cloud = await trivyCloud();
+ await expect(
+ cloud.selected(rows, { ...trivyOptions, repository: ambiguous }),
+ ).rejects.toThrow(error);
+ cloud.state.repositoryUrl = ambiguous;
+ await expect(cloud.selected(rows)).rejects.toThrow(error);
+});
+
+const credentialUrl = "https://scanner:[email protected]/example/project";
+
+test.each([
+ ["filesystem", credentialUrl, "without credentials"],
+ [undefined, credentialUrl, "without credentials"],
+ ["unknown", credentialUrl, "without credentials"],
+ [undefined, foreignArtifactUrl, "does not match"],
+ ["filesystem", foreignArtifactUrl, undefined],
+] as const)(
+ "checks retained Trivy artifact type %s with URL %s",
+ async (ArtifactType, ArtifactName, error) => {
+ const input = normalizeTrivyFindings(
+ { ...trivyReport(), Metadata: {} },
+ "cloud",
+ ".",
+ );
+ input.findings[0]!.evidence.source_data!["report"] = {
+ SchemaVersion: 2,
+ ...(ArtifactType && { ArtifactType }),
+ ArtifactName,
+ };
+ await expectTrivyReplay(input, error);
+ },
+);
+
+test.each([
+ ["repository", "other", false],
+ ["repository", "project", true],
+ ["filesystem", "other", true],
+])(
+ "Trivy %s artifact URL ending in %s binds individual findings when it identifies a repository",
+ async (ArtifactType, project, accepts) => {
+ const ArtifactName = `ssh://[email protected]/example/${project}.git`;
+ const report = {
+ ...trivyReport(),
+ ArtifactType,
+ ArtifactName,
+ Metadata: {},
+ };
+ const cloud = await trivyCloud(report);
+ for (const prepare of [
+ cloud.fileImport,
+ () => cloud.selected(selectedTrivyRows(report)),
+ ]) {
+ if (!accepts) {
+ await expect(prepare()).rejects.toThrow("does not match");
+ continue;
+ }
+ const prepared = await prepare();
+ if (ArtifactType === "repository") {
+ const other = await trivyCloud(report, foreignArtifactUrl);
+ await expect(
+ other.selected(JSON.parse(JSON.stringify(prepared.preview))),
+ ).rejects.toThrow("does not match");
+ }
+ await prepared.publish();
+ expect(
+ JSON.parse(cloud.posts.at(-1)!).items[0].evidence.source_data.report
+ .ArtifactName,
+ ).toBe(ArtifactName);
+ }
+ },
+);
+
+test.each([
+ ["empty", [], "No supported findings are ready to publish"],
+ [
+ "excluded-only",
+ [{ Class: "os-pkgs" }],
+ "Unsupported Trivy result class: os-pkgs",
+ ],
+] as const)(
+ "an %s Trivy report stops before Cloud authentication or repository discovery",
+ async (_name, Results, error) => {
+ const report = {
+ ...trivyReport(),
+ Metadata: { RepoURL: "ssh://git.example.test/example/project" },
+ Results,
+ };
+ const cloud = await fixture(report);
+ const unexpected = async () => {
+ throw new Error("Unexpected Cloud access");
+ };
+ const deps = {
+ environment: cloud.environment,
+ credentials: unexpected,
+ fetch: unexpected,
+ };
+ await expect(
+ prepareExternalPublication(cloud.file, trivyOptions, deps),
+ ).rejects.toThrow(error);
+ const input = normalizeTrivyFindings(report, "cloud", ".");
+ await expect(
+ prepareNormalizedExternalPublication(input, trivyOptions, deps),
+ ).rejects.toThrow(error);
+ input.report = trivyRepositoryHeader(credentialUrl);
+ await expect(
+ prepareNormalizedExternalPublication(input, trivyOptions, deps),
+ ).rejects.toThrow("without credentials");
+ },
+);
+
+test.each([
+ [
+ {
+ provider: "trivy",
+ trivyScanRoot: ".",
+ sourceRepositoryUrl: "https://github.com/example/other",
+ },
+ "--source-repository-url",
+ ],
+ [{ provider: "trivy" }, "--trivy-scan-root"],
+ [{ provider: "wiz", trivyScanRoot: "." }, "only to --provider trivy"],
+ [{ provider: "snyk", trivyScanRoot: "." }, "only to --provider trivy"],
+ [{ provider: "semgrep", trivyScanRoot: "." }, "only to --provider trivy"],
+] as const)(
+ "rejects invalid file import options %p",
+ async (settings, message) => {
+ const f = await fixture(trivyReport());
+ await expect(
+ prepareExternalPublication(f.file, { ...options, ...settings }, f.deps),
+ ).rejects.toThrow(message);
+ expect(f.posts).toHaveLength(0);
+ },
+);
+
const tenantProject = "https://tenant.ghe.com/example/project";
const snykRepositoryAliases: [string, string][] = [
@@ -9819,6 +10336,76 @@ test("Endor JSON and SARIF reuse UUID identity through Cloud publication", async
result: sarif.runs[0]!.results[0],
});
});
+test.each(["file", "selected rows"] as const)(
+ "a Trivy %s publication resumes its original request across entrypoints and a repository rename",
+ async (initialKind) => {
+ const report = {
+ ...trivyReport(),
+ Metadata: {},
+ ArtifactName: "ssh://[email protected]/example/project.git",
+ };
+ const cloud = await trivyCloud(report);
+ const file = cloud.fileImport;
+ const selected = (header?: Record<string, unknown>) =>
+ cloud.selected({ ...selectedTrivyRows(report), report: header });
+ const first = initialKind === "file" ? await file() : await selected();
+ await cloud.loseResponse(first);
+ const body = cloud.posts[0]!;
+ expect(JSON.parse(body)).toEqual(first.preview.requests[0]);
+ await writeFile(
+ cloud.file,
+ JSON.stringify({ ...report, ArtifactName: foreignArtifactUrl }),
+ );
+ await expect(file()).rejects.toThrow("does not match");
+ await writeFile(cloud.file, JSON.stringify(report));
+
+ cloud.state.repositoryUrl = "https://github.com/example/renamed";
+ await expect(
+ selected(trivyRepositoryHeader(cloud.state.repositoryUrl)),
+ ).rejects.toThrow("does not match");
+ expect(cloud.posts).toEqual([body]);
+ expect(
+ (await selected(trivyRepositoryHeader(gitHubProject))).preview.resumed,
+ ).toBe(true);
+ const retry = initialKind === "file" ? await selected() : await file();
+ expect(retry.preview.resumed).toBe(true);
+ expect(retry.preview.requests).toEqual(first.preview.requests);
+ expect((await retry.publish()).status).toBe("complete");
+ expect(cloud.posts).toEqual([body, body]);
+ await expect(file()).rejects.toThrow("does not match");
+ },
+);
+
+test("unverified Trivy checkpoints retain their requests and receipts for the original importer", async () => {
+ const cloud = await trivyCloud();
+ const prepare = cloud.fileImport;
+ cloud.state.brokenReadback = true;
+ const failure = await (
+ await prepare()
+ )
+ .publish()
+ .catch((error: unknown) => error);
+ if (!(failure instanceof ExternalPublicationError)) throw failure;
+ const filename = failure.result.savedSubmission!;
+ cloud.state.brokenReadback = false;
+ const retry = await prepare();
+ const { accountId, requests, receipts, inputProjection } = JSON.parse(
+ await readFile(filename, "utf8"),
+ );
+ expect(receipts).toHaveLength(1);
+ const original = JSON.stringify({
+ accountId,
+ requests,
+ receipts,
+ inputProjection,
+ });
+ await writeFile(filename, original);
+ await expect(prepare()).rejects.toThrow("the build that created it");
+ await expect(retry.publish()).rejects.toThrow();
+ expect(await readFile(filename, "utf8")).toBe(original);
+ expect(cloud.posts).toHaveLength(1);
+});
+
test("Endor source repository binding preserves immutable requests across a repository rename", async () => {
const input: any = endorSarif();
input.runs[0].versionControlProvenance = [
diff --git a/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts b/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts
index 1789d4237..9e4f016db 100644
--- a/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts
+++ b/sdk/typescript/tests-ts/support/trivy-import-fixtures.ts
@@ -1,3 +1,11 @@
+export function trivyRepositoryHeader(RepoURL: string) {
+ return {
+ SchemaVersion: 2,
+ ArtifactType: "repository",
+ Metadata: { RepoURL },
+ };
+}
+
export function trivyReport() {
const name = "@example/package";
const version = "1.0.0";
diff --git a/sdk/typescript/tests-ts/trivy-findings-local.test.ts b/sdk/typescript/tests-ts/trivy-findings-local.test.ts
new file mode 100644
index 000000000..94e7735bf
--- /dev/null
+++ b/sdk/typescript/tests-ts/trivy-findings-local.test.ts
@@ -0,0 +1,541 @@
+import { expect, test } from "bun:test";
+import { mkdir, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { prepareNormalizedExternalPublication } from "../src/external-findings-publish.js";
+import {
+ listLocalExternalFindings,
+ normalizeTrivyFindings,
+ prepareLocalExternalImport,
+ prepareNormalizedLocalImport,
+} from "../src/index.js";
+import type { ExternalFindings } from "../src/external-findings.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+import { git } from "./git-fixture.js";
+import {
+ trivyReport,
+ trivyRepositoryHeader,
+} from "./support/trivy-import-fixtures.js";
+
+const checkoutUrl = "https://github.com/example/project";
+const foreignUrl = "https://github.com/example/other";
+const enterpriseUrl = "https://git.example.test/Example/Project";
+const enterpriseHttp = enterpriseUrl.replace("https:", "http:");
+const singleSuffix = `${enterpriseUrl.toLowerCase()}.git`;
+const doubleSuffix = `${singleSuffix}.git`;
+const enterpriseSsh = "[email protected]:example/project.git";
+const mismatch = "does not match a configured remote";
+const ambiguousSsh = /Trivy omitted the SSH user/u;
+
+function repositoryClaims(artifactName: string, repoUrl: string) {
+ return { ArtifactName: artifactName, Metadata: { RepoURL: repoUrl } };
+}
+
+async function trivyCheckout(remote?: string, githubSource?: string) {
+ const fixture = await localFindingsFixture({ remote });
+ const options = {
+ provider: "trivy" as const,
+ repository: fixture.repository,
+ sourceKey: "example/project/main",
+ };
+ const deps = {
+ environment: fixture.environment,
+ sourceRepositories: githubSource
+ ? [{ url: githubSource, platform: "github" as const }]
+ : [],
+ };
+ const file = join(fixture.root, "trivy.json");
+ const prepare = (input: ExternalFindings, repository = fixture.repository) =>
+ prepareNormalizedLocalImport(input, { ...options, repository }, deps);
+ return {
+ [Symbol.asyncDispose]: fixture.dispose,
+ repository: fixture.repository,
+ prepare,
+ async fromFile(report: unknown) {
+ await writeFile(file, JSON.stringify(report));
+ return prepareLocalExternalImport(
+ file,
+ { ...options, trivyScanRoot: "." },
+ deps,
+ );
+ },
+ async fromNormalized(report: unknown) {
+ return prepare(normalizeTrivyFindings(report, "local", "."));
+ },
+ list: () => listLocalExternalFindings(options, deps),
+ };
+}
+
+test("normalized Trivy headers reject credentials before local or Cloud preparation", async () => {
+ const input = normalizeTrivyFindings(trivyReport(), "local", ".");
+ const options = {
+ provider: "trivy" as const,
+ repository: "repo-example",
+ sourceKey: "example/project/main",
+ };
+ const environment = { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" };
+ await expect(
+ prepareNormalizedLocalImport(
+ input,
+ { ...options, sourceRepositoryUrl: foreignUrl },
+ { environment },
+ ),
+ ).rejects.toThrow("--source-repository-url");
+ input.report = trivyRepositoryHeader(
+ "https://scanner:[email protected]/example/other",
+ );
+ const error = "without credentials";
+ await using local = await trivyCheckout(checkoutUrl);
+ await expect(local.prepare(input)).rejects.toThrow(error);
+ await expect(
+ prepareNormalizedExternalPublication(input, options, {
+ environment,
+ credentials: async () => {
+ throw new Error("Unexpected Cloud authentication");
+ },
+ }),
+ ).rejects.toThrow(error);
+});
+
+const mixedScheme = checkoutUrl.replace("https:", "HTTPS:");
+const localMirror = "file:///synthetic/mirror";
+const differentRepositories = "identify different repositories";
+const excludedGroups = [{ Class: "os-pkgs" }];
+const artifactOnly = (ArtifactName: string) => ({ ArtifactName, Metadata: {} });
+
+test.each([
+ [{}, foreignUrl, mismatch],
+ [{ Results: excludedGroups }, foreignUrl, mismatch],
+ [repositoryClaims(".", mixedScheme), mixedScheme, null],
+ [artifactOnly(mixedScheme), mixedScheme, "mixed-case HTTP target"],
+ [artifactOnly(foreignUrl), checkoutUrl, mismatch],
+ [{ ArtifactName: foreignUrl }, localMirror, differentRepositories],
+ [
+ repositoryClaims(enterpriseUrl.toLowerCase(), enterpriseSsh),
+ undefined,
+ differentRepositories,
+ ],
+ [
+ repositoryClaims(enterpriseUrl, enterpriseUrl.toLowerCase()),
+ enterpriseUrl,
+ differentRepositories,
+ ],
+ [
+ repositoryClaims(enterpriseHttp, enterpriseHttp.toLowerCase() + ".git"),
+ undefined,
+ differentRepositories,
+ ],
+ [
+ {
+ ...repositoryClaims(
+ ".",
+ "ssh://[email protected]:443/example/project.git",
+ ),
+ Results: excludedGroups,
+ },
+ checkoutUrl,
+ null,
+ ],
+ [artifactOnly(checkoutUrl), checkoutUrl, null],
+ [
+ { ...artifactOnly(foreignUrl), ArtifactType: "filesystem" },
+ checkoutUrl,
+ null,
+ ],
+ [repositoryClaims("C:\\ci\\checkout", "D:mirror.git"), checkoutUrl, null],
+ [{ Metadata: {} }, foreignUrl, null],
+ [{}, localMirror, null],
+] as const)(
+ "checks report header %j against remote %s even with no accepted findings",
+ async (overrides, remote, error) => {
+ await using checkout = await trivyCheckout(remote);
+ const report = { ...trivyReport(), Results: [], ...overrides };
+ for (const prepare of [checkout.fromFile, checkout.fromNormalized]) {
+ const pending = prepare(report);
+ if (error) await expect(pending).rejects.toThrow(error);
+ else {
+ const { preview } = await pending;
+ expect(preview.findings).toEqual([]);
+ expect(preview.excluded).toHaveLength(report.Results.length);
+ }
+ }
+ },
+);
+
+test.each([
+ [singleSuffix, enterpriseUrl, "different repositories"],
+ [
+ singleSuffix.replace("https:", "http:"),
+ enterpriseHttp,
+ "different repositories",
+ ],
+ [
+ "ssh://git.example.test/example/project",
+ "ssh://[email protected]/example/project",
+ ambiguousSsh,
+ ],
+ [
+ "ssh://git.example.test/example/other",
+ "ssh://[email protected]/example/other",
+ ambiguousSsh,
+ ],
+ [
+ "ssh://git.example.test/example/project",
+ "ssh://[email protected]/example/project",
+ ambiguousSsh,
+ ],
+] as const)(
+ "a local GitHub source hint rejects conflicting report %s and artifact %s",
+ async (remote, artifact, error) => {
+ const scheme = remote.startsWith("http:") ? "http" : "https";
+ const url = `${scheme}://git.example.test/example/project`;
+ await using checkout = await trivyCheckout(url, url);
+ const report = { ...trivyReport(), ...repositoryClaims(artifact, remote) };
+ for (const prepare of [checkout.fromNormalized, checkout.fromFile])
+ await expect(prepare(report)).rejects.toThrow(error);
+ },
+);
+
+test("a reader's GitHub web hint cannot change the meaning of the raw Trivy transport", async () => {
+ const web = "HTTPS://github.com/example/project";
+ await using checkout = await trivyCheckout(checkoutUrl, web);
+ for (const raw of [checkoutUrl, web]) {
+ const { findings, read, excluded } = normalizeTrivyFindings(
+ { ...trivyReport(), ArtifactName: ".", Metadata: { RepoURL: raw } },
+ "local",
+ ".",
+ );
+ findings[0]!.evidence.details = { kind: "sast", repository: { url: web } };
+ const pending = checkout.prepare({ findings, read, excluded });
+ if (raw === checkoutUrl)
+ expect((await pending).preview.findings).toHaveLength(1);
+ else await expect(pending).rejects.toThrow("different repositories");
+ }
+});
+
+test("an unbound local Trivy import keeps a standalone typed repository link", async () => {
+ await using checkout = await trivyCheckout();
+ const report = { ...trivyReport(), ...repositoryClaims(".", "") };
+ const input = normalizeTrivyFindings(report, "local", ".");
+ const finding = input.findings[0]!;
+ finding.evidence.details = {
+ kind: "sast",
+ repository: { url: "https://example.test/team/archive/../project" },
+ };
+ expect((await checkout.prepare(input)).preview.findings).toEqual([finding]);
+});
+
+test("Trivy treats an explicit curl helper argument as a URL", async () => {
+ await using checkout = await trivyCheckout("https::" + mixedScheme);
+ expect(
+ (await checkout.fromNormalized(trivyReport())).preview.findings,
+ ).toHaveLength(1);
+ const report = trivyReport();
+ report.Metadata.RepoURL = mixedScheme;
+ await expect(checkout.fromNormalized(report)).rejects.toThrow(mismatch);
+});
+
+test("Trivy can match a checkout with an unrelated malformed remote", async () => {
+ await using checkout = await trivyCheckout(checkoutUrl);
+ git(checkout.repository, "remote", "add", "broken", "https://[invalid");
+ const prepared = await checkout.fromNormalized(trivyReport());
+ expect(prepared.preview.findings).toHaveLength(1);
+});
+
+test("Trivy preserves Unicode path bytes in GitHub report and typed repository claims", async () => {
+ const ascii = "https://github.com/example/Kit";
+ const unicode = "https://github.com/example/Kit";
+ const encoded = "https://github.com/example/%E2%84%AAit";
+ const report = {
+ ...trivyReport(),
+ ArtifactName: ".",
+ Metadata: { RepoURL: unicode },
+ };
+ await using different = await trivyCheckout(ascii);
+ await expect(different.fromFile(report)).rejects.toThrow(mismatch);
+ const input = normalizeTrivyFindings(report, "local", ".");
+ const finding = input.findings[0]!;
+ finding.evidence.details = { kind: "sast", repository: { url: ascii } };
+ await expect(different.prepare(input)).rejects.toThrow(
+ "different repositories",
+ );
+ finding.evidence.details.repository = { url: encoded };
+ await using same = await trivyCheckout(encoded);
+ expect((await same.prepare(input)).preview.findings).toHaveLength(1);
+});
+
+test("a reader-declared Trivy source must agree with the finding even when both are checkout remotes", async () => {
+ await using checkout = await trivyCheckout(checkoutUrl, foreignUrl);
+ git(checkout.repository, "remote", "add", "upstream", foreignUrl);
+ await expect(checkout.fromNormalized(trivyReport())).rejects.toThrow(
+ "different repositories",
+ );
+});
+
+test("selected and stored Trivy findings retain their artifact-only checkout binding", async () => {
+ await using source = await trivyCheckout(checkoutUrl);
+ await using other = await trivyCheckout(foreignUrl);
+ const artifact = "ssh://[email protected]/example/project.git";
+ const report = trivyReport();
+ report.Results.push({
+ ...report.Results[0]!,
+ Target: "nested/package-lock.json",
+ });
+ const input = normalizeTrivyFindings(
+ { ...report, ArtifactName: artifact, Metadata: {} },
+ "local",
+ ".",
+ );
+ const prepared = await source.prepare(input);
+ const reloaded = JSON.parse(JSON.stringify(prepared.preview));
+ await prepared.import();
+ const stored = await source.list();
+ expect(stored).toHaveLength(2);
+ const record = stored[0]!;
+ expect(record.evidence.source_data).toMatchObject({
+ report: { ArtifactName: artifact },
+ });
+ const storedFinding = {
+ source_finding_id: record.sourceFindingId,
+ evidence: record.evidence,
+ };
+ for (const selected of [
+ reloaded,
+ { read: 1, findings: [input.findings[0]!], excluded: [] },
+ { read: 1, findings: [storedFinding], excluded: [] },
+ ])
+ await expect(source.prepare(selected, other.repository)).rejects.toThrow(
+ mismatch,
+ );
+});
+
+test("Trivy import preserves the occurrence across revisions without assessing it", async () => {
+ await using checkout = await trivyCheckout(
+ "[email protected]:example/project.git",
+ );
+ const report = trivyReport();
+ const prepare = () => checkout.fromFile(report);
+ const preview = await prepare();
+ expect(preview.preview.excluded).toEqual([]);
+ expect(await checkout.list()).toEqual([]);
+ expect((await preview.import()).counts.created).toBe(1);
+ expect((await (await prepare()).import()).counts.unchanged).toBe(1);
+
+ const updatedCommit = "b".repeat(40);
+ report.Metadata.Commit = updatedCommit;
+ expect((await (await prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 1,
+ unchanged: 0,
+ });
+ const stored = await checkout.list();
+ expect(stored).toHaveLength(1);
+ expect(stored[0]).toMatchObject({
+ provider: "trivy",
+ sourceFindingId: preview.preview.findings[0]!.source_finding_id,
+ version: 2,
+ evidence: {
+ code_revision: null,
+ source_data: { report: { Metadata: { Commit: updatedCommit } } },
+ },
+ assessment: { state: "not_assessed" },
+ });
+});
+
+test("local Trivy paths use the checkout root even without a report remote", async () => {
+ await using checkout = await trivyCheckout();
+ const nested = join(checkout.repository, "apps", "web");
+ await mkdir(nested, { recursive: true });
+ const findings = normalizeTrivyFindings(
+ { ...trivyReport(), Metadata: {} },
+ "local",
+ "apps/web",
+ );
+ await expect(checkout.prepare(findings, nested)).rejects.toThrow(
+ `Git found the checkout at ${JSON.stringify(checkout.repository)}.`,
+ );
+ await expect(
+ checkout.prepare(findings, join(checkout.repository, ".git", "objects")),
+ ).rejects.toThrow("must be run in a work tree");
+ const { preview } = await checkout.prepare(findings);
+ expect(
+ join(preview.repository, preview.findings[0]!.evidence.locations![0]!.path),
+ ).toBe(join(nested, "package-lock.json"));
+});
+
+test("Trivy distinguishes a differently cased checkout alias from a separate directory", async () => {
+ await using checkout = await trivyCheckout();
+ const alternate = join(dirname(checkout.repository), "REPOSITORY");
+ const created = await mkdir(alternate, { recursive: true });
+ git(checkout.repository, "config", "core.worktree", alternate);
+ const prepared = checkout.fromNormalized(trivyReport());
+ if (created)
+ await expect(prepared).rejects.toThrow(
+ "Trivy finding paths are checkout-relative",
+ );
+ else expect((await prepared).preview.findings).toHaveLength(1);
+});
+
+test.each([
+ [foreignUrl, checkoutUrl, undefined, "."],
+ [enterpriseUrl, enterpriseSsh, enterpriseUrl, "."],
+ [doubleSuffix, singleSuffix, doubleSuffix, doubleSuffix],
+ [singleSuffix, singleSuffix, doubleSuffix, "."],
+] as const)(
+ "normalized Trivy report %s, finding %s and reader hint %s must agree",
+ async (reportUrl, findingUrl, githubSource, artifact) => {
+ await using checkout = await trivyCheckout(undefined, githubSource);
+ const plainDirectory = join(dirname(checkout.repository), "unpacked");
+ await mkdir(plainDirectory);
+ const input = normalizeTrivyFindings(
+ { ...trivyReport(), ...repositoryClaims(artifact, findingUrl) },
+ "local",
+ ".",
+ );
+ input.report = trivyRepositoryHeader(reportUrl);
+ const reject = (repository: string) =>
+ expect(checkout.prepare(input, repository)).rejects.toThrow(
+ "different repositories",
+ );
+ await reject(plainDirectory);
+ await reject(checkout.repository);
+ const origin = githubSource ?? reportUrl;
+ git(checkout.repository, "remote", "add", "origin", origin);
+ git(checkout.repository, "remote", "add", "upstream", findingUrl);
+ await reject(checkout.repository);
+ },
+);
+
+const aliasWeb = "https://work/team/project";
+const aliasScp = "git@work:team/project.git";
+const aliasSsh = "ssh://git@work/team/project.git";
+const githubScp = "[email protected]:example/project.git";
+const noUser = "ssh://github.com/example/project";
+const hostedTenant = "ssh://tenant.ghe.com/team/project";
+const isWindows = process.platform === "win32";
+const loginEnterprise =
+ "https://[email protected]/Example/Project";
+const sshAlias = "ssh://[email protected]/example/project";
+const httpsLogin = "https://[email protected]/example/";
+
+test.each([
+ // Each remote must agree with the source, including when the reader supplies a GitHub hint.
+ [checkoutUrl, foreignUrl, true, mismatch],
+ [checkoutUrl, githubScp, true, null],
+ [aliasScp, aliasWeb, true, mismatch],
+ [aliasWeb, aliasScp, true, mismatch],
+ [aliasWeb, aliasSsh, true, mismatch],
+ [aliasScp, aliasScp, true, null],
+ [aliasSsh, aliasSsh, true, null],
+ [aliasWeb, aliasWeb, true, null],
+ [enterpriseHttp, enterpriseHttp, true, null],
+ [doubleSuffix, doubleSuffix, true, null],
+ [enterpriseUrl, loginEnterprise, true, mismatch],
+ [enterpriseUrl, loginEnterprise, false, mismatch],
+ [enterpriseUrl, enterpriseUrl.toLowerCase(), true, mismatch],
+ [enterpriseUrl, enterpriseUrl.toLowerCase(), false, mismatch],
+ ["git@host:/org/repo", "git@host:org/repo", false, mismatch],
+ ["alice@host:project", "bob@host:project", true, mismatch],
+ ["alice@host:repo.git", "alice@host:repo", true, mismatch],
+ [githubScp, sshAlias + "?", true, mismatch],
+ [checkoutUrl, "g:team/two", false, isWindows ? null : mismatch],
+ [checkoutUrl, "g:/srv/other.git", false, isWindows ? null : mismatch],
+ [
+ "ssh://g/srv/project.git",
+ "g:/srv/other.git",
+ false,
+ isWindows ? null : ambiguousSsh,
+ ],
+ ["user@g:team/one", "user@g:team/two", false, mismatch],
+ [noUser, githubScp, false, ambiguousSsh],
+ [
+ hostedTenant,
+ "ssh://[email protected]/team/project",
+ false,
+ ambiguousSsh,
+ ],
+ [
+ hostedTenant,
+ "ssh://[email protected]/team/project",
+ false,
+ ambiguousSsh,
+ ],
+ [checkoutUrl, httpsLogin + "project.git", false, null],
+ [checkoutUrl, httpsLogin + "other.git", false, mismatch],
+ [checkoutUrl, "https://a@[email protected]/example/project.git", false, mismatch],
+ [checkoutUrl, noUser, false, mismatch],
+ [checkoutUrl, sshAlias, false, null],
+ [checkoutUrl, "SSH://github.com/example/project", false, mismatch],
+ [checkoutUrl, mixedScheme, false, mismatch],
+ [checkoutUrl, "git+" + sshAlias + ".git", false, null],
+ [checkoutUrl, sshAlias.replace("ssh:", "ssh+git:") + ".git", false, null],
+] as const)(
+ "checks source %s against checkout %s (GitHub hint %j)",
+ async (source, remote, githubHint, error) => {
+ await using checkout = await trivyCheckout(
+ remote,
+ githubHint ? source : undefined,
+ );
+ const report = { ...trivyReport(), ...repositoryClaims(".", source) };
+ const prepared = checkout.fromFile(report);
+ if (error) await expect(prepared).rejects.toThrow(error);
+ else expect((await prepared).preview.findings).toHaveLength(1);
+ },
+);
+
+test.each([
+ { ArtifactName: checkoutUrl.replace("https:", "HTTPS:"), Metadata: {} },
+ {
+ ArtifactName: ".",
+ Metadata: { RepoURL: "ssh://github.com/example/project" },
+ },
+ repositoryClaims(
+ "ssh://[email protected]/team/project",
+ "ssh://source.example/team/project",
+ ),
+])(
+ "unresolved Git transport can be retained in an unverified local import",
+ async (source) => {
+ await using checkout = await trivyCheckout("file:///local/fixture.git");
+ const unpacked = join(dirname(checkout.repository), "unpacked");
+ await mkdir(unpacked);
+ const report = { ...trivyReport(), ...source };
+ const { findings, read, excluded } = normalizeTrivyFindings(
+ report,
+ "local",
+ ".",
+ );
+ const stored = await checkout.prepare(
+ { findings, read, excluded },
+ unpacked,
+ );
+ expect(stored.preview.findings).toEqual(findings);
+ expect((await checkout.fromFile(report)).preview.findings).toEqual(
+ findings,
+ );
+ },
+);
+
+test.each([
+ "ssh://[email protected]/team/unrelated",
+ "ssh://[email protected]/team/unrelated",
+])(
+ "an omitted SSH user cannot explain the conflicting Trivy target %s",
+ async (artifact) => {
+ await using checkout = await trivyCheckout();
+ const report = {
+ ...trivyReport(),
+ ...repositoryClaims(artifact, "ssh://source.example/team/project"),
+ };
+ expect(() => normalizeTrivyFindings(report)).toThrow("--trivy-scan-root");
+ const { read, excluded, findings } = normalizeTrivyFindings(
+ report,
+ "local",
+ ".",
+ );
+ for (const prepare of [
+ () => checkout.fromFile(report),
+ () => checkout.prepare({ read, excluded, findings }),
+ ])
+ await expect(prepare()).rejects.toThrow("different repositories");
+ },
+);
diff --git a/sdk/typescript/tests-ts/trivy-findings.test.ts b/sdk/typescript/tests-ts/trivy-findings.test.ts
index beb733a90..726ad6d14 100644
--- a/sdk/typescript/tests-ts/trivy-findings.test.ts
+++ b/sdk/typescript/tests-ts/trivy-findings.test.ts
@@ -6,6 +6,7 @@ import { gzipSync } from "node:zlib";
import {
normalizeTrivyFindings,
readTrivyFindings,
+ trivyRepositoryUrl,
} from "../src/trivy-findings.js";
import { trivyReport } from "./support/trivy-import-fixtures.js";
@@ -34,7 +35,7 @@ test("filesystem labels and uncorroborated repository targets require a scan roo
{ ...repositoryReport(origin, origin), ArtifactType: "filesystem" },
{ ...repositoryReport(schemeLess, origin), ArtifactType: "filesystem" },
])
- expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ expect(() => normalizeTrivyFindings(report)).toThrow("--trivy-scan-root");
});
test.each([
@@ -54,6 +55,7 @@ test.each([
);
const retained = evidence.source_data!["report"];
expect(retained).toMatchObject({ ArtifactName: target });
+ if (target === schemeLess) expect(trivyRepositoryUrl(retained)).toBeNull();
});
test.each([
@@ -103,12 +105,21 @@ test.each([
expect(() => normalizeTrivyFindings(report, "local", "nested")).toThrow(
"must be .",
);
- } else expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ } else
+ expect(() => normalizeTrivyFindings(report)).toThrow(
+ "--trivy-scan-root",
+ );
const saved = input.findings[0]!.evidence.source_data!["report"];
expect(saved).toMatchObject({
ArtifactName: report.ArtifactName,
Metadata: report.Metadata,
});
+ if (matches || prefix !== clonedBase)
+ expect(trivyRepositoryUrl(saved)).toBe(report.Metadata.RepoURL);
+ else
+ expect(() => trivyRepositoryUrl(saved)).toThrow(
+ "different repositories",
+ );
}
},
);
@@ -129,13 +140,16 @@ test.each([
"conflicting artifact %s and origin %s require explicit inspection",
(artifact, remote) => {
const report = repositoryReport(artifact, remote);
- expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ expect(() => normalizeTrivyFindings(report)).toThrow("--trivy-scan-root");
const retained = normalizeTrivyFindings(report, "local", "apps/web")
.findings[0]!.evidence.source_data!["report"];
expect(retained).toMatchObject({
ArtifactName: artifact,
Metadata: { RepoURL: remote },
});
+ expect(() => trivyRepositoryUrl(retained)).toThrow(
+ "different repositories",
+ );
},
);
@@ -145,10 +159,10 @@ test("a repository display label cannot supply an SSH account omitted from Git m
ArtifactName: "ssh://[email protected]:2222/org/project",
Metadata: { RepoURL: "ssh://git.example.test:2222/org/project" },
};
- expect(() => normalizeTrivyFindings(report)).toThrow("scanRoot");
+ expect(() => normalizeTrivyFindings(report)).toThrow("--trivy-scan-root");
const retained =
normalizeAtRoot(report).findings[0]!.evidence.source_data!["report"];
-
+ expect(trivyRepositoryUrl(retained)).toBe(report.Metadata.RepoURL);
expect(retained).toMatchObject({
ArtifactName: report.ArtifactName,
Metadata: report.Metadata,
@@ -170,7 +184,7 @@ test("rejects unsafe scan directories before importing even a clean local report
"a\0b",
])
expect(() => normalizeTrivyFindings(report, "local", root)).toThrow(
- "scanRoot",
+ "--trivy-scan-root",
);
});
@@ -354,6 +368,7 @@ test("filesystem scans without inventory or Git metadata do not invent lines, ve
],
locations: [{ path: "app\\package-lock.json", line: null }],
});
+ expect(trivyRepositoryUrl(evidence.source_data?.["report"])).toBeNull();
});
function normalizeResult(result: unknown) {
@@ -679,9 +694,56 @@ test("clean native reports differ from unsupported, mixed and malformed findings
);
});
-test("clean reports reject unsafe remote URLs", () => {
- const report = { ...trivyReport(), Results: [] };
+test.each([
+ [
+ ".",
+ "[email protected]:group/project.git",
+ "[email protected]:group/project.git",
+ ],
+ [
+ "C:\\work\\project",
+ "ssh://[email protected]/project",
+ "ssh://[email protected]/project",
+ ],
+ [
+ "https://example.invalid/project",
+ undefined,
+ "https://example.invalid/project",
+ ],
+ [
+ "https://github.com/example/project",
+ "https://github.com/example/project.git",
+ "https://github.com/example/project.git",
+ ],
+ ["relative/project", "file:///work/project", null],
+ ["C:\\work\\checkout", "D:mirrors\\project.git", null],
+ ["\\\\server\\share\\checkout", "D:mirrors/project.git", null],
+ ["//server/share/checkout", "D:mirror.git", null],
+ [".", "r:org/repo", null],
+ [".", "git@host:org@ver/repo", "git@host:org@ver/repo"],
+ [".", "user@r:org/repo", "user@r:org/repo"],
+ [".", "ssh://r/org/repo", "ssh://r/org/repo"],
+] as const)(
+ "retains Git repository provenance for artifact %s and remote %s",
+ (ArtifactName, RepoURL, expected) => {
+ const report = { ...trivyReport(), ArtifactName, Metadata: { RepoURL } };
+ expect(
+ trivyRepositoryUrl(
+ normalizeTrivyFindings(report, "cloud", ".").findings[0]!.evidence
+ .source_data?.["report"],
+ ),
+ ).toBe(expected);
+ },
+);
+test("binding rejects conflicting repository claims; clean reports still reject unsafe remote URLs", () => {
+ const report = { ...trivyReport(), Results: [] };
+ expect(() =>
+ trivyRepositoryUrl({
+ ...report,
+ ArtifactName: "https://example.invalid/other",
+ }),
+ ).toThrow(/different repositories/);
for (const source of [
"https://[email protected]/repo",
"https://example\\scanner:[email protected]/repo",
@@ -701,6 +763,12 @@ test("clean reports reject unsafe remote URLs", () => {
expect(() =>
normalizeTrivyFindings({ ...report, ArtifactName: source }, "cloud", "."),
).toThrow(/without credentials/);
+ expect(() => trivyRepositoryUrl({ ArtifactName: source })).toThrow(
+ /without credentials/,
+ );
+ expect(() => trivyRepositoryUrl({ Metadata: { RepoURL: source } })).toThrow(
+ /without credentials/,
+ );
}
});
@@ -717,6 +785,10 @@ test("a repository target can carry an HTTPS account without an explicit scheme"
expect(() =>
normalizeAtRoot({ ...report, ...header, Results: [] }),
).toThrow(/without credentials/);
+ expect(() => trivyRepositoryUrl(header)).toThrow(/without credentials/);
+ expect(() =>
+ trivyRepositoryUrl({ Metadata: { RepoURL: ArtifactName } }),
+ ).toThrow(/without credentials/);
}
for (const ArtifactName of [
"/checkout/team@local/repo",
@@ -736,7 +808,7 @@ test("reads native JSON and gzip by content, applying the destination's evidence
const path = join(directory, "report.json");
const report = trivyReport();
await writeFile(path, JSON.stringify(report));
- await expect(readTrivyFindings(path)).rejects.toThrow("scanRoot");
+ await expect(readTrivyFindings(path)).rejects.toThrow("--trivy-scan-root");
expect(await readTrivyFindings(path, "cloud", "apps/web")).toEqual(
normalizeTrivyFindings(report, "cloud", "apps/web"),
);