OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(import): track Veracode static application policy flaws (#2099)
Michael D'Angelofa80b7f7cb24
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.mdindex c2bfb4feb..b51aa6b13 100644--- a/docs/scanner-imports/schema-guide.md+++ b/docs/scanner-imports/schema-guide.md@@ -30,10 +30,13 @@ to investigate records together, not instructions to merge them.| [GitHub saved `import github` output](../../sdk/typescript/docs/cli.md#import-github-findings-locally-or-to-cloud) | Host, repository, alert number and hash of selected ref | Host, repository and code-scanning family || [GitHub saved `import github-advisories` output](../../sdk/typescript/docs/cli.md#import-ghsa-advisories-separately) | Host, repository **or** global scope, and GHSA ID | Separate advisory stream from alerts || [Black Duck BOM-6 collection or selected rows](blackduck.md) | Project version, component version, origin, advisory source and advisory name | Deployment, project and version |+| [Veracode Static Analysis Findings API pages](veracode.md) | API origin, application and context, and native issue ID | Deployment, application and static policy |Within **one input**, duplicate IDs are ambiguous, not corroboration. Wiz andGitHub reject a selection with duplicate accepted IDs. Endor, Snyk and Semgrep-exclude every record with the colliding identity. Black Duck rejects duplicate occurrences in a complete collection, and excludes all colliding rows in an explicit selection. Inspect the source and select+exclude every record with the colliding identity. Black Duck rejects duplicate occurrences in a complete collection, and excludes all colliding rows in an explicit selection.+Veracode rejects a capture that repeats an issue ID for the same scan type.+Inspect the source and selectthe intended occurrence; don't rename records simply to make them import. Across**separate local imports**, changed evidence updates the same record; omissiondoes not delete or resolve it. Cloud publication sends an expected version;diff --git a/docs/scanner-imports/veracode.md b/docs/scanner-imports/veracode.mdnew file mode 100644index 000000000..aee3331f7--- /dev/null+++ b/docs/scanner-imports/veracode.md@@ -0,0 +1,85 @@+# Import Veracode Static Analysis policy findings++Use `--provider veracode` for the **Findings API** backlog of one Veracode+application mapped to one source repository. This importer handles+`scan_type=STATIC` in the application context. A Veracode application may+aggregate multiple repositories or binary modules: do not bind that aggregate+to a single checkout. Pipeline Scan JSON, sandboxes, SCA, DAST, policy pass/fail+summaries and the findings converter's SARIF output are not this format.++## Export unmodified Findings API pages++Set `VERACODE_APPLICATION_GUID` to the application you intend to import. Use a+client with read access to that application and the Results API. This example+uses HTTPie with the Veracode HMAC plugin and `jq`. Set `api` to the hostname+for your region. Store the exported pages outside the checkout.++```bash+set -eu+umask 077+out=$(mktemp -d)+: "${VERACODE_APPLICATION_GUID:?Set the intended application GUID}"+api=https://api.veracode.com+guid=$(jq -ner --arg guid "$VERACODE_APPLICATION_GUID" '$guid | ascii_downcase |+ select(test("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))')+application="$api/appsec/v1/applications/$guid"+page=0+while :; do+ http --ignore-stdin --check-status --body --timeout 20 --auth-type veracode_hmac GET \+ "$api/appsec/v2/applications/$guid/findings" \+ scan_type==STATIC page=="$page" size==100 > "$out/page.tmp"+ pages=$(jq -er --arg app "$application" --argjson n "$page" '+ select(._links.application.href == $app and .page.number == $n) |+ .page.total_pages | numbers' "$out/page.tmp")+ cat "$out/page.tmp" >> "$out/pages.stream"+ page=$((page + 1))+ [ "$page" -lt "$pages" ] || break+done+jq -s '.' "$out/pages.stream" > "$out/policy-findings.json"+```++Collect every page from the configured API host and keep each page intact.+Apply any Findings API filters when downloading the pages and use the same+selection throughout. The importer checks page counts, application scope and+the selection reported in the HAL links. Its preview includes the returned+rows with their original evidence, including any annotations. If the backlog+changes during pagination, collect it again.++## Preview and import++```bash+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1+codex-security publish findings "$out/policy-findings.json" \+ --to local --repository ./project --provider veracode \+ --source-repository-url https://github.com/example/project \+ --source-key veracode/region/application-guid/static \+ --dry-run --format json+```++Review the destination, count and exclusions. Remove `--dry-run` to import.+Use the same source key for later exports from the same application and+context; an application GUID is not evidence of a Git URL. For Cloud use an+authorized GitHub repository and a deployment that accepts provider `veracode`.++Local import compares the source with the checkout’s Git remotes when+comparable remotes are configured.++If an interrupted Cloud upload reports `result.savedSubmission`, keep its+checkpoint and use the same build, state directory, account and import settings.+Preview the original export with `--dry-run --format json`. Check `accountId`+and `destination`. When `resumed` is false, review the new upload before approving it.+For `prepareNormalizedExternalPublication`, pass your original normalized+`ExternalFindings` and check `preview.resumed` before calling `publish()`.+Passing different normalized findings prepares a new upload. Save each finding+with its original `source_finding_id` and `evidence.source_data` so the SDK can+verify its application and repository when replayed with the Veracode provider.++| Veracode evidence | What Codex Security tracks |+| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |+| API origin, application/context and `issue_id` | A stable policy flaw occurrence. Build number, line, CWE and the separate Pipeline flaw ID are not its identity. |+| Native severity, CWE and flaw description | SAST evidence, preserving the original numeric severity, description and status in the raw record. |+| Static analysis path, line and module | Reported evidence, not proof that a similarly named file exists in the checkout. No fabricated column or Git commit. |+| Finding status, mitigation and resolution | Upstream workflow history, not a Codex assessment. Replaying an update does not mark a fix verified; omissions do not delete records. |++References: [Veracode Findings API](https://docs.veracode.com/r/c_findings_v2_intro),+[vendor-supported policy and Pipeline conversion examples](https://github.com/veracode/veracode-pipeline-scan-results-to-sarif).diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex 90817e8c2..da894d130 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -39,6 +39,10 @@ Use `--provider inspector` and `--source-repository-url` with a complete InspectUse `--provider blackduck` for a BOM-6 vulnerable-components export from one project version. Supply `--source-repository-url` after verifying the project version maps to that repository. Keep the same source key on replay and preview the destination before importing.+## Veracode Static Analysis policy findings++Use `--provider veracode` with all Findings API pages for one application’s STATIC policy findings. Verify that the application maps to the repository named by `--source-repository-url`. Keep the source key stable for that application and preview the import before writing.+## Endor Labs findingsFor Endor Labs imports, prefer native Finding JSON from authenticated `endorctl`, scoped to one project and context. Omit `--field-mask` and fetch all pages with `--list-all`:diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 22346abad..699ad36b3 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -696,6 +696,11 @@ export for one project version. Map that version to its source repository with`--source-repository-url`. See the[Black Duck guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/blackduck.md).+For Veracode Static Analysis policy findings, use `--provider veracode` with+every Findings API page from one application. Set `--source-repository-url`+to the source repository mapped to that application. See the+[Veracode guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/veracode.md).+For OpenGrep, use `--provider opengrep` with native JSON or gzip and an explicit`--source-repository-url`. Local and Cloud imports retain unassessed OpenGrepevidence through the existing Semgrep source-provider contract. See thediff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 99f7ed083..131911b04 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1308,6 +1308,7 @@ Wiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-finding[Endor Labs Finding JSON and SARIF](#import-endor-labs-findings),[Amazon Inspector repository findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/inspector.md),[Black Duck SCA project-version vulnerabilities](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/blackduck.md),+[Veracode Static Analysis policy findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/veracode.md),[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),[OpenGrep native JSON](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md),[GitHub Dependabot repository alerts](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md),diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.jsonindex 5eadb5b1a..bec300246 100644--- a/sdk/typescript/schemas/external-findings.schema.json+++ b/sdk/typescript/schemas/external-findings.schema.json@@ -385,7 +385,8 @@"github","semgrep","inspector",- "blackduck"+ "blackduck",+ "veracode"],"title": "Provider","type": "string"diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex dcd2621bb..856975c69 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -41,6 +41,7 @@ const distModules = ["endor-findings","blackduck-findings","wiz-csv",+ "veracode-findings","wiz-findings","codex-prompt","codex-sdk-environment",diff --git a/sdk/typescript/src/blackduck-findings.ts b/sdk/typescript/src/blackduck-findings.tsindex 61503861a..9945b948e 100644--- a/sdk/typescript/src/blackduck-findings.ts+++ b/sdk/typescript/src/blackduck-findings.ts@@ -3,15 +3,9 @@ import { CodexSecurityError } from "./errors.js";import type { Provider } from "./external-import-models.js";import {type ExternalImportTarget,- cloudRepositoryUrlKey,- repositoryUrlKey,validateExternalEvidence,} from "./external-import-contract.js";-import type {- ExternalFinding,- ExternalFindings,- ExternalSourceRepository,-} from "./external-findings.js";+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";import { canonicalJson, isRecord } from "./record.js";import {array,@@ -23,7 +17,10 @@ import {text,} from "./scanner-import.js";import { FailureSeveritySchema } from "./scan-settings.js";-import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";+import {+ declaredScannerRepositoryUrl,+ repositoryScopeValidator,+} from "./scanner-repository-url.js";const format = "blackduck-bom-6";const componentVersionPath = /^components\/[^/]+\/versions\/[^/]+$/u;@@ -57,7 +54,7 @@ function retainedRepository(provider: Provider,finding: ExternalFinding,target: ExternalImportTarget,-): { url: string; projectVersion?: string } | undefined {+): { url: string; scope?: string } | undefined {const {source_finding_id: id,evidence: { source_data: data },@@ -99,54 +96,13 @@ function retainedRepository(throw new Error("Black Duck source finding ID contradicts the retained native occurrence.",);- return { url, projectVersion };+ return { url, scope: projectVersion };}-export function blackDuckReportRepositories(- provider: Provider,- findings: readonly ExternalFinding[],- target: ExternalImportTarget,- sameRepositories: (urls: Iterable<string>) => boolean = (urls) =>- new Set(- Array.from(- urls,- target === "cloud" ? cloudRepositoryUrlKey : repositoryUrlKey,- ),- ).size <= 1,-): Map<string, ExternalSourceRepository> {- const repositories = new Map<string, ExternalSourceRepository>();- const projects = new Set<string>();- const sources = new Set<string>();- for (const finding of findings) {- const { source_finding_id: id, evidence } = finding;- const retained = retainedRepository(provider, finding, target);- const declared = evidence.details?.repository?.url;- if (declared) sources.add(declared);- if (!retained) continue;- sources.add(retained.url);- if (- declared &&- declared !== retained.url &&- !sameRepositories([declared, retained.url])- )- throw new Error(- "Retained scanner repository does not match the normalized evidence repository.",- );- if (retained.projectVersion) projects.add(retained.projectVersion);- repositories.set(id, { url: retained.url });- }- if (provider !== "blackduck") return repositories;- if (- projects.size > 1 ||- ((target === "local" || projects.size > 0) &&- sources.size > 1 &&- !sameRepositories(sources))- )- throw new Error(- "Black Duck occurrences must belong to the same project version and source repository.",- );- return repositories;-}+export const blackDuckReportRepositories = repositoryScopeValidator(+ { provider: "blackduck", label: "Black Duck", scope: "project version" },+ retainedRepository,+);function parseApiResource(href: string | null) {const url = href && URL.parse(href);diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex 863f3b270..aa3d14376 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -28,6 +28,7 @@ import {projectedBlackDuckRepositoryUrl,} from "./blackduck-findings.js";import { isGitHubCloudHost, parseGitRemote } from "./git-remote.js";+import { veracodeReportRepositories } from "./veracode-findings.js";import { inspectorReportRepository } from "./inspector-findings.js";import { isRecord } from "./record.js";import { dependabotRepository } from "./github-dependabot-findings.js";@@ -276,7 +277,7 @@ function localRepositoryPlatform(};}-function sameBlackDuckRepositories(+function sameScannerRepositories(remotes: Iterable<RemoteRepositoryIdentity>,): boolean {let known: RemoteRepositoryIdentity | undefined;@@ -539,7 +540,10 @@ async function requireMatchingRepository(const urls = await readGit(["remote", "get-url", "--all", "--", name]);remotes.push(...urls.split(/\r?\n/u));}- const boundProvider = provider === "inspector" || provider === "blackduck";+ const boundProvider =+ provider === "inspector" ||+ provider === "blackduck" ||+ provider === "veracode";const loosePlatformFor = localRepositoryPlatform(provider, sources, false);for (const source of sources) {const bound = boundProvider || strictSources.has(source.url);@@ -721,12 +725,22 @@ export async function prepareLocalImport(readerSources,true,);+ const sameRepositories = (urls: Iterable<string>) =>+ sameScannerRepositories(Array.from(urls, identify));const bound = blackDuckReportRepositories(options.provider,current.findings,"local",- (urls) => sameBlackDuckRepositories(Array.from(urls, identify)),+ sameRepositories,);+ for (const source of veracodeReportRepositories(+ options.provider,+ current.findings,+ "local",+ sameRepositories,+ ).values()) {+ sources.set(source.url, source);+ }const strictSources = new Map<string, Provider>();const known = new Set<string>(parsedSources.map(({ url }) => url));for (const finding of current.findings) {@@ -748,7 +762,7 @@ export async function prepareLocalImport(? "github": operatorPlatform({ url: claim });if (- !sameBlackDuckRepositories(+ !sameScannerRepositories(claims.map((claim) =>remoteRepository(claim, rowPlatform(claim), true) ?? {@@ -780,7 +794,7 @@ export async function prepareLocalImport(.filter((remote) => !represented.has(JSON.stringify(remote)));for (const [key, group] of Map.groupBy(aliases, (remote) => remote.key)) {const candidates = byKey.get(key);- if (!candidates || !sameBlackDuckRepositories([...candidates, ...group]))+ if (!candidates || !sameScannerRepositories([...candidates, ...group]))throw new CodexSecurityError("Reader repository does not match a source in the normalized findings.",);@@ -816,7 +830,7 @@ export async function prepareLocalImport(options.provider === "blackduck" &¤t.findings.length &&sources.size > 1 &&- !sameBlackDuckRepositories(Array.from(sources.keys(), identify))+ !sameScannerRepositories(Array.from(sources.keys(), identify)))throw new CodexSecurityError("Black Duck occurrences must belong to the same project version and source repository.",diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 7ce12fbb1..3ac2032ae 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -40,6 +40,7 @@ import {blackDuckReportRepositories,projectedBlackDuckRepositoryUrl,} from "./blackduck-findings.js";+import { veracodeReportRepositories } from "./veracode-findings.js";import { inspectorReportRepository } from "./inspector-findings.js";import {snapshotImportOptions,@@ -758,7 +759,19 @@ async function preparePublicationInput(const repositories = replay? undefined: blackDuckReportRepositories(options.provider, findings, "cloud");- if (!replay || options.provider === "inspector") {+ if (!saved || options.provider === "veracode") {+ for (const [id, source] of veracodeReportRepositories(+ options.provider,+ findings,+ "cloud",+ ))+ requireDestination(id, source.url);+ }+ if (+ !replay ||+ options.provider === "inspector" ||+ options.provider === "veracode"+ ) {const binding = inspectorReportRepository(options.provider,findings,@@ -772,7 +785,13 @@ async function preparePublicationInput(const projected = repositories? repositories.get(id)?.url: projectedBlackDuckRepositoryUrl(finding, "cloud");- if (replay && !projected && options.provider !== "inspector") continue;+ if (+ replay &&+ !projected &&+ options.provider !== "inspector" &&+ options.provider !== "veracode"+ )+ continue;const urls = [projected,evidence.details?.repository?.url,diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex 2b40fcf85..1fbe29145 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -12,6 +12,7 @@ import { readOpenGrepFindings } from "./opengrep-findings.js";import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";import { dependabotRepository } from "./github-dependabot-findings.js";import { readGitHubFindings } from "./github-findings.js";+import { readVeracodeFindings } from "./veracode-findings.js";import { readBlackDuckFindings } from "./blackduck-findings.js";import { readInspectorFindings } from "./inspector-findings.js";import { isRecord } from "./record.js";@@ -31,6 +32,7 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {github: "github",inspector: "inspector",blackduck: "blackduck",+ veracode: "veracode",} as const satisfies Record<string, Provider>;export type ExternalFindingsReader = keyof typeof EXTERNAL_FINDINGS_PROVIDERS;@@ -134,18 +136,21 @@ export async function readExternalFindings(}if (options.provider === "github")return { findings: await readGitHubFindings(path, target) };- if (options.provider === "inspector" || options.provider === "blackduck") {+ if (+ options.provider === "inspector" ||+ options.provider === "blackduck" ||+ options.provider === "veracode"+ ) {const url = options.sourceRepositoryUrl ?? "";- const findings =- options.provider === "inspector"- ? await readInspectorFindings(- path,- url,- target,- options.inspectorProjectMap,- )- : await readBlackDuckFindings(path, url, target);- return { findings, sourceRepositories: [{ url }] };+ const read = {+ inspector: readInspectorFindings,+ blackduck: readBlackDuckFindings,+ veracode: readVeracodeFindings,+ }[options.provider];+ return {+ findings: await read(path, url, target, options.inspectorProjectMap),+ sourceRepositories: [{ url }],+ };}const publication = await readVendorFindingsForPublication(path, target);const sourceRepositories = publication.current.findings.flatMap((finding) =>diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.tsindex 663b89845..50188cbb5 100644--- a/sdk/typescript/src/external-import-models.ts+++ b/sdk/typescript/src/external-import-models.ts@@ -6,7 +6,14 @@ export type RepoConnectorId = string;export type EnvironmentId = string;export type ResetMarker = string;export type Provider =- "wiz" | "endor" | "snyk" | "github" | "semgrep" | "inspector" | "blackduck";+ | "wiz"+ | "endor"+ | "snyk"+ | "github"+ | "semgrep"+ | "inspector"+ | "blackduck"+ | "veracode";export type SourceKey = string;export type ClientId = string;export type SourceFindingId = string;diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 14e57044a..3c9dc1981 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -331,6 +331,10 @@ export {readOpenGrepFindings,type OpenGrepImportOptions,} from "./opengrep-findings.js";+export {+ normalizeVeracodeFindings,+ readVeracodeFindings,+} from "./veracode-findings.js";export {normalizeBlackDuckFindings,readBlackDuckFindings,diff --git a/sdk/typescript/src/scanner-repository-url.ts b/sdk/typescript/src/scanner-repository-url.tsindex 315b92ad4..eb348109c 100644--- a/sdk/typescript/src/scanner-repository-url.ts+++ b/sdk/typescript/src/scanner-repository-url.ts@@ -1,4 +1,13 @@-import type { ExternalImportTarget } from "./external-import-contract.js";+import type { Provider } from "./external-import-models.js";+import {+ type ExternalImportTarget,+ cloudRepositoryUrlKey,+ repositoryUrlKey,+} from "./external-import-contract.js";+import type {+ ExternalFinding,+ ExternalSourceRepository,+} from "./external-findings.js";import { requiredText } from "./scanner-import.js";function repositorySegment(encoded: string): boolean {@@ -39,3 +48,63 @@ export function declaredScannerRepositoryUrl();return source;}++/** A native application or project version maps to one source repository per report. */+export function repositoryScopeValidator(+ scanner: { provider: Provider; label: string; scope: string },+ retainedRepository: (+ provider: Provider,+ finding: ExternalFinding,+ target: ExternalImportTarget,+ ) => { url: string; scope?: string } | undefined,+) {+ return (+ provider: Provider,+ findings: readonly ExternalFinding[],+ target: ExternalImportTarget,+ sameRepositories: (urls: Iterable<string>) => boolean = (urls) =>+ new Set(+ Array.from(+ urls,+ target === "cloud" ? cloudRepositoryUrlKey : repositoryUrlKey,+ ),+ ).size <= 1,+ ): Map<string, ExternalSourceRepository> => {+ const repositories = new Map<string, ExternalSourceRepository>();+ const wholeReport =+ provider === "blackduck" && scanner.provider === provider;+ const scopes = new Set<string>();+ const sources = new Set<string>();+ for (const finding of findings) {+ const { source_finding_id: id, evidence } = finding;+ const retained = retainedRepository(provider, finding, target);+ const declared = evidence.details?.repository?.url;+ // A Black Duck BOM binds its entire report. A Veracode application binds its native rows.+ if (wholeReport || retained?.scope) {+ if (declared) sources.add(declared);+ if (retained) sources.add(retained.url);+ }+ if (!retained) continue;+ if (retained.scope) scopes.add(retained.scope);+ if (+ declared &&+ declared !== retained.url &&+ !sameRepositories([declared, retained.url])+ )+ throw new Error(+ "Retained scanner repository does not match the normalized evidence repository.",+ );+ repositories.set(id, { url: retained.url });+ }+ if (+ scopes.size > 1 ||+ ((scopes.size > 0 || (wholeReport && target === "local")) &&+ sources.size > 1 &&+ !sameRepositories(sources))+ )+ throw new Error(+ `${scanner.label} occurrences must belong to the same ${scanner.scope} and source repository.`,+ );+ return repositories;+ };+}diff --git a/sdk/typescript/src/veracode-findings.ts b/sdk/typescript/src/veracode-findings.tsnew file mode 100644index 000000000..2b78596b9--- /dev/null+++ b/sdk/typescript/src/veracode-findings.ts@@ -0,0 +1,540 @@+import { z } from "zod";+import { CodexSecurityError } from "./errors.js";+import type { Provider } from "./external-import-models.js";+import {+ type ExternalImportTarget,+ validateExternalEvidence,+} from "./external-import-contract.js";+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";+import { isRecord } from "./record.js";+import {+ array,+ normalizeRecords,+ readScannerJson,+ record,+ requiredText,+ stableId,+ text,+} from "./scanner-import.js";+import {+ declaredScannerRepositoryUrl,+ repositoryScopeValidator,+} from "./scanner-repository-url.js";++const count = z.int().nonnegative();+const positive = z.int().positive();+const cvssScore = z+ .union([z.string().trim().min(1), z.number()])+ .pipe(z.coerce.number<string | number>().min(0).max(10));+const scores = ["severity", "cvss"] as const;+const pageMetadata = z.object({+ total_elements: count,+ number: count,+ size: positive,+ total_pages: count,+});+const severityByScore = [+ "informational",+ "low",+ "low",+ "medium",+ "high",+ "critical",+] as const;+const applicationGuid = z.guid().toLowerCase();+const applicationPath = /^\/appsec\/v1\/applications\/([^/]+)$/u;++function integer(value: unknown, label: string, minimum = 0): number {+ const result = (minimum === 0 ? count : positive).safeParse(value);+ if (!result.success)+ throw new Error(+ `Veracode ${label} must be an integer of at least ${minimum}.`,+ );+ return result.data;+}++function guid(value: unknown): string {+ const result = applicationGuid.safeParse(value);+ if (!result.success)+ throw new Error("Expected a Veracode application context GUID.");+ return result.data;+}++function halUrl(value: unknown, label: string): URL {+ const link = record(value, `Veracode ${label} link`);+ const href = requiredText(link["href"], `Veracode ${label} href`);+ const template =+ link["templated"] === true && /\{([?&])[\w]+(?:,[\w]+)*\}$/u.exec(href);+ const concrete = template ? href.slice(0, template.index) : href;+ const parts = /^https?:\/\/([^/?#\\]+)(\/[^?#]*)(?:\?[^#]*)?$/iu.exec(+ concrete,+ );+ const url = URL.parse(concrete);+ if (+ !url ||+ !parts ||+ (template && (template[1] === "&") !== concrete.includes("?")) ||+ parts[1]!.includes("@") ||+ /[{}\\\s\p{Cc}]/u.test(concrete) ||+ parts[2] !== url.pathname+ )+ throw new Error(`Invalid Veracode ${label} HAL URL.`);+ return url;+}++function applicationScope(url: URL) {+ const match = applicationPath.exec(url.pathname);+ if (!match || url.href.includes("?"))+ throw new Error(+ "Expected a Veracode application HAL URL without query parameters.",+ );+ const application = guid(match[1]);+ return {+ origin: url.origin,+ application,+ applicationUrl: `${url.origin}/appsec/v1/applications/${application}`,+ };+}++type Scope = ReturnType<typeof applicationScope>;++function requireApplication(row: Record<string, unknown>, scope: Scope) {+ if (+ row["context_type"] !== "APPLICATION" ||+ guid(row["context_guid"]) !== scope.application+ )+ throw new Error(+ "Veracode findings must belong to the same APPLICATION policy context; sandbox and mixed applications are unsupported.",+ );+}++function occurrenceId(row: Record<string, unknown>, scope: Scope): string {+ if (row["scan_type"] !== "STATIC")+ throw new Error("Only Veracode STATIC findings are supported.");+ return stableId("veracode-static-policy", [+ scope.origin,+ scope.application,+ row["context_type"],+ scope.application,+ integer(row["issue_id"], "issue_id", 1),+ ]);+}++const nativeId = /^veracode-static-policy:[a-f0-9]{64}$/u;++function hasVeracodeRow(row: unknown): boolean {+ return (+ isRecord(row) &&+ "context_guid" in row &&+ "context_type" in row &&+ "scan_type" in row &&+ "issue_id" in row+ );+}++function hasVeracodeEvidence(data: unknown, id: string): boolean {+ if (!isRecord(data)) return false;+ const application =+ typeof data["applicationUrl"] === "string" &&+ applicationPath.test(URL.parse(data["applicationUrl"])?.pathname ?? "");+ const repository = "sourceRepositoryUrl" in data;+ const row = hasVeracodeRow(data["row"]);+ // Other providers can retain a raw vendor row or choose any occurrence ID.+ // Corroborate the native row or ID with its repository and application envelope.+ return (+ (row && (application || repository)) ||+ (nativeId.test(id) && application && repository)+ );+}++function retainedRepository(+ provider: Provider,+ finding: ExternalFinding,+ target: ExternalImportTarget,+): { url: string; scope?: string } | undefined {+ const {+ source_finding_id: id,+ evidence: { source_data: sourceData },+ } = finding;+ if (provider !== "veracode") {+ if (hasVeracodeEvidence(sourceData, id))+ throw new CodexSecurityError(+ "Retained Veracode evidence requires the veracode provider.",+ );+ return;+ }+ const data = isRecord(sourceData) ? sourceData : {};+ const native =+ nativeId.test(id) ||+ hasVeracodeRow(isRecord(data["row"]) ? data["row"] : data);+ if (!native && !("sourceRepositoryUrl" in data)) return;+ const url = declaredScannerRepositoryUrl(+ data["sourceRepositoryUrl"],+ "Veracode",+ target,+ );+ if (!native) return { url };+ const scope = applicationScope(+ halUrl({ href: data["applicationUrl"] }, "retained application"),+ );+ const row = record(data["row"], "Veracode retained finding");+ requireApplication(row, scope);+ if (id !== occurrenceId(row, scope))+ throw new Error(+ "Veracode source finding ID contradicts the retained native occurrence.",+ );+ return { url, scope: scope.applicationUrl };+}++export const veracodeReportRepositories = repositoryScopeValidator(+ { provider: "veracode", label: "Veracode", scope: "application" },+ retainedRepository,+);++function selection(+ url: URL,+ scope: Scope,+ number: number,+ size: number,+ rel: string,+) {+ const match = /^\/appsec\/v2\/applications\/([^/]+)\/findings$/u.exec(+ url.pathname,+ );+ if (+ url.origin !== scope.origin ||+ !match ||+ guid(match[1]) !== scope.application+ )+ throw new Error(+ "Veracode HAL links must identify the same origin and findings application.",+ );+ const query = url.searchParams;+ const scans = query.getAll("scan_type");+ if (+ query.has("context") ||+ query.has("sca_dep_mode") ||+ query.has("sca_scan_mode") ||+ scans.length > 1 ||+ scans.some((type) => type !== "STATIC")+ )+ throw new Error(+ "Only the Veracode STATIC APPLICATION policy selection is supported, not sandbox, DAST or SCA.",+ );+ for (const key of [+ "violates_policy",+ "new",+ "include_annot",+ "include_exp_date",+ ]) {+ const flags = query.getAll(key);+ if (!flags.length) continue;+ if (flags.length !== 1 || !/^(true|false)$/iu.test(flags[0]!))+ throw new Error(`Invalid Veracode ${key} selection.`);+ query.set(key, flags[0]!.toLowerCase());+ }+ for (const key of ["cwe", "finding_category"]) {+ const ids = query+ .getAll(key)+ .flatMap((value) =>+ value.split(",").map((id) => id.replace(/^0+(?=\d)/u, "")),+ );+ if (ids.length) query.set(key, [...new Set(ids)].sort().join(","));+ }+ for (const field of scores) {+ for (const key of [field, `${field}_gte`]) {+ const values = query.getAll(key);+ if (!values.length) continue;+ const value = values[0]!;+ const score =+ field === "severity"+ ? /^[0-5]$/u.test(value) && Number(value)+ : cvssScore.safeParse(value).data;+ if (values.length !== 1 || typeof score !== "number")+ throw new Error(`Invalid Veracode ${key} selection.`);+ query.set(key, String(score));+ }+ }+ // Collection self links may omit pagination. Navigation uses the API defaults.+ for (const [key, expected, defaultValue] of [+ ["page", number, 0],+ ["size", size, 50],+ ] as const) {+ const values = query.getAll(key);+ if (+ values.length+ ? values.length !== 1 || values[0] !== String(expected)+ : rel !== "self" && expected !== defaultValue+ )+ throw new Error(`Veracode HAL ${key} does not match the declared page.`);+ query.delete(key);+ }+ query.sort();+ return query;+}++function readPage(input: unknown) {+ const document = record(input, "Veracode HAL findings page");+ const metadata = pageMetadata.safeParse(+ record(document["page"], "Veracode page metadata"),+ );+ if (!metadata.success) {+ const field = metadata.error.issues[0]!.path[0];+ throw new Error(+ `Veracode page.${String(field)} must be an integer of at least ${field === "size" ? 1 : 0}.`,+ );+ }+ const {+ number,+ size,+ total_pages: pages,+ total_elements: total,+ } = metadata.data;+ const embedded =+ document["_embedded"] === undefined && total === 0+ ? { findings: [] }+ : record(document["_embedded"], "Veracode HAL _embedded");+ if (+ document["error"] != null ||+ (document["status"] != null && document["status"] !== 200) ||+ [document["errors"], embedded["errors"]].some(+ (errors) =>+ errors != null && !(Array.isArray(errors) && errors.length === 0),+ )+ )+ throw new Error(+ "Veracode returned an error, not a complete findings page.",+ );+ const rows = array(embedded["findings"], "Veracode _embedded.findings");+ if (+ !(pages === Math.ceil(total / size) || (total === 0 && pages === 1)) ||+ number >= Math.max(1, pages) ||+ rows.length !== Math.min(size, total - number * size)+ )+ throw new Error("Incomplete or inconsistent Veracode HAL page counts.");+ const links = record(document["_links"], "Veracode HAL _links");+ const scope = applicationScope(halUrl(links["application"], "application"));+ const query = selection(+ halUrl(links["self"], "self"),+ scope,+ number,+ size,+ "self",+ );+ const filter = query.toString();+ const positions: Record<string, number> = {+ first: 0,+ last: Math.max(0, pages - 1),+ next: number + 1,+ prev: number - 1,+ previous: number - 1,+ };+ for (const [rel, link] of Object.entries(links)) {+ if (rel === "application" || rel === "self") continue;+ if (Object.hasOwn(positions, rel)) {+ const position = positions[rel]!;+ if (+ position < 0 ||+ position >= Math.max(1, pages) ||+ selection(halUrl(link, rel), scope, position, size, rel).toString() !==+ filter+ )+ throw new Error(+ `Contradictory Veracode ${rel} page link or selection.`,+ );+ } else {+ for (const reference of Array.isArray(link) ? link : [link]) {+ const url = halUrl(reference, rel);+ const app = /^\/appsec\/v[12]\/applications\/([^/]+)/u.exec(+ url.pathname,+ );+ if (+ url.origin !== scope.origin ||+ (app && guid(app[1]) !== scope.application)+ )+ throw new Error(+ `Veracode ${rel} link contradicts the origin or application.`,+ );+ }+ }+ }+ return { rows, scope, query, filter, number, size, total, pages };+}++function readReport(input: unknown) {+ const pages = (Array.isArray(input) ? input : [input])+ .map(readPage)+ .sort((left, right) => left.number - right.number);+ const first = pages[0];+ if (+ !first ||+ pages.length !== Math.max(1, first.pages) ||+ pages.some(+ (page, index) =>+ page.number !== index ||+ page.total !== first.total ||+ page.size !== first.size ||+ page.scope.applicationUrl !== first.scope.applicationUrl ||+ page.filter !== first.filter,+ )+ )+ throw new Error(+ "Supply every Veracode page exactly once with stable totals, selection, origin and application context.",+ );+ const { scope, query } = first;+ const selectedScores = scores.filter(+ (field) => query.has(field) || query.has(`${field}_gte`),+ );+ const staticOnly = query.has("scan_type");+ const violates = query.get("violates_policy");+ const newOnly = query.get("new") === "true";+ const cwes = query.get("cwe")?.split(",");+ const categories = query.get("finding_category")?.split(",");+ const seen = new Set<string>();+ const rows: Record<string, unknown>[] = [];+ for (const page of pages) {+ for (const value of page.rows) {+ const row = record(value, "Veracode finding");+ requireApplication(row, scope);+ if (+ newOnly &&+ record(row["finding_status"], "Veracode finding_status")["new"] !== true+ )+ throw new Error("Veracode finding contradicts the new selection.");+ if (+ query.get("include_annot") === "false" &&+ Array.isArray(row["annotations"]) &&+ row["annotations"].length+ )+ throw new Error(+ "Veracode finding contradicts the include_annot selection.",+ );+ if (cwes || categories || selectedScores.length) {+ const details = record(+ row["finding_details"],+ "Veracode finding_details",+ );+ for (const [field, ids] of [+ ["cwe", cwes],+ ["finding_category", categories],+ ] as const) {+ if (!ids || row["scan_type"] !== "STATIC") continue;+ const entry = record(details[field], `Veracode ${field}`);+ const id = integer(entry["id"], `${field} ID`);+ if (!ids.includes(String(id)))+ throw new Error(+ `Veracode finding contradicts the ${field} selection.`,+ );+ }+ for (const field of selectedScores) {+ const score =+ field === "severity"+ ? integer(details[field], field)+ : cvssScore.safeParse(details[field]).data;+ const exact = query.get(field);+ const minimum = query.get(`${field}_gte`);+ if (+ score === undefined ||+ (exact !== null && score !== Number(exact)) ||+ (minimum !== null && score < Number(minimum))+ )+ throw new Error(+ `Veracode finding contradicts the ${field} selection.`,+ );+ }+ }+ if (staticOnly && row["scan_type"] !== "STATIC")+ throw new Error(+ "Veracode finding contradicts the requested STATIC scan type.",+ );+ if (violates !== null && row["violates_policy"] !== (violates === "true"))+ throw new Error(+ "Veracode finding contradicts the violates_policy selection.",+ );++ const issue = row["issue_id"];+ if (+ typeof row["scan_type"] === "string" &&+ positive.safeParse(issue).success+ ) {+ const key = `${row["scan_type"]}:${issue}`;+ if (seen.has(key))+ throw new Error(+ "Overlapping Veracode findings repeat a native issue; recollect the complete selection.",+ );+ seen.add(key);+ }+ rows.push(row);+ }+ }+ return { scope, rows };+}++export function normalizeVeracodeFindings(+ input: unknown,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+): ExternalFindings {+ const repository = declaredScannerRepositoryUrl(+ sourceRepositoryUrl,+ "Veracode",+ target,+ );+ const { scope, rows } = readReport(input);+ return normalizeRecords(+ rows,+ (row) => {+ const details = record(+ row["finding_details"],+ "Veracode finding_details",+ );+ const status = record(row["finding_status"], "Veracode finding_status");+ const cwe = record(details["cwe"], "Veracode CWE");+ const weakness = `CWE-${integer(cwe["id"], "CWE ID", 1)}`;+ const category =+ details["finding_category"] == null+ ? null+ : record(details["finding_category"], "Veracode finding category");+ const severity =+ severityByScore[integer(details["severity"], "severity")];+ if (!severity)+ throw new Error("Veracode severity must be on the native 0–5 scale.");+ return validateExternalEvidence(+ {+ title: text(category?.["name"]) ?? text(cwe["name"]) ?? weakness,+ severity,+ description: text(row["description"]),+ details: {+ kind: "sast",+ repository: { url: repository },+ source_status: requiredText(+ status["status"],+ "Veracode finding status",+ ),+ weakness_ids: [weakness],+ },+ source_data: structuredClone({+ sourceRepositoryUrl: repository,+ applicationUrl: scope.applicationUrl,+ row,+ }),+ },+ target,+ );+ },+ (row) => occurrenceId(row, scope),+ target,+ );+}++export async function readVeracodeFindings(+ path: string,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+): Promise<ExternalFindings> {+ return normalizeVeracodeFindings(+ await readScannerJson(path),+ sourceRepositoryUrl,+ target,+ );+}diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 1803513b4..7202d140f 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -71,6 +71,11 @@ import {inspectorRepositoryUrl,} from "./support/inspector-import-fixtures.js";import { normalizeBlackDuckFindings } from "../src/blackduck-findings.js";+import { normalizeVeracodeFindings } from "../src/veracode-findings.js";+import {+ veracodePolicyPage,+ veracodePolicyRow,+} from "./support/veracode-import-fixtures.js";import {blackDuckBomReport,blackDuckBomRow,@@ -213,6 +218,7 @@ for (const provider of ["wiz", "snyk"] as const) {test("Wiz's gzip JSON report retains finding identity, evidence and repository locations", async () => {const report = {id: "vendor-report-1",+ row: veracodePolicyRow(),name: "CVE-2026-0001",detailedName: "example-package",version: "1.2.3",@@ -234,7 +240,7 @@ test("Wiz's gzip JSON report retains finding identity, evidence and repository lawait writeFile(f.file,gzipSync(- [report, { ...report, id: "vendor-report-2" }]+ [report, { ...report, id: `veracode-static-policy:${"a".repeat(64)}` }].map((record) => JSON.stringify(record)).join("\n"),),@@ -1216,27 +1222,60 @@ test("a normalized Inspector retry checks its typed repository without native evexpect(f.posts).toHaveLength(1);});+const savedBlackDuckEvidence = {+ data: { format: "blackduck-bom-6" },+ requiredProvider: "blackduck",+ digest: "d3001de83673b0f42b1d1d42cb19ea546869d41ed99504ca213b303267bb1346",+};++const savedDependabotData = {+ ...githubDependabotAlert(),+ sourceRepositoryUrl: "https://github.com/example/different",+};+test.each([- ["wiz", "2dfdb44c2c7494f4eed20e59244df967598fc3a284589ec2f6c3a24bfff7b2d0"],- [- "inspector",- "d0ba21fbe6c5927206db937694c98f69ad59e33fc390cae6eb6bd01249b5ca10",- ],- [- "github",- "2dc327e13b7b9548e828b0fe3193988a26c53c9c956b364c69990abdb418c298",- ],-] as const)(- "checks a saved %s request from before Black Duck provider checks",- async (provider, checkpointKey) => {+ {+ ...savedBlackDuckEvidence,+ selected: options,+ filename:+ "2dfdb44c2c7494f4eed20e59244df967598fc3a284589ec2f6c3a24bfff7b2d0.pending.json",+ },+ {+ ...savedBlackDuckEvidence,+ selected: { ...options, provider: "inspector" as const },+ filename:+ "d0ba21fbe6c5927206db937694c98f69ad59e33fc390cae6eb6bd01249b5ca10.pending.json",+ },+ {+ selected: { ...options, provider: "github" as const },+ data: savedDependabotData,+ requiredProvider: "blackduck",+ filename:+ "2dc327e13b7b9548e828b0fe3193988a26c53c9c956b364c69990abdb418c298.pending.json",+ digest: "abe417c10599f27dc9adc599465af29f693069deaca7942f79c952871216070e",+ },+ {+ selected: { ...options, provider: "inspector" as const },+ data: {+ sourceRepositoryUrl: inspectorRepositoryUrl,+ applicationUrl: veracodePolicyPage()._links.application.href,+ row: veracodePolicyRow(),+ },+ requiredProvider: "veracode",+ filename:+ "7d21ed6ce9acbc4bf00c5c7d7ed02b8e7937e92efa796e6218d57273eb9ce2f4.pending.json",+ digest: "13b472f7b050ef94705eed1fb4487b206386130f988d3ee6f87824f02f4d79f0",+ },+])(+ "checks a saved $selected.provider request from before $requiredProvider checks",+ async ({ selected, data, requiredProvider, filename, digest }) => {const f = await fixture();- const settings = { ...options, provider };const environment: NodeJS.ProcessEnv = { ...f.environment };// These persisted keys came from the default deployment.delete environment["CODEX_SECURITY_CLOUD_BASE_URL"];delete environment["CODEX_SECURITY_CLOUD_WEB_URL"];- const alert = provider === "github" ? githubDependabotAlert() : undefined;- const other = "https://github.com/example/different";+ const alert =+ selected.provider === "github" ? savedDependabotData : undefined;const row = normalized();const finding = {source_finding_id: alert@@ -1248,14 +1287,14 @@ test.each([title: "Dependabot alert",severity: "high",url: alert.html_url,- source_data: { ...alert, sourceRepositoryUrl: other },+ source_data: data,}- : { ...row.evidence, source_data: { format: "blackduck-bom-6" } },+ : { ...row.evidence, source_data: data },),};const input = { read: 1, excluded: [], findings: [finding] };const prepare = () =>- prepareNormalizedExternalPublication(input, settings, {+ prepareNormalizedExternalPublication(input, selected, {...f.deps,environment,});@@ -1266,23 +1305,20 @@ test.each([f.environment.CODEX_SECURITY_STATE_DIR,"external-finding-publications",);- const digest = alert- ? "abe417c10599f27dc9adc599465af29f693069deaca7942f79c952871216070e"- : "d3001de83673b0f42b1d1d42cb19ea546869d41ed99504ca213b303267bb1346";const request = {request_id: "efbc3c2e-0462-4411-89aa-9ced1d34223c",repository: {- id: options.repository,+ id: selected.repository,repo_connector_id: "github",environment_id: f.state.environmentId,reset_marker: f.state.marker,},- source: { provider, source_key: options.sourceKey },+ source: { provider: selected.provider, source_key: selected.sourceKey },items: [{ client_id: "item-1", ...finding, expected_version: 0 }],};await mkdir(directory, { recursive: true, mode: 0o700 });await writeFile(- join(directory, `${checkpointKey}.pending.json`),+ join(directory, filename),JSON.stringify({accountId: "synthetic-account",requests: [request],@@ -1295,7 +1331,7 @@ test.each([// The original publisher selected the alert's repository. Changing the// catalog to match the projection must not permit replay to another repo.const originalRepository = f.state.repositoryUrl;- f.state.repositoryUrl = other;+ f.state.repositoryUrl = alert.sourceRepositoryUrl;await expect(prepare()).rejects.toThrow(`belongs to "${originalRepository}"`,);@@ -1306,7 +1342,9 @@ test.each([expect(retry.preview.resumed).toBe(true);expect((await retry.publish()).counts.created).toBe(1);expect(f.posts.map((body) => JSON.parse(body))).toEqual([request]);- await expect(prepare()).rejects.toThrow("requires the blackduck provider");+ await expect(prepare()).rejects.toThrow(+ `requires the ${requiredProvider} provider`,+ );},);@@ -1475,6 +1513,101 @@ test("Black Duck Cloud replay preserves package occurrence and rejects a differeexpect(correct.posts.slice(-2)).toEqual([expected, expected]);});+test("Veracode Cloud replays an application policy issue and rejects a foreign destination before POST", async () => {+ const page = veracodePolicyPage([veracodePolicyRow(1)]);+ const correct = await fixture([page]);+ const selected = {+ ...options,+ provider: "veracode" as const,+ sourceRepositoryUrl: "https://github.com/example/project",+ sourceKey: "veracode/example/static",+ };+ const prepare = () =>+ prepareExternalPublication(correct.file, selected, correct.deps);+ const first = await prepare();+ expect(first.preview.requests[0]!.source.provider).toBe("veracode");+ await expect(+ prepareNormalizedExternalPublication(+ normalizeVeracodeFindings(page, selected.sourceRepositoryUrl),+ { ...selected, provider: "wiz" },+ correct.deps,+ ),+ ).rejects.toThrow(/requires the veracode provider/i);+ for (const row of [+ { ...veracodePolicyRow(), context_type: "SANDBOX" },+ { ...veracodePolicyRow(), scan_type: "DYNAMIC" },+ ]) {+ const input = normalizeVeracodeFindings(page, selected.sourceRepositoryUrl);+ input.findings[0]!.source_finding_id = "sdk-id";+ input.findings[0]!.evidence.source_data!["row"] = row;+ await expect(+ prepareNormalizedExternalPublication(input, selected, correct.deps),+ ).rejects.toThrow(/context|STATIC/);+ }+ const partial = normalizeVeracodeFindings(page, selected.sourceRepositoryUrl);+ const finding = partial.findings[0]!;+ delete finding.evidence.source_data!["applicationUrl"];+ const foreignUrl = "https://github.com/example/other";+ const foreign = await fixture(undefined, foreignUrl);+ finding.evidence.details!.repository!.url = foreignUrl;+ for (const id of [finding.source_finding_id, "sdk-id"]) {+ finding.source_finding_id = id;+ await expect(+ prepareNormalizedExternalPublication(+ partial,+ { ...selected, provider: "wiz" },+ foreign.deps,+ ),+ ).rejects.toThrow(/requires the veracode provider/i);+ }+ finding.evidence.details!.repository!.url = selected.sourceRepositoryUrl;+ await expect(+ prepareNormalizedExternalPublication(partial, selected, correct.deps),+ ).rejects.toThrow(/retained application/i);+ finding.evidence.source_data = {+ sourceRepositoryUrl: selected.sourceRepositoryUrl,+ applicationUrl:+ "https://scanner.example.test/appsec/v1/applications/dashboard",+ row: { status: "ready" },+ };+ expect(+ (+ await prepareNormalizedExternalPublication(+ partial,+ { ...selected, provider: "wiz" },+ correct.deps,+ )+ ).preview.findings,+ ).toHaveLength(1);+ const mixed = normalizeVeracodeFindings(page, selected.sourceRepositoryUrl);+ const sdkFinding = structuredClone(mixed.findings[0]!);+ sdkFinding.source_finding_id = "sdk-id";+ delete sdkFinding.evidence.source_data;+ sdkFinding.evidence.details!.repository!.url =+ "https://github.com/example/other";+ mixed.findings.push(sdkFinding);+ mixed.read++;+ await expect(+ prepareNormalizedExternalPublication(mixed, selected, correct.deps),+ ).rejects.toThrow(/does not match/);+ expect(correct.posts).toHaveLength(0);+ first.preview.requests[0]!.items[0]!.evidence.source_data![+ "sourceRepositoryUrl"+ ] = "https://github.com/example/other";+ correct.state.loseResponse = true;+ await expect(first.publish()).rejects.toThrow("resume the saved request");+ const retry = await prepare();+ expect(retry.preview.resumed).toBe(true);+ expect((await retry.publish()).counts.created).toBe(1);+ expect(correct.posts[1]).toBe(correct.posts[0]);+ expect((await (await prepare()).publish()).counts.unchanged).toBe(1);+ const other = await fixture([page], "https://github.com/example/other");+ await expect(+ prepareExternalPublication(other.file, selected, other.deps),+ ).rejects.toThrow(/does not match/i);+ expect(other.posts).toHaveLength(0);+});+test("CLI preview and rejected confirmation never POST or persist an upload", async () => {const f = await fixture();const cli = createCliTest(main);diff --git a/sdk/typescript/tests-ts/support/veracode-import-fixtures.ts b/sdk/typescript/tests-ts/support/veracode-import-fixtures.tsnew file mode 100644index 000000000..37ca04631--- /dev/null+++ b/sdk/typescript/tests-ts/support/veracode-import-fixtures.ts@@ -0,0 +1,49 @@+const origin = "https://scanner.example.test";+const application = "00000000-0000-4000-8000-000000000001";++export function veracodePolicyRow(issueId = 1) {+ return {+ issue_id: issueId,+ scan_type: "STATIC",+ context_type: "APPLICATION",+ context_guid: application,+ violates_policy: true,+ build_id: 12,+ count: 1,+ description: "Vendor description",+ finding_status: {+ status: "OPEN",+ resolution: "UNRESOLVED",+ mitigation_review_status: "NONE",+ },+ finding_details: {+ severity: 4,+ cwe: { id: 79, name: "Example weakness" },+ finding_category: { id: 4, name: "Example category" },+ module: "example.jar",+ file_path: "compiled/Example.java",+ file_line_number: 17,+ },+ };+}++export function veracodePolicyPage(+ findings = [veracodePolicyRow()],+ { number = 0, size = 20, total = findings.length } = {},+) {+ const resource = `${origin}/appsec/v2/applications/${application}/findings`;+ const link = (page: number) => ({+ href: `${resource}?scan_type=STATIC&page=${page}&size=${size}`,+ });+ const pages = Math.ceil(total / size);+ return {+ _embedded: { findings },+ _links: {+ self: link(number),+ application: { href: `${origin}/appsec/v1/applications/${application}` },+ ...(number > 0 ? { prev: link(number - 1) } : {}),+ ...(number + 1 < pages ? { next: link(number + 1) } : {}),+ },+ page: { size, number, total_elements: total, total_pages: pages },+ };+}diff --git a/sdk/typescript/tests-ts/veracode-findings.test.ts b/sdk/typescript/tests-ts/veracode-findings.test.tsnew file mode 100644index 000000000..53794f7ea--- /dev/null+++ b/sdk/typescript/tests-ts/veracode-findings.test.ts@@ -0,0 +1,523 @@+import { expect, test } from "bun:test";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { gzipSync } from "node:zlib";+import {+ normalizeVeracodeFindings,+ readVeracodeFindings,+ veracodeReportRepositories,+} from "../src/veracode-findings.js";+import {+ veracodePolicyPage,+ veracodePolicyRow,+} from "./support/veracode-import-fixtures.js";++const repository = "https://vcs.example.test/org/application";+const normalize = (input: unknown, target: "cloud" | "local" = "cloud") =>+ normalizeVeracodeFindings(input, repository, target);+const otherApp = "00000000-0000-4000-8000-000000000002";++function capture() {+ return [0, 1, 2].map((number) =>+ veracodePolicyPage([veracodePolicyRow(number + 1)], {+ number,+ size: 1,+ total: 3,+ }),+ );+}++test("keeps only finding-level evidence, not a generated checkout location or a policy verdict", () => {+ const row = {+ ...veracodePolicyRow(),+ count: 4,+ violates_policy: false,+ extra: { retained: [1] },+ };+ const report = veracodePolicyPage([row]);+ const result = normalize({+ ...report,+ build: "unrelated collection snapshot",+ });+ expect(result).toEqual(normalize(report, "local"));+ expect(result.read).toBe(1);+ expect(result.excluded).toEqual([]);+ const { evidence } = result.findings[0]!;+ expect(evidence).toMatchObject({+ title: "Example category",+ severity: "high",+ description: row.description,+ locations: [],+ code_revision: null,+ source_scan_id: null,+ details: {+ kind: "sast",+ source_status: "OPEN",+ weakness_ids: ["CWE-79"],+ repository: { url: repository },+ },+ });+ const original = structuredClone(row);+ expect(evidence.source_data).toEqual({+ sourceRepositoryUrl: repository,+ applicationUrl: report._links.application.href,+ row: original,+ });+ row.extra.retained.push(2);+ expect(evidence.source_data?.["row"]).toEqual(original);+});++test("canonical severity covers the six native levels and malformed levels are not guessed", () => {+ const rows = [0, 1, 2, 3, 4, 5, 6, -1, 1.5].map((severity, index) => {+ const row = veracodePolicyRow(index + 1);+ row.finding_details.severity = severity;+ return row;+ });+ const result = normalize(veracodePolicyPage(rows));+ expect(result.findings.map(({ evidence }) => evidence.severity)).toEqual([+ "informational",+ "low",+ "low",+ "medium",+ "high",+ "critical",+ ]);+ expect(result.excluded.map(({ position }) => position)).toEqual([7, 8, 9]);+});++test("fully enumerated pages replay identically after reordering, page-size changes and omitted issues", () => {+ const pages = capture();+ const single = veracodePolicyPage(+ pages.flatMap((page) => page._embedded.findings),+ );+ const full = normalize(single);+ expect(full.findings).toHaveLength(3);+ expect(normalize(pages)).toEqual(full);+ expect(normalize(pages.toReversed())).toEqual(full);+ expect(+ normalize(veracodePolicyPage([veracodePolicyRow(2)])).findings,+ ).toEqual([full.findings[1]!]);+ const changed = veracodePolicyRow(2);+ changed.finding_status = {+ status: "CLOSED",+ resolution: "MITIGATED",+ mitigation_review_status: "APPROVED",+ };+ changed.build_id++;+ changed.finding_details.file_line_number++;+ const finding = normalize(veracodePolicyPage([changed])).findings[0]!;+ expect(finding.source_finding_id).toBe(full.findings[1]!.source_finding_id);+ expect(finding.evidence).not.toEqual(full.findings[1]!.evidence);+ expect(finding.evidence.source_data?.["row"]).toEqual(changed);+});++test("rejects holes, duplicate pages, changing totals or selection, and contradictory navigation", () => {+ const [first, middle, last] = capture() as [+ ReturnType<typeof veracodePolicyPage>,+ ReturnType<typeof veracodePolicyPage>,+ ReturnType<typeof veracodePolicyPage>,+ ];+ for (const input of [+ first,+ [first, last],+ [first, middle, middle],+ [first, middle, last, last],+ [first, { ...middle, _embedded: { findings: [] } }, last],+ [+ first,+ {+ ...middle,+ page: { ...middle.page, total_elements: 4, total_pages: 4 },+ },+ last,+ ],+ [first, { ...middle, page: { ...middle.page, size: 2 } }, last],+ [+ first,+ middle,+ { ...last, _links: { ...last._links, next: first._links.self } },+ ],+ [+ { ...first, _links: { ...first._links, next: first._links.self } },+ middle,+ last,+ ],+ ])+ expect(() => normalize(input)).toThrow();+ const filtered = structuredClone(middle);+ for (const [rel, link] of Object.entries(filtered._links))+ if (rel !== "application") link.href += "&violates_policy=true";+ expect(() => normalize([first, filtered, last])).toThrow(/selection/);+});++test("accepts collection self links while requiring navigation to identify the destination page", () => {+ const pages = capture();+ const expected = normalize(pages);+ for (const page of pages)+ page._links.self = {+ ...page._links.self,+ href: page._links.self.href.replace(/&page=\d+&size=\d+/u, ""),+ };+ expect(normalize(pages)).toEqual(expected);+ const before = pages[0]!._links.next!.href;+ pages[0]!._links.next!.href = before.replace("&size=1", "");+ expect(() => normalize(pages)).toThrow(/size/);+ pages[0]!._links.next!.href = pages[0]!._links.self.href;+ expect(() => normalize(pages)).toThrow(/page/);+});++test("matches row filters and equivalent HAL list and boolean selections", () => {+ const pages = capture();+ const expected = normalize(pages);+ for (const page of pages) {+ for (const [rel, link] of Object.entries(page._links)) {+ if (rel === "application") continue;+ link.href +=+ rel === "self"+ ? "&cwe=079,89&finding_category=04,20&include_annot=TRUE"+ : "&cwe=89&cwe=79&finding_category=20,4&include_annot=true";+ }+ }+ expect(normalize(pages)).toEqual(expected);+ const row = veracodePolicyRow();+ const status = (isNew: boolean) => ({+ ...row,+ finding_status: { ...row.finding_status, new: isNew },+ });+ for (const [query, message] of [+ ["cwe=89", "cwe"],+ ["finding_category=20", "finding_category"],+ ["new=TRUE", "new"],+ ] as const) {+ const page = veracodePolicyPage([status(false)]);+ page._links.self.href += "&" + query;+ expect(() => normalize(page)).toThrow(message);+ }+ const page = veracodePolicyPage([+ status(false),+ { ...status(true), issue_id: 2 },+ ]);+ page._links.self.href += "&new=false";+ expect(normalize(page).findings).toHaveLength(2);+});++test("a CWE-filtered capture retains static findings alongside unsupported manual findings", () => {+ const row = veracodePolicyRow();+ const page = veracodePolicyPage([row, row]);+ page._links.self.href = page._links.self.href.replace(+ "scan_type=STATIC",+ "cwe=79",+ );+ const manual = { ...row, scan_type: "MANUAL", finding_details: { cwe: 79 } };+ const report = normalize({ ...page, _embedded: { findings: [row, manual] } });+ expect(report.findings).toHaveLength(1);+ expect(report.excluded).toHaveLength(1);+});++test("checks explicit score, annotation and new-finding selections before retaining a row", () => {+ const row = veracodePolicyRow();+ const native = {+ ...row,+ finding_details: { ...row.finding_details, cvss: "9.1" },+ annotations: [{ comment: "Example annotation" }],+ finding_status: { ...row.finding_status, new: "false" },+ };+ const page = veracodePolicyPage([native]);+ const self = page._links.self.href;+ for (const [query, reason] of [+ ["cvss_gte=9.2", "cvss"],+ ["cvss=9", "cvss"],+ ["include_annot=false", "include_annot"],+ ["new=true", "new"],+ ["new=false&new=true", "new"],+ ] as const) {+ page._links.self.href = self + "&" + query;+ expect(() => normalize(page)).toThrow(reason);+ }+ page._links.self.href = self + "&cvss=9.10&include_annot=true";+ expect(+ normalize({+ ...page,+ _links: {+ ...page._links,+ first: { href: self + "&cvss=9.1&include_annot=TRUE" },+ },+ }).findings,+ ).toHaveLength(1);+ page._links.self.href = self + "&finding_category=4";+ const wrong = {+ ...native,+ finding_details: {+ ...native.finding_details,+ finding_category: { id: "20", name: "Other" },+ },+ };+ expect(() =>+ normalize({ ...page, _embedded: { findings: [wrong] } }),+ ).toThrow(/finding_category/);+});++test("accepts a scoped native empty page but rejects errors, summaries, Pipeline and raw row arrays", () => {+ const overlapping = capture();+ overlapping[1]!._embedded.findings = overlapping[0]!._embedded.findings;+ expect(() => normalize(overlapping)).toThrow(/Overlapping/);+ const empty = veracodePolicyPage([]);+ const { _embedded, ...omitted } = empty;+ expect(normalize(omitted)).toEqual(normalize(empty));+ expect(() =>+ normalize({ ...omitted, page: veracodePolicyPage().page }),+ ).toThrow();+ expect(normalize(empty)).toEqual({ read: 0, findings: [], excluded: [] });+ expect(+ normalize({ ...empty, page: { ...empty.page, total_pages: 1 } }),+ ).toEqual(normalize(empty));+ for (const input of [+ [],+ {},+ [veracodePolicyRow()],+ { scan_status: "SUCCESS", findings: [] },+ { policy_compliance_status: "PASSED" },+ { ...empty, status: 403 },+ { ...empty, error: "unavailable" },+ { ...empty, _embedded: { findings: [], errors: [{ detail: "failed" }] } },+ { ...empty, _embedded: {} },+ { ...empty, page: { ...empty.page, total_elements: "0" } },+ { ...empty, _links: { self: empty._links.self } },+ ])+ expect(() => normalize(input)).toThrow();+});++test("enforces exact and minimum native severity selections", () => {+ const page = veracodePolicyPage();+ const self = page._links.self.href;+ for (const filter of ["severity=4", "severity_gte=4", "severity_gte=0"]) {+ page._links.self.href = self + "&" + filter;+ expect(normalize(page).findings).toHaveLength(1);+ }+ for (const filter of ["severity=3", "severity_gte=5", "severity=6"]) {+ page._links.self.href = self + "&" + filter;+ expect(() => normalize(page)).toThrow(/severity/);+ }+});++test("detects overlap in unfiltered pages without conflating issues from different engines", () => {+ const pages = capture();+ for (const page of pages)+ for (const link of Object.values(page._links))+ link.href = link.href.replace("scan_type=STATIC&", "");+ const dynamic = { ...veracodePolicyRow(1), scan_type: "DYNAMIC" };+ pages[1]!._embedded.findings = [dynamic];+ expect(normalize(pages).findings).toHaveLength(2);+ pages[2]!._embedded.findings = [dynamic];+ expect(() => normalize(pages)).toThrow(/Overlapping/);+});++test("never widens the app, host, sandbox or requested engine, including through HAL links", () => {+ const page = veracodePolicyPage();+ const row = veracodePolicyRow();+ const self = page._links.self.href;+ for (const href of [+ self.replace("scanner.example.test", "other.example.test"),+ self.replace(row.context_guid, otherApp),+ self.replace("STATIC", "DYNAMIC"),+ self.replace("STATIC", "SCA"),+ self + `&context=${row.context_guid}`,+ self + "&scan_type=DAST",+ self + "&sca_dep_mode=DIRECT",+ self + "&sca_scan_mode=UPLOAD",+ self.replace("page=0", "page=1"),+ self.replace("size=20", "size=1"),+ self.replace("/findings", "/summary"),+ self.replace("/findings", "/wrong/../findings"),+ self + "#fragment",+ ])+ expect(() =>+ normalize({ ...page, _links: { ...page._links, self: { href } } }),+ ).toThrow();+ for (const finding of [+ { ...row, context_type: "SANDBOX" },+ { ...row, context_guid: otherApp },+ { ...row, scan_type: "DYNAMIC" },+ ])+ expect(() => normalize(veracodePolicyPage([row, finding]))).toThrow();+ expect(() =>+ normalize({+ ...page,+ _links: {+ ...page._links,+ sca: {+ href: self.replace("scanner.example.test", "other.example.test"),+ },+ },+ }),+ ).toThrow(/origin/);+ const mixed = capture();+ mixed[1] = JSON.parse(+ JSON.stringify(mixed[1]).replaceAll(row.context_guid, otherApp),+ );+ expect(() => normalize(mixed)).toThrow(/application/);+ const moved = JSON.parse(+ JSON.stringify(page).replaceAll(+ "scanner.example.test",+ "other.example.test",+ ),+ );+ const other = JSON.parse(+ JSON.stringify(page).replaceAll(row.context_guid, otherApp),+ );+ expect(+ new Set(+ [page, moved, other].map(+ (value) => normalize(value).findings[0]!.source_finding_id,+ ),+ ).size,+ ).toBe(3);+});++test("optional HAL query templates are not sandbox scope, and discovery links do not select SCA", () => {+ const row = veracodePolicyRow();+ const page = veracodePolicyPage([row]);+ const path = page._links.self.href.split("?")[0]!;+ const template = "{&context,severity,severity_gte,scan_type}";+ const links = {+ ...page._links,+ self: { href: `${path}?violates_policy=true${template}`, templated: true },+ sca: {+ href: `${path}?violates_policy=true&scan_type=SCA${template}`,+ templated: true,+ },+ };+ expect(normalize({ ...page, _links: links })).toEqual(normalize(page));+ const uppercase = {+ ...links,+ self: { ...links.self, href: links.self.href.replace("=true", "=TRUE") },+ };+ expect(normalize({ ...page, _links: uppercase })).toEqual(normalize(page));+ const invalidTemplate = {+ ...links,+ self: { ...links.self, href: links.self.href.replace("{&", "{?") },+ };+ expect(() => normalize({ ...page, _links: invalidTemplate })).toThrow(+ /HAL URL/,+ );+ expect(() =>+ normalize({+ ...page,+ _links: { ...links, self: { href: links.self.href } },+ }),+ ).toThrow();+ expect(() =>+ normalize({+ ...page,+ _links: links,+ _embedded: { findings: [{ ...row, violates_policy: false }] },+ }),+ ).toThrow(/violates_policy/);+ const rows = [+ row,+ { ...row, scan_type: "DYNAMIC" },+ { ...row, scan_type: "SCA" },+ ];+ const result = normalize({ ...veracodePolicyPage(rows), _links: links });+ expect(result.read).toBe(3);+ expect(result.findings).toHaveLength(1);+ expect(result.excluded.map(({ position }) => position)).toEqual([2, 3]);+});++test("declared totals cannot hide duplicate issues; malformed IDs do not consume valid occurrences", () => {+ const sparse = veracodePolicyPage();+ delete sparse._embedded.findings[0];+ expect(() => normalize(sparse)).toThrow(+ "Veracode finding must be an object.",+ );+ const valid = veracodePolicyRow(3);+ expect(() =>+ normalize(veracodePolicyPage([valid, veracodePolicyRow(2), valid])),+ ).toThrow(/duplicate|overlap/i);+ const result = normalize(veracodePolicyPage([valid, veracodePolicyRow(0)]));+ expect(result.findings).toHaveLength(1);+ expect(result.excluded).toMatchObject([+ { position: 2, source_finding_id: null },+ ]);+});++test("prepared provenance binds the repository and native occurrence", () => {+ const [first, second] = normalize(+ veracodePolicyPage([veracodePolicyRow(), veracodePolicyRow(2)]),+ ).findings;+ const data = first!.evidence.source_data;+ const retained = (source_data: typeof data, id = first!.source_finding_id) =>+ veracodeReportRepositories(+ "veracode",+ [+ {+ source_finding_id: id,+ evidence: { ...first!.evidence, source_data },+ },+ ],+ "cloud",+ ).get(id);+ expect(retained(data)?.url).toBe(repository);+ expect(() => retained(data, second!.source_finding_id)).toThrow(+ /source finding ID/,+ );+ expect(() => retained({ ...data, row: null })).toThrow(/retained finding/);+ expect(() =>+ retained({+ ...data,+ row: { ...veracodePolicyRow(), context_guid: otherApp },+ }),+ ).toThrow(/context/);+ expect(+ retained(+ { applicationUrl: "https://scanner.example.test/dashboard" },+ "custom-issue-id",+ ),+ ).toBeUndefined();+ expect(() => retained(undefined)).toThrow(/source-repository-url/);+ for (const source of [+ "",+ "https://vcs.example.test",+ "https://vcs.example.test/org",+ "https://[email protected]/org/repo",+ `${repository}?filter=1`,+ `${repository}#ref`,+ `${repository}/%2e%2e/repo`,+ `${repository}%2frepo`,+ `${repository}\\repo`,+ ]) {+ expect(() =>+ normalizeVeracodeFindings(veracodePolicyPage([]), source),+ ).toThrow(/source-repository-url/);+ expect(() => retained({ ...data, sourceRepositoryUrl: source })).toThrow(+ /source-repository-url/,+ );+ }+});++test("gzip replay preserves the native row, while Cloud and local retain their existing evidence limits", async () => {+ const path = await mkdtemp(join(tmpdir(), "veracode-findings-"));+ try {+ const report = join(path, "findings.json");+ const pages = capture();+ for (const bytes of [+ Buffer.from(JSON.stringify(pages)),+ gzipSync(JSON.stringify(pages)),+ ]) {+ await writeFile(report, bytes);+ for (const target of ["cloud", "local"] as const)+ expect(await readVeracodeFindings(report, repository, target)).toEqual(+ normalize(pages),+ );+ }+ const large = { ...veracodePolicyRow(), original: "x".repeat(270_000) };+ expect(normalize(veracodePolicyPage([large])).excluded).toHaveLength(1);+ expect(+ normalize(veracodePolicyPage([large]), "local").findings[0]!.evidence+ .source_data?.["row"],+ ).toEqual(large);+ } finally {+ await rm(path, { recursive: true, force: true });+ }+});diff --git a/sdk/typescript/tests-ts/veracode-repository-import.test.ts b/sdk/typescript/tests-ts/veracode-repository-import.test.tsnew file mode 100644index 000000000..6f0471b88--- /dev/null+++ b/sdk/typescript/tests-ts/veracode-repository-import.test.ts@@ -0,0 +1,147 @@+import { expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { writeFile } from "node:fs/promises";+import { join } from "node:path";+import { gzipSync } from "node:zlib";+import { prepareLocalExternalImport } from "../src/external-findings-import.js";+import {+ listLocalExternalFindings,+ prepareNormalizedLocalImport,+} from "../src/external-findings-local.js";+import { localFindingsFixture } from "./external-findings-local-helpers.js";+import {+ veracodePolicyPage,+ veracodePolicyRow,+} from "./support/veracode-import-fixtures.js";++test("replaying a Veracode policy flaw tracks evidence without assessing another build or repository", async () => {+ const url = "https://github.com/example/project";+ const fixture = await localFindingsFixture({ remote: url });+ try {+ const path = join(fixture.root, "veracode.json.gz");+ const options = {+ provider: "veracode" as const,+ repository: fixture.repository,+ sourceRepositoryUrl: url,+ sourceKey: "veracode/example/static",+ };+ const dependencies = { environment: fixture.environment };+ const prepare = async (rows: ReturnType<typeof veracodePolicyRow>[]) => {+ await writeFile(path, gzipSync(JSON.stringify(veracodePolicyPage(rows))));+ return prepareLocalExternalImport(path, options, dependencies);+ };+ const row = veracodePolicyRow(1);+ const first = await prepare([row, veracodePolicyRow(2)]);+ expect((await first.import()).counts.created).toBe(2);+ expect((await (await prepare([row])).import()).counts.unchanged).toBe(1);+ expect(+ (+ await (+ await prepare([+ {+ ...row,+ build_id: 13,+ finding_status: { ...row.finding_status, status: "CLOSED" },+ },+ ])+ ).import()+ ).counts.updated,+ ).toBe(1);+ expect((await (await prepare([])).import()).counts).toEqual({+ created: 0,+ updated: 0,+ unchanged: 0,+ });+ const records = await listLocalExternalFindings(options, dependencies);+ expect(records.map(({ version }) => version).sort()).toEqual([1, 2]);+ expect(+ records.every(({ assessment }) => assessment.state === "not_assessed"),+ ).toBe(true);+ await expect(+ prepareLocalExternalImport(+ path,+ { ...options, sourceRepositoryUrl: "https://github.com/example/other" },+ dependencies,+ ),+ ).rejects.toThrow(/remote|repository/i);+ const mixed = structuredClone(first.preview);+ const typed = mixed.findings[1]!;+ typed.source_finding_id = "sdk-id";+ delete typed.evidence.source_data;+ typed.evidence.details!.repository!.url =+ "[email protected]:example/mirror.git";+ const prepareMixed = () =>+ prepareNormalizedLocalImport(mixed, options, dependencies);+ const remote = (...args: string[]) =>+ execFileSync("git", ["-C", fixture.repository, "remote", ...args]);+ await expect(prepareMixed()).rejects.toThrow(/configured remote/);+ remote("add", "mirror", "https://github.com/example/mirror");+ expect((await prepareMixed()).preview.findings).toHaveLength(2);+ const wrong = structuredClone(first.preview);+ wrong.findings[0]!.evidence.details!.repository!.url =+ "https://github.com/example/other";+ await expect(+ prepareNormalizedLocalImport(wrong, options, dependencies),+ ).rejects.toThrow(/retained scanner repository/i);+ const relabeled = structuredClone(first.preview);+ relabeled.findings.splice(1);+ relabeled.findings[0]!.source_finding_id =+ first.preview.findings[1]!.source_finding_id;+ await expect(+ prepareNormalizedLocalImport(relabeled, options, dependencies),+ ).rejects.toThrow(/source finding ID|occurrence/i);+ const otherApplication = JSON.stringify(+ veracodePolicyPage([row]),+ ).replaceAll(row.context_guid, "00000000-0000-4000-8000-000000000002");+ await writeFile(path, gzipSync(otherApplication));+ const other = await prepareLocalExternalImport(path, options, dependencies);+ const findings = [...first.preview.findings, ...other.preview.findings];+ await expect(+ prepareNormalizedLocalImport(+ { ...first.preview, findings, read: findings.length },+ options,+ dependencies,+ ),+ ).rejects.toThrow(/same application/i);+ remote("set-url", "origin", "ssh://[email protected]/example/project?other");+ await expect(prepareMixed()).rejects.toThrow(/configured remote/);+ } finally {+ await fixture.dispose();+ }+});++test("a mixed SDK batch recognizes the repository retained by each Veracode row", async () => {+ await using fixture = await localFindingsFixture();+ const projected = "https://github.com/example/project";+ const typed = "https://github.com/example/other";+ const findings = (+ [+ [`blackduck-bom:${"a".repeat(64)}`, projected],+ ["sdk-id", typed],+ ] as const+ ).map(([source_finding_id, sourceRepositoryUrl]) => ({+ source_finding_id,+ evidence: {+ title: "Example",+ severity: "unknown" as const,+ source_data: { sourceRepositoryUrl },+ },+ }));+ const prepare = (url: string) =>+ prepareNormalizedLocalImport(+ { findings, read: 2, excluded: [] },+ {+ provider: "veracode",+ sourceKey: "example",+ repository: fixture.repository,+ },+ {+ environment: fixture.environment,+ sourceRepositories: [{ url: projected }, { url }],+ },+ );+ expect((await prepare(typed)).preview.findings).toHaveLength(2);+ await expect(prepare("https://github.com/example/third")).rejects.toThrow(+ /Reader repository does not match/,+ );+});diff --git a/sdk/typescript/tests-ts/wiz-findings-local.test.ts b/sdk/typescript/tests-ts/wiz-findings-local.test.tsindex 5ddbfb1d6..29e5ca1d9 100644--- a/sdk/typescript/tests-ts/wiz-findings-local.test.ts+++ b/sdk/typescript/tests-ts/wiz-findings-local.test.ts@@ -23,6 +23,10 @@ const row: Record<string, string> = {LocationPath: "/package-lock.json",Version: "1.0.0",FixedVersion: "2.0.0",+ context_type: "",+ context_guid: "",+ scan_type: "",+ issue_id: "",};function csvReport(source: Record<string, string>): string {