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): collect Snyk Code and Open Source findings locally (#2168)

Michael D'Angelo0d324b7314ed
diff --git a/docs/scanner-imports/snyk.md b/docs/scanner-imports/snyk.md
index 0a4ee3296..1dc3e4b2a 100644
--- a/docs/scanner-imports/snyk.md
+++ b/docs/scanner-imports/snyk.md
@@ -1,9 +1,92 @@
-# Import Snyk Open Source findings
+# Import Snyk findings
Import dependency vulnerabilities from a saved `snyk test` JSON report, a
`snyk-findings-export/v1` plugin bundle or self-contained Open Source SARIF.
Native CLI JSON preserves individual dependency paths and remediation details.
+For existing monitored projects, collect Open Source or Code issues through the Snyk Issues API.
+
+## Existing issues from Snyk
+
+To import a monitored project's existing issues into the local workbench, set
+`SNYK_TOKEN` to a read-authorized token for the selected region. See the
+[Snyk API access requirements](https://docs.snyk.io/developer-tools/snyk-api/authentication-for-api)
+and [Issues API permissions](https://docs.snyk.io/developer-tools/snyk-api/reference/issues).
+Select the organization ID, project ID and source repository URL. Open Source
+is the default. For a Snyk Code project, add `--snyk-product code`. For a
+regional deployment, set `--snyk-api-origin` to its documented API origin.
+
+Run the commands from a trusted directory outside the project checkout. The
+example saves a fresh report there and imports it into the checkout at `./project`.
+
+```sh
+report=$(mktemp ./snyk-issues.XXXXXX) &&
+ codex-security import snyk PROJECT_ID --snyk-org ORG_ID \
+ --source-repository-url https://github.com/example/project \
+ --format json > "$report" &&
+ codex-security publish findings "$report" --to local --provider snyk \
+ --source-key ORG_ID/PROJECT_ID --repository ./project --dry-run
+```
+
+Confirm the preview, then repeat the publish command without `--dry-run`.
+Collection reads open and resolved issues across all pages, including ignored issues.
+For Open Source it requests package vulnerabilities. For Code it requests code issues.
+The SDK's `collectSnykIssues` defaults to Open Source and returns the same report.
+Passing the configured `SNYK_TOKEN` explicitly retains its configured regional
+API origin. Pass independently verified `sourceRepositories` in its
+dependencies when a private repository uses an SSH target. The offline reader
+`readSnykFindings(path, "local")` accepts `snyk-rest-issues/v1` and
+`snyk-rest-issues/v2` reports from Snyk REST API version `2026-03-25`.
+The collector writes v2 and preserves the original project and issue evidence.
+For open Snyk Code issues from an SCM integration, both versions import
+repository-relative paths from open coordinates. V2 also imports each
+coordinate's reported start line when available. For resolved issues, closed
+coordinates, and projects monitored through the CLI or API, read the original
+location from `evidence.source_data.issue` in v1 or from the JSON text in
+`evidence.source_data.issueJson` in v2.
+
+Use the same source key on later imports. The issue key within the API
+origin, organization, project and product identifies the finding. Replaying the
+same evidence leaves the version unchanged. Whitespace, object key order and
+equivalent JSON number spellings in v2 native records do not affect replay.
+JSON strings remain distinct from numbers. Importing a different capture for
+that issue updates the same row, even if the capture is older.
+
+To select a subset in the SDK, filter the normalized report’s `findings`
+array. Keep the report’s `snykRestContext` and each selected finding’s
+`source_finding_id` and `evidence.source_data`. Every hosted row must retain
+the native issue and its generated ID. The verified report context can supply
+the monitored project for a row that retains only its original issue. For a v1
+row, keep `source_data.issue` and the original `source_data.numericFields`
+when present. If you trim the metadata, keep its matching entries for every
+`issue`, `project`, and `target` object you retain. V1 uses those entries to
+distinguish exact numbers from strings with the same spelling. For a v2 row,
+keep `source_data.issueJson`.
+The local workbench stores the verified project and target with that issue,
+so the stored row can be imported again. All selected issues must share the
+report’s API region, organization, project and product. Keep SCM-integrated
+findings separate from CLI- or API-monitored findings. If the report identifies
+a native target or its repository URL, retain that evidence in the selected
+project and target. Snyk’s optional integration relationship is retained when
+the target supplies it.
+
+SDK readers that define their own findings and IDs can use the ordinary
+normalized Snyk import with their own evidence and no hosted report context.
+
+The offline reader can interpret SCM aliases recorded in an archived project.
+Local import compares the source to the checkout’s configured external Git
+remotes. For a checkout with only filesystem remotes or none, the selected
+directory is the import destination.
+For private source-control hosts, use the same repository URL as the checkout.
+SDK callers that have independently verified a GitHub Enterprise or GitLab
+repository can pass its canonical HTTPS URL and platform to the local importer.
+This allows that repository's standard SSH clone URL and `.git` suffix. For
+example, a GitLab repository uses
+`sourceRepositories: [{ url: sourceRepositoryUrl, platform: "gitlab" }]`
+in the SDK dependencies. Use `platform: "github"` for GitHub Enterprise.
+When reading the saved file directly, pass the same verified sources as the
+third argument to `readSnykFindings(path, "local", sourceRepositories)`.
+
## Quick start
[Enable external imports](README.md#preview-a-report). For a first local import,
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 5317520b2..23be6607e 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -72,13 +72,15 @@ Validate the acquisition path against actual responses from an authorized Wiz te
Use a stable Wiz tenant/finding namespace as `--source-key`; a project filter does not create a new identity. Confirm the selected assets or builds belong to the destination repository. Do not infer source branches or revisions from the current checkout, invent missing evidence, or import vendor credentials, unrelated records, or local assessments as original scanner evidence. Do not retrieve or test credentials or apply suggested fixes.
-## Snyk Open Source
+## Snyk findings
+
+For an existing monitored Open Source or Code project, follow the [Snyk Issues API import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk). With a read-authorized `SNYK_TOKEN`, run `codex-security import snyk PROJECT_ID --snyk-org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a Code project and `--snyk-api-origin` for a regional deployment. Save the complete successful JSON output, preview with `publish findings --to local --provider snyk`, then confirm the local import.
Prefer the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex) when available. Ask its `snyk-findings-export` skill for **SCA only from the repository’s Git root** and save the `snyk-findings-export/v1` bundle. It scans the current workspace through local MCP; it cannot list existing platform projects or retrieve earlier findings. Do not substitute a fresh scan for a request to read a platform backlog. Authentication, relevant Snyk access and the project's package tooling are required.
Import the bundle with `--provider snyk`, choosing `--to local --repository /path/to/project` or `--to cloud --repository https://github.com/example/project`. Use a stable repository/branch/scan-target/acquisition namespace such as `github.com/example/project/main/root/plugin-sca`. Check the bundle's scan outcomes, collection completeness and limitations alongside the preview. Only Open Source SCA vulnerability records are supported; other categories are explicit exclusions. Preserve the native MCP record and unavailable fields. MCP descriptions may be shortened and alternate dependency paths omitted; do not reconstruct missing evidence. Plugin v1 paths are target-relative without a Git-root offset, so the importer keeps them in original evidence instead of repository locations. Use a distinct source key for each scan target. Ignore status is a source policy decision, not a Codex assessment or a fix.
-For CLI automation, prefer `snyk test --file=package.json --json-file-output=snyk-open-source.json` from the selected repository root. Exit 1 means vulnerabilities were found; stop on other nonzero exits instead of importing a stale file. The existing `--provider snyk` autodetects native JSON (one project or an `--all-projects` array), plugin JSON and Open Source SARIF. Native JSON preserves per-dependency-path records and remediation fields; do not use `--group-issues`. Project errors stop import. Native JSON paths also lack a Git-root offset and stay in original evidence. Only **Open Source SCA vulnerabilities** are imported: licenses, Code, Container, IaC and platform backlog ingestion are outside this adapter.
+For CLI automation, prefer `snyk test --file=package.json --json-file-output=snyk-open-source.json` from the selected repository root. Exit 1 means vulnerabilities were found; stop on other nonzero exits instead of importing a stale file. The existing `--provider snyk` autodetects native JSON (one project or an `--all-projects` array), plugin JSON and Open Source SARIF. Native JSON preserves per-dependency-path records and remediation fields; do not use `--group-issues`. Project errors stop import. Native JSON paths also lack a Git-root offset and stay in original evidence. These workspace scan formats import Open Source SCA vulnerabilities.
Use one format consistently per repository, branch and scan target, with a stable source key such as `github.com/example/project/main/root/native-sca`. Plugin, native JSON and SARIF have distinct identities; use separate keys when switching, without claiming cross-format deduplication or removal of older records. Existing `snyk test --sarif-file-output=snyk-open-source.sarif` reports remain a compatibility path. SARIF groups advisory occurrences and exposes one package coordinate, so prefer JSON for acquisition. Its target-relative manifest paths lack a Git-root offset and stay in original evidence with synthetic line numbers, without being projected as repository locations or package manifest paths.
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 630fb8beb..edd993ca3 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -709,6 +709,8 @@ Use `normalizeSelectedSemgrepPlatformFindings` for selected SAST findings from s
Semgrep Web API responses. See the [Semgrep SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk).
Use `selectSemgrepPlatformFindings` to [save a selection for the local CLI](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#existing-platform-findings).
Use `collectSemgrepPlatformFindings` to [collect one project at an explicit ref](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#collect-a-platform-project-and-branch) for a single product (default `sast`).
+Use `import snyk` to [collect existing Open Source or Code issues](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk) for local import.
+For a private repository with a verified SCM, pass its URL and `platform: "gitlab"` or `"github"` in `sourceRepositories` to match standard SSH clone URLs.
This does not affect scan publishing or the existing GitHub alert collector.
The SDK also exposes `prepareExternalPublication(file, options)` for supported
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index b7015ffdb..45712e17d 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1340,7 +1340,7 @@ Each guide shows how to preview its input for a local repository. Follow the [sh
to confirm the import and read the resulting records.
Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` to enable `publish findings`,
-`findings imported`, `import sonar`, `import semgrep`, and `import github-advisories`. Only `1`
+`findings imported`, `import sonar`, `import semgrep`, `import snyk`, and `import github-advisories`. Only `1`
enables these commands in help and schemas. The SDK's corresponding operations
require the flag in their effective environment. Pure normalizers, file readers,
and the existing `import github` alert collector remain available independently.
@@ -1455,7 +1455,14 @@ readback verify source-record identity and evidence. Codex assessment and
visibility in the shared Cloud Findings view are separate. `cloudUrl`, when
available, links to the destination repository in Cloud.
-### Import Snyk Open Source findings
+### Import Snyk findings
+
+For an existing monitored Snyk project, use
+`codex-security import snyk PROJECT_ID --snyk-org ORG_ID --source-repository-url URL --format json`
+and save its output for `publish findings --to local --provider snyk`. Set
+`SNYK_TOKEN` with read access. The default product is Open Source. Select
+`--snyk-product code` for Code and `--snyk-api-origin` for a regional API
+(default `https://api.snyk.io`). See the [hosted import example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk).
Use `--provider snyk` for Open Source SCA vulnerabilities. Native CLI JSON, plugin
exports, and Open Source SARIF can produce different occurrence IDs. Use a
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 120b25654..cceca9ecd 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -33,6 +33,9 @@ const distModules = [
"inspector-findings",
"continuum-findings",
"snyk-findings",
+ "snyk-rest-findings",
+ "snyk-rest-v1",
+ "snyk-token-origin",
"scanner-repository-url",
"semgrep-findings",
"semgrep-guardian-findings",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 40628c955..92bc12c3e 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -232,6 +232,10 @@ import {
GITHUB_ADVISORY_STATES,
importGitHubAdvisories,
} from "./github-advisories.js";
+import {
+ collectSnykIssues,
+ SNYK_REST_ISSUES_FORMAT,
+} from "./snyk-rest-findings.js";
import type { HostedScannerHttpOptions } from "./hosted-scanner-http.js";
import { semgrepPlatformFormat } from "./semgrep-platform-findings.js";
import {
@@ -2128,7 +2132,7 @@ export async function main(
let frameworkExit: number | undefined;
const frameworkCapture = captureOutput();
let rawExportOutput = false;
- let escapeSemgrepOutput = false;
+ let escapeHostedOutput = false;
let batchedVerification = false;
let deferredVerificationDiagnostic: string | undefined;
let streamedLogs: Awaited<ReturnType<typeof readSavedScanLogs>> | undefined;
@@ -3985,7 +3989,7 @@ export async function main(
});
const imports = Cli.create("import", {
description: importsEnabled
- ? "Import Sonar security issues or read hosted Semgrep and GitHub findings."
+ ? "Import Sonar security issues or read hosted Semgrep, Snyk, and GitHub findings."
: "Read GitHub code scanning alerts.",
}).command("github", {
description: "Read GitHub code scanning alerts without changing GitHub.",
@@ -4069,7 +4073,7 @@ export async function main(
});
function registerOptInCollectors() {
async function collect<T>(
- provider: "GitHub advisory" | "Semgrep",
+ provider: "GitHub advisory" | "Semgrep" | "Snyk",
fail: (error: {
code: string;
message: string;
@@ -4090,9 +4094,11 @@ export async function main(
const diagnostic = interrupted
? `${provider} import ${interrupted === 130 ? "canceled" : "terminated"}.`
: message;
- errorOutput.write(
- `codex-security: ${provider === "Semgrep" ? escapeTerminalText(diagnostic) : diagnostic}\n`,
- );
+ const terminalDiagnostic =
+ provider === "Semgrep" || provider === "Snyk"
+ ? escapeTerminalText(diagnostic)
+ : diagnostic;
+ errorOutput.write(`codex-security: ${terminalDiagnostic}\n`);
if (argv.includes("--full-output")) {
structuredError = true;
return fail({
@@ -4100,7 +4106,8 @@ export async function main(
provider === "GitHub advisory"
? "GITHUB_IMPORT_FAILED"
: "HOSTED_IMPORT_FAILED",
- message: provider === "Semgrep" ? errorMessage(error) : message,
+ message:
+ provider === "GitHub advisory" ? message : errorMessage(error),
exitCode,
});
}
@@ -4181,6 +4188,10 @@ export async function main(
environment: dependencies.environment,
fetch: dependencies.hostedScannerFetch,
};
+ function setHostedOutputFormat(format?: string) {
+ escapeHostedOutput =
+ format === "md" || (format === "toon" && output.isTTY === true);
+ }
const semgrepReport = z
.object({
format: z.literal(semgrepPlatformFormat),
@@ -4201,6 +4212,67 @@ export async function main(
),
})
.optional();
+ imports.command("snyk", {
+ description:
+ "Read Snyk Open Source or Code issues for one monitored project.",
+ hint: "Requires SNYK_TOKEN. Save complete --format json output and import it with publish findings --to local --provider snyk.",
+ destructive: false,
+ mcp: false,
+ args: z.object({
+ project: z.string().min(1).describe("Snyk project ID."),
+ }),
+ options: z.object({
+ snykOrg: optionValue("--snyk-org").describe("Snyk organization ID."),
+ snykProduct: z
+ .enum(["open-source", "code"])
+ .default("open-source")
+ .describe("Snyk product to retrieve."),
+ snykApiOrigin: optionValue("--snyk-api-origin")
+ .optional()
+ .describe(
+ "Official regional Snyk API origin (default: https://api.snyk.io).",
+ ),
+ sourceRepositoryUrl: optionValue("--source-repository-url").describe(
+ "Explicit source-control repository mapping for the monitored project.",
+ ),
+ }),
+ output: z
+ .object({
+ format: z.literal(SNYK_REST_ISSUES_FORMAT),
+ apiVersion: z.string(),
+ apiOrigin: z.string(),
+ organizationId: z.string(),
+ projectId: z.string(),
+ product: z.enum(["open-source", "code"]),
+ sourceRepositoryUrl: z.string(),
+ complete: z.literal(true),
+ projectJson: z.string(),
+ targetJson: z.string(),
+ pages: z.array(
+ z.object({
+ startingAfter: z.string().nullable(),
+ responseJson: z.string(),
+ }),
+ ),
+ })
+ .optional(),
+ run: ({ args, options, error, format }) => {
+ setHostedOutputFormat(format);
+ return collect("Snyk", error, (signal) =>
+ collectSnykIssues(
+ {
+ projectId: args.project,
+ organizationId: options.snykOrg,
+ product: options.snykProduct,
+ apiOrigin: options.snykApiOrigin,
+ sourceRepositoryUrl: options.sourceRepositoryUrl,
+ signal,
+ },
+ http,
+ ),
+ );
+ },
+ });
imports.command("semgrep", {
description:
"Read a full Semgrep Platform project and ref through the Web API.",
@@ -4232,8 +4304,7 @@ export async function main(
}),
output: semgrepReport,
run: ({ args, options, error, format }) => {
- escapeSemgrepOutput =
- format === "md" || (format === "toon" && output.isTTY === true);
+ setHostedOutputFormat(format);
return collect("Semgrep", error, (signal) =>
collectSemgrepPlatformFindings(
{
@@ -7244,7 +7315,9 @@ export async function main(
const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;
const optInCollector =
command === "import" &&
- ["github-advisories", "semgrep", "sonar"].includes(subcommand ?? "");
+ ["github-advisories", "semgrep", "snyk", "sonar"].includes(
+ subcommand ?? "",
+ );
if (
command === "import" &&
subcommand !== "sonar" &&
@@ -7530,7 +7603,7 @@ export async function main(
renderedOutput = failureOutput.text();
}
let frameworkOutput = frameworkCapture.text();
- if (escapeSemgrepOutput)
+ if (escapeHostedOutput)
frameworkOutput = escapeTerminalText(frameworkOutput, true);
const writeUpdateNotice = () => {
if (notice === undefined || batchedVerification) return;
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index 5afd42aa5..4f3a86d62 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -29,6 +29,7 @@ import {
cloudRepositoryUrlKey,
requireSafeJsonInteger,
repositoryUrlKey,
+ validateExternalEvidence,
} from "./external-import-contract.js";
import type {
ExternalFindingEvidence,
@@ -62,6 +63,11 @@ import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";
import { sonarRepositoryUrls } from "./sonar-findings.js";
import { isRecord } from "./record.js";
import { dependabotRepository } from "./github-dependabot-findings.js";
+import {
+ type SnykIssuesFindings,
+ snykRestImportRepository,
+ snykRestCheckoutMatches,
+} from "./snyk-rest-findings.js";
import {
bundledPluginRoot,
canonicalConfigPath,
@@ -548,15 +554,16 @@ async function requireMatchingRepository(
strictSources: ReadonlyMap<string, Provider>,
hostedSources: readonly ExternalSourceRepository[],
platformFor: (source: ExternalSourceRepository, bound: boolean) => Provider,
+ snyk: ReturnType<typeof snykRestImportRepository>,
protectedRoots: string[],
environment: WorkbenchCommandOptions["environment"],
signal?: AbortSignal,
possibleSshHost?: string,
fetchRemotes?: readonly ConfiguredFetchRemote[],
): Promise<boolean> {
- if (sources.length === 0 && hostedSources.length === 0) return false;
+ if (!snyk && sources.length === 0 && hostedSources.length === 0) return false;
let allSourcesMatched = true;
- if (hostedSources.length) {
+ if (snyk || hostedSources.length) {
if (!(await hasGitMetadata(repository, signal))) return false;
const remotes = await readHostedGitRemotes(
repository,
@@ -567,6 +574,16 @@ async function requireMatchingRepository(
environment,
signal,
);
+ if (snyk) {
+ if (
+ remotes &&
+ !remotes.some((remote) => snykRestCheckoutMatches(snyk, remote))
+ )
+ throw new CodexSecurityError(
+ `Imported repository ${JSON.stringify(snyk.url)} does not match a configured remote of ${repository}. Select the matching local repository.`,
+ );
+ return remotes !== undefined;
+ }
allSourcesMatched = remotes !== undefined;
if (remotes) {
for (const source of hostedSources)
@@ -642,6 +659,7 @@ export function sonarCheckoutMatchesSource(
new Map(),
[],
() => "sonar",
+ undefined,
[...protectedRoots],
environment,
signal,
@@ -712,8 +730,8 @@ export async function prepareNormalizedLocalImport(
/** @internal Prepare evidence using settings captured by either local import entrypoint. */
export async function prepareLocalImport(
- input: ExternalFindings,
- options: NormalizedLocalImportOptions,
+ input: ExternalFindings & Partial<SnykIssuesFindings>,
+ options: NormalizedLocalImportOptions & { sourceRepositoryUrl?: string },
dependencies: LocalExternalImportDependencies,
readerSources = snapshotSourceRepositories(dependencies.sourceRepositories),
parsedSources: readonly ExternalSourceRepository[] = [],
@@ -721,6 +739,17 @@ export async function prepareLocalImport(
): Promise<PreparedLocalExternalImport> {
requireIdentity(options.sourceKey, "Source key");
const current = snapshotNormalizedFindings(input, checkStoredNumber);
+ // The JSON snapshot omits inherited or non-enumerable SDK reader properties.
+ if (!("snykRestContext" in current) && "snykRestContext" in input)
+ current.snykRestContext = structuredClone(input.snykRestContext);
+ if (options.provider === "snyk" || current.snykRestContext !== undefined) {
+ for (const key of [
+ "sourceRepositoryUrl",
+ "sourceRepositoryPlatform",
+ ] as const)
+ if (key in input && !(key in current))
+ Object.assign(current, { [key]: structuredClone(input[key]) });
+ }
let dependabotSource: string | undefined;
const identities = new Set<string>();
for (const finding of current.findings) {
@@ -1143,6 +1172,36 @@ export async function prepareLocalImport(
url: dependabotSource,
platform: "github",
});
+ const snyk = snykRestImportRepository(
+ current,
+ options.provider,
+ [
+ ...sources.keys(),
+ ...(options.sourceRepositoryUrl === undefined
+ ? []
+ : [options.sourceRepositoryUrl]),
+ ],
+ readerSources,
+ (finding, source) => {
+ finding.evidence.source_data = source;
+ },
+ );
+ if (snyk) {
+ // Preserve reader display fields while validating their complete native evidence.
+ for (const { evidence } of current.findings)
+ validateExternalEvidence(structuredClone(evidence), "local");
+ } else if (options.provider === "snyk" && current.sourceRepositoryUrl) {
+ const declared = { url: current.sourceRepositoryUrl };
+ const native = current.findings.flatMap((finding) =>
+ localFindingRepositories("snyk", finding),
+ );
+ for (const source of [declared, ...native])
+ if (!sources.has(source.url)) sources.set(source.url, source);
+ if (!sameRepositories(sources.keys()))
+ throw new CodexSecurityError(
+ "The normalized repository does not match the Snyk reader's repository.",
+ );
+ }
const ordinarySources = [...sources.values()];
// A reader can identify the VCS for both a hosted project and an ordinary row.
const loosePlatformFor = localRepositoryPlatform(
@@ -1158,6 +1217,7 @@ export async function prepareLocalImport(
strictSources,
hosted,
(source, bound) => (bound ? platformFor(source) : loosePlatformFor(source)),
+ snyk,
workbenchOptions.protectedRoot,
workbenchOptions.environment,
dependencies.signal,
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index aaf1099d5..1640cfcfb 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -37,6 +37,7 @@ import {
isSemgrepPlatformEvidence,
semgrepPlatformReportRepository,
} from "./semgrep-platform-findings.js";
+import { isSnykRestFinding, isSnykRestReport } from "./snyk-rest-findings.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { requireExternalImports } from "./external-imports-feature.js";
import {
@@ -510,21 +511,24 @@ function storedFindingId(finding: ExternalFinding): string {
return "";
}
-function rejectLocalSemgrepReports(
+function rejectLocalScannerReports(
input: ExternalFindings,
provider: string,
): void {
if (!input || (typeof input !== "object" && typeof input !== "function"))
return;
+ const stored = (row: ExternalFinding) => ({
+ source_finding_id: storedFindingId(row),
+ evidence: row.evidence,
+ });
const isPlatform = (row: ExternalFinding) => {
if (!row) return false;
- const id = storedFindingId(row);
- const evidence = row.evidence;
+ const finding = stored(row);
return (
- /^semgrep-guardian:[0-9a-f]{64}$/u.test(id) ||
- ownData(ownData(evidence, "source_data"), "format") ===
+ /^semgrep-guardian:[0-9a-f]{64}$/u.test(finding.source_finding_id) ||
+ ownData(ownData(finding.evidence, "source_data"), "format") ===
guardianSelectionFormat ||
- isSemgrepPlatformEvidence({ source_finding_id: id, evidence }, provider)
+ isSemgrepPlatformEvidence(finding, provider)
);
};
const hasPlatformRows = (rows: ExternalFinding[]) =>
@@ -537,6 +541,8 @@ function rejectLocalSemgrepReports(
throw new CodexSecurityError(
"Semgrep Platform findings require a local import.",
);
+ if (isSnykRestReport(input, (row) => row && isSnykRestFinding(stored(row))))
+ throw new CodexSecurityError("Snyk REST findings require a local import.");
}
export async function prepareExternalPublication(
@@ -547,7 +553,7 @@ export async function prepareExternalPublication(
requireExternalImports(dependencies.environment);
const settings = snapshotImportOptions(options);
const parsed = await readExternalFindings(path, settings);
- rejectLocalSemgrepReports(parsed.findings, settings.provider);
+ rejectLocalScannerReports(parsed.findings, settings.provider);
return preparePublicationInput(
parsed.publication ??
normalizedPublicationInput(parsed.findings, settings.provider),
@@ -565,7 +571,7 @@ export async function prepareNormalizedExternalPublication(
): Promise<PreparedExternalPublication> {
requireExternalImports(dependencies.environment);
const settings = snapshotImportOptions(options);
- rejectLocalSemgrepReports(input, settings.provider);
+ rejectLocalScannerReports(input, settings.provider);
return preparePublicationInput(
normalizedPublicationInput(input, settings.provider),
settings,
@@ -827,7 +833,7 @@ function normalizedPublicationInput(
: undefined;
if (reader) native = reader.snapshot;
const original = historicalPublication(native);
- if (original) rejectLocalSemgrepReports(original.parsed, provider);
+ if (original) rejectLocalScannerReports(original.parsed, provider);
try {
validatePublicationFindings(current, validateExternalEvidence);
} catch (error) {
@@ -840,7 +846,7 @@ function normalizedPublicationInput(
// Only the old selection can be reviewed when fresh validation failed.
current = { read: original.parsed.read, findings: [], excluded: [] };
}
- rejectLocalSemgrepReports(current, provider);
+ rejectLocalScannerReports(current, provider);
const identity = publicationIdentity(current);
return {
current,
@@ -1187,7 +1193,7 @@ async function preparePublicationInput(
!verifiableLegacyMetadata(originalParsed, true)
)
throw unmatchedPreviousNumbers();
- rejectLocalSemgrepReports({ ...parsed, findings: saved }, options.provider);
+ rejectLocalScannerReports({ ...parsed, findings: saved }, options.provider);
return content;
}
@@ -1222,7 +1228,7 @@ async function preparePublicationInput(
!verifiableLegacyMetadata(originalParsed, false)
)
throw unmatchedPreviousNumbers();
- rejectLocalSemgrepReports({ ...parsed, findings: saved }, options.provider);
+ rejectLocalScannerReports({ ...parsed, findings: saved }, options.provider);
content.legacyApproval = true;
content.inputProjection = {
identityFormat: 2,
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index 951cb0e45..3bf7cbd7e 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -157,7 +157,7 @@ export async function readExternalFindings(
const provider = options.provider;
const findings =
provider === "snyk"
- ? await readSnykFindings(path, target)
+ ? await readSnykFindings(path, target, references)
: await readEndorFindings(path, target);
return {
findings,
diff --git a/sdk/typescript/src/hosted-git-repository.ts b/sdk/typescript/src/hosted-git-repository.ts
index 17a6199ae..180e31bb1 100644
--- a/sdk/typescript/src/hosted-git-repository.ts
+++ b/sdk/typescript/src/hosted-git-repository.ts
@@ -240,7 +240,7 @@ export function hostedRepositoryUrlKey(
}
/** The Git HTTP Host and TLS server name can differ from the web URL's parsed IP literal. */
-function ambiguousGitIpHost(url: string): boolean {
+export function ambiguousGitIpHost(url: string): boolean {
const host = URL.parse(url)?.hostname;
if (!host || (!isIPv4(host) && !host.startsWith("["))) return false;
const authority = /^https?:\/\/([^/?#]*)/iu.exec(url)?.[1] ?? "";
diff --git a/sdk/typescript/src/hosted-scanner-http.ts b/sdk/typescript/src/hosted-scanner-http.ts
index 455fcca7a..d24086965 100644
--- a/sdk/typescript/src/hosted-scanner-http.ts
+++ b/sdk/typescript/src/hosted-scanner-http.ts
@@ -1,3 +1,4 @@
+import { canonicalNumber } from "./external-import-contract.js";
import { CodexSecurityError } from "./errors.js";
import { normalizeHostedGitRepositoryUrl } from "./hosted-git-repository.js";
import { importEnvironmentSetting } from "./external-imports-feature.js";
@@ -19,6 +20,15 @@ export function hostedNumberToken(value: unknown): string | undefined {
return wireJson.isRawJSON(value) ? value.rawJSON : undefined;
}
+/** Store native evidence by exact numeric value, independently of its wire spelling. */
+export function stringifyHostedEvidence(value: unknown): string {
+ return JSON.stringify(value, (_key, field: unknown) =>
+ wireJson.isRawJSON(field)
+ ? wireJson.rawJSON(canonicalNumber(field.rawJSON))
+ : field,
+ );
+}
+
/** Keep vendor numeric IDs and evidence exact when a response is saved as JSON. */
export function parseHostedScannerJson(source: string): unknown {
return JSON.parse(
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index e6664c2a8..2b483d7aa 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -360,6 +360,15 @@ export {
normalizeSnykSarif,
readSnykFindings,
} from "./snyk-findings.js";
+export {
+ collectSnykIssues,
+ normalizeSnykIssues,
+ SNYK_REST_ISSUES_FORMAT,
+ type CollectSnykIssuesOptions,
+ type SnykIssuesExport,
+ type SnykIssuesFindings,
+ type SnykIssuesProduct,
+} from "./snyk-rest-findings.js";
export {
normalizeSemgrepFindings,
normalizeSemgrepSarif,
diff --git a/sdk/typescript/src/snyk-findings.ts b/sdk/typescript/src/snyk-findings.ts
index a9b1b17f9..927f37843 100644
--- a/sdk/typescript/src/snyk-findings.ts
+++ b/sdk/typescript/src/snyk-findings.ts
@@ -1,6 +1,16 @@
import type { ExternalImportTarget } from "./external-import-contract.js";
import { validateExternalEvidence } from "./external-import-contract.js";
-import type { ExternalFindings } from "./external-findings.js";
+import type {
+ ExternalFindings,
+ ExternalSourceRepository,
+} from "./external-findings.js";
+import {
+ encodeSnykV1File,
+ isSnykRestFormat,
+ parseSnykReport,
+ SNYK_REST_ISSUES_V1,
+} from "./snyk-rest-v1.js";
+import type { SnykIssuesFindings } from "./snyk-rest-findings.js";
import { isRecord } from "./record.js";
import {
array,
@@ -514,10 +524,23 @@ export function normalizeSnykJson(
export async function readSnykFindings(
path: string,
target: ExternalImportTarget = "cloud",
-): Promise<ExternalFindings> {
- const input = await readScannerJson(path);
+ references: readonly ExternalSourceRepository[] = [],
+): Promise<ExternalFindings & Partial<SnykIssuesFindings>> {
+ const input = await readScannerJson(path, parseSnykReport);
if (Array.isArray(input)) return normalizeSnykJson(input, target);
const document = record(input, "Snyk findings");
+ if (isSnykRestFormat(document["format"])) {
+ if (target !== "local")
+ throw new Error("Snyk REST issues currently support local import only.");
+ const { normalizeSnykIssues } = await import("./snyk-rest-findings.js");
+ return normalizeSnykIssues(
+ document["format"] === SNYK_REST_ISSUES_V1
+ ? encodeSnykV1File(document)
+ : document,
+ target,
+ references,
+ );
+ }
if (document["format"] === "snyk-findings-export/v1")
return normalizeSnykFindingsExport(document, target);
if (document["version"] === "2.1.0")
diff --git a/sdk/typescript/src/snyk-rest-findings.ts b/sdk/typescript/src/snyk-rest-findings.ts
new file mode 100644
index 000000000..f1597eccd
--- /dev/null
+++ b/sdk/typescript/src/snyk-rest-findings.ts
@@ -0,0 +1,1359 @@
+import {
+ validateExternalEvidence,
+ type ExternalImportTarget,
+} from "./external-import-contract.js";
+import {
+ snapshotSourceRepositories,
+ type ExternalFinding,
+ type ExternalFindings,
+ type ExternalSourceRepository,
+} from "./external-findings.js";
+import type { ImportedPackage, Provider } from "./external-import-models.js";
+import {
+ SNYK_REST_ISSUES_FORMAT,
+ encodeSnykV1File,
+ isSnykRestFormat,
+ SNYK_REST_ISSUES_V1,
+ originalSnykEvidence,
+ readSnykRestDocument,
+} from "./snyk-rest-v1.js";
+import { snykRepositoryUrls } from "./snyk-findings.js";
+import { requireExternalImports } from "./external-imports-feature.js";
+import { isGitHubCloudHost } from "./git-remote.js";
+import {
+ gitPathToHttpPath,
+ ambiguousGitIpHost,
+ gitServiceHostname,
+ gitTransportBytes,
+ hostedRepositoryMatches,
+ hostedRepositoryUrlKey,
+ isPublicGitHost,
+ normalizeHostedGitRepositoryUrl,
+} from "./hosted-git-repository.js";
+import {
+ hostedNumberToken,
+ parseHostedScannerJson,
+ stringifyHostedEvidence,
+ hostedScannerHttp,
+ hostedRepositoryUrl,
+ type HostedScannerHttpOptions,
+} from "./hosted-scanner-http.js";
+import { isRecord } from "./record.js";
+import { legacyDecimalInteger } from "./hosted-scanner-v1.js";
+import { isSafeNonNegativeInteger } from "./value.js";
+import { checkSnykTokenOrigin, snykApiToken } from "./snyk-token-origin.js";
+import { regexes } from "zod/v4/core";
+import {
+ array,
+ normalizeRecords,
+ record as scannerRecord,
+ hostedRepositoryPath,
+ requiredText,
+ scannerSeverity,
+ stableId,
+ strings,
+ text,
+} from "./scanner-import.js";
+
+export interface SnykIssuesFindings extends ExternalFindings {
+ sourceRepositoryUrl: string;
+ sourceRepositoryPlatform?: "github" | "other";
+ snykRestContext?: Record<string, unknown>;
+}
+export { SNYK_REST_ISSUES_FORMAT, isSnykRestFormat } from "./snyk-rest-v1.js";
+const issueTimestamp = new RegExp(
+ regexes.datetime({ offset: true }).source,
+ "i",
+);
+const apiVersion = "2026-03-25";
+const formatVersion = { format: SNYK_REST_ISSUES_FORMAT, apiVersion } as const;
+const defaultOrigin = "https://api.snyk.io";
+const origins = new Set([
+ defaultOrigin,
+ "https://api.us.snyk.io",
+ "https://api.eu.snyk.io",
+ "https://api.au.snyk.io",
+]);
+// Some project origins name a provider, while app integrations identify a deployment.
+const githubDeployments = ["github-cloud", "github-server"];
+const scmOrigins = new Map<string, readonly string[]>([
+ ["azure-repos", ["azure-repos"]],
+ ["bitbucket-cloud", ["bitbucket-cloud"]],
+ ["bitbucket-connect-app", ["bitbucket-cloud"]],
+ ["bitbucket-server", ["bitbucket-server"]],
+ ["github", githubDeployments],
+ ["github-app", githubDeployments],
+ ["github-cloud-app", ["github-cloud"]],
+ ["github-enterprise", githubDeployments],
+ ["github-server-app", ["github-server"]],
+ ["gitlab", ["gitlab"]],
+]);
+const openSourceProjects = new Set([
+ "cargo",
+ "cocoapods",
+ "composer",
+ "conan",
+ "cpp",
+ "golang",
+ "golangdep",
+ "gomodules",
+ "govendor",
+ "gradle",
+ "hex",
+ "maven",
+ "npm",
+ "nuget",
+ "paket",
+ "pip",
+ "pipenv",
+ "pnpm",
+ "poetry",
+ "pub",
+ "rubygems",
+ "sbt",
+ "swift",
+ "unmanaged",
+ "uv",
+ "yarn",
+ "yarn-workspace",
+]);
+const issueTypes = {
+ "open-source": "package_vulnerability",
+ code: "code",
+} as const;
+export type SnykIssuesProduct = keyof typeof issueTypes;
+
+interface SnykScope {
+ organizationId: string;
+ projectId: string;
+ product: SnykIssuesProduct;
+ sourceRepositoryUrl: string;
+}
+
+export interface CollectSnykIssuesOptions extends Omit<SnykScope, "product"> {
+ product?: SnykIssuesProduct;
+ token?: string;
+ apiOrigin?: string;
+ signal?: AbortSignal;
+}
+
+type Resource = Record<string, unknown>;
+
+export interface SnykIssuesExport extends SnykScope {
+ format: typeof SNYK_REST_ISSUES_FORMAT;
+ apiVersion: typeof apiVersion;
+ apiOrigin: string;
+ complete: true;
+ projectJson: string;
+ targetJson: string;
+ pages: { startingAfter: string | null; responseJson: string }[];
+}
+
+function isUuid(value: unknown): value is string {
+ return (
+ typeof value === "string" &&
+ /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu.test(value)
+ );
+}
+
+function uuid(value: unknown, label: string): string {
+ if (!isUuid(value)) throw new Error(`${label} must be a UUID.`);
+ return value.toLowerCase();
+}
+
+type Scope = SnykScope & { apiOrigin: string };
+
+function scope(
+ input: Resource | CollectSnykIssuesOptions,
+ origin: unknown,
+ product: unknown = input["product"],
+): Scope {
+ const apiOrigin = requiredText(origin, "Snyk API origin").replace(/\/$/u, "");
+ if (!origins.has(apiOrigin))
+ throw new Error("Select a documented Snyk regional HTTPS API origin.");
+ if (product !== "open-source" && product !== "code")
+ throw new Error("Snyk product must be open-source or code.");
+ return {
+ apiOrigin,
+ product,
+ sourceRepositoryUrl: hostedRepositoryUrl(
+ input["sourceRepositoryUrl"],
+ "Snyk source repository URL",
+ ),
+ organizationId: uuid(input["organizationId"], "Snyk organization ID"),
+ projectId: uuid(input["projectId"], "Snyk project ID"),
+ };
+}
+
+function endpoint(selected: Scope, route: string) {
+ const url = new URL(
+ `/rest/orgs/${selected.organizationId}/${route}`,
+ selected.apiOrigin,
+ );
+ url.searchParams.set("version", apiVersion);
+ return url;
+}
+
+function issuesEndpoint(selected: Scope) {
+ const url = endpoint(selected, "issues");
+ url.searchParams.set("scan_item.type", "project");
+ url.searchParams.set("scan_item.id", selected.projectId);
+ url.searchParams.set("type", issueTypes[selected.product]);
+ url.searchParams.set("status", "open,resolved");
+ url.searchParams.set("limit", "100");
+ if (selected.product === "code")
+ url.searchParams.set("include_code_flows", "true");
+ return url;
+}
+
+function jsonApi(input: unknown, label: string) {
+ const document = record(input, label);
+ if ("errors" in document)
+ throw new Error(
+ `${label}: JSON:API errors: ${JSON.stringify(document["errors"])}`,
+ );
+ return document;
+}
+
+function resourceIdentifier(resource: Resource, type: string) {
+ if (resource["type"] !== type)
+ throw new Error(`Expected a Snyk ${type} resource.`);
+ return resource["id"];
+}
+
+function resourceId(resource: Resource, type: string) {
+ return uuid(resourceIdentifier(resource, type), `Snyk ${type} ID`);
+}
+
+function relationship(relationships: Resource, name: string) {
+ return record(
+ record(relationships[name], `Snyk ${name} relationship`)["data"],
+ `Snyk ${name} linkage`,
+ );
+}
+
+function checkOrganization(
+ relationships: Resource,
+ selected: Scope,
+ project = false,
+) {
+ const org = relationship(relationships, "organization");
+ if (
+ (org["type"] !== "organization" && !(project && org["type"] === "org")) ||
+ uuid(org["id"], "Snyk organization relationship ID") !==
+ selected.organizationId
+ )
+ throw new Error(
+ "Snyk resource does not belong to the selected organization.",
+ );
+}
+
+type RepositoryBinding = {
+ url: string;
+ platform?: "github" | "other";
+ gitlab?: boolean;
+ nativeUrl?: string;
+};
+
+function scmUrl(
+ binding: RepositoryBinding,
+ remote: string,
+): string | undefined {
+ try {
+ const hostname = new URL(binding.url).hostname;
+ if (hostname === "dev.azure.com") {
+ const uri =
+ /^(?:ssh|git\+ssh|ssh\+git):\/\/git@([^/:]+)(?::22)?\/(v3\/.+)$/u.exec(
+ remote,
+ );
+ const address = uri ?? /^git@([^/:]+):(v3\/.+)$/u.exec(remote);
+ if (address && address[1]!.toLowerCase() === "ssh.dev.azure.com") {
+ // Azure clone paths may already contain URL escapes in the upload-pack path.
+ const path = gitPathToHttpPath(
+ gitTransportBytes(address[2]!, uri === null),
+ ).replace(/%25(?=[\da-f]{2})/giu, "%");
+ const parts = /^v3\/([^/]+)\/([^/]+)\/([^/]+)$/u.exec(path);
+ if (parts)
+ return hostedRepositoryUrl(
+ `https://dev.azure.com/${parts[1]}/${parts[2]}/_git/${parts[3]}`,
+ "Snyk target URL",
+ );
+ }
+ }
+ const url = normalizeHostedGitRepositoryUrl(
+ remote,
+ binding.url,
+ binding.platform === "github" || binding.gitlab === true,
+ );
+ return hostedRepositoryUrl(url, "Snyk target URL");
+ } catch {
+ return undefined;
+ }
+}
+
+export function snykRestRepositoryMatches(
+ binding: RepositoryBinding,
+ remote: string,
+): boolean {
+ const candidate = scmUrl(binding, remote);
+ if (
+ !candidate ||
+ ambiguousGitIpHost(candidate) ||
+ ambiguousGitIpHost(binding.url)
+ )
+ return false;
+ const key = (url: string) =>
+ hostedRepositoryUrlKey(url, binding.platform === "github", binding.gitlab);
+ return key(binding.url) === key(candidate);
+}
+
+/** Git's HTTP checkout may use credentials or spell out the default port. */
+export function snykRestCheckoutMatches(
+ binding: RepositoryBinding,
+ remote: string,
+): boolean {
+ const url = /^https?:\/\//iu.test(remote) ? remote : scmUrl(binding, remote);
+ return url !== undefined && hostedRepositoryMatches(binding, url);
+}
+
+function reportedScm(url: string, origin: string) {
+ const host = gitServiceHostname(new URL(url).hostname);
+ const publicGitHub = isGitHubCloudHost(host);
+ const custom =
+ !isPublicGitHost(host) &&
+ host !== "dev.azure.com" &&
+ !/^[a-z\d-]+\.visualstudio\.com$/u.test(host);
+ const enterprise =
+ (custom || publicGitHub) &&
+ (origin === "github-enterprise" || origin === "github-server-app");
+ const gitlab = origin === "gitlab" && (custom || host === "gitlab.com");
+ const github = origin.startsWith("github") && (custom || publicGitHub);
+ return { custom, publicGitHub, enterprise, gitlab, github };
+}
+
+function trustedScmBinding(
+ url: string,
+ references: readonly ExternalSourceRepository[],
+ allowGitHub: boolean,
+ allowGitLab: boolean,
+): RepositoryBinding {
+ for (const hint of references) {
+ const github = allowGitHub && hint.platform === "github";
+ const gitlab = allowGitLab && hint.platform === "gitlab";
+ if (github || gitlab) {
+ const candidate: RepositoryBinding = {
+ url,
+ platform: github ? "github" : undefined,
+ gitlab,
+ };
+ if (snykRestRepositoryMatches(candidate, hint.url)) return candidate;
+ }
+ }
+ return { url };
+}
+
+function checkRemote(
+ remote: unknown,
+ selected: Scope,
+ origin: string,
+ references: readonly ExternalSourceRepository[],
+) {
+ if (remote === null || remote === "") return;
+ const url = requiredText(remote, "Snyk target URL");
+ // Snyk monitor can render a local path and a Git server as the same HTTP target.
+ if (
+ origin === "cli" &&
+ selected.product === "open-source" &&
+ /^http:\/\//iu.test(url)
+ )
+ throw new Error(
+ "Snyk CLI HTTP target URL cannot verify a repository. Set an explicit HTTPS URL with snyk monitor --remote-repo-url.",
+ );
+ const { custom, publicGitHub, enterprise, gitlab, github } = reportedScm(
+ selected.sourceRepositoryUrl,
+ origin,
+ );
+ const platformNeutral = !scmOrigins.has(origin);
+ const binding: RepositoryBinding =
+ custom && (platformNeutral || references.length > 0)
+ ? trustedScmBinding(
+ selected.sourceRepositoryUrl,
+ references,
+ platformNeutral || github,
+ platformNeutral || gitlab,
+ )
+ : {
+ url: selected.sourceRepositoryUrl,
+ platform: publicGitHub || enterprise ? "github" : undefined,
+ gitlab,
+ };
+ if (!snykRestRepositoryMatches(binding, url))
+ throw new Error(
+ "Snyk target URL does not match the selected source repository URL.",
+ );
+ return {
+ github,
+ enterprise,
+ gitlab,
+ // Recheck the exact target with the caller's platform mapping at import time.
+ nativeUrl: url,
+ };
+}
+
+function projectContext(project: Resource, selected: Scope) {
+ if (resourceId(project, "project") !== selected.projectId)
+ throw new Error(
+ "Snyk returned a different project from the selected project.",
+ );
+ const attributes = record(project["attributes"], "Snyk project attributes");
+ const manager = requiredText(attributes["type"], "Snyk project type");
+ const origin = requiredText(attributes["origin"], "Snyk project origin");
+ const scm = scmOrigins.has(origin);
+ if (
+ (!scm && origin !== "cli" && origin !== "api") ||
+ (selected.product === "code"
+ ? manager !== "sast"
+ : !openSourceProjects.has(manager))
+ )
+ throw new Error(
+ `Snyk project type ${manager} from ${origin} is not a supported ${selected.product} project.`,
+ );
+ const context = {
+ manager,
+ scm,
+ origin,
+ targetFile: scm ? attributes["target_file"] : null,
+ };
+ const relationships =
+ project["relationships"] === undefined
+ ? undefined
+ : record(project["relationships"], "Snyk project relationships");
+ if (relationships) checkOrganization(relationships, selected, true);
+ const target = relationships?.["target"];
+ const linkage =
+ target === undefined
+ ? null
+ : record(target, "Snyk target relationship")["data"];
+ if (linkage === null)
+ return {
+ ...context,
+ targetId: undefined,
+ lookupTargetId: undefined,
+ expandedUrl: undefined,
+ integration: undefined,
+ };
+ const link = record(linkage, "Snyk target linkage");
+ const expandedUrl =
+ link["attributes"] === undefined
+ ? undefined
+ : record(link["attributes"], "Snyk expanded target attributes")["url"];
+ const targetId = resourceId(link, "target");
+ const integration = checkTargetRelationships(link, selected, origin);
+ return {
+ ...context,
+ targetId,
+ integration,
+ lookupTargetId:
+ expandedUrl == null || expandedUrl === "" ? targetId : undefined,
+ expandedUrl,
+ };
+}
+
+function checkTarget(
+ value: unknown,
+ selected: Scope,
+ {
+ expandedUrl,
+ lookupTargetId,
+ origin,
+ integration,
+ }: ReturnType<typeof projectContext>,
+ references: readonly ExternalSourceRepository[] = [],
+) {
+ if (lookupTargetId === undefined) {
+ if (value !== null)
+ throw new Error(
+ "Unexpected separate Snyk target without a project target lookup.",
+ );
+ return {
+ ...checkRemote(expandedUrl ?? null, selected, origin, references),
+ integrationId: integration?.id,
+ deployment: integration?.deployment,
+ };
+ }
+ const target = record(value, "Snyk target resource");
+ if (resourceId(target, "target") !== lookupTargetId)
+ throw new Error(
+ "Snyk target does not match the selected project's target.",
+ );
+ const fetched = checkTargetRelationships(
+ target,
+ selected,
+ origin,
+ integration?.deployment,
+ );
+ if (integration?.id && fetched?.id && integration.id !== fetched.id)
+ throw new Error(
+ "The fetched Snyk target names a different integration than the project's target.",
+ );
+ const remote = checkRemote(
+ record(target["attributes"], "Snyk target attributes")["url"],
+ selected,
+ origin,
+ references,
+ );
+ return {
+ ...remote,
+ integrationId: fetched?.id ?? integration?.id,
+ deployment: fetched?.deployment ?? integration?.deployment,
+ };
+}
+
+function checkTargetRelationships(
+ target: Resource,
+ selected: Scope,
+ origin: string,
+ linkedDeployment?: string,
+) {
+ if (target["relationships"] === undefined) return;
+ const relationships = record(
+ target["relationships"],
+ "Snyk target relationships",
+ );
+ if (relationships["organization"] !== undefined)
+ checkOrganization(relationships, selected, true);
+ if (relationships["integration"] === undefined) return;
+ const linkage = record(
+ relationships["integration"],
+ "Snyk integration relationship",
+ )["data"];
+ if (linkage === null && !scmOrigins.has(origin)) return;
+ const integration = record(linkage, "Snyk integration linkage");
+ if (integration["type"] !== "integration")
+ throw new Error("Expected a Snyk integration resource.");
+ const attributes = integration["attributes"];
+ // The Targets API allows a null ID on an expanded integration.
+ const id =
+ attributes === undefined || integration["id"] !== null
+ ? uuid(integration["id"], "Snyk integration ID")
+ : undefined;
+ if (attributes === undefined) return { id };
+ const type = requiredText(
+ record(attributes, "Snyk integration attributes")["integration_type"],
+ "Snyk integration type",
+ );
+ const deployments = scmOrigins.get(origin);
+ const claimed = scmOrigins.get(type);
+ if (
+ deployments &&
+ !claimed?.some(
+ (candidate) =>
+ deployments.includes(candidate) &&
+ (linkedDeployment === undefined || linkedDeployment === candidate),
+ )
+ ) {
+ const source = linkedDeployment ? "target linkage" : `${origin} origin`;
+ throw new Error(
+ `Snyk target integration ${type} must be a supported SCM integration for the project's ${source}.`,
+ );
+ }
+ return {
+ id,
+ deployment: deployments && claimed?.length === 1 ? claimed[0] : undefined,
+ };
+}
+
+function pageLinkCursor(
+ link: unknown,
+ endpoint: URL,
+ label: string,
+ cursorName = "starting_after",
+) {
+ const href = requiredText(isRecord(link) ? link["href"] : link, label);
+ const url = new URL(
+ href.startsWith("/orgs/") ? `/rest${href}` : href,
+ endpoint,
+ );
+ if (
+ url.origin !== endpoint.origin ||
+ url.pathname !== endpoint.pathname ||
+ url.username ||
+ url.password ||
+ url.hash
+ )
+ throw new Error(`${label} leaves the selected Issues endpoint.`);
+ for (const [key, value] of url.searchParams) {
+ if (
+ url.searchParams.getAll(key).length !== 1 ||
+ (key !== cursorName && endpoint.searchParams.get(key) !== value)
+ )
+ throw new Error(`${label} changes the selected Issues query.`);
+ }
+ return url.searchParams.get(cursorName);
+}
+
+function nextCursor(value: unknown, endpoint: URL, current: string | null) {
+ if (value === undefined) return null;
+ const links = record(value, "Snyk issue page links");
+ if (links["prev"] != null) {
+ if (current === null)
+ throw new Error("The first Snyk issue page has a previous page link.");
+ pageLinkCursor(
+ links["prev"],
+ endpoint,
+ "Snyk previous page link",
+ "ending_before",
+ );
+ }
+ if (
+ links["self"] != null &&
+ pageLinkCursor(links["self"], endpoint, "Snyk self page link") !== current
+ )
+ throw new Error("Snyk self page link does not match the requested cursor.");
+ if (links["next"] == null) return null;
+ return requiredText(
+ pageLinkCursor(links["next"], endpoint, "Snyk next page link"),
+ "Snyk next page starting_after cursor",
+ );
+}
+
+function scopedIssue(value: unknown, selected: Scope) {
+ const issue = record(value, "Snyk issue");
+ const relationships = record(
+ issue["relationships"],
+ "Snyk issue relationships",
+ );
+ checkOrganization(relationships, selected);
+ const item = relationship(relationships, "scan_item");
+ if (resourceId(item, "project") !== selected.projectId)
+ throw new Error("Snyk issue does not belong to the selected project.");
+ return issue;
+}
+
+function selectedIssueAttributes(issue: Resource, selected: Scope) {
+ const attributes = record(issue["attributes"], "Snyk issue attributes");
+ if (attributes["type"] !== issueTypes[selected.product])
+ throw new Error(
+ `Only ${issueTypes[selected.product]} issues are supported for this Snyk project selection.`,
+ );
+ return attributes;
+}
+
+function selectedIssue(issue: Resource, selected: Scope) {
+ return {
+ id: resourceId(issue, "issue"),
+ attributes: selectedIssueAttributes(issue, selected),
+ };
+}
+
+function snykIssueId(
+ attributes: Resource,
+ source: Scope,
+ retainedKey?: unknown,
+): string {
+ const key = requiredText(attributes["key"], "Snyk issue key");
+ if (retainedKey !== undefined && retainedKey !== key)
+ throw new Error(
+ "The retained Snyk issue key does not match the original issue.",
+ );
+ return stableId("snyk-rest", [
+ source.apiOrigin,
+ source.organizationId,
+ source.projectId,
+ source.product,
+ key,
+ ]);
+}
+
+function issuePage(
+ response: Resource,
+ selected: Scope,
+ url: URL,
+ seen: Set<string>,
+ current: string | null,
+) {
+ const issues = array(response["data"], "Snyk issue page data").map((value) =>
+ scopedIssue(value, selected),
+ );
+ const next = nextCursor(response["links"], url, current);
+ if (next !== null) {
+ if (seen.has(next))
+ throw new Error("Snyk Issues pagination repeated a cursor.");
+ seen.add(next);
+ }
+ return { issues, next };
+}
+
+export async function collectSnykIssues(
+ options: CollectSnykIssuesOptions,
+ dependencies: HostedScannerHttpOptions & {
+ sourceRepositories?: readonly ExternalSourceRepository[];
+ } = {},
+): Promise<SnykIssuesExport> {
+ const environment = dependencies.environment ?? process.env;
+ requireExternalImports(environment);
+ const { getJson, signal } = hostedScannerHttp(dependencies, options.signal);
+ const { product = "open-source" } = options;
+ const selected = scope(options, options.apiOrigin ?? defaultOrigin, product);
+ const references = snapshotSourceRepositories(
+ dependencies.sourceRepositories,
+ );
+ const token = requiredText(
+ snykApiToken(environment, selected.apiOrigin, options.token),
+ "Snyk API token (SNYK_TOKEN)",
+ );
+ checkSnykTokenOrigin(token, selected.apiOrigin);
+ const get = async (url: URL, label: string) =>
+ jsonApi(await getJson(url, `token ${token}`), label);
+ const getResource = async (url: URL, kind: string) =>
+ record(
+ (await get(url, `Snyk ${kind} response`))["data"],
+ `Snyk ${kind} resource`,
+ );
+ const projectUrl = endpoint(selected, `projects/${selected.projectId}`);
+ projectUrl.searchParams.set("expand", "target");
+ const project = await getResource(projectUrl, "project");
+ const context = projectContext(project, selected);
+ const target =
+ context.lookupTargetId === undefined
+ ? null
+ : await getResource(
+ endpoint(selected, `targets/${context.lookupTargetId}`),
+ "target",
+ );
+ checkTarget(target, selected, context, references);
+ const pages: SnykIssuesExport["pages"] = [];
+ const base = issuesEndpoint(selected);
+ const cursors = new Set<string>();
+ const issueIds = new Set<string>();
+ let startingAfter: string | null = null;
+ do {
+ const url = new URL(base);
+ if (startingAfter !== null)
+ url.searchParams.set("starting_after", startingAfter);
+ const response = await get(url, "Snyk issue page");
+ const page = issuePage(response, selected, base, cursors, startingAfter);
+ for (const issue of page.issues) {
+ const { id } = selectedIssue(issue, selected);
+ if (issueIds.has(id))
+ throw new Error(
+ "Snyk Issues returned overlapping issue IDs. Retry the collection.",
+ );
+ issueIds.add(id);
+ }
+ pages.push({
+ startingAfter,
+ responseJson: JSON.stringify(response),
+ });
+ startingAfter = page.next;
+ } while (startingAfter !== null);
+ signal?.throwIfAborted();
+ return {
+ ...formatVersion,
+ ...selected,
+ complete: true,
+ projectJson: JSON.stringify(project),
+ targetJson: JSON.stringify(target),
+ pages,
+ };
+}
+
+function savedContext(
+ document: Resource,
+ references: readonly ExternalSourceRepository[],
+) {
+ if (
+ document["format"] !== SNYK_REST_ISSUES_FORMAT ||
+ document["apiVersion"] !== apiVersion
+ )
+ throw new Error(
+ `Expected ${SNYK_REST_ISSUES_FORMAT} for API version ${apiVersion}.`,
+ );
+ const selected = scope(document, document["apiOrigin"]);
+ const project = record(
+ parseHostedScannerJson(
+ requiredText(document["projectJson"], "Snyk original project"),
+ ),
+ "Snyk project resource",
+ );
+ const context = projectContext(project, selected);
+ const target = parseHostedScannerJson(
+ requiredText(document["targetJson"], "Snyk original target"),
+ );
+ const remote = checkTarget(target, selected, context, references);
+ const nativeUrl = remote.nativeUrl;
+ const gitlab =
+ remote.gitlab ??
+ reportedScm(selected.sourceRepositoryUrl, context.origin).gitlab;
+ const github = remote.github ?? context.origin.startsWith("github");
+ const platform: SnykIssuesFindings["sourceRepositoryPlatform"] =
+ remote.enterprise ? "github" : context.scm && !github ? "other" : undefined;
+ return {
+ project,
+ target,
+ source: {
+ ...formatVersion,
+ ...selected,
+ projectJson: stringifyHostedEvidence(project),
+ targetJson: stringifyHostedEvidence(target),
+ },
+ context,
+ repository: {
+ scope: selected,
+ scm: context.scm,
+ targetId: context.targetId,
+ integrationId: remote.integrationId,
+ deployment: remote.deployment,
+ url: selected.sourceRepositoryUrl,
+ platform,
+ ...(gitlab && { gitlab: true }),
+ ...(nativeUrl && { nativeUrl }),
+ },
+ };
+}
+
+const snykRestId = /^snyk-rest:[0-9a-f]{64}$/u;
+
+/** A Snyk Issues resource carries its own product and links to both its organization and project. */
+function linkedSnykResources(
+ data: Resource,
+ json: boolean,
+ hosted: boolean,
+): { issue?: Resource } | undefined {
+ const original = (field: string) => {
+ const value = data[field + (json ? "Json" : "")];
+ if (!json) return isRecord(value) ? value : undefined;
+ if (typeof value !== "string") return;
+ try {
+ const parsed = parseHostedScannerJson(value);
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return;
+ }
+ };
+ const issue = original("issue");
+ if (issue?.["type"] === "issue" && (hosted || isUuid(issue["id"]))) {
+ const attributes = issue["attributes"];
+ const links = issue["relationships"];
+ const relationType = (name: string) => {
+ const link = isRecord(links) ? links[name] : undefined;
+ const resource = isRecord(link) ? link["data"] : undefined;
+ return isRecord(resource) && (hosted || isUuid(resource["id"]))
+ ? resource["type"]
+ : undefined;
+ };
+ if (
+ isRecord(attributes) &&
+ "key" in attributes &&
+ (hosted ||
+ attributes["type"] === issueTypes.code ||
+ attributes["type"] === issueTypes["open-source"]) &&
+ relationType("organization") === "organization" &&
+ relationType("scan_item") === "project"
+ )
+ return { issue };
+ }
+ if (!hosted && data["apiVersion"] !== apiVersion) return;
+ const project = original("project");
+ const attributes = project?.["attributes"];
+ const nativeProject =
+ project?.["type"] === "project" &&
+ isUuid(project["id"]) &&
+ isRecord(attributes) &&
+ "origin" in attributes &&
+ "type" in attributes;
+ if (!nativeProject) {
+ const target = original("target");
+ if (target?.["type"] !== "target" || !isUuid(target["id"])) return;
+ }
+ if (!hosted) {
+ // A project or target alone only identifies an unmarked row with the complete monitor scope.
+ try {
+ scope(data, data["apiOrigin"]);
+ } catch {
+ return;
+ }
+ }
+ return {};
+}
+
+function snykRowEvidence(finding: ExternalFinding, hostedReport = false) {
+ const retained = finding.evidence?.source_data;
+ const marked =
+ snykRestId.test(finding.source_finding_id) ||
+ isSnykRestFormat(retained?.["format"]);
+ const hosted = hostedReport || marked;
+ const v1 = retained && linkedSnykResources(retained, false, hosted);
+ const v2 = retained && linkedSnykResources(retained, true, hosted);
+ if (v1 || v2 || marked) return { v1, v2 };
+}
+
+export function isSnykRestFinding(finding: ExternalFinding): boolean {
+ return snykRowEvidence(finding) !== undefined;
+}
+
+export function snykRestFindingRepository(
+ finding: ExternalFinding,
+ references: readonly ExternalSourceRepository[] = [],
+) {
+ return bindSnykFinding(finding, references, snykRowEvidence(finding));
+}
+
+function bindSnykFinding(
+ finding: ExternalFinding,
+ references: readonly ExternalSourceRepository[],
+ originals: ReturnType<typeof snykRowEvidence>,
+ report?: Resource,
+ retain?: (finding: ExternalFinding, source: Resource) => void,
+) {
+ const retained = record(
+ finding.evidence.source_data,
+ "Original Snyk REST issue evidence",
+ );
+ const format =
+ retained["format"] === undefined
+ ? originals?.v1
+ ? SNYK_REST_ISSUES_V1
+ : SNYK_REST_ISSUES_FORMAT
+ : retained["format"];
+ if (
+ isSnykRestFormat(format) &&
+ (format === SNYK_REST_ISSUES_V1 ? originals?.v2 : originals?.v1)
+ )
+ throw new Error(
+ "A normalized Snyk row cannot claim both v1 and v2 native representations.",
+ );
+ const document = readSnykRestDocument({ ...retained, format }, report);
+ const issue =
+ (format === SNYK_REST_ISSUES_FORMAT ? originals?.v2?.issue : undefined) ??
+ parseHostedScannerJson(
+ requiredText(document["issueJson"], "Snyk original issue"),
+ );
+ // A selected issue can retain any of its original monitor fields. Fill only those it omitted.
+ let projected = false;
+ if (report && (originals?.v1?.issue || originals?.v2?.issue)) {
+ for (const [field, value] of Object.entries(report)) {
+ if (document[field] !== undefined) continue;
+ document[field] = value;
+ projected = true;
+ }
+ }
+ const asset = savedContext(document, references);
+ const { source, repository } = asset;
+ const { id: issueId, attributes } = selectedIssue(
+ scopedIssue(issue, source),
+ source,
+ );
+ const nativeId = snykIssueId(
+ attributes,
+ source,
+ retained["snykRestIssueKey"],
+ );
+ if (nativeId !== finding.source_finding_id)
+ throw new Error(
+ "The normalized finding ID does not match the original Snyk issue key and project.",
+ );
+ projectSnykIssue(attributes, asset, { ...retained, format }, "local");
+ if (retain && format === SNYK_REST_ISSUES_V1) {
+ // The legacy witness stores the original decimal token, including its spelling.
+ const context: Resource = projected
+ ? encodeSnykV1File({
+ ...repository.scope,
+ apiVersion: source.apiVersion,
+ format,
+ project: asset.project,
+ target: asset.target,
+ })
+ : { format };
+ retain(finding, {
+ ...retained,
+ ...context,
+ ...(isRecord(context["numericFields"]) && {
+ numericFields: {
+ ...context["numericFields"],
+ ...(isRecord(retained["numericFields"]) && retained["numericFields"]),
+ },
+ }),
+ });
+ } else if (retain && format === SNYK_REST_ISSUES_FORMAT) {
+ retain(finding, {
+ ...retained,
+ ...(projected && source),
+ format,
+ snykRestIssueKey: attributes["key"],
+ projectJson: source.projectJson,
+ targetJson: source.targetJson,
+ issueJson: stringifyHostedEvidence(issue),
+ });
+ }
+ return { ...repository, issueId };
+}
+
+/** Recognize a retained hosted report before verifying its selected issues. */
+export function isSnykRestReport(
+ input: ExternalFindings & Partial<SnykIssuesFindings>,
+ matchesFinding = isSnykRestFinding,
+): boolean {
+ if (input.snykRestContext !== undefined) return true;
+ const rows = input.findings;
+ return Array.isArray(rows) && rows.some(matchesFinding);
+}
+
+function readIssues(document: Resource, selected: Scope) {
+ if (document["complete"] !== true)
+ throw new Error("Expected a complete Snyk REST Issues export.");
+ const url = issuesEndpoint(selected);
+ const pages = array(document["pages"], "Snyk issue pages");
+ if (!pages.length)
+ throw new Error("Incomplete Snyk collection: no issue page.");
+ const seen = new Set<string>();
+ let cursor: string | null = null;
+ const issues = pages.flatMap((value, index) => {
+ const page = record(value, "Snyk saved page");
+ if ((index !== 0 && cursor === null) || page["startingAfter"] !== cursor)
+ throw new Error("Incomplete or inconsistent Snyk issue page sequence.");
+ const parsed = issuePage(
+ jsonApi(
+ parseHostedScannerJson(
+ requiredText(page["responseJson"], "Snyk original issue page"),
+ ),
+ "Snyk issue page",
+ ),
+ selected,
+ url,
+ seen,
+ cursor,
+ );
+ cursor = parsed.next;
+ return parsed.issues;
+ });
+ if (cursor !== null)
+ throw new Error("Incomplete Snyk collection: missing next issue page.");
+ return issues;
+}
+
+// Lossless parsing preserves JSON numbers in raw token objects.
+function record(value: unknown, label: string): Resource {
+ return scannerRecord(hostedNumberToken(value) ?? value, label);
+}
+
+function records(parent: Resource, field: string) {
+ const label = `Snyk ${field}`;
+ return array(parent[field] ?? [], label).map((entry) => record(entry, label));
+}
+
+function problemIds(entries: Resource[], type?: string) {
+ const ids = new Set<string>();
+ for (const entry of entries) {
+ if (type === undefined || entry["type"] === type)
+ ids.add(requiredText(entry["id"], "Snyk problem or class ID"));
+ }
+ return [...ids];
+}
+
+function findingFilePath(value: unknown, v2: boolean) {
+ const path = hostedRepositoryPath(value);
+ const filename = path?.split("/").at(-1);
+ return v2 && (!filename || filename === ".") ? null : path;
+}
+
+function packageEvidence(
+ coordinates: Resource[],
+ { manager, targetFile }: ReturnType<typeof projectContext>,
+ v2: boolean,
+) {
+ const manifest = findingFilePath(targetFile, v2);
+ const packages: ImportedPackage[] = [];
+ for (const coordinate of coordinates) {
+ const fixed = records(coordinate, "remedies").flatMap((remedy) => {
+ const meta = remedy["meta"];
+ return isRecord(meta) &&
+ meta["schema_version"] === "package_vulnerability/v0"
+ ? strings(record(meta["data"], "Snyk package remedy data")["fixed_in"])
+ : [];
+ });
+ for (const representation of records(coordinate, "representations")) {
+ if (!("dependency" in representation)) continue;
+ const dependency = record(
+ representation["dependency"],
+ "Snyk dependency",
+ );
+ packages.push({
+ name: requiredText(
+ dependency["package_name"],
+ "Snyk dependency package name",
+ ),
+ installed_version: requiredText(
+ dependency["package_version"],
+ "Snyk dependency package version",
+ ),
+ ecosystem: manager,
+ manifest_path: manifest,
+ fixed_versions: [...new Set(fixed)],
+ });
+ }
+ }
+ return packages;
+}
+
+function codeStartLine(region: unknown): number | null {
+ const start = isRecord(region) ? region["start"] : undefined;
+ const token = isRecord(start) ? hostedNumberToken(start["line"]) : undefined;
+ const line = token && Number(legacyDecimalInteger(token));
+ return isSafeNonNegativeInteger(line) && line > 0 ? line : null;
+}
+
+function codeEvidence(coordinates: Resource[], scm: boolean, v2: boolean) {
+ const locations: { path: string; line?: number | null }[] = [];
+ const revisions = new Set<string | null>();
+ for (const coordinate of coordinates) {
+ for (const representation of records(coordinate, "representations")) {
+ const value =
+ representation["sourceLocation"] ?? representation["source_location"];
+ if (value === undefined) continue;
+ const location = record(value, "Snyk source location");
+ revisions.add(text(location["commit_id"]));
+ const path = findingFilePath(location["file"], v2);
+ if (scm && path)
+ locations.push(
+ v2 ? { path, line: codeStartLine(location["region"]) } : { path },
+ );
+ }
+ }
+ return {
+ locations,
+ code_revision: revisions.size === 1 ? ([...revisions][0] ?? null) : null,
+ };
+}
+
+function projectSnykIssue(
+ attributes: Resource,
+ { source, context }: ReturnType<typeof savedContext>,
+ sourceData: Resource,
+ target: ExternalImportTarget,
+) {
+ const code = source.product === "code";
+ const v2 = sourceData["format"] !== SNYK_REST_ISSUES_V1;
+ const status = attributes["status"];
+ if (
+ (status !== "open" && status !== "resolved") ||
+ typeof attributes["ignored"] !== "boolean"
+ )
+ throw new Error(
+ "Snyk issue must have a source status and an ignored flag.",
+ );
+ const updatedAt = requiredText(attributes["updated_at"], "Snyk updated_at");
+ const updated = Date.parse(updatedAt);
+ if (
+ updatedAt.startsWith("0000") ||
+ !issueTimestamp.test(updatedAt) ||
+ !Number.isFinite(updated) ||
+ updated < 0
+ )
+ throw new Error("Invalid Snyk issue updated_at.");
+ const severity = requiredText(
+ attributes["effective_severity_level"],
+ "Snyk effective severity",
+ );
+ const problems = records(attributes, "problems");
+ const rules = problemIds(problems, "rule");
+ const activeCoordinates = records(attributes, "coordinates").filter(
+ (coordinate) => status === "open" && coordinate["state"] === "open",
+ );
+ return validateExternalEvidence(
+ {
+ title: requiredText(attributes["title"], "Snyk issue title"),
+ description: text(attributes["description"]),
+ severity:
+ severity === "info" ? "informational" : scannerSeverity(severity),
+ advisory_ids: code ? [] : problemIds(problems),
+ ...(code
+ ? codeEvidence(activeCoordinates, context.scm, v2)
+ : {
+ packages: packageEvidence(activeCoordinates, context, v2),
+ }),
+ source_updated_at: Math.floor(updated / 1000),
+ source_data: sourceData,
+ ...(code && {
+ details: {
+ kind: "sast",
+ repository: { url: source.sourceRepositoryUrl },
+ scanner_origin: "Snyk Code",
+ source_status: status,
+ rule: rules.length === 1 ? { id: rules[0] } : null,
+ weakness_ids: problemIds(records(attributes, "classes"), "weakness"),
+ },
+ }),
+ },
+ target,
+ );
+}
+
+export function normalizeSnykIssues(
+ input: unknown,
+ target: ExternalImportTarget = "local",
+ references: readonly ExternalSourceRepository[] = [],
+): SnykIssuesFindings {
+ if (target !== "local")
+ throw new Error("Snyk REST issues currently support local import only.");
+ const wire = record(input, "Snyk REST Issues export");
+ const document = readSnykRestDocument(wire);
+ const asset = savedContext(document, references);
+ const { source, repository } = asset;
+ const issues = readIssues(document, source);
+ const legacy = originalSnykEvidence(wire, source);
+ // normalizeRecords identifies every row before projecting any evidence.
+ const resourceCounts = new Map<string, number>();
+ const result = normalizeRecords(
+ issues.map((issue, index) => ({ issue, original: legacy?.rows[index] })),
+ ({ issue, original }) => {
+ if (resourceCounts.get(resourceId(issue, "issue"))! > 1)
+ throw new Error(
+ "The saved Snyk report contains overlapping issue IDs.",
+ );
+ const attributes = record(issue["attributes"], "Snyk issue attributes");
+ const sourceData = original
+ ? structuredClone(original)
+ : {
+ ...source,
+ snykRestIssueKey: attributes["key"],
+ issueJson: stringifyHostedEvidence(issue),
+ };
+ return projectSnykIssue(attributes, asset, sourceData, target);
+ },
+ ({ issue }) => {
+ const identifier = resourceIdentifier(issue, "issue");
+ const raw = issue["attributes"];
+ const product = isRecord(raw) ? raw["type"] : undefined;
+ // A missing product cannot establish that this resource belongs to another selection.
+ if (
+ isUuid(identifier) &&
+ (!text(product) || product === issueTypes[source.product])
+ ) {
+ const id = identifier.toLowerCase();
+ resourceCounts.set(id, (resourceCounts.get(id) ?? 0) + 1);
+ }
+ return snykIssueId(selectedIssueAttributes(issue, source), source);
+ },
+ target,
+ );
+ return {
+ ...result,
+ sourceRepositoryUrl: source.sourceRepositoryUrl,
+ ...(repository.platform && {
+ sourceRepositoryPlatform: repository.platform,
+ }),
+ snykRestContext: legacy ? structuredClone(legacy.context) : source,
+ };
+}
+
+/** Reconcile the original records, normalized projections, and reader or destination URLs. */
+export function snykRestImportRepository(
+ input: ExternalFindings & Partial<SnykIssuesFindings>,
+ provider: Provider,
+ urls: Iterable<string> = [],
+ trustedSources: readonly ExternalSourceRepository[] = [],
+ retain?: (finding: ExternalFinding, source: Resource) => void,
+): RepositoryBinding | undefined {
+ const project =
+ input.snykRestContext !== undefined
+ ? savedContext(
+ readSnykRestDocument(
+ record(input.snykRestContext, "Snyk report context"),
+ ),
+ trustedSources,
+ )
+ : undefined;
+ const rows = input.findings.map((finding) => ({
+ finding,
+ originals: snykRowEvidence(finding, project !== undefined),
+ }));
+ if (!project && !rows.some(({ originals }) => originals)) return;
+ const context = project && {
+ ...project.source,
+ projectJson: JSON.stringify(project.project),
+ targetJson: JSON.stringify(project.target),
+ };
+ const boundRows = rows.map(({ finding, originals }) =>
+ bindSnykFinding(finding, trustedSources, originals, context, retain),
+ );
+ const selected = project?.repository.scope ?? boundRows[0]?.scope;
+ const bindings = project ? [...boundRows, project.repository] : boundRows;
+ const sourceBinding = bindings[0];
+ if (!sourceBinding) return;
+ if (provider !== "snyk")
+ throw new Error("Use the snyk provider for Snyk REST issues.");
+
+ if (
+ project &&
+ boundRows.some(
+ (row) =>
+ (project.repository.targetId && !row.targetId) ||
+ (project.repository.nativeUrl && !row.nativeUrl),
+ )
+ )
+ throw new Error(
+ "The selected Snyk finding is missing the report's native target. Keep its full project or omit the project to use the report context.",
+ );
+ for (const key of ["targetId", "integrationId", "deployment"] as const) {
+ const ids = new Set(bindings.flatMap((binding) => binding[key] ?? []));
+ if (ids.size > 1)
+ throw new Error(
+ "The Snyk project scope names conflicting targets or integrations.",
+ );
+ }
+ if (
+ selected &&
+ bindings.some(
+ ({ scope, scm }) =>
+ scm !== sourceBinding.scm ||
+ scope.apiOrigin !== selected.apiOrigin ||
+ scope.organizationId !== selected.organizationId ||
+ scope.projectId !== selected.projectId ||
+ scope.product !== selected.product,
+ )
+ )
+ throw new Error(
+ "The normalized finding does not match the retained Snyk project scope.",
+ );
+
+ const claims = new Set(bindings.map((binding) => binding.url));
+ for (const binding of bindings)
+ if (binding.nativeUrl) claims.add(binding.nativeUrl);
+ if (input.sourceRepositoryUrl !== undefined)
+ claims.add(input.sourceRepositoryUrl);
+ for (const { evidence } of input.findings) {
+ const typed = evidence.details?.repository?.url;
+ if (typed) claims.add(typed);
+ for (const native of snykRepositoryUrls(evidence.source_data, {
+ normalizeGitRemote: false,
+ }))
+ claims.add(native);
+ }
+ if (
+ new Set(boundRows.map(({ issueId }) => issueId)).size !== boundRows.length
+ )
+ throw new Error(
+ "The normalized Snyk selection contains overlapping issue IDs.",
+ );
+ for (const url of urls) claims.add(url);
+ // Saved SCM metadata can contradict a caller's mapping but cannot establish one.
+ const source = trustedScmBinding(
+ sourceBinding.url,
+ trustedSources,
+ input.sourceRepositoryPlatform !== "other" &&
+ bindings.every(
+ (binding) => binding.platform !== "other" && !binding.gitlab,
+ ),
+ input.sourceRepositoryPlatform !== "github" &&
+ bindings.every(
+ (binding) => binding.gitlab || binding.platform === undefined,
+ ),
+ );
+ for (const url of claims)
+ if (!snykRestRepositoryMatches(source, url))
+ throw new Error(
+ "The normalized repository does not match the original Snyk project.",
+ );
+ return source;
+}
diff --git a/sdk/typescript/src/snyk-rest-v1.ts b/sdk/typescript/src/snyk-rest-v1.ts
new file mode 100644
index 000000000..6f18c4abc
--- /dev/null
+++ b/sdk/typescript/src/snyk-rest-v1.ts
@@ -0,0 +1,145 @@
+import {
+ hostedNumberToken,
+ parseHostedScannerJson,
+} from "./hosted-scanner-http.js";
+import {
+ isLegacyWitness,
+ restoreLegacyHostedNumbers,
+} from "./hosted-scanner-v1.js";
+import { canonicalJson, isRecord } from "./record.js";
+import { array, record } from "./scanner-import.js";
+
+type Resource = Record<string, unknown>;
+export const SNYK_REST_ISSUES_V1 = "snyk-rest-issues/v1";
+export const SNYK_REST_ISSUES_FORMAT = "snyk-rest-issues/v2";
+export function isSnykRestFormat(value: unknown): boolean {
+ return value === SNYK_REST_ISSUES_FORMAT || value === SNYK_REST_ISSUES_V1;
+}
+
+/** Only v1 can carry native JSON numbers outside the lossless evidence strings. */
+export function parseSnykReport(text: string): unknown {
+ const document: unknown = JSON.parse(text);
+ return isRecord(document) && document["format"] === SNYK_REST_ISSUES_V1
+ ? parseHostedScannerJson(text)
+ : document;
+}
+
+function encodeNumbers(data: object): Resource | undefined {
+ const fields: Resource = Object.create(null);
+ const values = data as Resource;
+ for (const [key, value] of Object.entries(values)) {
+ const token = hostedNumberToken(value);
+ if (token !== undefined) {
+ if (isLegacyWitness(token)) {
+ values[key] = token;
+ fields[key] = token;
+ } else {
+ values[key] = Number(token);
+ }
+ } else if (value !== null && typeof value === "object") {
+ const nested = encodeNumbers(value);
+ if (nested) fields[key] = nested;
+ }
+ }
+ return Object.keys(fields).length ? fields : undefined;
+}
+
+/** Recover the exact v1 wire representation whether numbers were native or witnessed strings. */
+export function encodeSnykV1File(document: Resource): Resource {
+ const source = restoreLegacyHostedNumbers(document);
+ delete source["numericFields"];
+ const fields = encodeNumbers(source);
+ if (fields) source["numericFields"] = fields;
+ return source;
+}
+
+/** Read v1 exports, retained source records, and empty-report project contexts. */
+export function readSnykRestDocument(
+ document: Resource,
+ context?: Resource,
+): Resource {
+ if (document["format"] !== SNYK_REST_ISSUES_V1) return document;
+ const fields = document["numericFields"];
+ if (context && isRecord(fields)) {
+ // A projected row may keep witnesses for assets that now come from its report.
+ const inline = { ...fields };
+ for (const field of ["project", "target"]) {
+ const json = context[field + "Json"];
+ if (
+ document[field] !== undefined ||
+ !(field in fields) ||
+ typeof json !== "string"
+ )
+ continue;
+ const asset = encodeSnykV1File({ [field]: parseHostedScannerJson(json) });
+ if (
+ canonicalJson(fields[field]) !==
+ canonicalJson(at(asset, "numericFields", field))
+ )
+ throw new Error(
+ "Invalid scanner numeric fields for the retained Snyk asset.",
+ );
+ delete inline[field];
+ document = { ...document, numericFields: inline };
+ }
+ }
+ const exact = restoreLegacyHostedNumbers(document);
+ return {
+ ...exact,
+ format: SNYK_REST_ISSUES_FORMAT,
+ projectJson: JSON.stringify(exact["project"]),
+ targetJson: JSON.stringify(exact["target"]),
+ issueJson: JSON.stringify(exact["issue"]),
+ ...(exact["pages"] !== undefined && {
+ pages: array(exact["pages"], "Snyk issue pages").map((entry) => {
+ const page = record(entry, "Snyk saved page");
+ return {
+ startingAfter: page["startingAfter"],
+ responseJson: JSON.stringify(page["response"]),
+ };
+ }),
+ }),
+ };
+}
+
+function at(value: unknown, ...path: (string | number)[]): unknown {
+ for (const segment of path)
+ value = isRecord(value) ? value[segment] : undefined;
+ return value;
+}
+
+/** Retain v1's evidence representation so replaying an existing import stays unchanged. */
+export function originalSnykEvidence(document: Resource, source: Resource) {
+ if (document["format"] !== SNYK_REST_ISSUES_V1) return;
+ const { projectJson: _project, targetJson: _target, ...scope } = source;
+ const fields = document["numericFields"];
+ const assetFields: Resource = {};
+ for (const key of ["project", "target"]) {
+ const field = at(fields, key);
+ if (field !== undefined) assetFields[key] = field;
+ }
+ const context = {
+ ...scope,
+ format: SNYK_REST_ISSUES_V1,
+ project: document["project"],
+ target: document["target"],
+ ...(Object.keys(assetFields).length > 0 && { numericFields: assetFields }),
+ };
+ const rows = array(document["pages"], "Snyk issue pages").flatMap(
+ (value, i) => {
+ const page = record(value, "Snyk saved page");
+ const response = record(page["response"], "Snyk issue page");
+ return array(response["data"], "Snyk issue page data").map((issue, j) => {
+ const field = at(fields, "pages", i, "response", "data", j);
+ return {
+ ...context,
+ issue,
+ ...(field !== undefined && {
+ numericFields: { ...assetFields, issue: field },
+ }),
+ };
+ });
+ },
+ );
+ return { context, rows };
+}
diff --git a/sdk/typescript/src/snyk-token-origin.ts b/sdk/typescript/src/snyk-token-origin.ts
new file mode 100644
index 000000000..2107b9259
--- /dev/null
+++ b/sdk/typescript/src/snyk-token-origin.ts
@@ -0,0 +1,97 @@
+import { importEnvironmentSetting } from "./external-imports-feature.js";
+import { isRecord } from "./record.js";
+
+function endpointSetting(environment: NodeJS.ProcessEnv, name: string) {
+ if (name === "SNYK_API_V3_URL" || name === "SNYK_API_REST_URL") {
+ // snyk-config preserves key case and converts boolean literals before interpolation.
+ for (const key in environment) {
+ if (key !== name) continue;
+ const raw = environment[key];
+ if (raw === "false" || raw === "FALSE") return undefined;
+ return raw?.replace(
+ /\$\{([^}\r\n\u2028\u2029]*)\}?/gu,
+ (match, reference: string) => {
+ // Consume an unterminated reference once, leaving it literal.
+ if (!match.endsWith("}")) return match;
+ const requested =
+ process.platform === "win32" ? reference.toUpperCase() : reference;
+ const value = importEnvironmentSetting(environment, requested)?.value;
+ if (value === undefined)
+ throw new Error(
+ `${name} references missing environment variable ${reference}.`,
+ );
+ return value;
+ },
+ );
+ }
+ return undefined;
+ }
+ return importEnvironmentSetting(environment, name)?.value;
+}
+
+function endpointOrigin(value: string, snykBase: boolean): string | undefined {
+ const url = URL.parse(value);
+ if (url?.protocol !== "https:") return undefined;
+ // Snyk derives its REST host from the general endpoint (e.g. app.eu.snyk.io).
+ if (snykBase && !url.hostname.startsWith("api."))
+ url.hostname = `api.${url.hostname.replace(/^app\./u, "")}`;
+ return url.origin;
+}
+
+export function checkSnykTokenOrigin(token: string, origin: string): void {
+ // Snyk user and service access tokens carry their API hostname in the h claim.
+ const payload =
+ /^snyk_(?:uat|sat)\.[a-z0-9]{8}\.([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+$/u.exec(
+ token.trim(),
+ )?.[1];
+ if (!payload) return;
+ let claims: unknown;
+ try {
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
+ } catch {
+ return;
+ }
+ const host = isRecord(claims) ? claims["h"] : undefined;
+ if (typeof host !== "string" || !host) return;
+ const base = host.startsWith("http") ? host : `https://${host}`;
+ if (endpointOrigin(base, true) !== origin)
+ throw new Error(
+ `The Snyk access token's API host does not match ${origin}. Select its API origin before collecting findings.`,
+ );
+}
+
+/** Keep the environment credential bound to its configured origin when an SDK caller forwards it. */
+export function snykApiToken(
+ environment: NodeJS.ProcessEnv,
+ origin: string,
+ explicitToken?: string,
+): string | undefined {
+ const tokenName = "SNYK_TOKEN";
+ const originNames = [
+ "API_V3_URL",
+ "SNYK_API_V3_URL",
+ "API_REST_URL",
+ "SNYK_API_REST_URL",
+ "SNYK_API",
+ "SNYK_CFG_ENDPOINT",
+ ];
+ const environmentToken = importEnvironmentSetting(
+ environment,
+ tokenName,
+ )?.value;
+ const token = explicitToken ?? environmentToken;
+ // HTTP trims trailing whitespace from the Authorization header.
+ if (token && token.trim() === environmentToken?.trim()) {
+ for (const name of originNames) {
+ const configured = endpointSetting(environment, name);
+ if (!configured) continue;
+ const snykBase = name === "SNYK_API" || name === "SNYK_CFG_ENDPOINT";
+ if (endpointOrigin(configured, snykBase) !== origin)
+ throw new Error(
+ `${name} does not match ${origin}. Select a matching API origin and ${tokenName} before collecting findings.`,
+ );
+ break;
+ }
+ }
+ return token;
+}
diff --git a/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts b/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts
index cb5448d6f..2368ceaba 100644
--- a/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts
+++ b/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts
@@ -17,6 +17,7 @@ const commands = [
["publish", "findings"],
["findings", "imported"],
["import", "github-advisories"],
+ ["import", "snyk"],
["import", "sonar"],
];
diff --git a/sdk/typescript/tests-ts/cli-import-snyk.test.ts b/sdk/typescript/tests-ts/cli-import-snyk.test.ts
new file mode 100644
index 000000000..34a1e50e0
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-import-snyk.test.ts
@@ -0,0 +1,230 @@
+import { expect, mock, test } from "bun:test";
+import { main } from "../src/cli.js";
+import { canonicalJson } from "../src/record.js";
+import { normalizeSnykIssues } from "../src/snyk-rest-findings.js";
+import { dependencies } from "./cli-fixtures.js";
+import { createCliTest } from "./support/cli-run.js";
+
+import {
+ snykIssue,
+ snykOptions,
+ snykRestFixture,
+} from "./support/snyk-rest-fixtures.js";
+
+const { organizationId, projectId, sourceRepositoryUrl } = snykOptions;
+const command = [
+ "import",
+ "snyk",
+ projectId,
+ "--snyk-org",
+ organizationId,
+ "--source-repository-url",
+ sourceRepositoryUrl,
+ "--format",
+ "json",
+];
+const environment = {
+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",
+ SNYK_TOKEN: "synthetic",
+};
+
+test.each(["open-source", "code"] as const)(
+ "import snyk emits the selected %s report directly",
+ async (product) => {
+ const cli = createCliTest(main);
+ const code = product === "code";
+ const apiOrigin = code ? snykOptions.apiOrigin : "https://api.snyk.io";
+ const report = { ...snykRestFixture(product), apiOrigin };
+ const productFlags = code
+ ? ["--snyk-product", product, "--snyk-api-origin", apiOrigin]
+ : [];
+ const status = await cli.runCli([...command, ...productFlags], {
+ ...dependencies({ environment }),
+ hostedScannerFetch: async (url) => {
+ expect(url.origin).toBe(apiOrigin);
+ if (
+ url.pathname === `/rest/orgs/${organizationId}/projects/${projectId}`
+ )
+ return Response.json({ data: JSON.parse(report.projectJson) });
+ expect(url.pathname).toBe(`/rest/orgs/${organizationId}/issues`);
+ expect(url.searchParams.get("type")).toBe(
+ code ? "code" : "package_vulnerability",
+ );
+ return new Response(report.pages[0]!.responseJson);
+ },
+ });
+ expect({ status, error: cli.stderr.text() }).toEqual({
+ status: 0,
+ error: "",
+ });
+ expect(JSON.parse(cli.stdout.text())).toEqual(report);
+ },
+);
+
+test("import snyk requires opt-in and keeps failed collections out of redirected JSON", async () => {
+ const detail = "projet refusé \u202edenied\npermissions:\tread";
+ const fetch = mock(async (_url: URL, init: RequestInit) => {
+ expect(new Headers(init.headers).get("authorization")).toBe(
+ "token synthetic",
+ );
+ return new Response(detail, { status: 403 });
+ });
+ const disabled = createCliTest(main);
+ expect(
+ await disabled.runCli(command, {
+ ...dependencies({ environment: {} }),
+ hostedScannerFetch: fetch,
+ }),
+ ).toBe(2);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(disabled.stdout.text()).toBe("");
+ expect(disabled.stderr.text()).toContain(
+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",
+ );
+
+ const enabled = createCliTest(main);
+ expect(
+ await enabled.runCli(command, {
+ ...dependencies({ environment }),
+ hostedScannerFetch: fetch,
+ }),
+ ).toBe(2);
+ expect(enabled.stdout.text()).toBe("");
+ expect(enabled.stderr.text()).toContain(
+ "projet refusé \\u202edenied permissions: read",
+ );
+
+ const full = createCliTest(main, { stdout: true, stderr: true });
+ expect(
+ await full.runCli([...command, "--full-output"], {
+ ...dependencies({ environment }),
+ hostedScannerFetch: fetch,
+ }),
+ ).toBe(2);
+ expect(JSON.parse(full.stdout.text()).error.message).toContain(detail);
+ expect(full.stderr.text()).toBe(enabled.stderr.text());
+});
+
+test("Snyk CLI escapes cursors in human output and retains the native JSON value", async () => {
+ const cursor = "pré\u001b[2Jcursor";
+ const report = snykRestFixture("open-source");
+ for (const format of ["md", "default", "toon", "json"] as const) {
+ const cli = createCliTest(main, { stdout: true });
+ const args =
+ format === "default" ? command.slice(0, -2) : command.with(-1, format);
+ const status = await cli.runCli(args, {
+ ...dependencies({ environment }),
+ hostedScannerFetch: async (url) => {
+ if (url.pathname.endsWith("/projects/" + projectId))
+ return Response.json({ data: JSON.parse(report.projectJson) });
+ if (url.searchParams.has("starting_after"))
+ return Response.json({ data: [] });
+ return Response.json({
+ data: [],
+ links: { next: "?starting_after=" + encodeURIComponent(cursor) },
+ });
+ },
+ });
+ expect(status).toBe(0);
+ const output = cli.stdout.text();
+ if (format !== "json") {
+ expect(output).not.toContain("\u001b");
+ expect(output).toContain("pré\\u001b[2Jcursor");
+ } else {
+ expect(JSON.parse(output).pages[1].startingAfter).toBe(cursor);
+ }
+ }
+});
+
+test("Snyk --schema describes the complete saved report", async () => {
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(
+ ["import", "snyk", "--schema", "--json"],
+ dependencies({
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ }),
+ ),
+ ).toBe(0);
+ const { output } = JSON.parse(cli.stdout.text());
+ expect(output.properties).toMatchObject({
+ format: { const: "snyk-rest-issues/v2" },
+ complete: { const: true },
+ projectJson: { type: "string" },
+ targetJson: { type: "string" },
+ pages: { items: { properties: { responseJson: { type: "string" } } } },
+ });
+});
+
+test.each([
+ ["open-source", "repeated"],
+ ["code", "rekeyed"],
+ ["open-source", "distinct"],
+] as const)(
+ "import snyk handles %s pages with %s resource IDs",
+ async (product, variant) => {
+ const report = snykRestFixture(product);
+ const first = {
+ ...snykIssue(product === "code"),
+ id: "abcdef01-4444-4444-8444-444444444444",
+ };
+ const second = {
+ ...first,
+ id:
+ variant === "distinct"
+ ? "bbbbbbbb-4444-4444-8444-444444444444"
+ : first.id.toUpperCase(),
+ attributes: {
+ ...first.attributes,
+ key: variant === "rekeyed" ? "updated-key" : first.attributes.key,
+ },
+ };
+ const pages = [
+ {
+ startingAfter: null,
+ responseJson: canonicalJson({
+ data: [first],
+ links: { next: "?starting_after=page-two" },
+ }),
+ },
+ {
+ startingAfter: "page-two",
+ responseJson: canonicalJson({ data: [second] }),
+ },
+ ];
+ const cursors: (string | null)[] = [];
+ const cli = createCliTest(main);
+ const status = await cli.runCli([...command, "--snyk-product", product], {
+ ...dependencies({ environment }),
+ hostedScannerFetch: async (url) => {
+ if (url.pathname.endsWith("/projects/" + projectId))
+ return Response.json({ data: JSON.parse(report.projectJson) });
+ const page = pages[cursors.length]!;
+ cursors.push(url.searchParams.get("starting_after"));
+ return new Response(page.responseJson);
+ },
+ });
+ expect(cursors).toEqual([null, "page-two"]);
+ if (variant === "distinct") {
+ expect(status).toBe(0);
+ expect(JSON.parse(cli.stdout.text())).toMatchObject({
+ complete: true,
+ pages,
+ });
+ } else {
+ expect(status).toBe(2);
+ expect(cli.stdout.text()).toBe("");
+ expect(cli.stderr.text()).toContain("overlapping issue IDs");
+ }
+ const saved = normalizeSnykIssues({ ...report, pages });
+ const reason =
+ variant === "rekeyed"
+ ? "overlapping issue IDs"
+ : "Ambiguous duplicate source identity";
+ expect(saved.findings).toBeEmpty();
+ expect(saved.excluded).toMatchObject([
+ { position: 1, reason: expect.stringContaining(reason) },
+ { position: 2, reason: expect.stringContaining(reason) },
+ ]);
+ },
+);
diff --git a/sdk/typescript/tests-ts/external-findings-local.test.ts b/sdk/typescript/tests-ts/external-findings-local.test.ts
index c86d5ed5d..887f4ac7a 100644
--- a/sdk/typescript/tests-ts/external-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-local.test.ts
@@ -12,6 +12,8 @@ import { delimiter, join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, test } from "bun:test";
import type { ExternalFindings } from "../src/external-findings.js";
+import { normalizeSnykIssues } from "../src/snyk-rest-findings.js";
+import { snykRestFixture } from "./support/snyk-rest-fixtures.js";
import {
listLocalExternalFindings,
prepareNormalizedLocalImport,
@@ -629,10 +631,19 @@ describe("local normalized scanner findings", () => {
},
);
- test.each(["repository", "prepare-state", "read-state", "prepare-metadata"])(
+ const pendingPaths = [
+ "repository",
+ "prepare-state",
+ "read-state",
+ "prepare-metadata",
+ "prepare-snyk-remotes",
+ ];
+ test.each(pendingPaths)(
"cancels %s resolution while its filesystem lookup is pending",
async (operation) => {
- const { repository, stateDirectory, environment } = await fixture();
+ const { repository, stateDirectory, environment } = await fixture({
+ isolatedGit: operation === "prepare-snyk-remotes",
+ });
if (operation === "prepare-metadata")
await rm(join(repository, ".git"), { recursive: true });
const module = new URL(
@@ -649,7 +660,9 @@ describe("local normalized scanner findings", () => {
const operation = ${JSON.stringify(operation)};
const heldPath = operation === "repository" ? repository
: operation === "prepare-metadata" ? ${JSON.stringify(join(repository, "HEAD"))}
+ : operation === "prepare-snyk-remotes" ? ${JSON.stringify(join(repository, ".git", "remotes"))}
: ${JSON.stringify(stateDirectory)};
+ const holdLstat = operation === "prepare-metadata" || operation === "prepare-snyk-remotes";
const originalRealpath = fs.realpath;
const originalLstat = fs.lstat;
let enteredLookup, releaseLookup;
@@ -657,13 +670,13 @@ describe("local normalized scanner findings", () => {
const lookup = new Promise((_, reject) => { releaseLookup = reject; });
mockFs(() => ({
realpath: (path, ...args) => {
- if (operation === "prepare-metadata" || path !== heldPath)
+ if (holdLstat || path !== heldPath)
return originalRealpath(path, ...args);
enteredLookup();
return lookup;
},
lstat: (path, ...args) => {
- if (operation !== "prepare-metadata" || path !== heldPath)
+ if (!holdLstat || path !== heldPath)
return originalLstat(path, ...args);
enteredLookup();
return lookup;
@@ -676,7 +689,15 @@ describe("local normalized scanner findings", () => {
let outcome;
const pending = operation.startsWith("prepare-")
? prepareNormalizedLocalImport(
- { read: 0, findings: [], excluded: [] },
+ ${JSON.stringify(
+ operation === "prepare-snyk-remotes"
+ ? normalizeSnykIssues(
+ snykRestFixture("open-source", {
+ sourceRepositoryUrl: "https://github.com/example/project",
+ }),
+ )
+ : { read: 0, findings: [], excluded: [] },
+ )},
{ repository, provider: "snyk", sourceKey: "synthetic-project" },
{ signal: controller.signal,
sourceRepositories: [{ url: "https://github.com/example/project" }] },
diff --git a/sdk/typescript/tests-ts/snyk-rest-boundaries.test.ts b/sdk/typescript/tests-ts/snyk-rest-boundaries.test.ts
new file mode 100644
index 000000000..dbf873d43
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-boundaries.test.ts
@@ -0,0 +1,909 @@
+import { expect, mock, test } from "bun:test";
+import { readSnykFindings } from "../src/snyk-findings.js";
+import { snykJson, snykSarif } from "./support/snyk-import-fixtures.js";
+import { prepareNormalizedExternalPublication } from "../src/external-findings-publish.js";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import { normalizeSnykIssues } from "../src/snyk-rest-findings.js";
+import {
+ snykIssue,
+ snykLocalFixture,
+ snykOptions,
+ snykRestFixture,
+} from "./support/snyk-rest-fixtures.js";
+
+test("a generic Snyk reader can import findings with an SSH repository URL", async () => {
+ const target = { repository: snykOptions.sourceRepositoryUrl };
+ const report = {
+ read: 1,
+ findings: [
+ {
+ source_finding_id: "reader-id",
+ evidence: {
+ title: "Reader finding",
+ severity: "high" as const,
+ source_data: {
+ format: "snyk-findings-export/v1",
+ collection: { target },
+ },
+ },
+ },
+ ],
+ excluded: [],
+ sourceRepositoryUrl: "[email protected]:example/repository.git",
+ };
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ const prepare = (checkout = fixture) => checkout.prepareNormalized(report);
+ const first = await prepare();
+ expect((await first.import()).counts.created).toBe(1);
+ const second = await prepare();
+ expect((await second.import()).counts.unchanged).toBe(1);
+ await using other = await snykLocalFixture({
+ remote: "[email protected]:example/other.git",
+ });
+ await expect(prepare(other)).rejects.toThrow(
+ "does not match a configured remote",
+ );
+ target.repository = "https://github.com/example/other";
+ await expect(prepare()).rejects.toThrow("Snyk reader's repository");
+});
+
+test("normalized Snyk REST Open Source rows cannot publish to Cloud", async () => {
+ const report = snykRestFixture("open-source");
+ const normalized = normalizeSnykIssues(report);
+ const fetch = mock(async () => {
+ throw new Error("Unexpected Cloud request");
+ });
+ const serialized = {
+ source_finding_id: "example",
+ evidence: { title: "Example", severity: "low" as const },
+ toJSON: () => normalized.findings[0],
+ };
+ for (const input of [
+ normalized,
+ { read: 1, excluded: [], findings: [serialized] },
+ ]) {
+ await expect(
+ prepareNormalizedExternalPublication(
+ input,
+ {
+ provider: "snyk",
+ repository: "https://github.com/example/another",
+ sourceKey: "example",
+ },
+ { environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" }, fetch },
+ ),
+ ).rejects.toThrow("local import");
+ }
+ expect(fetch).not.toHaveBeenCalled();
+ expect(() => normalizeSnykIssues(report, "cloud")).toThrow("local import");
+});
+
+test("an empty normalized Snyk capture keeps its local publication boundary", async () => {
+ const capture = snykRestFixture("open-source");
+ capture.pages[0]!.responseJson = JSON.stringify({ data: [], links: {} });
+ const normalized = normalizeSnykIssues(capture);
+ expect(normalized.findings).toHaveLength(0);
+ await expect(
+ prepareNormalizedExternalPublication(
+ normalized,
+ {
+ provider: "snyk",
+ repository: "https://github.com/example/another",
+ sourceKey: "example",
+ },
+ { environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" } },
+ ),
+ ).rejects.toThrow("Snyk REST findings require a local import");
+});
+
+test("a Snyk asset cannot authorize a projected row from a second repository", async () => {
+ const normalized = normalizeSnykIssues(snykRestFixture("open-source"));
+ const other = "https://github.com/example/another";
+ normalized.findings.push({
+ source_finding_id: "blackduck-bom:" + "a".repeat(64),
+ evidence: {
+ title: "Projected package",
+ severity: "high",
+ source_data: { sourceRepositoryUrl: other },
+ },
+ });
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ await expect(
+ prepareNormalizedLocalImport(
+ normalized,
+ {
+ repository: fixture.repository,
+ provider: "snyk",
+ sourceKey: "example",
+ },
+ { environment: fixture.environment },
+ ),
+ ).rejects.toThrow("Snyk original issue");
+});
+
+test("Snyk Open Source rows still verify the native project after losing their format and report headers", async () => {
+ const { read, findings, excluded } = normalizeSnykIssues(
+ snykRestFixture("open-source"),
+ );
+ delete findings[0]!.evidence.source_data!["format"];
+ await using f = await snykLocalFixture({
+ remote: "https://github.com/example/other",
+ });
+ await expect(
+ f.prepareNormalized({ read, findings, excluded }),
+ ).rejects.toThrow("configured remote");
+
+ // A changed ID and provider cannot relabel the original linked Snyk resources.
+ findings[0]!.source_finding_id = "wiz-example";
+ await expect(
+ prepareNormalizedLocalImport(
+ { read, findings, excluded },
+ {
+ provider: "wiz",
+ sourceKey: f.sourceKey,
+ repository: f.repository,
+ },
+ { environment: f.environment },
+ ),
+ ).rejects.toThrow("Snyk issue key");
+});
+
+test("direct import rejects another Snyk issue’s evidence under a stored finding ID", async () => {
+ const report = snykRestFixture("open-source");
+ await using f = await snykLocalFixture();
+ await f.writeJson(report);
+ await (await f.prepare()).import();
+ const prior = await f.read();
+ const oldId = prior[0]!.sourceFindingId;
+ expect(prior[0]!.evidence.source_data?.["snykRestIssueKey"]).toBe(
+ "opaque-issue-key",
+ );
+ report.pages[0]!.responseJson = report.pages[0]!.responseJson.replace(
+ "opaque-issue-key",
+ "another-issue-key",
+ );
+ const second = normalizeSnykIssues(report);
+ expect(second.findings[0]!.source_finding_id).not.toBe(oldId);
+ const row = second.findings[0]!;
+ row.source_finding_id = oldId;
+ const prepare = () => f.prepareNormalized(second);
+ await expect(prepare()).rejects.toThrow("Snyk issue key");
+ row.source_finding_id =
+ normalizeSnykIssues(report).findings[0]!.source_finding_id;
+ row.evidence.source_data!["snykRestIssueKey"] = "opaque-issue-key";
+ await expect(prepare()).rejects.toThrow("retained Snyk issue key");
+ row.source_finding_id = oldId;
+ for (const source of [{}, undefined]) {
+ row.evidence.source_data = source;
+ await expect(prepare()).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ expect(await f.read()).toEqual(prior);
+});
+
+test("a saved Snyk origin cannot establish that a private host uses GitHub path aliases", async () => {
+ const source = "https://scm.example.invalid/Org/repo";
+ const alias = "https://scm.example.invalid/org/REPO.git";
+ const report = snykRestFixture("open-source", {
+ sourceRepositoryUrl: source,
+ });
+ const project = JSON.parse(report.projectJson);
+ project.attributes.origin = "github-enterprise";
+ report.projectJson = JSON.stringify(project);
+ await using fixture = await snykLocalFixture({ remote: alias });
+ const settings = {
+ provider: "snyk" as const,
+ sourceKey: "example/project",
+ repository: fixture.repository,
+ };
+ const normalized = normalizeSnykIssues(report);
+ const prepare = (
+ sourceRepositories?: { url: string; platform: "github" }[],
+ ) =>
+ prepareNormalizedLocalImport(normalized, settings, {
+ environment: fixture.environment,
+ sourceRepositories,
+ });
+ await expect(prepare()).rejects.toThrow("configured remote");
+ await expect(
+ prepare([
+ { url: "https://scm.example.invalid/other/project", platform: "github" },
+ ]),
+ ).rejects.toThrow();
+ expect(
+ (await prepare([{ url: source, platform: "github" }])).preview.findings,
+ ).toHaveLength(1);
+
+ // A native URL that only matches the declared URL under GitHub's rules needs
+ // the same independent repository identity as the checkout.
+ await using exact = await snykLocalFixture({ remote: source });
+ for (const native of [alias, "[email protected]:Org/repo"]) {
+ project.relationships.target.data.attributes.url = native;
+ report.projectJson = JSON.stringify(project);
+ await expect(
+ prepareNormalizedLocalImport(
+ normalizeSnykIssues(report),
+ { ...settings, repository: exact.repository },
+ { environment: exact.environment },
+ ),
+ ).rejects.toThrow("original Snyk project");
+ }
+});
+
+test("unrelated Wiz evidence with Snyk-like field names remains importable locally and reaches Cloud credentials", async () => {
+ await using f = await snykLocalFixture();
+ const source_data: Record<string, unknown> = {
+ ...snykOptions,
+ snykRestIssueKey: "upstream-ticket",
+ apiVersion: "2026-03-25",
+ projectJson: JSON.stringify({
+ type: "project",
+ id: "repo-name",
+ attributes: { origin: "github", type: "npm" },
+ }),
+ issueJson: "{}",
+ targetJson: JSON.stringify({ type: "target", id: 42 }),
+ project: { name: "sample" },
+ issue: { name: "sample issue" },
+ };
+ const finding = {
+ source_finding_id: "snyk-rest:ticket-42",
+ evidence: { title: "Example", severity: "medium" as const, source_data },
+ };
+ const input = {
+ read: 1,
+ findings: [finding],
+ excluded: [],
+ snykRestContext: undefined,
+ };
+ const options = {
+ provider: "wiz" as const,
+ sourceKey: "example",
+ repository: f.repository,
+ };
+ const credentials = mock(async () => {
+ throw new Error("Reached Wiz Cloud credentials");
+ });
+ const sources: Record<string, unknown>[] = [
+ {
+ snykRestIssueKey: "upstream-ticket",
+ projectJson: JSON.stringify({
+ type: "project",
+ id: snykOptions.projectId,
+ attributes: { origin: "ticketing", type: "service" },
+ }),
+ },
+ ];
+ const original = snykIssue(true);
+ for (const [id, org, project] of [
+ [42, undefined, undefined],
+ ["ticket-42", snykOptions.organizationId, snykOptions.projectId],
+ [original.id, undefined, snykOptions.projectId],
+ [original.id, snykOptions.organizationId, undefined],
+ ]) {
+ const issue = {
+ ...original,
+ id,
+ relationships: {
+ organization: { data: { type: "organization", id: org } },
+ scan_item: { data: { type: "project", id: project } },
+ },
+ };
+ sources.push({
+ ...source_data,
+ issue,
+ issueJson: JSON.stringify(issue),
+ ...(id === original.id && { format: "wiz-export/v1" }),
+ });
+ }
+ for (const source of sources) {
+ finding.evidence.source_data = source;
+ expect(
+ (
+ await prepareNormalizedLocalImport(input, options, {
+ environment: f.environment,
+ })
+ ).preview.findings,
+ ).toHaveLength(1);
+ await expect(
+ prepareNormalizedExternalPublication(input, options, {
+ environment: f.environment,
+ credentials,
+ }),
+ ).rejects.toThrow("Reached Wiz Cloud credentials");
+ }
+ expect(credentials).toHaveBeenCalledTimes(sources.length);
+});
+
+test("a reader may copy an optional hosted context from Snyk CLI JSON or SARIF", async () => {
+ await using f = await snykLocalFixture();
+ const options = {
+ provider: "snyk" as const,
+ repository: f.repository,
+ sourceKey: "example",
+ };
+ const credentials = mock(async () => {
+ throw new Error("Reached Snyk credentials");
+ });
+ for (const file of [snykJson(), snykSarif()]) {
+ await f.writeJson(file);
+ const report = await readSnykFindings(f.file, "local");
+ const dependencies = { environment: f.environment, credentials };
+ for (const input of [
+ report,
+ { ...report, snykRestContext: report.snykRestContext },
+ ]) {
+ expect(
+ (await prepareNormalizedLocalImport(input, options, dependencies))
+ .preview.findings,
+ ).toHaveLength(1);
+ await expect(
+ prepareNormalizedExternalPublication(input, options, dependencies),
+ ).rejects.toThrow("Reached Snyk credentials");
+ }
+ const malformed = { ...report, snykRestContext: null };
+ await expect(
+ prepareNormalizedLocalImport(malformed, options, dependencies),
+ ).rejects.toThrow(/Snyk report context/);
+ await expect(
+ prepareNormalizedExternalPublication(malformed, options, dependencies),
+ ).rejects.toThrow(/Snyk/);
+ }
+ expect(credentials).toHaveBeenCalledTimes(4);
+});
+
+test("a hosted selection cannot store another normalized project's projected assets", async () => {
+ const report = normalizeSnykIssues(snykRestFixture("open-source"));
+ const capture = snykRestFixture("open-source", {
+ sourceRepositoryUrl: "https://github.com/example/another",
+ });
+ const otherId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+ const resource = JSON.parse(capture.projectJson);
+ const target = resource.relationships.target.data;
+ resource.id = otherId;
+ resource.relationships.target.data = { type: "target", id: target.id };
+ const response = JSON.parse(capture.pages[0]!.responseJson);
+ response.data[0].relationships.scan_item.data.id = otherId;
+ const foreign = normalizeSnykIssues({
+ ...capture,
+ projectId: otherId,
+ projectJson: JSON.stringify(resource),
+ targetJson: JSON.stringify(target),
+ pages: [{ startingAfter: null, responseJson: JSON.stringify(response) }],
+ });
+ const native = foreign.findings[0]!.evidence.source_data!;
+ const row = report.findings[0]!;
+ await using fixture = await snykLocalFixture({
+ remote: report.sourceRepositoryUrl,
+ });
+ const prepare = () => fixture.prepareNormalized(report);
+ row.source_finding_id = "reader-row";
+ for (const key of ["project", "target"]) {
+ const json = String(native[key + "Json"]);
+ for (const projected of [
+ { [key + "Json"]: json },
+ { [key]: JSON.parse(json) },
+ ]) {
+ row.evidence.source_data = projected;
+ await expect(prepare()).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ }
+ const license = JSON.parse(String(native["issueJson"]));
+ license.attributes.type = "license";
+ for (const projected of [
+ { issue: license },
+ { issueJson: JSON.stringify(license) },
+ ]) {
+ row.evidence.source_data = projected;
+ await expect(prepare()).rejects.toThrow("selected project");
+ }
+ delete row.evidence.source_data;
+ await expect(prepare()).rejects.toThrow("Original Snyk REST issue evidence");
+ expect(await fixture.read()).toBeEmpty();
+});
+
+test("retagged original Snyk records remain scoped without a matching source ID or format", async () => {
+ const full = normalizeSnykIssues(snykRestFixture("open-source"));
+ const row = full.findings[0]!;
+ const original = row.evidence.source_data!;
+ const { read, findings, excluded } = full;
+ const projected = { read, findings, excluded };
+ row.source_finding_id = "wiz-reader-row";
+ const legacy = {
+ ...original,
+ project: JSON.parse(String(original["projectJson"])),
+ issue: JSON.parse(String(original["issueJson"])),
+ target: null,
+ };
+ delete (legacy as Record<string, unknown>)["projectJson"];
+ delete (legacy as Record<string, unknown>)["issueJson"];
+ await using f = await snykLocalFixture();
+ const opts = {
+ provider: "wiz" as const,
+ sourceKey: "example",
+ repository: f.repository,
+ };
+ const credentials = mock(async () => {
+ throw new Error("Unexpected Cloud credentials");
+ });
+ for (const source of [
+ original,
+ legacy,
+ { ...legacy, issueJson: "{}", projectJson: "{" },
+ { ...original, issue: {}, project: {} },
+ ]) {
+ row.evidence.source_data = { ...source, format: "reader/v1" };
+ delete row.evidence.source_data["snykRestIssueKey"];
+ delete row.evidence.source_data["apiVersion"];
+ await expect(
+ prepareNormalizedExternalPublication(projected, opts, {
+ environment: f.environment,
+ credentials,
+ }),
+ ).rejects.toThrow("local import");
+ await expect(
+ prepareNormalizedLocalImport(projected, opts, {
+ environment: f.environment,
+ }),
+ ).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ const mismatched = { ...legacy.project, id: snykOptions.organizationId };
+ const target = legacy.project.relationships.target.data;
+ for (const resources of [
+ { project: mismatched, issue: legacy.issue, target: null },
+ { target },
+ {
+ projectJson: JSON.stringify(mismatched),
+ issueJson: original["issueJson"],
+ targetJson: "null",
+ },
+ {
+ projectJson: JSON.stringify(mismatched),
+ snykRestIssueKey: original["snykRestIssueKey"],
+ targetJson: "null",
+ },
+ {
+ snykRestIssueKey: original["snykRestIssueKey"],
+ targetJson: JSON.stringify(target),
+ },
+ ]) {
+ row.evidence.source_data = {
+ ...snykOptions,
+ apiVersion: original["apiVersion"],
+ ...resources,
+ };
+ await expect(
+ prepareNormalizedExternalPublication(projected, opts, {
+ environment: f.environment,
+ credentials,
+ }),
+ ).rejects.toThrow("local import");
+ await expect(
+ prepareNormalizedLocalImport(projected, opts, {
+ environment: f.environment,
+ }),
+ ).rejects.toThrow(
+ "issue" in resources || "issueJson" in resources
+ ? /different project/
+ : /Snyk/,
+ );
+ }
+ for (const missing of ["issueJson", "projectJson"]) {
+ row.evidence.source_data = { ...original, format: "reader/v1" };
+ delete row.evidence.source_data[missing];
+ await expect(
+ prepareNormalizedExternalPublication(projected, opts, {
+ environment: f.environment,
+ credentials,
+ }),
+ ).rejects.toThrow("local import");
+ await expect(
+ prepareNormalizedLocalImport(projected, opts, {
+ environment: f.environment,
+ }),
+ ).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ row.source_finding_id = normalizeSnykIssues(
+ snykRestFixture("open-source"),
+ ).findings[0]!.source_finding_id;
+ const otherTarget = {
+ ...target,
+ id: snykOptions.organizationId,
+ attributes: { url: "https://github.com/example/another-repository" },
+ };
+ for (const extra of [
+ { project: legacy.project, issue: legacy.issue },
+ { target: otherTarget },
+ ]) {
+ row.evidence.source_data = { ...original, ...extra };
+ await expect(
+ prepareNormalizedLocalImport(
+ projected,
+ { ...opts, provider: "snyk" },
+ { environment: f.environment },
+ ),
+ ).rejects.toThrow("both v1 and v2");
+ }
+ expect(credentials).not.toHaveBeenCalled();
+});
+
+test("an independently verified GitHub source applies to a CLI-monitored Snyk project", async () => {
+ const url = "https://scm.example.invalid/Org/repo";
+ const report = snykRestFixture("open-source", { sourceRepositoryUrl: url });
+ const project = JSON.parse(report.projectJson);
+ project.attributes.origin = "cli";
+ report.projectJson = JSON.stringify(project);
+ await using fixture = await snykLocalFixture({
+ remote: "[email protected]:org/REPO.git",
+ });
+ const normalized = normalizeSnykIssues(report);
+ const prepare = (
+ sourceRepositories?: { url: string; platform: "github" }[],
+ ) =>
+ prepareNormalizedLocalImport(
+ normalized,
+ {
+ provider: "snyk",
+ repository: fixture.repository,
+ sourceKey: "example/project",
+ },
+ { environment: fixture.environment, sourceRepositories },
+ );
+ await expect(prepare()).rejects.toThrow("configured remote");
+ expect(
+ (await prepare([{ url, platform: "github" }])).preview.findings,
+ ).toHaveLength(1);
+ delete normalized.findings[0]!.evidence.source_data;
+ await expect(prepare([{ url, platform: "github" }])).rejects.toThrow(/Snyk/);
+ normalized.findings[0]!.source_finding_id = "projected-issue";
+ await expect(prepare([{ url, platform: "github" }])).rejects.toThrow(/Snyk/);
+});
+
+test("a serialized Snyk report keeps its monitored asset when a reader supplies a repository URL", async () => {
+ const repository = "https://scm.example.invalid/team/project";
+ const other = "https://scm.example.invalid/another/project";
+ const report = normalizeSnykIssues(
+ snykRestFixture("open-source", { sourceRepositoryUrl: repository }),
+ );
+ const serialized = JSON.parse(JSON.stringify(report)) as typeof report;
+
+ const credentials = mock(async () => {
+ throw new Error("Unexpected Cloud credentials");
+ });
+ await using matching = await snykLocalFixture({ remote: repository });
+ const options = {
+ provider: "snyk" as const,
+ sourceKey: "project",
+ repository: matching.repository,
+ };
+ await expect(
+ prepareNormalizedExternalPublication(
+ serialized,
+ { ...options, repository: other },
+ { environment: matching.environment, credentials },
+ ),
+ ).rejects.toThrow("local import");
+ expect(credentials).not.toHaveBeenCalled();
+ expect(
+ (
+ await prepareNormalizedLocalImport(serialized, options, {
+ environment: matching.environment,
+ })
+ ).preview.findings,
+ ).toHaveLength(1);
+
+ await using foreign = await snykLocalFixture({ remote: other });
+ const { sourceRepositoryUrl: _url, ...fields } = serialized;
+ const foreignUrl = Object.assign(
+ Object.create({
+ get sourceRepositoryUrl() {
+ return other;
+ },
+ }),
+ fields,
+ );
+ await expect(
+ prepareNormalizedLocalImport(
+ foreignUrl,
+ { ...options, repository: foreign.repository },
+ { environment: foreign.environment },
+ ),
+ ).rejects.toThrow("original Snyk project");
+});
+
+test("projected Snyk findings cannot change destination by losing the report format", async () => {
+ const report = normalizeSnykIssues(snykRestFixture("open-source"));
+ const row = report.findings[0]!;
+ row.source_finding_id = "reader-id";
+ delete row.evidence.source_data;
+ const credentials = mock(async () => {
+ throw new Error("Unexpected credentials");
+ });
+ await using f = await snykLocalFixture({
+ remote: report.sourceRepositoryUrl,
+ });
+ const options = {
+ provider: "wiz" as const,
+ repository: f.repository,
+ sourceKey: "example",
+ };
+ for (const format of [undefined, "other-format/v1"]) {
+ const context = { ...report.snykRestContext };
+ if (format) context["format"] = format;
+ else delete context["format"];
+ const { snykRestContext: _original, ...fields } = report;
+ const projected = Object.assign(
+ Object.create({
+ get snykRestContext() {
+ return context;
+ },
+ }),
+ fields,
+ );
+ await expect(
+ prepareNormalizedExternalPublication(projected, options, {
+ environment: f.environment,
+ credentials,
+ }),
+ ).rejects.toThrow(/Snyk|snyk-rest/);
+ await expect(
+ prepareNormalizedLocalImport(projected, options, {
+ environment: f.environment,
+ }),
+ ).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ expect(credentials).not.toHaveBeenCalled();
+});
+
+test("rows from a different Snyk monitor cannot use the report's source key even on the same Git URL", async () => {
+ const capture = snykRestFixture("open-source");
+ const project = JSON.parse(capture.projectJson);
+ const target = project.relationships.target.data;
+ const integrationId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
+ project.relationships.target.data = { type: target.type, id: target.id };
+ capture.projectJson = JSON.stringify(project);
+ capture.targetJson = JSON.stringify({
+ ...target,
+ relationships: {
+ integration: {
+ data: {
+ type: "integration",
+ id: integrationId,
+ attributes: { integration_type: "github-cloud-app" },
+ },
+ },
+ },
+ });
+ const report = normalizeSnykIssues(capture);
+ const code = snykRestFixture("code");
+ const otherId = "aaaa0000-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+ const replace = (old: string, replacement = otherId) =>
+ JSON.parse(
+ JSON.stringify(capture)
+ .replaceAll(old, replacement)
+ .replace(snykIssue(false).attributes.key, "other-issue-key")
+ .replace(snykIssue(false).id, otherId),
+ ) as typeof capture;
+ const credentials = mock(async () => {
+ throw new Error("Unexpected credentials");
+ });
+ await using f = await snykLocalFixture({
+ remote: report.sourceRepositoryUrl,
+ });
+ const original = report.findings[0]!;
+ for (const other of [
+ replace(capture.organizationId),
+ replace(capture.projectId),
+ replace(target.id),
+ replace(integrationId),
+ replace("github-cloud-app", "github-server-app"),
+ code,
+ { ...capture, apiOrigin: "https://api.au.snyk.io" },
+ ]) {
+ report.findings = normalizeSnykIssues(other).findings;
+ const rowsOnly = {
+ read: 2,
+ findings: [original, ...report.findings],
+ excluded: [],
+ };
+ for (const input of [report, rowsOnly]) {
+ await expect(f.prepareNormalized(input)).rejects.toThrow(
+ "Snyk project scope",
+ );
+ }
+ await expect(
+ prepareNormalizedExternalPublication(
+ report,
+ {
+ provider: "snyk",
+ sourceKey: f.sourceKey,
+ repository: report.sourceRepositoryUrl,
+ },
+ { environment: f.environment, credentials },
+ ),
+ ).rejects.toThrow(/Snyk|snyk-rest/);
+ }
+ expect(credentials).not.toHaveBeenCalled();
+ expect(await f.read()).toHaveLength(0);
+});
+
+test.each(["v1", "v2"] as const)(
+ "a linked %s issue projection uses its report's project and stays local",
+ async (version) => {
+ const report = normalizeSnykIssues(snykRestFixture("open-source"));
+ const row = report.findings[0]!;
+ const full = structuredClone(report);
+ const nativeId = row.source_finding_id;
+ const json = String(row.evidence.source_data!["issueJson"]);
+ const project = (id: string) => {
+ const issue = JSON.parse(json);
+ issue.relationships.scan_item.data.id = id;
+ return {
+ ...snykOptions,
+ ...(version === "v1"
+ ? { issue }
+ : { issueJson: JSON.stringify(issue) }),
+ };
+ };
+ row.source_finding_id = "reader-row";
+ row.evidence.source_data = project("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ const options = {
+ provider: "snyk" as const,
+ sourceKey: fixture.sourceKey,
+ repository: fixture.repository,
+ };
+ const credentials = mock(async () => {
+ throw new Error("Unexpected Cloud credentials");
+ });
+ const { read, findings, excluded } = report;
+ await expect(
+ prepareNormalizedExternalPublication(
+ { read, findings, excluded },
+ { ...options, provider: "wiz" },
+ { environment: fixture.environment, credentials },
+ ),
+ ).rejects.toThrow("local import");
+ expect(credentials).not.toHaveBeenCalled();
+ const prepare = () => fixture.prepareNormalized(report);
+ await expect(prepare()).rejects.toThrow("selected project");
+ row.evidence.source_data = project(snykOptions.projectId);
+ await expect(prepare()).rejects.toThrow("normalized finding ID");
+ row.source_finding_id = nativeId;
+ const issue = JSON.parse(json);
+ const targetlessProject = JSON.parse(
+ String(full.snykRestContext!["projectJson"]),
+ );
+ delete targetlessProject.relationships;
+ Object.assign(
+ row.evidence.source_data,
+ version === "v1"
+ ? { project: targetlessProject }
+ : { projectJson: JSON.stringify(targetlessProject) },
+ );
+ await expect(prepare()).rejects.toThrow(
+ "missing the report's native target",
+ );
+ const foreign = snykRestFixture("open-source", {
+ sourceRepositoryUrl: "https://github.com/example/other",
+ });
+ const alternateId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+ const original = normalizeSnykIssues(
+ JSON.parse(
+ JSON.stringify(foreign).replaceAll(foreign.projectId, alternateId),
+ ),
+ ).snykRestContext!;
+ row.evidence.source_data =
+ version === "v1"
+ ? { issue, projectJson: original["projectJson"] }
+ : {
+ issueJson: json,
+ project: JSON.parse(String(original["projectJson"])),
+ };
+ await expect(prepare()).rejects.toThrow("both v1 and v2");
+ expect(await fixture.read()).toBeEmpty();
+ const asset = report.snykRestContext!;
+ const selected =
+ version === "v1"
+ ? {
+ issue,
+ project: JSON.parse(String(asset["projectJson"])),
+ target: null,
+ }
+ : {
+ issueJson: json,
+ projectJson: asset["projectJson"],
+ targetJson: asset["targetJson"],
+ };
+ row.evidence.source_data = { ...selected, projectId: alternateId };
+ await expect(prepare()).rejects.toThrow("project");
+ row.evidence.source_data = selected;
+ expect((await (await prepare()).import()).counts.created).toBe(1);
+ expect((await (await prepare()).import()).counts.unchanged).toBe(1);
+ const [stored] = await fixture.read();
+ const listed = {
+ read: 1,
+ findings: [
+ {
+ source_finding_id: stored!.sourceFindingId,
+ evidence: stored!.evidence,
+ },
+ ],
+ excluded: [],
+ };
+ const replay = await fixture.prepareNormalized(listed);
+ expect((await replay.import()).counts.unchanged).toBe(1);
+ await expect(
+ prepareNormalizedExternalPublication(
+ listed,
+ { ...options, provider: "wiz" },
+ { environment: fixture.environment, credentials },
+ ),
+ ).rejects.toThrow("local import");
+ expect(credentials).not.toHaveBeenCalled();
+ const complete = await fixture.prepareNormalized(full);
+ expect((await complete.import()).counts.created).toBe(0);
+ expect(await fixture.read()).toHaveLength(1);
+ },
+);
+
+test("unmarked native v1 rows survive unrelated issueJson data", async () => {
+ const { read, findings, excluded } = normalizeSnykIssues(
+ snykRestFixture("open-source"),
+ );
+ const row = findings[0]!;
+ const original = row.evidence.source_data!;
+ row.evidence.source_data = {
+ ...snykOptions,
+ apiVersion: original["apiVersion"],
+ project: JSON.parse(String(original["projectJson"])),
+ target: null,
+ issue: JSON.parse(String(original["issueJson"])),
+ issueJson: "{}",
+ };
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ const result = await fixture.prepareNormalized({ read, findings, excluded });
+ expect((await result.import()).counts.created).toBe(1);
+});
+
+test("a complete SDK row replays with reformatted native JSON and reader annotations", async () => {
+ const wire = snykRestFixture("open-source");
+ const report = normalizeSnykIssues(wire);
+ const row = report.findings[0]!;
+ row.evidence.title = "Reader title";
+ const retained = row.evidence.source_data!;
+ retained["readerNote"] = "preserved";
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ const prepare = () => fixture.prepareNormalized(report);
+ expect((await (await prepare()).import()).counts.created).toBe(1);
+ for (const field of ["projectJson", "issueJson"]) {
+ const entries = Object.entries(JSON.parse(String(retained[field])));
+ retained[field] = JSON.stringify(
+ Object.fromEntries(entries.reverse()),
+ null,
+ 2,
+ );
+ }
+ retained["targetJson"] = " null\n";
+ const key = retained["snykRestIssueKey"];
+ delete retained["snykRestIssueKey"];
+ delete retained["format"];
+ expect((await (await prepare()).import()).counts.unchanged).toBe(1);
+ const [stored] = await fixture.read();
+ expect(stored!.version).toBe(1);
+ expect(stored!.evidence.title).toBe("Reader title");
+ expect(stored!.evidence.source_data).toMatchObject({
+ format: wire.format,
+ snykRestIssueKey: key,
+ readerNote: "preserved",
+ });
+});
diff --git a/sdk/typescript/tests-ts/snyk-rest-findings.test.ts b/sdk/typescript/tests-ts/snyk-rest-findings.test.ts
new file mode 100644
index 000000000..35bdc095a
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-findings.test.ts
@@ -0,0 +1,820 @@
+import { expect, test } from "bun:test";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import {
+ collectSnykIssues,
+ normalizeSnykIssues,
+ type CollectSnykIssuesOptions,
+} from "../src/snyk-rest-findings.js";
+import {
+ createAndReplayFinding,
+ updateStoredFinding,
+} from "./external-findings-local-helpers.js";
+
+import {
+ snykLocalFixture,
+ snykOptions as options,
+ snykProject as project,
+ snykRestFixture,
+ snykIssue as issue,
+} from "./support/snyk-rest-fixtures.js";
+
+const environment = {
+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",
+ SNYK_TOKEN: "test-token",
+};
+
+function transport(...responses: unknown[]) {
+ const calls: URL[] = [];
+ return {
+ calls,
+ collect(
+ selected: CollectSnykIssuesOptions = options,
+ env: NodeJS.ProcessEnv = environment,
+ ) {
+ return collectSnykIssues(selected, {
+ environment: env,
+ fetch: async (url, init) => {
+ calls.push(url);
+ expect(init.redirect).toBe("error");
+ expect(new Headers(init.headers).get("authorization")).toBe(
+ "token test-token",
+ );
+ if (responses.length === 0) throw new Error("Unexpected request");
+ return Response.json(responses.shift());
+ },
+ });
+ },
+ };
+}
+
+test.each(["open-source", "code"] as const)(
+ "Snyk %s follows scoped pagination, saves original evidence, and replays unchanged in SQLite",
+ async (product) => {
+ const code = product === "code";
+ const asset = project(code ? "sast" : "npm");
+ const record = issue(code);
+ if (code) {
+ const { representations } = record.attributes.coordinates[0]!;
+ const location = representations[0]!.sourceLocation!;
+ for (const file of [".", "src/", "src/.", "src\\app.ts"])
+ representations.push({ sourceLocation: { ...location, file } });
+ }
+ const path = `/rest/orgs/${options.organizationId}/issues`;
+ const cursor = "next+/=";
+ const api = transport(
+ asset,
+ {
+ data: [],
+ links: {
+ self: path,
+ prev: null,
+ next: `?starting_after=${encodeURIComponent(cursor)}`,
+ },
+ },
+ {
+ data: [record],
+ links: {
+ self: { href: `?starting_after=${encodeURIComponent(cursor)}` },
+ prev: "?ending_before=opaque",
+ },
+ },
+ );
+ const report = await api.collect({ ...options, product });
+ expect(api.calls.map((url) => url.pathname)).toEqual([
+ `/rest/orgs/${options.organizationId}/projects/${options.projectId}`,
+ path,
+ path,
+ ]);
+ for (const url of api.calls.slice(1)) {
+ expect(url.origin).toBe(options.apiOrigin);
+ expect(Object.fromEntries(url.searchParams)).toMatchObject({
+ "scan_item.type": "project",
+ "scan_item.id": options.projectId,
+ type: record.attributes.type,
+ status: "open,resolved",
+ });
+ expect(url.searchParams.get("include_code_flows")).toBe(
+ code ? "true" : null,
+ );
+ }
+ expect(api.calls[2]!.searchParams.get("starting_after")).toBe(cursor);
+ await using f = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ await f.writeJson(report);
+ const stored = await createAndReplayFinding(f);
+ const retained = stored.evidence.source_data!;
+ expect(JSON.parse(retained["issueJson"] as string)).toEqual(record);
+ expect(JSON.parse(retained["projectJson"] as string)).toEqual(asset.data);
+ if (code) {
+ expect(stored.evidence).toMatchObject({
+ locations: [{ path: "src/app.ts", line: 3 }],
+ code_revision: "abc123",
+ details: { kind: "sast", rule: { id: "sample-rule" } },
+ });
+ } else {
+ expect(stored.evidence.packages).toMatchObject([
+ {
+ name: "example-lib",
+ installed_version: "1.0.0",
+ manifest_path: "app/package.json",
+ },
+ ]);
+ }
+ },
+);
+
+test.each([
+ ["uat", "api.eu.snyk.io"],
+ ["sat", "https://api.eu.snyk.io"],
+])(
+ "an explicit regional Snyk %s token only reaches its own API",
+ async (kind, host) => {
+ const payload = Buffer.from(JSON.stringify({ h: host })).toString(
+ "base64url",
+ );
+ const token = `snyk_${kind}.12345678.${payload}.synthetic`;
+ const seen: string[] = [];
+ const collect = (apiOrigin: string) =>
+ collectSnykIssues(
+ { ...options, apiOrigin, token },
+ {
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ fetch: async (url, init) => {
+ seen.push(url.origin);
+ expect(new Headers(init.headers).get("authorization")).toBe(
+ `token ${token}`,
+ );
+ return Response.json(
+ url.pathname.endsWith("/issues") ? { data: [] } : project(),
+ );
+ },
+ },
+ );
+ await expect(collect("https://api.snyk.io")).rejects.toThrow(
+ "token's API host",
+ );
+ expect(seen).toHaveLength(0);
+ expect((await collect(options.apiOrigin)).complete).toBe(true);
+ expect(seen).toEqual([options.apiOrigin, options.apiOrigin]);
+ },
+);
+
+test("forwarding the environment token keeps its region while a separate SDK token chooses its own", async () => {
+ const calls: Array<[string, string | null]> = [];
+ const collect = (token: string, apiOrigin?: string) =>
+ collectSnykIssues(
+ { ...options, token, apiOrigin },
+ {
+ environment: { ...environment, SNYK_API: options.apiOrigin },
+ fetch: async (url, init) => {
+ calls.push([
+ url.origin,
+ new Headers(init.headers).get("authorization"),
+ ]);
+ return Response.json(
+ url.pathname.endsWith("/issues") ? { data: [] } : project(),
+ );
+ },
+ },
+ );
+ for (const token of [environment.SNYK_TOKEN, environment.SNYK_TOKEN + " "])
+ await expect(collect(token)).rejects.toThrow("SNYK_API");
+ expect(calls).toBeEmpty();
+ await collect(environment.SNYK_TOKEN, options.apiOrigin);
+ await collect("separate-token");
+ expect(calls).toEqual([
+ [options.apiOrigin, "token test-token"],
+ [options.apiOrigin, "token test-token"],
+ ["https://api.snyk.io", "token separate-token"],
+ ["https://api.snyk.io", "token separate-token"],
+ ]);
+});
+
+test("the Snyk token stays in its configured region and on the selected Issues route", async () => {
+ const regional = transport();
+ await expect(
+ regional.collect(options, {
+ ...environment,
+ SNYK_API: "https://api.snyk.io",
+ }),
+ ).rejects.toThrow();
+ expect(regional.calls).toEqual([]);
+
+ const next = "https://other.example.invalid/steal?starting_after=more";
+ const crossOrigin = transport(project(), { data: [], links: { next } });
+ await expect(crossOrigin.collect()).rejects.toThrow();
+ expect(crossOrigin.calls.map((url) => url.origin)).toEqual([
+ options.apiOrigin,
+ options.apiOrigin,
+ ]);
+});
+
+test("compares the Git HTTP authority of native and selected Snyk repositories", async () => {
+ const canonical = "https://127.0.0.1/org/project";
+ const ambiguous = "https://0177.1./org/project";
+ for (const [source, target] of [
+ [canonical, ambiguous],
+ [ambiguous, canonical],
+ ] as const) {
+ const asset = project("npm", target);
+ asset.data.attributes.origin = "cli";
+ const api = transport(asset, { data: [] });
+ await expect(
+ api.collect({ ...options, sourceRepositoryUrl: source }),
+ ).rejects.toThrow("target URL");
+ expect(api.calls).toHaveLength(1);
+ const report = snykRestFixture("open-source", {
+ sourceRepositoryUrl: source,
+ });
+ report.projectJson = JSON.stringify(asset.data);
+ expect(() => normalizeSnykIssues(report)).toThrow("target URL");
+ }
+ expect(
+ normalizeSnykIssues(
+ snykRestFixture("open-source", { sourceRepositoryUrl: canonical }),
+ ).findings,
+ ).toHaveLength(1);
+});
+
+test.each([
+ ["numeric links", 123],
+ ["a self cursor from a later page", { self: "?starting_after=page-two" }],
+ ["a self link to another project", { self: "?scan_item.id=another-project" }],
+ ["a self link to another endpoint", { self: "/v1/issues" }],
+ ["a previous page before the first", { prev: "?ending_before=opaque" }],
+] as const)(
+ "rejects %s during collection and saved replay",
+ async (_, links) => {
+ const page = { data: [issue(false)], links };
+ const api = transport(project(), page);
+ await expect(api.collect()).rejects.toThrow();
+ expect(api.calls).toHaveLength(2);
+
+ const report = snykRestFixture("open-source");
+ report.pages[0]!.responseJson = JSON.stringify(page);
+ expect(() => normalizeSnykIssues(report)).toThrow();
+ },
+);
+
+test.each([
+ "https://api.snyk.io/rest/orgs/" +
+ options.organizationId +
+ "/issues?ending_before=opaque",
+ "/rest/orgs/another-organization/issues?ending_before=opaque",
+ "?scan_item.id=another-project&ending_before=opaque",
+ "?ending_before=first&ending_before=second",
+ "?starting_after=forward",
+])(
+ "rejects a later page with an out-of-scope previous link %s",
+ async (prev) => {
+ const first = { data: [], links: { next: "?starting_after=page-two" } };
+ const last = { data: [], links: { prev } };
+ const api = transport(project(), first, last);
+ await expect(api.collect()).rejects.toThrow("Snyk previous page link");
+ expect(api.calls).toHaveLength(3);
+
+ const report = snykRestFixture("open-source");
+ report.pages = [
+ { startingAfter: null, responseJson: JSON.stringify(first) },
+ { startingAfter: "page-two", responseJson: JSON.stringify(last) },
+ ];
+ expect(() => normalizeSnykIssues(report)).toThrow(
+ "Snyk previous page link",
+ );
+ },
+);
+
+test("an invalid issue key cannot hide a duplicate resource UUID in saved pages", async () => {
+ const valid = issue(false);
+ const invalid = { ...valid, attributes: { ...valid.attributes, key: null } };
+ const page = { data: [valid, invalid] };
+ await expect(transport(project(), page).collect()).rejects.toThrow(
+ "overlapping issue IDs",
+ );
+
+ const report = snykRestFixture("open-source");
+ report.pages[0]!.responseJson = JSON.stringify(page);
+ const result = normalizeSnykIssues(report);
+ expect(result.findings).toBeEmpty();
+ expect(result.excluded).toMatchObject([
+ { position: 1, reason: expect.stringContaining("overlapping issue IDs") },
+ { position: 2, reason: expect.stringContaining("Snyk issue key") },
+ ]);
+});
+
+test("a malformed copy of a scoped issue cannot update its stored evidence", async () => {
+ const valid = issue(false);
+ const report = snykRestFixture("open-source");
+ await using fixture = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ await fixture.writeJson(report);
+ const saved = await createAndReplayFinding(fixture);
+
+ const changed = {
+ ...valid,
+ attributes: { ...valid.attributes, title: "Changed" },
+ };
+ const { attributes, ...missing } = valid;
+ const independent = {
+ ...valid,
+ id: "55555555-5555-4555-8555-555555555555",
+ attributes: { ...attributes, key: "independent" },
+ };
+ // An explicitly different product remains a per-row exclusion.
+ const otherProduct = {
+ ...independent,
+ attributes: { ...independent.attributes, type: "code" },
+ };
+ for (const malformed of [
+ missing,
+ { ...valid, id: undefined },
+ { ...valid, id: "invalid" },
+ ]) {
+ const page = { data: [changed, malformed, independent, otherProduct] };
+ report.pages[0]!.responseJson = JSON.stringify(page);
+ await fixture.writeJson(report);
+
+ const prepared = await fixture.prepare();
+ expect(prepared.preview.excluded.map((row) => row.position)).toEqual([
+ 1, 2, 4,
+ ]);
+ expect((await prepared.import()).counts.updated).toBe(0);
+ const rows = await fixture.read();
+ expect(rows).toHaveLength(2);
+ expect(rows).toContainEqual(saved);
+ }
+});
+
+test("Snyk selections keep SCM coordinates out of CLI and API projects", async () => {
+ async function capture(origin: string, independent = false) {
+ const asset = project("sast");
+ asset.data.attributes.origin = origin;
+ const row = issue(true);
+ if (independent) {
+ row.id = "55555555-5555-4555-8555-555555555555";
+ row.attributes.key = "independent";
+ }
+ const report = await transport(asset, { data: [row] }).collect({
+ ...options,
+ product: "code",
+ });
+ return normalizeSnykIssues(report);
+ }
+
+ const cli = await capture("cli");
+ const scm = await capture("github");
+ const api = await capture("api", true);
+ await using fixture = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ await (await fixture.prepareNormalized(cli)).import();
+ const saved = await fixture.read();
+ expect(saved[0]!.evidence.locations).toEqual([]);
+ expect(scm.findings[0]!.evidence.locations).toEqual([
+ { path: "src/app.ts", line: 3 },
+ ]);
+
+ await expect(
+ fixture.prepareNormalized({ ...cli, findings: scm.findings }),
+ ).rejects.toThrow("project scope");
+ await expect(
+ fixture.prepareNormalized({
+ read: 2,
+ excluded: [],
+ findings: [...scm.findings, ...api.findings],
+ }),
+ ).rejects.toThrow("project scope");
+ expect(await fixture.read()).toEqual(saved);
+ expect(
+ (
+ await (
+ await fixture.prepareNormalized({ ...cli, findings: api.findings })
+ ).import()
+ ).counts.created,
+ ).toBe(1);
+});
+
+test("normalized Snyk selections cannot import two keys for one native issue", async () => {
+ const first = normalizeSnykIssues(snykRestFixture("open-source"));
+ const nextIssue = issue(false);
+ nextIssue.attributes.key = "rekeyed";
+ const report = snykRestFixture("open-source");
+ report.pages[0]!.responseJson = JSON.stringify({ data: [nextIssue] });
+ const second = normalizeSnykIssues(report);
+ expect(first.findings[0]!.source_finding_id).not.toBe(
+ second.findings[0]!.source_finding_id,
+ );
+ await using fixture = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ const selected = {
+ ...first,
+ read: 2,
+ findings: [...first.findings, ...second.findings],
+ };
+ const prepare = () => fixture.prepareNormalized(selected);
+ await expect(prepare()).rejects.toThrow("overlapping issue IDs");
+ expect(await fixture.read()).toBeEmpty();
+
+ nextIssue.id = "55555555-5555-4555-8555-555555555555";
+ report.pages[0]!.responseJson = JSON.stringify({ data: [nextIssue] });
+ selected.findings = [
+ ...first.findings,
+ ...normalizeSnykIssues(report).findings,
+ ];
+ expect((await (await prepare()).import()).counts.created).toBe(2);
+ expect((await (await prepare()).import()).counts.unchanged).toBe(2);
+});
+
+const invalidCoordinates = [
+ 7,
+ { state: "open", representations: [{ sourceLocation: 7 }] },
+];
+test.each(invalidCoordinates)("rejects numeric Code data %j", async (value) => {
+ const report = snykRestFixture("code");
+ await using fixture = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ await fixture.writeJson(report);
+ expect((await (await fixture.prepare()).import()).counts.created).toBe(1);
+ const stored = await fixture.read();
+
+ const malformed = issue(true);
+ report.pages[0]!.responseJson = JSON.stringify({
+ data: [
+ {
+ ...malformed,
+ attributes: { ...malformed.attributes, coordinates: [value] },
+ },
+ ],
+ });
+ await fixture.writeJson(report);
+ const prepared = await fixture.prepare();
+ expect((await prepared.import()).counts.updated).toBe(0);
+ expect(prepared.preview.findings).toBeEmpty();
+ expect(prepared.preview.excluded).toMatchObject([
+ { position: 1, reason: expect.stringContaining("must be an object") },
+ ]);
+ expect(await fixture.read()).toEqual(stored);
+});
+
+test("rejects mismatched project evidence before persisting a local import", async () => {
+ const other = "https://github.com/example/other";
+ const wrongProject = transport(project("npm", other));
+ await expect(wrongProject.collect()).rejects.toThrow();
+ expect(wrongProject.calls).toHaveLength(1);
+ const wrongIssue = transport(project(), {
+ data: [issue(false, "55555555-5555-4555-8555-555555555555")],
+ });
+ await expect(wrongIssue.collect()).rejects.toThrow();
+
+ const report = await transport(project(), { data: [issue(false)] }).collect();
+ await using f = await snykLocalFixture({ remote: other });
+ await f.writeJson(report);
+ await expect(f.prepare()).rejects.toThrow();
+ expect(await f.read()).toEqual([]);
+});
+
+test("retains numeric evidence exactly and identifies an issue by its vendor key across resurfacings", async () => {
+ const original = issue(false);
+ const raw = JSON.stringify({
+ data: [{ ...original, original_count: 0 }],
+ }).replace('"original_count":0', '"original_count":-90071992547409930e-1');
+ const responses = [JSON.stringify(project()), raw];
+ const report = await collectSnykIssues(options, {
+ environment,
+ fetch: async () => new Response(responses.shift()),
+ });
+ expect(report.pages[0]!.responseJson).toContain(
+ '"original_count":-90071992547409930e-1',
+ );
+ const row = normalizeSnykIssues(JSON.parse(JSON.stringify(report)))
+ .findings[0]!;
+ expect(row.evidence.source_data?.["issueJson"]).toContain(
+ '"original_count":-9007199254740993',
+ );
+ report.pages[0]!.responseJson = raw.replace(
+ original.id,
+ "77777777-7777-4777-8777-777777777777",
+ );
+ expect(normalizeSnykIssues(report).findings[0]!.source_finding_id).toBe(
+ row.source_finding_id,
+ );
+});
+
+test("rechecks Snyk Code repository evidence for direct normalized imports without Git remotes", async () => {
+ const report = await transport(project("sast"), {
+ data: [issue(true)],
+ }).collect({
+ ...options,
+ product: "code",
+ });
+ const normalized = normalizeSnykIssues(report);
+ await using f = await snykLocalFixture();
+ const settings = {
+ provider: "snyk" as const,
+ sourceKey: f.sourceKey,
+ repository: f.repository,
+ };
+ const deps = { environment: f.environment };
+ await expect(
+ prepareNormalizedLocalImport(
+ normalized,
+ { ...settings, provider: "github" },
+ deps,
+ ),
+ ).rejects.toThrow("snyk provider");
+ const other = "https://github.com/example/other";
+ await expect(
+ prepareNormalizedLocalImport(normalized, settings, {
+ ...deps,
+ sourceRepositories: [{ url: other }],
+ }),
+ ).rejects.toThrow("original Snyk project");
+ normalized.findings[0]!.evidence.details!.repository!.url = other;
+ await expect(
+ prepareNormalizedLocalImport(normalized, settings, deps),
+ ).rejects.toThrow("original Snyk project");
+});
+
+test("an empty Snyk report still binds the selected checkout to the monitored project", async () => {
+ const sourceRepositoryUrl = "https://git.example.invalid/team/repository";
+ const asset = project("npm", sourceRepositoryUrl);
+ asset.data.attributes.origin = "cli";
+ const report = await transport(asset, { data: [] }).collect({
+ ...options,
+ sourceRepositoryUrl,
+ });
+ // A custom HTTP server can assign the two URLs to different repositories.
+ await using f = await snykLocalFixture({
+ remote: sourceRepositoryUrl + ".git",
+ });
+ await f.writeJson(report);
+ await expect(f.prepare()).rejects.toThrow("configured remote");
+ await expect(
+ f.prepare({ sourceRepositoryUrl: options.sourceRepositoryUrl }),
+ ).rejects.toThrow("original Snyk project");
+});
+
+test("requires target details when the project links a target without its URL", async () => {
+ const expanded = project();
+ const link = expanded.data.relationships.target.data;
+ link.attributes.url = "";
+ const separate = {
+ type: "target",
+ id: link.id,
+ attributes: { url: options.sourceRepositoryUrl },
+ };
+ const api = transport(expanded, { data: separate }, { data: [issue(false)] });
+ const report = await api.collect();
+ expect(normalizeSnykIssues(report).findings).toHaveLength(1);
+ expect(() =>
+ normalizeSnykIssues({
+ ...report,
+ sourceRepositoryUrl: "https://example.invalid/other/repo",
+ targetJson: "null",
+ }),
+ ).toThrow("target");
+});
+
+test("a contradictory integration label cannot alias a distinct Azure repository", async () => {
+ const url = "https://dev.azure.com/example/project/_git/repo";
+ const response = project("npm", url + ".git");
+ response.data.attributes.origin = "github-enterprise";
+ await expect(
+ transport(response).collect({ ...options, sourceRepositoryUrl: url }),
+ ).rejects.toThrow("target URL");
+});
+
+test("checks typed Snyk repository URLs against original evidence and the checkout", async () => {
+ const sourceRepositoryUrl = "https://gitlab.com/Team/Repo";
+ const asset = project("sast", sourceRepositoryUrl);
+ asset.data.attributes.origin = "gitlab";
+ const report = normalizeSnykIssues(
+ await transport(asset, { data: [issue(true)] }).collect({
+ ...options,
+ product: "code",
+ sourceRepositoryUrl,
+ }),
+ );
+ const evidence = report.findings[0]!.evidence;
+ await using f = await snykLocalFixture({ remote: sourceRepositoryUrl });
+ const settings = {
+ provider: "snyk" as const,
+ sourceKey: f.sourceKey,
+ repository: f.repository,
+ };
+ const prepare = (environment = f.environment) =>
+ prepareNormalizedLocalImport(report, settings, { environment });
+ expect((await prepare()).preview.findings).toHaveLength(1);
+ await expect(
+ prepare({
+ ...f.environment,
+ GIT_CONFIG_COUNT: "1",
+ GIT_CONFIG_KEY_0: "url.https://gitlab.com/other/repository.insteadOf",
+ GIT_CONFIG_VALUE_0: sourceRepositoryUrl,
+ } as typeof f.environment),
+ ).rejects.toThrow("configured remote");
+ evidence.details!.repository!.url = "https://gitlab.com/team/repo";
+ await expect(prepare()).rejects.toThrow("original Snyk project");
+});
+
+test("preserves explicit repository ports and literal Git paths on custom hosts", async () => {
+ const sourceRepositoryUrl = "https://scm.example.invalid/team/repo";
+ for (const [source, original] of [
+ [sourceRepositoryUrl, "https://scm.example.invalid:443/team/repo"],
+ [sourceRepositoryUrl + "{a}", sourceRepositoryUrl + "%7Ba%7D"],
+ ] as const) {
+ const asset = project("npm", original);
+ asset.data.attributes.origin = "api";
+ await expect(
+ transport(asset).collect({ ...options, sourceRepositoryUrl: source }),
+ ).rejects.toThrow("target URL");
+ }
+});
+
+test("accepts standard GitHub Enterprise clone path spellings from saved Snyk targets", async () => {
+ const url = "https://scm.example.invalid/Org/repo";
+ const withClone = (clone: string) => {
+ const asset = project("npm", clone);
+ asset.data.attributes.origin = "github-enterprise";
+ return transport(asset, { data: [] }).collect({
+ ...options,
+ sourceRepositoryUrl: url,
+ });
+ };
+ expect(
+ normalizeSnykIssues(
+ await withClone("[email protected]:/org/REPO.git"),
+ ).read,
+ ).toBe(0);
+ expect(
+ normalizeSnykIssues(
+ await withClone("ssh://[email protected]/Org/%72epo%2Egit"),
+ ).read,
+ ).toBe(0);
+ await expect(
+ withClone("ssh://[email protected]/elsewhere/%2e%2e/Org/repo"),
+ ).rejects.toThrow("target URL");
+});
+
+test.each([
+ [
+ "gitlab",
+ "https://git.example.invalid/Team/Repo",
+ "[email protected]:Team/Repo.git",
+ ],
+ [
+ "gitlab",
+ "https://git.example.invalid/Team/Repo",
+ "https://git.example.invalid/Team/Repo.git",
+ ],
+ [
+ "azure-repos",
+ "https://dev.azure.com/org/My%20Project/_git/Repo",
+ "[email protected]:v3/org/My%20Project/Repo",
+ ],
+ [
+ "azure-repos",
+ "https://dev.azure.com/org/My%20Project/_git/Repo",
+ "ssh://[email protected]/v3/org/My Project/Repo",
+ ],
+ [
+ "azure-repos",
+ "https://dev.azure.com/org/My%20Project/_git/Repo",
+ "ssh://[email protected]:22/v3/org/My%20Project/Repo",
+ ],
+ [
+ "azure-repos",
+ "https://dev.azure.com/org/My%20Project/_git/Repo",
+ "ssh://[email protected]/v3/org/My%2520Project/Repo",
+ ],
+])(
+ "matches a monitored %s project at %s to the checkout %s",
+ async (origin, sourceRepositoryUrl, remote) => {
+ const asset = project("npm", sourceRepositoryUrl);
+ asset.data.attributes.origin = origin;
+ const report = await transport(asset, { data: [issue(false)] }).collect({
+ ...options,
+ sourceRepositoryUrl,
+ });
+ await using fixture = await snykLocalFixture({ remote });
+ await fixture.writeJson(report);
+ if (origin === "gitlab") {
+ await expect(fixture.prepare()).rejects.toThrow("configured remote");
+ const prepare = (url: string) =>
+ prepareNormalizedLocalImport(
+ normalizeSnykIssues(report),
+ {
+ provider: "snyk",
+ sourceKey: options.projectId,
+ repository: fixture.repository,
+ },
+ {
+ environment: fixture.environment,
+ sourceRepositories: [{ url, platform: "gitlab" }],
+ },
+ );
+ expect(
+ (await prepare(sourceRepositoryUrl)).preview.findings,
+ ).toHaveLength(1);
+ await expect(
+ prepare(sourceRepositoryUrl.replace("Repo", "repo")),
+ ).rejects.toThrow();
+ } else {
+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);
+ }
+ const scoped = async (clone: string, provider: string) => {
+ const asset = project("npm", clone);
+ asset.data.attributes.origin = provider;
+ return transport(asset, { data: [] }).collect({
+ ...options,
+ sourceRepositoryUrl,
+ });
+ };
+ await expect(
+ scoped(remote.replace("Repo", "repo"), origin),
+ ).rejects.toThrow("target URL");
+ await expect(
+ scoped(
+ remote.replace(
+ /(^git@|^https:\/\/|^ssh:\/\/git@)[^/:]+/u,
+ "$1other.example.invalid",
+ ),
+ origin,
+ ),
+ ).rejects.toThrow("target URL");
+ if (remote.startsWith("ssh://[email protected]:22/")) {
+ await expect(
+ scoped(remote.replace(":22/", ":2222/"), origin),
+ ).rejects.toThrow("target URL");
+ await expect(
+ scoped(remote.replace("git@", "reader@"), origin),
+ ).rejects.toThrow("target URL");
+ }
+ if (origin === "gitlab")
+ await expect(scoped(remote, "api")).rejects.toThrow("target URL");
+ },
+);
+
+test.each([
+ ["https://github.com:443/example/repository", true],
+ ["https://[email protected]:443/example/repository", true],
+ ["https://github.com:8443/example/repository", false],
+] as const)(
+ "compares the checkout's actual HTTPS endpoint for %s",
+ async (remote, matches) => {
+ await using fixture = await snykLocalFixture({ remote });
+ await fixture.writeJson(snykRestFixture("open-source"));
+ if (matches)
+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);
+ else await expect(fixture.prepare()).rejects.toThrow("configured remote");
+ },
+);
+
+test.each(["git+ssh", "ssh+git"])(
+ "matches %s GitHub checkouts with the same URI path as ssh",
+ async (scheme) => {
+ const remote = `${scheme}://[email protected]/example/%72epository.git`;
+ await using fixture = await snykLocalFixture({ remote });
+ await fixture.writeJson(snykRestFixture("open-source"));
+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);
+ },
+);
+
+test("a v1 Code location stays unchanged until v2 adds its reported source line to the same row", async () => {
+ const { projectJson, targetJson, pages, ...scope } = snykRestFixture("code");
+ const v1 = {
+ ...scope,
+ format: "snyk-rest-issues/v1",
+ project: JSON.parse(projectJson),
+ target: JSON.parse(targetJson),
+ pages: pages.map(({ startingAfter, responseJson }) => ({
+ startingAfter,
+ response: JSON.parse(responseJson),
+ })),
+ };
+ await using fixture = await snykLocalFixture({
+ remote: options.sourceRepositoryUrl,
+ });
+ await fixture.writeJson(v1);
+ const stored = await createAndReplayFinding(fixture);
+ expect(stored.evidence.locations).toEqual([
+ { path: "src/app.ts", line: null },
+ ]);
+ await fixture.writeJson(snykRestFixture("code"));
+ const updated = await updateStoredFinding(fixture, stored);
+ expect(updated.evidence.locations).toEqual([{ path: "src/app.ts", line: 3 }]);
+ expect((await (await fixture.prepare()).import()).counts.unchanged).toBe(1);
+
+ const v2 = snykRestFixture("code");
+ v2.pages[0]!.responseJson = v2.pages[0]!.responseJson.replace(
+ '"line":3',
+ '"line":"3"',
+ );
+ expect(normalizeSnykIssues(v2).findings[0]!.evidence.locations).toEqual([
+ { path: "src/app.ts", line: null },
+ ]);
+});
diff --git a/sdk/typescript/tests-ts/snyk-rest-git-config.test.ts b/sdk/typescript/tests-ts/snyk-rest-git-config.test.ts
new file mode 100644
index 000000000..581a307bc
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-git-config.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { appendFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import { normalizeSnykIssues } from "../src/snyk-rest-findings.js";
+import {
+ snykLocalFixture,
+ snykOptions,
+ snykRestFixture,
+} from "./support/snyk-rest-fixtures.js";
+
+function prepare(
+ fixture: Awaited<ReturnType<typeof snykLocalFixture>>,
+ sourceRepositoryUrl: string,
+ overrides: NodeJS.ProcessEnv = {},
+) {
+ return prepareNormalizedLocalImport(
+ normalizeSnykIssues(
+ snykRestFixture("open-source", { sourceRepositoryUrl }),
+ ),
+ { repository: fixture.repository, provider: "snyk", sourceKey: "project" },
+ { environment: { ...fixture.environment, ...overrides } },
+ );
+}
+
+test("Snyk checks the remote helper used by fetch when GIT_CONFIG selects a different file", async () => {
+ const remote = snykOptions.sourceRepositoryUrl;
+ await using fixture = await snykLocalFixture({ remote });
+ const config = join(fixture.root, "empty-config");
+ await writeFile(config, "");
+ for (const helper of ["other", ""]) {
+ execFileSync("git", [
+ "config",
+ "--file",
+ join(fixture.repository, ".git", "config"),
+ "remote.origin.vcs",
+ helper,
+ ]);
+ await expect(
+ prepare(fixture, remote, { GIT_CONFIG: config }),
+ ).rejects.toThrow("configured remote");
+ }
+});
+
+test.skipIf(process.platform === "win32")(
+ "invalid UTF-8 in a Git URL cannot alias a Snyk project containing the replacement character",
+ async () => {
+ const prefix = "https://github.com/example/repo";
+ const reported = prefix + "%EF%BF%BD";
+ await using fixture = await snykLocalFixture();
+ await appendFile(
+ join(fixture.repository, ".git", "config"),
+ Buffer.concat([
+ Buffer.from('\n[remote "origin"]\n\turl = ' + prefix),
+ Buffer.from([0xff, 0x0a]),
+ ]),
+ );
+ await expect(prepare(fixture, reported)).rejects.toThrow(
+ "configured remote",
+ );
+ execFileSync("git", ["remote", "add", "upstream", reported], {
+ cwd: fixture.repository,
+ env: fixture.environment,
+ });
+ expect((await prepare(fixture, reported)).preview.findings).toHaveLength(1);
+ },
+);
+
+test("a later fetch URL on the same Git remote cannot bind a Snyk project", async () => {
+ const selected = snykOptions.sourceRepositoryUrl;
+ await using fixture = await snykLocalFixture({
+ remote: selected + "-different",
+ });
+ execFileSync("git", [
+ "config",
+ "--file",
+ join(fixture.repository, ".git", "config"),
+ "--add",
+ "remote.origin.url",
+ selected,
+ ]);
+ await expect(prepare(fixture, selected)).rejects.toThrow("configured remote");
+});
diff --git a/sdk/typescript/tests-ts/snyk-rest-response-scope.test.ts b/sdk/typescript/tests-ts/snyk-rest-response-scope.test.ts
new file mode 100644
index 000000000..900fc5450
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-response-scope.test.ts
@@ -0,0 +1,409 @@
+import { expect, test } from "bun:test";
+import { readSnykFindings } from "../src/snyk-findings.js";
+import { isolatedGitReportFixture } from "./external-findings-local-helpers.js";
+import {
+ collectSnykIssues,
+ normalizeSnykIssues,
+} from "../src/snyk-rest-findings.js";
+import {
+ snykIssue,
+ snykLocalFixture,
+ snykOptions,
+ snykProject,
+ snykRestFixture,
+} from "./support/snyk-rest-fixtures.js";
+
+function capture(...responses: unknown[]) {
+ return collectSnykIssues(
+ { ...snykOptions, token: "example-token" },
+ {
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ fetch: async () => {
+ if (!responses.length) throw new Error("Unexpected Snyk request");
+ return Response.json(responses.shift());
+ },
+ },
+ );
+}
+
+test("project and target JSON formatting preserves exact native numbers and text", () => {
+ const project = snykProject("npm", "").data;
+ const target = {
+ ...project.relationships.target.data,
+ attributes: { url: snykOptions.sourceRepositoryUrl },
+ };
+ const report = snykRestFixture("open-source");
+ const source = (members: string) => {
+ const json = (resource: object) =>
+ `{${members},${JSON.stringify(resource).slice(1)}`;
+ return normalizeSnykIssues({
+ ...report,
+ projectJson: json(project),
+ targetJson: json(target),
+ }).findings[0]!.evidence.source_data!;
+ };
+ const token = "9007199254740993";
+ const original = source(`"amount":${token},"label":"${token}"`);
+ expect(
+ source(`
+ "label": "${token}", "amount": ${token}e0`),
+ ).toEqual(original);
+ for (const field of ["projectJson", "targetJson"]) {
+ expect(original[field]).toContain(`"amount":${token}`);
+ expect(original[field]).toContain(`"label":"${token}"`);
+ }
+});
+
+test("a saved target accepts unexpanded integration linkage and checks a supplied integration type", async () => {
+ const project = snykProject("npm", "");
+ const { type, id } = project.data.relationships.target.data;
+ const target = (attributes?: Record<string, unknown>) => ({
+ data: {
+ type,
+ id,
+ attributes: { url: snykOptions.sourceRepositoryUrl },
+ relationships: {
+ organization: project.data.relationships.organization,
+ integration: {
+ data: {
+ type: "integration",
+ id: "88888888-8888-4888-8888-888888888888",
+ attributes,
+ },
+ },
+ },
+ },
+ });
+ const linked = target().data.relationships.integration;
+ Object.assign(project.data.relationships.target.data, {
+ relationships: { integration: linked },
+ });
+ const saved = await capture(project, target({ integration_type: "github" }), {
+ data: [snykIssue(false)],
+ });
+ const normalizedTarget = (data: unknown) =>
+ normalizeSnykIssues({ ...saved, targetJson: JSON.stringify(data) });
+ expect(normalizedTarget(target().data).findings).toHaveLength(1);
+ expect(() => normalizedTarget(target({}).data)).toThrow(
+ "Snyk integration type",
+ );
+ expect(() =>
+ normalizedTarget(target({ integration_type: "gitlab" }).data),
+ ).toThrow("project's github origin");
+
+ Object.assign(linked.data, {
+ attributes: { integration_type: "github-cloud-app" },
+ });
+ const server = target({ integration_type: "github-server-app" });
+ await expect(
+ capture(project, server, { data: [snykIssue(false)] }),
+ ).rejects.toThrow("target linkage");
+ expect(() =>
+ normalizeSnykIssues({
+ ...saved,
+ projectJson: JSON.stringify(project.data),
+ targetJson: JSON.stringify(server.data),
+ }),
+ ).toThrow("target linkage");
+ const replaced = target({ integration_type: "github" });
+ replaced.data.relationships.integration.data.id =
+ "99999999-9999-4999-8999-999999999999";
+ await using fixture = await snykLocalFixture();
+ await fixture.writeJson({
+ ...saved,
+ targetJson: JSON.stringify(replaced.data),
+ });
+ await expect(readSnykFindings(fixture.file, "local")).rejects.toThrow(
+ "different integration",
+ );
+ await expect(
+ capture(project, replaced, { data: [snykIssue(false)] }),
+ ).rejects.toThrow("different integration");
+});
+
+test("CLI and API targets can have empty integration linkage", async () => {
+ for (const origin of ["cli", "api"]) {
+ const project = snykProject();
+ project.data.attributes.origin = origin;
+ Object.assign(project.data.relationships.target.data, {
+ relationships: { integration: { data: null } },
+ });
+ const saved = await capture(project, { data: [snykIssue(false)] });
+ expect(normalizeSnykIssues(saved).findings).toHaveLength(1);
+ }
+});
+
+test("expanded integrations verify resource type, nullable UUID, and SCM deployment", async () => {
+ const project = snykProject();
+ const target = project.data.relationships.target.data;
+ const original = {
+ type: "integration",
+ id: "88888888-8888-4888-8888-888888888888",
+ attributes: { integration_type: "github" },
+ };
+ const integration = (type: string) => ({
+ attributes: { integration_type: type },
+ });
+ for (const [identity, error, origin = "github"] of [
+ [{ type: "project" }, "integration resource"],
+ [{ type: undefined }, "integration resource"],
+ [{ id: "invalid" }, "integration ID"],
+ [{ id: undefined }, "integration ID"],
+ [{ id: null }, undefined],
+ [
+ integration("bitbucket-cloud"),
+ "project's bitbucket-server",
+ "bitbucket-server",
+ ],
+ [
+ integration("bitbucket-server"),
+ "project's bitbucket-connect-app",
+ "bitbucket-connect-app",
+ ],
+ [integration("bitbucket-connect-app"), undefined, "bitbucket-cloud"],
+ [
+ integration("github-server-app"),
+ "project's github-cloud-app",
+ "github-cloud-app",
+ ],
+ [integration("github-cloud-app"), undefined, "github-enterprise"],
+ [integration("github-server-app"), undefined, "github-enterprise"],
+ ] as const) {
+ project.data.attributes.origin = origin;
+ Object.assign(target, {
+ relationships: { integration: { data: { ...original, ...identity } } },
+ });
+ const collecting = capture(project, { data: [snykIssue(false)] });
+ const saved = {
+ ...snykRestFixture("open-source"),
+ projectJson: JSON.stringify(project.data),
+ };
+ if (error) {
+ await expect(collecting).rejects.toThrow(error);
+ expect(() => normalizeSnykIssues(saved)).toThrow(error);
+ } else {
+ expect((await collecting).complete).toBe(true);
+ expect(normalizeSnykIssues(saved).findings).toHaveLength(1);
+ }
+ }
+});
+
+test("a cross-product issue fails collection but remains an exclusion when reading a saved report", async () => {
+ const data = [snykIssue(false), snykIssue(true)];
+ await expect(capture(snykProject(), { data })).rejects.toThrow(
+ "Only package_vulnerability",
+ );
+ const saved = snykRestFixture("open-source");
+ saved.pages[0]!.responseJson = JSON.stringify({ data });
+ const result = normalizeSnykIssues(saved);
+ expect(result.findings).toHaveLength(1);
+ expect(result.excluded).toMatchObject([
+ { reason: expect.stringContaining("Only package_vulnerability") },
+ ]);
+});
+
+test.each(["expanded", "fetched", "partly expanded"] as const)(
+ "the %s target cannot contradict the selected organization or SCM",
+ async (representation) => {
+ const project = snykProject();
+ const { organization, target } = project.data.relationships;
+ const integration = {
+ data: { type: "integration", id: "88888888-8888-4888-8888-888888888888" },
+ };
+ await using fixture = await isolatedGitReportFixture(
+ "snyk.json",
+ { provider: "snyk", sourceKey: snykOptions.projectId },
+ { remote: snykOptions.sourceRepositoryUrl },
+ );
+ for (const [relationships, error] of [
+ [{ integration }, undefined],
+ [
+ {
+ organization: {
+ data: {
+ ...organization.data,
+ id: "99999999-9999-4999-8999-999999999999",
+ },
+ },
+ },
+ "selected organization",
+ ],
+ [
+ {
+ organization,
+ integration: {
+ data: {
+ ...integration.data,
+ attributes: { integration_type: "gitlab" },
+ },
+ },
+ },
+ "project's github origin",
+ ],
+ ] as const) {
+ const full = { ...target.data, relationships };
+ const partial = {
+ type: full.type,
+ id: full.id,
+ ...(representation === "partly expanded" && { relationships }),
+ };
+ const resource = {
+ ...project.data,
+ relationships: {
+ organization,
+ target: { data: representation === "expanded" ? full : partial },
+ },
+ };
+ const lookup =
+ representation === "expanded"
+ ? null
+ : representation === "fetched"
+ ? full
+ : target.data;
+ const saved = {
+ ...snykRestFixture("open-source"),
+ projectJson: JSON.stringify(resource),
+ targetJson: JSON.stringify(lookup),
+ };
+ await fixture.writeJson(saved);
+ const collecting = capture(
+ { data: resource },
+ ...(lookup ? [{ data: lookup }] : []),
+ { data: [snykIssue(false)] },
+ );
+ if (error) {
+ await expect(collecting).rejects.toThrow(error);
+ expect(() => normalizeSnykIssues(saved)).toThrow(error);
+ await expect(fixture.prepare()).rejects.toThrow(error);
+ } else {
+ expect((await collecting).complete).toBe(true);
+ expect(normalizeSnykIssues(saved).findings).toHaveLength(1);
+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);
+ }
+ }
+ },
+);
+
+test.each([
+ ["cli", {}],
+ ["api", { target: { data: null } }],
+] as const)(
+ "a targetless %s project uses the explicit mapping and verifies its organization",
+ async (origin, target) => {
+ const { data } = snykProject();
+ const { organization } = data.relationships;
+ const project = {
+ ...data,
+ attributes: { ...data.attributes, origin },
+ relationships: { organization, ...target },
+ };
+ const saved = await capture(
+ { data: project },
+ { data: [snykIssue(false)] },
+ );
+ expect(saved.targetJson).toBe("null");
+ expect(normalizeSnykIssues(saved)).toMatchObject({
+ sourceRepositoryUrl: snykOptions.sourceRepositoryUrl,
+ findings: [expect.anything()],
+ });
+ expect(() =>
+ normalizeSnykIssues({
+ ...saved,
+ targetJson: JSON.stringify(data.relationships.target.data),
+ }),
+ ).toThrow("Unexpected separate Snyk target");
+ const unrelated = {
+ ...project,
+ relationships: {
+ ...project.relationships,
+ organization: {
+ data: {
+ ...organization.data,
+ id: "99999999-9999-4999-8999-999999999999",
+ },
+ },
+ },
+ };
+ await expect(capture({ data: unrelated })).rejects.toThrow(
+ "selected organization",
+ );
+ expect(() =>
+ normalizeSnykIssues({ ...saved, projectJson: JSON.stringify(unrelated) }),
+ ).toThrow("selected organization");
+ },
+);
+
+test("direct SDK projections can edit display fields but must retain an importable native Snyk issue", async () => {
+ const captured = snykRestFixture("open-source");
+ const normalized = normalizeSnykIssues(captured);
+ const row = normalized.findings[0]!;
+ const retained = row.evidence.source_data!;
+ const original = String(retained["issueJson"]);
+ await using fixture = await isolatedGitReportFixture(
+ "snyk.json",
+ { provider: "snyk", sourceKey: snykOptions.projectId },
+ { remote: snykOptions.sourceRepositoryUrl },
+ );
+ await fixture.writeJson(captured);
+ await (await fixture.prepare()).import();
+ const stored = await fixture.read();
+ const prepare = () => fixture.prepareNormalized(normalized);
+ row.evidence.title = "Reader projection";
+ for (const [field, value] of [
+ ["status", "absent"],
+ ["ignored", null],
+ ["updated_at", ""],
+ ["effective_severity_level", null],
+ ["title", ""],
+ ["coordinates", {}],
+ ] as const) {
+ const issue = JSON.parse(original);
+ issue.attributes[field] = value;
+ captured.pages[0]!.responseJson = JSON.stringify({ data: [issue] });
+ const saved = normalizeSnykIssues(captured);
+ expect(saved.findings).toHaveLength(0);
+ retained["issueJson"] = JSON.stringify(issue);
+ await expect(prepare()).rejects.toThrow(saved.excluded[0]!.reason);
+ }
+ retained["issueJson"] = original;
+ row.evidence.locations = [{ path: "../outside.ts" }];
+ await expect(prepare()).rejects.toThrow("repository-relative paths");
+ expect(await fixture.read()).toEqual(stored);
+ row.evidence.locations = [{ path: "src/reader.ts" }];
+ expect((await (await prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 1,
+ unchanged: 0,
+ });
+ expect((await fixture.read())[0]).toMatchObject({
+ id: stored[0]!.id,
+ evidence: {
+ title: "Reader projection",
+ locations: [{ path: "src/reader.ts" }],
+ },
+ });
+});
+
+test("a selected Snyk row retains the target URL supplied by its report", async () => {
+ const project = snykProject("npm", "");
+ const target = project.data.relationships.target.data;
+ const read = async (url: string | null) =>
+ normalizeSnykIssues(
+ await capture(
+ project,
+ { data: { ...target, attributes: { url } } },
+ { data: [snykIssue(false)] },
+ ),
+ );
+ const url = snykOptions.sourceRepositoryUrl;
+ const report = await read(url);
+ const withoutUrl = await read(null);
+ await using f = await snykLocalFixture({ remote: url });
+ await f.prepareNormalized(withoutUrl);
+ await (await f.prepareNormalized(report)).import();
+ const stored = await f.read();
+ await expect(
+ f.prepareNormalized({ ...report, findings: withoutUrl.findings }),
+ ).rejects.toThrow("missing the report's native target");
+ expect(await f.read()).toEqual(stored);
+});
diff --git a/sdk/typescript/tests-ts/snyk-rest-scm-proof.test.ts b/sdk/typescript/tests-ts/snyk-rest-scm-proof.test.ts
new file mode 100644
index 000000000..fd399ba38
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-scm-proof.test.ts
@@ -0,0 +1,148 @@
+import { expect, test } from "bun:test";
+import { prepareLocalExternalImport } from "../src/external-findings-import.js";
+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
+import {
+ collectSnykIssues,
+ normalizeSnykIssues,
+ type CollectSnykIssuesOptions,
+} from "../src/snyk-rest-findings.js";
+import type { ExternalSourceRepository } from "../src/external-findings.js";
+import { readSnykFindings } from "../src/snyk-findings.js";
+import { isolatedGitReportFixture } from "./external-findings-local-helpers.js";
+import { snykOptions, snykRestFixture } from "./support/snyk-rest-fixtures.js";
+
+const url = "https://scm.example.invalid/Team/Repo";
+const clone = "[email protected]:Team/Repo.git";
+
+test.each([
+ { origin: "cli", platform: "github", empty: false },
+ { origin: "github", platform: "github", empty: false },
+ { origin: "github-app", platform: "github", empty: false },
+ { origin: "api", platform: "gitlab", empty: true },
+ { origin: "gitlab", platform: "gitlab", empty: false },
+] as const)(
+ "requires independent $platform provenance for a private $origin checkout",
+ async ({ origin, platform, empty }) => {
+ const report = snykRestFixture("open-source", { sourceRepositoryUrl: url });
+ const project = JSON.parse(report.projectJson);
+ project.attributes.origin = origin;
+ // Private projects can report an SSH clone, while GitLab can omit its target.
+ if (origin === "gitlab") delete project.relationships;
+ else project.relationships.target.data.attributes.url = clone;
+ if (empty) report.pages[0]!.responseJson = '{"data":[]}';
+
+ const source = { provider: "snyk", sourceKey: "private/project" } as const;
+ await using fixture = await isolatedGitReportFixture("snyk.json", source, {
+ remote: clone,
+ });
+ const settings = { ...source, repository: fixture.repository };
+ const dependencies = {
+ environment: fixture.environment,
+ sourceRepositories: [{ url, platform }],
+ };
+
+ const options: CollectSnykIssuesOptions = {
+ organizationId: snykOptions.organizationId,
+ projectId: snykOptions.projectId,
+ sourceRepositoryUrl: url,
+ };
+ const collect = (
+ sourceRepositories?: readonly ExternalSourceRepository[],
+ ) =>
+ collectSnykIssues(options, {
+ environment: {
+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",
+ SNYK_TOKEN: "synthetic",
+ },
+ sourceRepositories,
+ fetch: async (request, init) => {
+ expect(new Headers(init.headers).get("authorization")).toBe(
+ "token synthetic",
+ );
+ if (request.pathname.endsWith("/issues")) {
+ expect(request.searchParams.get("type")).toBe(
+ "package_vulnerability",
+ );
+ return new Response(report.pages[0]!.responseJson);
+ }
+ return Response.json({ data: project });
+ },
+ });
+ if (origin !== "gitlab") {
+ await expect(collect()).rejects.toThrow("target URL");
+ await expect(
+ collect([{ url: url + "-other", platform }]),
+ ).rejects.toThrow("target URL");
+ }
+ const acquired = await collect(dependencies.sourceRepositories);
+ expect(acquired.product).toBe("open-source");
+ await fixture.writeJson(acquired);
+ await expect(fixture.prepare()).rejects.toThrow();
+ if (origin !== "gitlab")
+ await expect(readSnykFindings(fixture.file, "local")).rejects.toThrow(
+ "target URL",
+ );
+ const first = await prepareLocalExternalImport(
+ fixture.file,
+ settings,
+ dependencies,
+ );
+ expect((await first.import()).counts.created).toBe(empty ? 0 : 1);
+
+ const normalized = await readSnykFindings(
+ fixture.file,
+ "local",
+ dependencies.sourceRepositories,
+ );
+ await expect(
+ prepareNormalizedLocalImport(normalized, settings, {
+ environment: fixture.environment,
+ }),
+ ).rejects.toThrow();
+ const retry = await prepareNormalizedLocalImport(
+ normalized,
+ settings,
+ dependencies,
+ );
+ expect((await retry.import()).counts.unchanged).toBe(empty ? 0 : 1);
+ await expect(
+ prepareLocalExternalImport(fixture.file, settings, {
+ ...dependencies,
+ sourceRepositories: [{ url: url + "-other", platform }],
+ }),
+ ).rejects.toThrow();
+ },
+);
+
+test("saved Snyk exports must still identify the collected product", () => {
+ const { product: _product, ...unscoped } = snykRestFixture("open-source");
+ expect(() => normalizeSnykIssues(unscoped)).toThrow(
+ "Snyk product must be open-source or code",
+ );
+});
+
+test("a saved enterprise target cannot override a reader's verified GitLab repository", async () => {
+ const report = snykRestFixture("open-source", { sourceRepositoryUrl: url });
+ const project = JSON.parse(report.projectJson);
+ project.attributes.origin = "github-enterprise";
+ project.relationships.target.data.attributes.url = url.replace(
+ "Repo",
+ "repo",
+ );
+ await using f = await isolatedGitReportFixture(
+ "snyk.json",
+ { provider: "snyk", sourceKey: snykOptions.projectId },
+ { remote: url },
+ );
+ const read = (platform: "github" | "gitlab") =>
+ readSnykFindings(f.file, "local", [{ url, platform }]);
+ report.projectJson = JSON.stringify(project);
+ await f.writeJson(report);
+ expect((await read("github")).findings).toHaveLength(1);
+ await expect(read("gitlab")).rejects.toThrow("target URL");
+
+ project.relationships.target.data.attributes.url = url;
+ report.projectJson = JSON.stringify(project);
+ await f.writeJson(report);
+ expect((await read("gitlab")).findings).toHaveLength(1);
+});
diff --git a/sdk/typescript/tests-ts/snyk-rest-v1.test.ts b/sdk/typescript/tests-ts/snyk-rest-v1.test.ts
new file mode 100644
index 000000000..74f6fa04b
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-rest-v1.test.ts
@@ -0,0 +1,144 @@
+import { expect, test } from "bun:test";
+import { writeFile } from "node:fs/promises";
+import { gzipSync } from "node:zlib";
+import {
+ normalizeSnykIssues,
+ snykRestFindingRepository,
+} from "../src/snyk-rest-findings.js";
+import {
+ createAndReplayFinding,
+ updateStoredFinding,
+} from "./external-findings-local-helpers.js";
+import {
+ snykLocalFixture,
+ snykOptions,
+ snykRestFixture,
+ snykIssue,
+ snykProject,
+} from "./support/snyk-rest-fixtures.js";
+
+test("replays a v1 Snyk export with its original evidence, then updates the same stored ID from v2", async () => {
+ const token = "9007199254740993";
+ const projectToken = "9007199254740993e1";
+ const project = { ...snykProject().data, counter: projectToken };
+ project.attributes.target_file = "src/";
+ const issue = snykIssue(false);
+ const original = {
+ ...issue,
+ attributes: { ...issue.attributes, description: token, label: token },
+ };
+ const issueFields = { attributes: { description: token } };
+ const v1 = {
+ ...snykOptions,
+ format: "snyk-rest-issues/v1",
+ apiVersion: "2026-03-25",
+ complete: true,
+ project,
+ target: null,
+ pages: [{ startingAfter: null, response: { data: [original] } }],
+ numericFields: {
+ project: { counter: projectToken },
+ pages: { 0: { response: { data: { 0: issueFields } } } },
+ },
+ };
+ await using fixture = await snykLocalFixture({
+ remote: snykOptions.sourceRepositoryUrl,
+ });
+ await fixture.writeJson(v1);
+ const stored = await createAndReplayFinding(fixture);
+ expect(stored.evidence.packages?.[0]?.manifest_path).toBe("src/");
+ const source = stored.evidence.source_data!;
+ expect(stored.evidence.description).toBeNull();
+ expect(source).toEqual({
+ ...snykOptions,
+ format: v1.format,
+ apiVersion: v1.apiVersion,
+ project,
+ target: null,
+ issue: original,
+ numericFields: { project: { counter: projectToken }, issue: issueFields },
+ });
+ expect(
+ snykRestFindingRepository({
+ source_finding_id: stored.sourceFindingId,
+ evidence: stored.evidence,
+ }).url,
+ ).toBe(snykOptions.sourceRepositoryUrl);
+ const selected = normalizeSnykIssues(v1);
+ expect(selected).not.toHaveProperty("sourceRepositoryPlatform");
+ const row = selected.findings[0]!;
+ delete row.evidence.source_data!["format"];
+ const unmarked = await fixture.prepareNormalized(selected);
+ expect((await unmarked.import()).counts.unchanged).toBe(1);
+ expect((await fixture.read())[0]).toEqual(stored);
+ row.evidence.source_data = {
+ issue: original,
+ project: undefined,
+ target: undefined,
+ };
+ for (const fields of [{ issue: issueFields }, source["numericFields"]]) {
+ row.evidence.source_data["numericFields"] = fields;
+ const projected = await fixture.prepareNormalized(selected);
+ expect((await projected.import()).counts.unchanged).toBe(1);
+ expect((await fixture.read())[0]).toEqual(stored);
+ }
+ row.evidence.source_data["numericFields"] = {
+ project: { counter: "9007199254740994" },
+ };
+ await expect(fixture.prepareNormalized(selected)).rejects.toThrow(
+ "Invalid scanner numeric fields",
+ );
+
+ // A historical native project still identifies a hosted report after a reader removes the issue and ID.
+ const assetOnly = { ...source };
+ delete assetOnly["format"];
+ delete assetOnly["issue"];
+ assetOnly["numericFields"] = { project: { counter: projectToken } };
+ row.source_finding_id = "reader-id";
+ row.evidence.source_data = assetOnly;
+ await expect(
+ fixture.prepareNormalized({
+ read: 1,
+ findings: [row],
+ excluded: [],
+ }),
+ ).rejects.toThrow("Snyk original issue");
+ expect(() =>
+ normalizeSnykIssues({
+ ...v1,
+ numericFields: { project: { counter: "9007199254740994" } },
+ }),
+ ).toThrow("Invalid exact scanner number");
+
+ // Earlier v1 files also used native numbers and no sidecar. Both forms replay the same row.
+ const native = JSON.stringify({ ...v1, numericFields: undefined })
+ .replace(`"counter":"${projectToken}"`, `"counter":${projectToken}`)
+ .replace(`"description":"${token}"`, `"description":${token}`);
+ await writeFile(fixture.file, gzipSync(native));
+ expect((await (await fixture.prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 1,
+ });
+
+ const v2 = snykRestFixture("open-source");
+ v2.projectJson = JSON.stringify(project).replace(
+ `"counter":"${projectToken}"`,
+ `"counter":${projectToken}`,
+ );
+ v2.pages[0]!.responseJson = JSON.stringify(v1.pages[0]!.response).replace(
+ `"description":"${token}"`,
+ `"description":${token}`,
+ );
+ await fixture.writeJson(v2);
+ const updated = await updateStoredFinding(fixture, stored);
+ expect(updated.evidence.packages?.[0]?.manifest_path).toBeNull();
+ const retained = updated.evidence.source_data?.["issueJson"];
+ expect(retained).toContain(`"description":${token}`);
+ expect(retained).toContain(`"label":"${token}"`);
+ expect((await (await fixture.prepare()).import()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 1,
+ });
+});
diff --git a/sdk/typescript/tests-ts/support/snyk-rest-fixtures.ts b/sdk/typescript/tests-ts/support/snyk-rest-fixtures.ts
new file mode 100644
index 000000000..782aabaa9
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/snyk-rest-fixtures.ts
@@ -0,0 +1,110 @@
+import { isolatedGitReportFixture } from "../external-findings-local-helpers.js";
+import { canonicalJson } from "../../src/record.js";
+import {
+ SNYK_REST_ISSUES_FORMAT,
+ type CollectSnykIssuesOptions,
+ type SnykIssuesExport,
+ type SnykIssuesProduct,
+} from "../../src/snyk-rest-findings.js";
+
+export const snykOptions = {
+ apiOrigin: "https://api.eu.snyk.io",
+ organizationId: "11111111-1111-4111-8111-111111111111",
+ projectId: "22222222-2222-4222-8222-222222222222",
+ sourceRepositoryUrl: "https://github.com/example/repository",
+ product: "open-source",
+} satisfies CollectSnykIssuesOptions;
+
+export function snykLocalFixture(checkout?: { remote?: string }) {
+ return isolatedGitReportFixture(
+ "snyk.json",
+ { provider: "snyk", sourceKey: snykOptions.projectId },
+ checkout,
+ );
+}
+
+export function snykProject(
+ manager = "npm",
+ url = snykOptions.sourceRepositoryUrl,
+) {
+ return {
+ data: {
+ type: "project",
+ id: snykOptions.projectId,
+ attributes: {
+ type: manager,
+ origin: "github",
+ target_file: "app/package.json",
+ },
+ relationships: {
+ organization: { data: { type: "org", id: snykOptions.organizationId } },
+ target: {
+ data: {
+ type: "target",
+ id: "33333333-3333-4333-8333-333333333333",
+ attributes: { url },
+ },
+ },
+ },
+ },
+ };
+}
+
+export function snykIssue(code: boolean, projectId = snykOptions.projectId) {
+ const representation = code
+ ? {
+ sourceLocation: {
+ file: "src/app.ts",
+ region: { start: { line: 3 } },
+ commit_id: "abc123",
+ },
+ }
+ : { dependency: { package_name: "example-lib", package_version: "1.0.0" } };
+ return {
+ type: "issue",
+ id: "44444444-4444-4444-8444-444444444444",
+ attributes: {
+ key: "opaque-issue-key",
+ type: code ? "code" : "package_vulnerability",
+ title: "Synthetic finding",
+ status: "open",
+ ignored: true,
+ effective_severity_level: "high",
+ updated_at: "2026-01-01T00:00:00Z",
+ problems: [{ type: "rule", id: "sample-rule" }],
+ coordinates: [{ state: "open", representations: [representation] }],
+ },
+ relationships: {
+ organization: {
+ data: { type: "organization", id: snykOptions.organizationId },
+ },
+ scan_item: { data: { type: "project", id: projectId } },
+ },
+ };
+}
+
+/** A complete project response and issue page saved by the Snyk collector. */
+export function snykRestFixture(
+ product: SnykIssuesProduct,
+ { sourceRepositoryUrl = snykOptions.sourceRepositoryUrl } = {},
+): SnykIssuesExport {
+ const code = product === "code";
+ return {
+ ...snykOptions,
+ product,
+ sourceRepositoryUrl,
+ format: SNYK_REST_ISSUES_FORMAT,
+ apiVersion: "2026-03-25",
+ complete: true,
+ projectJson: canonicalJson(
+ snykProject(code ? "sast" : "npm", sourceRepositoryUrl).data,
+ ),
+ targetJson: "null",
+ pages: [
+ {
+ startingAfter: null,
+ responseJson: canonicalJson({ data: [snykIssue(code)] }),
+ },
+ ],
+ };
+}