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(snyk): import Open Source JSON findings (#1687)

Michael D'Angelo0391e838c57e
diff --git a/docs/scanner-imports/snyk.md b/docs/scanner-imports/snyk.md
new file mode 100644
index 000000000..f6c732c07
--- /dev/null
+++ b/docs/scanner-imports/snyk.md
@@ -0,0 +1,158 @@
+# Snyk Open Source imports
+
+Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
+to collect a fresh workspace scan. The existing
+[`publish findings` command](../../sdk/typescript/docs/cli.md#import-snyk-open-source-findings)
+accepts its `snyk-findings-export/v1` bundle with `--provider snyk` for local
+storage or Cloud publication. For CLI automation, prefer native JSON from
+`snyk test`; Open Source SARIF remains a compatibility input.
+
+**Scope: Open Source SCA vulnerabilities only.** License findings, Snyk Code,
+Container, IaC, SBOM results and existing platform backlog ingestion are outside
+this adapter. License records in otherwise supported reports appear as explicit
+exclusions; they are not imported as vulnerabilities.
+
+```sh
+codex plugin marketplace add snyk/studio-recipes
+codex plugin add snyk@snyk-studio-recipes
+```
+
+Ask Codex: “Use snyk-findings-export to export SCA findings from this repository’s Git root to
+snyk-findings.json. Run SCA only.” The plugin uses the local Snyk MCP server and
+needs Snyk authentication and the package tooling required by the project. Check
+its scan coverage and limitations before importing. Preview local storage with a
+repository path; no Cloud login is required:
+
+```sh
+codex-security publish findings snyk-findings.json --to local \
+ --provider snyk --repository ./project \
+ --source-key github.com/example/project/main/root/plugin-sca --dry-run
+```
+
+Or preview publication to a connected Cloud repository:
+
+```sh
+codex-security publish findings snyk-findings.json --to cloud \
+ --provider snyk --repository https://github.com/example/project \
+ --source-key github.com/example/project/main/root/plugin-sca --dry-run
+```
+
+Remove `--dry-run` from the selected command to review and confirm the import.
+The existing `--yes` option allows an already approved, noninteractive import.
+Read local records with `codex-security findings imported ./project --format json`.
+See the common [local import flow](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
+or [Cloud publication flow](../../sdk/typescript/docs/cli.md#import-wiz-findings)
+for destination requirements, confirmation and result handling. The publisher
+imports the saved evidence; it does not start another Snyk scan or assessment.
+
+This adapter imports Open Source SCA vulnerabilities. Other products, licenses
+and SBOM results in a mixed plugin bundle appear as exclusions. It preserves the
+complete selected finding, native MCP record, collection context, availability
+states and coverage limitations. Ignored status remains source evidence; it does
+not mark the finding fixed or assessed locally or in Cloud. A dirty workspace retains its
+revision in the original evidence without claiming it as the exact scanned commit.
+
+The MCP output is a projection: its SCA mapper shortens descriptions and can omit
+alternate dependency paths. The plugin cannot recover data its MCP server did
+not return. See the [official SCA mapper](https://github.com/snyk/studio-mcp/blob/main/internal/oss/map.go).
+The bundle's composite occurrence identity includes package version and dependency
+path. Keep the same source key for each repository, branch and scan target across
+exports; a changed occurrence has a new ID. Plugin v1 paths are relative to the
+scan target and do not carry its Git-root offset. They remain in original evidence
+without being projected as repository locations or package manifest paths.
+
+### Native CLI JSON
+
+For automation, use the [Snyk CLI](https://docs.snyk.io/developer-tools/snyk-cli/commands/test)
+with `--json-file-output`. This preserves native descriptions, dependency paths,
+identifiers and remediation evidence before the MCP or SARIF projections. For
+example, run from the selected repository root:
+
+```sh
+snyk_status=0
+snyk test --file=package.json --json-file-output=snyk-open-source.json || snyk_status=$?
+if [ "$snyk_status" -gt 1 ]; then
+ exit "$snyk_status"
+fi
+codex-security publish findings snyk-open-source.json --to cloud \
+ --provider snyk --repository https://github.com/example/project \
+ --source-key github.com/example/project/main/root/native-sca --dry-run
+```
+
+Snyk exits 1 when it finds vulnerabilities. Other failures must stop acquisition;
+do not publish an older report after a failed scan. `snyk test --json` emits the
+same result to stdout. A single project object and the array produced by
+`--all-projects` under one scan root are supported. For multiple projects, replace
+`--file=package.json` with `--all-projects --fail-fast` and keep the exit-code
+handling above. Snyk's [`--fail-fast` option](https://github.com/snyk/cli/blob/main/help/cli-commands/test.md#--fail-fast)
+stops the scan when a project fails. Without it, Snyk continues and omits
+vulnerability results for projects it could not scan. Keep independent scan roots
+in separate reports and source keys; identical manifest and dependency paths from
+different roots otherwise have ambiguous identities. A project error in the
+supplied JSON stops the import, including an error mixed with successful results.
+A successful empty scan has zero findings; a license-only report instead lists
+its records as exclusions. Use the default ungrouped JSON output;
+`--group-issues` combines package and dependency-path fields and is not supported.
+
+The mapper follows the CLI's [native result types and dependency-path producer](https://github.com/snyk/cli/blob/main/src/lib/snyk-test/legacy.ts).
+It preserves the complete selected vulnerability and the surrounding project
+context. Identity uses the package manager, literal display manifest (falling back
+to the target file), advisory, package name/version and dependency path. Different
+occurrences remain separate. A duplicate identity is excluded rather than merged.
+Native JSON does not establish a Git-root offset, repository URL or exact scanned
+revision: paths and scan context stay in original evidence, without being claimed
+as repository locations or manifest paths. Suggested upgrades and fixed versions
+remain source advice, not verified patches.
+
+To store this JSON locally, use the same file, provider and source key with
+`--to local --repository .` from the repository root. No Cloud login is required.
+
+### SARIF compatibility
+
+Existing Open Source SARIF exports are still accepted. Generate one with
+`snyk test --file=package.json --sarif-file-output=snyk-open-source.sarif` and
+handle the exit code as above. For multiple projects, use `--all-projects --fail-fast`
+with the same exit-code handling. Import with `--provider snyk` and a stable source
+key ending in `sarif-sca`. The mapper follows the
+[Open Source SARIF formatter](https://github.com/snyk/cli/blob/main/src/lib/formatters/open-source-sarif-output.ts).
+It retains the selected rule, result and report context. Unrelated artifact
+inventories are omitted when direct manifest locations do not depend on them;
+indexed context and matching artifact metadata are retained. Empty
+external-reference containers are accepted; reports with actual external property
+references remain unsupported. SARIF groups an advisory's occurrences and exposes
+one package coordinate, so native JSON is preferable for preserving individual
+dependency paths and remediation fields. Manifest paths are literal target-relative
+paths, including percent characters, without a Git-root offset. They stay in
+original evidence with synthetic line numbers instead of being projected as
+repository locations or package manifest paths. Snyk
+Code, Container, IaC, external SARIF property files and indexed or base-relative
+manifest locations are unsupported.
+
+### Identities and provenance
+
+All three formats support either destination, but their source IDs differ. Use
+one acquisition format consistently for a repository, branch and scan target,
+with a stable source key. Use a separate key if switching formats; the importer
+does not guess equivalence between plugin occurrences, native JSON occurrences
+and SARIF advisory groups. Switching does not remove earlier imported records.
+
+Unsafe or absolute paths remain in original evidence. Known source repository
+claims must match the selected Cloud repository or, for local imports when Git
+remotes are configured, one of those remotes. For Cloud publication, standard SSH
+remotes on the selected connected GitHub or GitHub Enterprise host match its HTTPS
+repository when using the default SSH port or port 22. The public
+`ssh://[email protected]:443/owner/repository.git` endpoint also matches
+`github.com`. Other hosts, nondefault SSH ports and explicit HTTPS ports remain
+distinct; the importer does not infer an Enterprise host from the artifact alone.
+Unknown repository context requires the user to select the correct destination.
+Gzip and UTF-8 BOM input are supported. All three file formats
+normalize to the Cloud evidence model before either local import or Cloud publication.
+Records exceeding that model's field or total-size limits appear as exclusions in
+the preview, without truncation. The normalized local SDK import API has a separate
+contract that accepts larger evidence. Inspect preview exclusions before importing.
+
+The plugin and CLI paths scan the current workspace. Existing Snyk platform
+findings need a separate [REST Issues API](https://docs.snyk.io/snyk-api/reference/issues)
+reader with tenant access and repository mapping. This adapter does not read that
+backlog or synchronize triage decisions. Synthetic contract and publication tests
+do not establish live tenant, plugin-runtime or deployed Cloud compatibility.
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 19c6ec2fb..89c6de398 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -1,6 +1,6 @@
---
name: publish-findings
-description: Import selected Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports normalized JSONL, repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.
+description: Import selected Snyk Open Source findings or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles and Open Source SARIF, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.
---
# Publish external findings
@@ -39,10 +39,24 @@ Use a stable Wiz tenant/finding namespace as `--source-key`. A project filter is
For an existing package vulnerability report or when a UI export is needed, use **Vulnerability Findings → Save as → Report**, keeping the repository and finding filters. Select **Repository Branch** (remove the default Virtual Machine selection), **JSON** or comma-separated **CSV**, and **Detailed** columns. Pass supported CSV reports directly to the command; their GitHub `CloudProviderURL` must identify the destination repository branch. The importer retains every original cell in `source_data.row` and uses the reported `ID` as occurrence identity. Download the completed report; gzip compression is supported regardless of the filename extension. **Raw Event** on Code & Build Scans contains scan metadata and cannot supply findings. Do not create a scheduled report or enable notifications or external storage unless requested.
-For SAST, repository secrets, and IaC, retain the explicit `data.sastFindings.nodes`, `data.secretInstances.nodes`, or `data.iacFindings.nodes` collection. Bare arrays cannot identify these finding families. Include a verified URL on the source repository metadata or supply `data.versionControlResources.nodes` with matching `repository.id` and `repository.url`. Retain the documented inventory `platform` field; explicit `GITHUB` establishes case-insensitive matching on custom GitHub Enterprise hosts. Resolve conflicting platform or URL metadata for a repository ID before publishing. For secrets, the repository is `resource.typedProperties.repository` and resource type must be `REPOSITORY_BRANCH`. Do not map names, inventory node IDs, `providerID`, or Wiz UUIDs directly to Cloud repository IDs. The importer verifies source URLs against the selected destination; resolve a missing or conflicting mapping before uploading.
+For SAST, repository secrets, and IaC, retain the explicit `data.sastFindings.nodes`, `data.secretInstances.nodes`, or `data.iacFindings.nodes` collection. Bare arrays cannot identify these finding families. Include a verified URL on the source repository metadata or supply `data.versionControlResources.nodes` with matching `repository.id` and `repository.url`. Retain the documented inventory `platform` field; explicit `GITHUB` establishes case-insensitive matching on custom GitHub Enterprise hosts. Resolve conflicting platform or URL metadata for a repository ID before importing. For secrets, the repository is `resource.typedProperties.repository` and resource type must be `REPOSITORY_BRANCH`. Do not map names, inventory node IDs, `providerID`, or Wiz UUIDs directly to Cloud repository IDs. Source URLs must match the selected Cloud repository or, for local import when Git remotes are configured, one of those remotes. Resolve a missing or conflicting source mapping before importing.
Keep raw source records unchanged in `source_data`. New raw occurrence IDs are prefixed `sast:`, `secret:`, or `iac:`; existing package IDs are unchanged. SAST, repository-secret, and IaC CSV reports still require a reviewed mapping of the actual header names into the documented normalized JSONL profile: set `evidence.details.kind` and the verified `details.repository.url`, and use the same prefixed occurrence ID. Select source paths and line numbers explicitly in secret reports; the standard metadata query lacks them. Preserve rule/CWE, range/snippet, detector validation, and IaC comparison fields in the typed details described in the CLI docs. Preserve empty comparison strings. Do not invent missing IDs, severity, revisions, or locations, retrieve credential values, test credentials, or apply suggested fixes. Vendor status, AI verdict, secret validation, introduced commits, and logical IaC resources are evidence, not Codex assessment or proof of runtime deployment.
+## Snyk Open Source
+
+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.
+
+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.
+
+Retain package versions, reported fixed versions, provenance and original evidence without claiming a fix was applied. Known repository claims must match the selected Cloud repository or, when available, a configured local Git remote. Resolve an unknown repository with the user; never infer that an export belongs to the current checkout. Follow [local imports](#local-imports) for preview, confirmation and readback or [Cloud publication](#review-and-publish-to-cloud) for upload authorization. All three Snyk formats support either destination.
+
+## Review and publish to Cloud
+
When publishing to staging or another Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its API root before both preview and upload. If the Cloud page or user supplies its app URL, also set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL so the command can return a repository link. The UI setting does not change API routing or authentication. Use that deployment's login and an isolated state directory for tests. Verify `cloudApiUrl` and any `cloudUrl` in the preview against the intended deployment; the former is the API endpoint and the latter is the UI link. Saved retries are separated by deployment. The native scan setting `CODEX_SECURITY_CLOUD_PUBLISH_URL` does not route vendor imports. Never fall back to production when staging is unavailable.
```sh
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index e31bb320b..658615480 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -11,6 +11,9 @@ security plugin, and TypeScript declarations. It uses ES modules.
- Review saved findings, identify duplicates, classify severity, and suggest owners.
- Import GitHub code scanning alerts, export SARIF, JSON, or CSV, and publish
findings to Linear or a findings service.
+- Import [Snyk Open Source findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md) from
+ official plugin JSON or native CLI JSON locally or into Cloud; Open Source
+ SARIF is also supported. License findings and other Snyk products are excluded.
- Automate scans across repositories and project components.
See the [CLI reference](docs/cli.md),
@@ -676,7 +679,10 @@ Use `publish findings FILE --to local --repository PATH --provider wiz
database. Preview with `--dry-run --format json`, then confirm interactively or
use `--yes`. Read it with `findings imported [REPOSITORY] --format json`; the
repository defaults to the current directory. No Cloud login or model call is
-needed. See [local imports](docs/cli.md#import-vendor-findings-locally).
+needed. Use `--provider snyk` for native CLI JSON, a Snyk plugin SCA bundle or
+Open Source SARIF. Prefer JSON, and keep one format and stable source key per scan
+target; switching formats creates separate source identities. See
+[local imports](docs/cli.md#import-vendor-findings-locally).
The SDK's `prepareLocalExternalImport(file, options)` returns a `preview` and a
separate `import()` operation. `prepareNormalizedLocalImport(findings,
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 94ba46459..d03068835 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1210,7 +1210,8 @@ replace a richer evidence snapshot with less detail. The importer does not merge
evidence or deduplicate equivalent vulnerabilities across different source IDs.
Use the same vendor input and parser as Cloud publication, selecting a local
-repository path instead of a Cloud repository ID or URL:
+repository path instead of a Cloud repository ID or URL. Supported inputs include
+Wiz findings and [Snyk Open Source JSON and SARIF](#import-snyk-open-source-findings):
```bash
codex-security publish findings selected-wiz.json \
@@ -1251,6 +1252,68 @@ exports.
## Publish findings to Cloud
+### Import Snyk Open Source findings
+
+Import **Open Source SCA vulnerabilities only**. Licenses, Code, Container, IaC,
+SBOM results and platform backlog ingestion are outside this adapter.
+
+Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
+with its `snyk-findings-export` skill to collect SCA findings from the repository's
+Git root. It runs a fresh local scan and writes a `snyk-findings-export/v1` bundle;
+it does not retrieve existing platform project findings.
+
+The same saved bundle supports [local import](#import-vendor-findings-locally)
+without a Cloud login:
+
+```sh
+codex-security publish findings snyk-findings.json --to local \
+ --provider snyk --repository ./project \
+ --source-key github.com/example/project/main/root/plugin-sca --dry-run
+```
+
+Or preview publication to a connected Cloud repository:
+
+```sh
+codex-security publish findings snyk-findings.json --to cloud \
+ --provider snyk --repository https://github.com/example/project \
+ --source-key github.com/example/project/main/root/plugin-sca --dry-run
+```
+
+Check the collection's scan outcomes and limitations. Only Open Source SCA
+vulnerabilities are imported; other products and licenses are explicit exclusions.
+The importer retains the selected finding, native MCP record and collection
+context. MCP may shorten descriptions and omit dependency paths. Plugin paths
+remain in original evidence because v1 lacks their offset from the Git root.
+
+For automation, prefer native JSON from
+`snyk test --file=package.json --json-file-output=snyk.json`. Exit 1 means findings;
+stop on other nonzero exits before importing. The existing `--provider snyk`
+autodetects a single project object or an `--all-projects` array; any project error
+stops the import. Use default ungrouped output, without `--group-issues`.
+Native JSON preserves individual dependency paths and remediation fields. Its
+paths remain original evidence because it does not establish their Git-root offset.
+
+Open Source SARIF from `snyk test --sarif-file-output=snyk.sarif` remains supported
+for compatibility. Its target-relative manifest paths and synthetic line numbers
+remain original evidence, without being projected as repository locations or
+package manifest paths. All three formats accept either destination. Use a consistent
+format and stable source key per repository, branch and scan target, for example
+`github.com/example/project/main/root/native-sca` for native JSON. Their source
+identities differ: use separate keys when switching acquisition formats. Imports
+do not deduplicate across formats or remove earlier imported records.
+
+Known repository claims must
+match the selected Cloud repository or, when available, a configured local Git
+remote. Unknown repository context still requires selecting the correct target;
+the importer does not infer provenance from the current checkout.
+
+Remove `--dry-run` from the selected command to review and confirm the import, or
+use `--yes` after reviewing the preview. Read local records with
+`codex-security findings imported ./project --format json`. Imported source
+evidence is not a Codex assessment. No Snyk-side triage state is changed. See the
+[Snyk import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md) for format limits and
+acquisition details.
+
### Import Wiz findings
Import selected Wiz package vulnerabilities, SAST findings, repository secrets,
diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.ts
index 403a902be..8607de66d 100644
--- a/sdk/typescript/scripts/fixtures/package-consumer.ts
+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts
@@ -6,6 +6,7 @@ import {
listLocalExternalFindings,
type NormalizedLocalImportOptions,
type StoredExternalFinding,
+ normalizeSnykFindingsExport,
prepareNormalizedExternalPublication,
type ExternalFindings,
type ExternalPublicationOptions,
@@ -392,3 +393,7 @@ export async function importLocalFile(
const prepared = await prepareLocalExternalImport(file, options);
return (await prepared.import()).findings;
}
+
+export function snykPluginFindings(bundle: unknown): ExternalFindings {
+ return normalizeSnykFindingsExport(bundle);
+}
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index b2f95dc48..832595b50 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -28,6 +28,7 @@ const distModules = [
"external-findings-import",
"external-findings-read",
"scanner-import",
+ "snyk-findings",
"external-findings-publish",
"external-import-contract",
"external-import-models",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index cac48b54a..0b68cf016 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -3531,15 +3531,15 @@ export async function main(
});
publication.command("findings", {
description:
- "Preview and import selected Wiz repository findings locally or to Cloud.",
- hint: "Prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; CSV does not cover SAST or cloud posture. Other CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
+ "Preview and import selected Wiz or Snyk findings locally or to Cloud.",
+ hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
destructive: true,
mcp: false,
args: z.object({
file: z
.string()
.describe(
- "Saved native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",
+ "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",
),
}),
options: z.object({
@@ -3548,7 +3548,7 @@ export async function main(
"Local repository path for --to local; authorized repository ID or URL for --to cloud.",
),
provider: z
- .literal("wiz")
+ .enum(["wiz", "snyk"])
.describe("Vendor that produced these findings."),
sourceKey: optionValue("--source-key").describe(
"Stable vendor tenant and finding namespace; not a project selection filter.",
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index 3f9a2d9a6..fdf5aae6f 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -29,6 +29,7 @@ import {
type ExternalFindingsReaderOptions,
} from "./external-findings-read.js";
import { wizCsvRepositoryUrl } from "./wiz-csv.js";
+import { snykRepositoryUrls } from "./snyk-findings.js";
import type {
ExternalFindings,
ExternalPublicationInput,
@@ -710,6 +711,11 @@ async function preparePublicationInput(
...(options.provider === "wiz"
? [wizCsvRepositoryUrl(finding.evidence)]
: []),
+ ...(options.provider === "snyk"
+ ? snykRepositoryUrls(finding.evidence.source_data, {
+ cloudRepositoryUrl: destination.url,
+ })
+ : []),
];
for (const sourceRepository of sourceRepositories)
if (
diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.ts
index b33147b98..9233237e8 100644
--- a/sdk/typescript/src/external-findings-read.ts
+++ b/sdk/typescript/src/external-findings-read.ts
@@ -4,13 +4,14 @@ import type {
ExternalSourceRepository,
} from "./external-findings.js";
import { wizCsvRepositoryUrl } from "./wiz-csv.js";
+import { readSnykFindings, snykRepositoryUrls } from "./snyk-findings.js";
import { isGitHubCloudHost } from "./git-remote.js";
import { isRecord } from "./record.js";
import { readVendorFindingsForPublication } from "./wiz-findings.js";
/** File readers available in this SDK, shared by local and Cloud imports. */
export interface ExternalFindingsReaderOptions {
- provider: "wiz";
+ provider: "wiz" | "snyk";
}
/** @internal Shared parser output, including immutable Cloud retry projections. */
@@ -24,8 +25,19 @@ export interface ReadExternalFindings {
/** @internal Read vendor evidence for the local and Cloud import entrypoints. */
export async function readExternalFindings(
path: string,
- _options: ExternalFindingsReaderOptions,
+ options: ExternalFindingsReaderOptions,
): Promise<ReadExternalFindings> {
+ if (options.provider === "snyk") {
+ const findings = await readSnykFindings(path);
+ return {
+ findings,
+ sourceRepositories: findings.findings.flatMap(({ evidence }) =>
+ snykRepositoryUrls(evidence.source_data, {
+ normalizeGitRemote: false,
+ }).map((url) => ({ url })),
+ ),
+ };
+ }
const publication = await readVendorFindingsForPublication(path);
// Raw package exports keep repository-branch URLs in retained source data.
const sourceRepositories = publication.current.findings.flatMap(
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 077042a27..afe56e6cb 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -312,3 +312,9 @@ export type {
} from "./validation-records.js";
export { prepareLocalExternalImport } from "./external-findings-import.js";
+export {
+ normalizeSnykFindingsExport,
+ normalizeSnykJson,
+ normalizeSnykSarif,
+ readSnykFindings,
+} from "./snyk-findings.js";
diff --git a/sdk/typescript/src/snyk-findings.ts b/sdk/typescript/src/snyk-findings.ts
new file mode 100644
index 000000000..3799bfe85
--- /dev/null
+++ b/sdk/typescript/src/snyk-findings.ts
@@ -0,0 +1,510 @@
+import { validateExternalEvidence } from "./external-import-contract.js";
+import type { ExternalFindings } from "./external-findings.js";
+import { isRecord } from "./record.js";
+import {
+ array,
+ hasSarifExternalPropertyReferences,
+ normalizeRecords,
+ readScannerJson,
+ record,
+ requiredText,
+ sarifRunContextForResult,
+ stableId,
+ strings,
+ text,
+} from "./scanner-import.js";
+
+function snykIdentity(value: unknown, project: string | null): string {
+ const result = record(value, "SARIF result");
+ const id = requiredText(result["ruleId"], "Snyk advisory ruleId");
+ const paths = array(result["locations"] ?? [], "Result locations")
+ .map((value) => {
+ const physical = record(
+ record(value, "Location")["physicalLocation"] ?? {},
+ "Physical location",
+ );
+ const artifact = record(
+ physical["artifactLocation"] ?? {},
+ "Artifact location",
+ );
+ if (
+ artifact["index"] !== undefined ||
+ artifact["uriBaseId"] !== undefined
+ )
+ throw new Error(
+ "Snyk SARIF artifact references are unsupported; use direct manifest URIs from the Snyk Open Source formatter.",
+ );
+ return text(artifact["uri"]);
+ })
+ .filter((path): path is string => path !== null);
+ const fields: unknown[] = [id, [...new Set(paths)].sort()];
+ if (project !== null) fields.push(project);
+ return stableId("snyk-sarif", fields);
+}
+
+function snykSarifProject(run: Record<string, unknown>): string | null {
+ const details = run["automationDetails"];
+ const id = isRecord(details) ? text(details["id"]) : null;
+ // The formatter appends a run index and export timestamp after the project name.
+ return /^Snyk\/Open Source\/(.+)\/\d+\/[^/]+$/su.exec(id ?? "")?.[1] ?? null;
+}
+
+function pluginIdentity(value: unknown): string {
+ const finding = record(value, "Snyk plugin finding");
+ const id = record(finding["id"], "Snyk plugin identity");
+ return stableId("snyk-plugin", [
+ requiredText(id["kind"], "Identity kind"),
+ requiredText(id["value"], "Finding identity"),
+ ]);
+}
+
+/** Import the official Snyk Codex plugin's documented local SCA bundle. */
+export function normalizeSnykFindingsExport(input: unknown): ExternalFindings {
+ const document = record(input, "Snyk plugin export");
+ if (
+ document["format"] !== "snyk-findings-export/v1" ||
+ document["provider"] !== "snyk"
+ )
+ throw new Error("Expected a snyk-findings-export/v1 bundle from Snyk.");
+ const collection = record(document["collection"], "Snyk collection");
+ const target = record(collection["target"], "Snyk target");
+ const { findings: _findings, ...context } = document;
+ return normalizeRecords(
+ array(document["findings"], "Snyk findings"),
+ (value, sourceFindingId) => {
+ const finding = record(value, "Snyk plugin finding");
+ const observation = record(finding["observation"], "Snyk observation");
+ if (
+ finding["originatingScanner"] !== "snyk-open-source" ||
+ finding["category"] !== "dependency_vulnerability" ||
+ observation["scan"] !== "sca"
+ )
+ throw new Error(
+ "Only Snyk Open Source SCA vulnerability findings are supported from plugin bundles.",
+ );
+ record(finding["nativeRecord"], "Snyk native MCP record");
+ const asset = record(finding["asset"], "Snyk asset");
+ const pkg = record(asset["package"], "Snyk package");
+ const rule = record(finding["rule"], "Snyk rule");
+ const aliases = record(rule["aliases"] ?? {}, "Snyk rule aliases");
+ const remediation = record(
+ finding["remediation"] ?? {},
+ "Snyk remediation",
+ );
+ const severity = text(
+ record(finding["severity"], "Snyk severity")["value"],
+ )?.toLowerCase();
+ const revision = text(target["revision"]);
+ return {
+ source_finding_id: sourceFindingId,
+ evidence: validateExternalEvidence({
+ title: requiredText(finding["title"], "Snyk title"),
+ description: text(
+ record(finding["description"] ?? {}, "Snyk description")["text"],
+ ),
+ severity: ["critical", "high", "medium", "low"].includes(
+ severity ?? "",
+ )
+ ? severity
+ : "unknown",
+ advisory_ids: [
+ ...new Set([
+ requiredText(rule["id"], "Snyk advisory ID"),
+ ...strings(aliases["cve"]),
+ ]),
+ ],
+ packages: [
+ {
+ name: requiredText(pkg["name"], "Snyk package name"),
+ ecosystem: text(pkg["ecosystem"]),
+ installed_version: text(pkg["version"]),
+ // Plugin v1 manifests are target-relative, without a Git-root offset.
+ manifest_path: null,
+ fixed_versions: strings(remediation["fixedIn"]),
+ },
+ ],
+ locations: [],
+ code_revision:
+ target["workingTreeDirty"] === false && revision !== "unknown"
+ ? revision
+ : null,
+ source_data: structuredClone({ ...context, finding }),
+ }),
+ };
+ },
+ pluginIdentity,
+ );
+}
+
+function normalizeGitRepositoryUrl(
+ repository: string,
+ cloudRepositoryUrl?: string,
+): string {
+ // Cloud's selected catalog repository supplies connected GitHub host context;
+ // imported evidence alone cannot establish an Enterprise host's SSH aliases.
+ const destination = cloudRepositoryUrl
+ ? new URL(cloudRepositoryUrl)
+ : undefined;
+ const connectedHost =
+ destination?.protocol === "https:"
+ ? destination.hostname.toLowerCase()
+ : undefined;
+ const connectedTenant = /^([^.]+)\.ghe\.com$/u.exec(connectedHost ?? "")?.[1];
+ const isGitHubSshUser = (username: string, hostname: string) =>
+ (username === "git" &&
+ (hostname === "github.com" || hostname === connectedHost)) ||
+ (username === connectedTenant && hostname === connectedHost);
+ const scp = /^([^@/:]+)@([^/:]+):(.+)$/u.exec(repository);
+ if (scp && isGitHubSshUser(scp[1]!, scp[2]!.toLowerCase()))
+ return `https://${scp[2]}/${scp[3]}`;
+ // Compare Git's literal SSH userinfo before URL strips tabs or newlines.
+ const ssh = /^ssh:\/\/([^/]+)@/u.exec(repository);
+ if (ssh) {
+ // Git retains these bytes, but URL parsing would erase them from the alias.
+ if (/[\t\r\n]/u.test(repository)) return repository;
+ const url = new URL(repository);
+ const hostname = url.hostname.toLowerCase();
+ const githubSsh =
+ isGitHubSshUser(ssh[1]!, hostname) &&
+ (url.port === "" || url.port === "22");
+ const githubSshOverHttps =
+ ssh[1] === "git" && hostname === "ssh.github.com" && url.port === "443";
+ if (githubSshOverHttps) return `https://github.com${url.pathname}`;
+ if (githubSsh) return `https://${hostname}${url.pathname}`;
+ }
+ return repository;
+}
+
+/** @internal Repository claims retained in original Snyk evidence. */
+export function snykRepositoryUrls(
+ sourceData: unknown,
+ {
+ normalizeGitRemote = true,
+ cloudRepositoryUrl,
+ }: {
+ normalizeGitRemote?: boolean;
+ /** The selected destination from the authenticated Cloud repository catalog. */
+ cloudRepositoryUrl?: string;
+ } = {},
+): string[] {
+ if (
+ !sourceData ||
+ typeof sourceData !== "object" ||
+ Array.isArray(sourceData)
+ )
+ return [];
+ const source = sourceData as Record<string, unknown>;
+ if (source["format"] === "snyk-findings-export/v1") {
+ const collection = record(source["collection"], "Snyk collection");
+ const target = record(collection["target"], "Snyk target");
+ const repository = text(target["repository"]);
+ if (repository === null || repository === "unknown") return [];
+ return [
+ normalizeGitRemote
+ ? normalizeGitRepositoryUrl(repository, cloudRepositoryUrl)
+ : repository,
+ ];
+ }
+ // Generic normalized evidence may use these field names for opaque metadata.
+ const document = source["document"];
+ const driver = source["driver"];
+ if (
+ !isRecord(document) ||
+ document["version"] !== "2.1.0" ||
+ !isRecord(driver) ||
+ driver["name"] !== "Snyk Open Source"
+ )
+ return [];
+ const run = source["run"];
+ if (run == null) return [];
+ return array(
+ record(run, "Snyk run context")["versionControlProvenance"] ?? [],
+ "Snyk version control provenance",
+ ).map((entry) => {
+ const repository = requiredText(
+ record(entry, "Snyk repository provenance")["repositoryUri"],
+ "Snyk repository URI",
+ );
+ return normalizeGitRemote
+ ? normalizeGitRepositoryUrl(repository, cloudRepositoryUrl)
+ : repository;
+ });
+}
+
+/** Snyk Open Source's formatter groups all dependency paths for an advisory in a project. */
+export function normalizeSnykSarif(input: unknown): ExternalFindings {
+ const document = record(input, "Snyk SARIF");
+ if (document["version"] !== "2.1.0")
+ throw new Error("Expected Snyk Open Source SARIF 2.1.0.");
+ const entries = array(document["runs"], "SARIF runs").flatMap((value) => {
+ const run = record(value, "SARIF run");
+ const driver = record(
+ record(run["tool"], "SARIF tool")["driver"],
+ "SARIF driver",
+ );
+ if (driver["name"] !== "Snyk Open Source")
+ throw new Error(
+ "Only Snyk Open Source SARIF is supported; Code, Container, and IaC need separate mappings.",
+ );
+ if (
+ hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])
+ )
+ throw new Error(
+ "External SARIF property files are unsupported; use a self-contained report.",
+ );
+ const rules = array(driver["rules"], "SARIF rules").map((rule) =>
+ record(rule, "SARIF rule"),
+ );
+ const rulesById = new Map<
+ unknown,
+ { rule: Record<string, unknown>; index: number } | null
+ >();
+ rules.forEach((rule, index) => {
+ const id = rule["id"];
+ rulesById.set(id, rulesById.has(id) ? null : { rule, index });
+ });
+ const project = snykSarifProject(run);
+ const { results: _results, tool: _tool, ...runContext } = run;
+ const { rules: _rules, ...driverContext } = driver;
+ const { driver: _driver, ...toolContext } = record(
+ run["tool"],
+ "SARIF tool",
+ );
+ runContext["tool"] = toolContext;
+ const { runs: _runs, ...documentContext } = document;
+ return array(run["results"], "SARIF results").map((result) => ({
+ result,
+ rulesById,
+ project,
+ runContext,
+ driverContext,
+ documentContext,
+ }));
+ });
+ return normalizeRecords(
+ entries,
+ (
+ { result: value, rulesById, runContext, driverContext, documentContext },
+ sourceFindingId,
+ ) => {
+ const result = record(value, "SARIF result");
+ const id = requiredText(result["ruleId"], "Snyk advisory ruleId");
+ const match = rulesById.get(id);
+ if (!match)
+ throw new Error("Result must reference exactly one rule in its run.");
+ const { rule, index } = match;
+ if (result["ruleIndex"] !== undefined && result["ruleIndex"] !== index)
+ throw new Error("Result ruleIndex and ruleId disagree.");
+ if (result["rule"] !== undefined) {
+ const ref = record(result["rule"], "Rule reference");
+ if (
+ ref["toolComponent"] !== undefined ||
+ (ref["id"] !== undefined && ref["id"] !== id) ||
+ (ref["index"] !== undefined && ref["index"] !== index) ||
+ (ref["guid"] !== undefined && ref["guid"] !== rule["guid"])
+ )
+ throw new Error(
+ "Result uses an inconsistent or external rule reference.",
+ );
+ }
+ const help = requiredText(
+ record(rule["help"], "Rule help")["markdown"],
+ "Rule help markdown",
+ );
+ const manager = /^\* Package Manager: (.+)$/mu.exec(help)?.[1] ?? null;
+ if (!manager || !/^\* Vulnerable module: .+$/mu.test(help))
+ throw new Error(
+ "Expected the Snyk Open Source vulnerability profile; license findings are unsupported.",
+ );
+ const title = requiredText(
+ record(rule["shortDescription"], "Rule shortDescription")["text"],
+ "Rule title",
+ );
+ const severity =
+ /^(Critical|High|Medium|Low) severity - /u
+ .exec(title)?.[1]
+ ?.toLowerCase() ?? "unknown";
+ const message = requiredText(
+ record(result["message"], "Result message")["text"],
+ "Result message text",
+ );
+ const locations = array(
+ result["locations"] ?? [],
+ "Result locations",
+ ).map((v) => record(v, "Location"));
+ const packages: {
+ name: string;
+ ecosystem: string;
+ installed_version: string | null;
+ manifest_path: string | null;
+ fixed_versions: string[];
+ }[] = [];
+ for (const location of locations) {
+ for (const logical of array(
+ location["logicalLocations"] ?? [],
+ "Logical locations",
+ )) {
+ const coordinate = text(
+ record(logical, "Logical location")["fullyQualifiedName"],
+ );
+ if (!coordinate) continue;
+ const split = coordinate.lastIndexOf("@");
+ if (split <= 0) continue;
+ packages.push({
+ name: coordinate.slice(0, split),
+ ecosystem: manager,
+ installed_version: coordinate.slice(split + 1) || null,
+ manifest_path: null,
+ fixed_versions: [],
+ });
+ }
+ }
+ const description = [message, help].join("\n\n");
+ // Use the project, advisory group, and literal manifest set within the caller's namespace.
+ return {
+ source_finding_id: sourceFindingId,
+ evidence: validateExternalEvidence({
+ title,
+ description,
+ severity,
+ advisory_ids: [
+ ...new Set([
+ id,
+ ...(text(
+ record(rule["fullDescription"] ?? {}, "Full description")[
+ "text"
+ ],
+ )?.match(/\bCVE-\d{4}-\d+\b/gu) ?? []),
+ ]),
+ ],
+ packages,
+ // Snyk emits target-relative paths without a Git-root offset and may
+ // synthesize startLine=1. Keep both only in the original evidence.
+ locations: [],
+ source_data: structuredClone({
+ document: documentContext,
+ run: sarifRunContextForResult(
+ runContext,
+ result,
+ rule,
+ driverContext,
+ documentContext,
+ ),
+ driver: driverContext,
+ rule,
+ result,
+ }),
+ }),
+ };
+ },
+ ({ result, project }) => snykIdentity(result, project),
+ );
+}
+
+/** Import native `snyk test --json` Open Source vulnerability occurrences. */
+export function normalizeSnykJson(input: unknown): ExternalFindings {
+ const projects = Array.isArray(input) ? input : [input];
+ const entries = projects.flatMap((value) => {
+ const project = record(value, "Snyk Open Source project");
+ if (project["error"])
+ throw new Error(`Snyk scan failed: ${String(project["error"])}`);
+ if (project["docker"] || project["applications"])
+ throw new Error(
+ "Snyk Container JSON is unsupported; use Open Source SCA results.",
+ );
+ if (typeof project["ok"] !== "boolean")
+ throw new Error("Expected a completed Snyk Open Source test result.");
+ const manager = requiredText(
+ project["packageManager"],
+ "Snyk package manager",
+ );
+ const manifest =
+ text(project["displayTargetFile"]) ?? text(project["targetFile"]);
+ const { vulnerabilities, ...context } = project;
+ return array(vulnerabilities, "Snyk vulnerabilities").map((value) => ({
+ value,
+ context,
+ manager,
+ manifest,
+ }));
+ });
+ return normalizeRecords(
+ entries,
+ ({ value, context, manager }, sourceFindingId) => {
+ const vulnerability = record(value, "Snyk vulnerability");
+ if (vulnerability["type"] === "license")
+ throw new Error(
+ "Snyk license findings are unsupported; only Open Source SCA vulnerabilities are imported.",
+ );
+ const identifiers = record(
+ vulnerability["identifiers"] ?? {},
+ "Snyk identifiers",
+ );
+ const severity = text(vulnerability["severity"])?.toLowerCase();
+ return {
+ source_finding_id: sourceFindingId,
+ evidence: validateExternalEvidence({
+ title: requiredText(
+ vulnerability["title"],
+ "Snyk vulnerability title",
+ ),
+ description: text(vulnerability["description"]),
+ severity: ["critical", "high", "medium", "low"].includes(
+ severity ?? "",
+ )
+ ? severity
+ : "unknown",
+ advisory_ids: [
+ ...new Set([
+ requiredText(vulnerability["id"], "Snyk advisory ID"),
+ ...strings(identifiers["CVE"]),
+ ]),
+ ],
+ packages: [
+ {
+ name: requiredText(
+ vulnerability["name"] ?? vulnerability["packageName"],
+ "Snyk package name",
+ ),
+ ecosystem: manager,
+ installed_version: text(vulnerability["version"]),
+ // Native test paths are scan-target-relative, without a Git-root offset.
+ manifest_path: null,
+ fixed_versions: strings(vulnerability["fixedIn"]),
+ },
+ ],
+ locations: [],
+ source_data: structuredClone({ project: context, vulnerability }),
+ }),
+ };
+ },
+ ({ value, manager, manifest }) => {
+ const vulnerability = record(value, "Snyk vulnerability");
+ return stableId("snyk-json", [
+ manager,
+ manifest,
+ requiredText(vulnerability["id"], "Snyk advisory ID"),
+ requiredText(
+ vulnerability["name"] ?? vulnerability["packageName"],
+ "Snyk package name",
+ ),
+ text(vulnerability["version"]),
+ array(vulnerability["from"] ?? [], "Snyk dependency path").map((item) =>
+ requiredText(item, "Snyk dependency"),
+ ),
+ ]);
+ },
+ );
+}
+
+export async function readSnykFindings(
+ path: string,
+): Promise<ExternalFindings> {
+ const input = await readScannerJson(path);
+ if (Array.isArray(input)) return normalizeSnykJson(input);
+ const document = record(input, "Snyk findings");
+ if (document["format"] === "snyk-findings-export/v1")
+ return normalizeSnykFindingsExport(document);
+ if (document["version"] === "2.1.0") return normalizeSnykSarif(document);
+ return normalizeSnykJson(document);
+}
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 01ba8d029..f47a7f7d9 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -143,7 +143,11 @@ test("a Wiz Raw Event export explains the finding-report path before contacting
expect(contactedCloud).toBe(false);
});
-async function fixture(records: unknown = [normalized()]) {
+async function fixture(
+ records: unknown = [normalized()],
+ repositoryUrl = "https://github.com/example/project",
+ repoConnectorId = "github",
+) {
const root = await mkdtemp(join(tmpdir(), "external-findings-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const file = join(root, "selected findings.json");
@@ -184,8 +188,8 @@ async function fixture(records: unknown = [normalized()]) {
const destination = () => ({
id: options.repository,
object: "security.repository",
- repo_connector_id: "github",
- url: "https://github.com/example/project",
+ repo_connector_id: repoConnectorId,
+ url: repositoryUrl,
default_branch: "main",
reset_marker: state.marker,
import_environment_id: state.environmentId,
@@ -2772,3 +2776,507 @@ test("normalized SDK publication accepts Cloud providers without their file read
expect((await prepared.publish()).verified).toBe(1);
expect(JSON.parse(f.posts[0]!).source.provider).toBe("endor");
});
+
+test.each([
+ { run: "scan-123" },
+ { run: { versionControlProvenance: "opaque scanner metadata" } },
+])(
+ "normalized Snyk publication preserves opaque source metadata: %j",
+ async (sourceData) => {
+ const original = normalized();
+ const finding = {
+ ...original,
+ evidence: validateExternalEvidence({
+ ...original.evidence,
+ source_data: sourceData,
+ }),
+ };
+ const f = await fixture();
+ const prepared = await prepareNormalizedExternalPublication(
+ { read: 1, findings: [finding], excluded: [] },
+ { ...options, provider: "snyk" },
+ f.deps,
+ );
+ expect((await prepared.publish()).verified).toBe(1);
+ expect([...f.reports.values()][0]!.evidence.source_data).toEqual(
+ sourceData,
+ );
+ },
+);
+
+test("Snyk SARIF publish, replay and changed evidence preserve Cloud identity", async () => {
+ const { snykSarif } = await import("./support/snyk-import-fixtures.js");
+ const input = snykSarif();
+ const f = await fixture(input);
+ const settings = {
+ ...options,
+ provider: "snyk" as const,
+ sourceKey: "organization/project/main",
+ };
+ const first = await (
+ await prepareExternalPublication(f.file, settings, f.deps)
+ ).publish();
+ expect(first.counts.created).toBe(1);
+ expect(first.verified).toBe(1);
+ const original = structuredClone([...f.reports.values()][0]!);
+ const second = await (
+ await prepareExternalPublication(f.file, settings, f.deps)
+ ).publish();
+ expect(second.counts.unchanged).toBe(1);
+ input.runs[0]!.results[0]!.message.text = "Updated source evidence";
+ await writeFile(f.file, JSON.stringify(input));
+ const third = await (
+ await prepareExternalPublication(f.file, settings, f.deps)
+ ).publish();
+ expect(third.counts.updated).toBe(1);
+ const updated = [...f.reports.values()][0]!;
+ expect(updated.id).toBe(original.id);
+ expect(updated.canonical_finding_id).toBe(original.canonical_finding_id);
+ expect(updated.version).toBe(2);
+});
+
+test("Snyk CLI dry run selects its adapter without writing an import", async () => {
+ const { snykSarif } = await import("./support/snyk-import-fixtures.js");
+ const f = await fixture(snykSarif());
+ const command = [...f.command, "--dry-run"];
+ command[command.indexOf("--provider") + 1] = "snyk";
+ const cli = createCliTest(main);
+ expect(await cli.runCli(command, f.cliDeps)).toBe(0);
+ expect(f.posts).toHaveLength(0);
+});
+
+test.each([
+ { uris: ["https://github.com/other/project"] },
+ {
+ uris: [
+ "https://github.com/example/project",
+ "https://github.com/other/project",
+ ],
+ },
+ { uris: ["https://github.com:443/example/project"] },
+])(
+ "Snyk source repository provenance binds both publication entrypoints: %p",
+ async ({ uris }) => {
+ const { snykSarif } = await import("./support/snyk-import-fixtures.js");
+ const { normalizeSnykSarif } = await import("../src/snyk-findings.js");
+ const input: any = snykSarif();
+ input.runs[0].versionControlProvenance = uris.map((repositoryUri) => ({
+ repositoryUri,
+ }));
+ const f = await fixture(input);
+ const selected = { ...options, provider: "snyk" as const };
+ await expect(
+ prepareExternalPublication(f.file, selected, f.deps),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ await expect(
+ prepareNormalizedExternalPublication(
+ normalizeSnykSarif(input),
+ selected,
+ f.deps,
+ ),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ expect(f.posts).toHaveLength(0);
+ expect(f.reports.size).toBe(0);
+ },
+);
+
+test("Snyk source repository binding is rechecked for a fresh import after completion", async () => {
+ const { snykSarif } = await import("./support/snyk-import-fixtures.js");
+ const input: any = snykSarif();
+ input.runs[0].versionControlProvenance = [
+ {
+ repositoryUri: "https://GITHUB.COM/EXAMPLE/PROJECT.git",
+ revisionId: "synthetic-revision",
+ },
+ ];
+ const original = structuredClone(input);
+ const f = await fixture(input);
+ const selected = { ...options, provider: "snyk" as const };
+ const first = await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish();
+ expect(first.verified).toBe(1);
+ expect([...f.reports.values()][0]!.evidence.source_data).toMatchObject({
+ run: {
+ versionControlProvenance: original.runs[0].versionControlProvenance,
+ },
+ });
+ const changedDestination = {
+ ...f.deps,
+ fetch: async (url: string, init: RequestInit) => {
+ const response = await f.deps.fetch(url, init);
+ if (new URL(url).pathname.endsWith("/repositories")) {
+ const body = await response.json();
+ body.data[0].url = "https://github.com/other/project";
+ return Response.json(body);
+ }
+ return response;
+ },
+ };
+ const posted = f.posts.length;
+ await expect(
+ prepareExternalPublication(f.file, selected, changedDestination),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ expect(f.posts).toHaveLength(posted);
+ expect(input).toEqual(original);
+});
+
+async function snykRepositoryEvidence(
+ format: "plugin" | "SARIF",
+ repository: string,
+) {
+ const { snykPluginExport, snykSarif } =
+ await import("./support/snyk-import-fixtures.js");
+ const { normalizeSnykFindingsExport, normalizeSnykSarif } =
+ await import("../src/snyk-findings.js");
+ if (format === "plugin") {
+ const input = snykPluginExport();
+ input.collection.target.repository = repository;
+ return {
+ input,
+ normalized: normalizeSnykFindingsExport(input),
+ original: { collection: input.collection, finding: input.findings[0] },
+ };
+ }
+ const sarif = snykSarif();
+ const provenance = [{ repositoryUri: repository }];
+ const input = {
+ ...sarif,
+ runs: sarif.runs.map((run) => ({
+ ...run,
+ versionControlProvenance: provenance,
+ })),
+ };
+ return {
+ input,
+ normalized: normalizeSnykSarif(input),
+ original: { run: { versionControlProvenance: provenance } },
+ };
+}
+
+const snykRepositoryAliases: [string, string][] = [
+ [
+ "https://github.com/example/project.git",
+ "https://github.com/example/project",
+ ],
+ ["[email protected]:example/project.git", "https://github.com/example/project"],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ // Preserve the existing generic git-user aliases for connected catalog hosts.
+ [
+ "[email protected]:example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "https://git.example.test/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+];
+
+test.each([
+ ...snykRepositoryAliases.flatMap(([repository, destination]) =>
+ (["plugin", "SARIF"] as const).map(
+ (format) => [format, repository, destination] as const,
+ ),
+ ),
+ ["plugin", "unknown", "https://github.com/example/project"] as const,
+])(
+ "Snyk %s export imports and replays with repository remote %s",
+ async (format, repository, destination) => {
+ const { input, normalized, original } = await snykRepositoryEvidence(
+ format,
+ repository,
+ );
+ const f = await fixture(input, destination, "connector-selected");
+ const selected = {
+ ...options,
+ provider: "snyk" as const,
+ sourceKey: "example/project/main/plugin-sca",
+ };
+ const first = await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish();
+ expect(first.counts.created).toBe(1);
+ expect(first.verified).toBe(1);
+ expect(JSON.parse(f.posts[0]!).repository.repo_connector_id).toBe(
+ "connector-selected",
+ );
+ expect([...f.reports.values()][0]!.evidence.source_data).toMatchObject(
+ original,
+ );
+ const second = await (
+ await prepareNormalizedExternalPublication(normalized, selected, f.deps)
+ ).publish();
+ expect(second.counts.unchanged).toBe(1);
+ },
+);
+
+const snykRepositoryMismatches: [string, string][] = [
+ ...["\t", "\r", "\n"].flatMap((control): [string, string][] => [
+ [
+ `ssh://git@github.${control}com/example/project.git`,
+ "https://github.com/example/project",
+ ],
+ [
+ `ssh://[email protected]/example/pro${control}ject.git`,
+ "https://github.com/example/project",
+ ],
+ [
+ `ssh://tenant@tenant.${control}ghe.com/example/project.git`,
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ `ssh://[email protected]/example/pro${control}ject.git`,
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ `ssh://[email protected].${control}com:443/example/project.git`,
+ "https://github.com/example/project",
+ ],
+ [
+ `ssh://[email protected]:443/example/pro${control}ject.git`,
+ "https://github.com/example/project",
+ ],
+ ]),
+ [
+ "ssh://tenant@other:[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://tenant@other:@tenant.ghe.com/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://git@other:[email protected]/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://git@other:@github.com/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://te\[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://te\[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://te\[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://gi\[email protected]/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://tenant@[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://other.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://api.tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://tenant:[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://tenant:@tenant.ghe.com/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://tenant.ghe.com:443/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://tenant.ghe.com:443/example/project",
+ ],
+ [
+ "[email protected]:other/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "http://tenant.ghe.com/example/project",
+ ],
+ ["[email protected]:other/project.git", "https://github.com/example/project"],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://github.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://git.example.test:2222/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://git.example.test:443/example/project",
+ ],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://github.com:2222/example/project",
+ ],
+ [
+ "ssh://[email protected]:443/example/project.git",
+ "https://github.com:443/example/project",
+ ],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://tenant.ghe.com:2222/example/project",
+ ],
+ [
+ "ssh://[email protected]:2222/example/project.git",
+ "https://ssh.github.com:2222/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "[email protected]:other/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://git.example.test:443/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://git.example.test:22/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "http://git.example.test/example/project",
+ ],
+];
+
+test.each([
+ ...snykRepositoryMismatches.flatMap(([repository, destination]) =>
+ (["plugin", "SARIF"] as const).map(
+ (format) => [format, repository, destination] as const,
+ ),
+ ),
+ ["SARIF", "unknown", "https://github.com/example/project"] as const,
+])(
+ "Snyk %s repository claim %s cannot target %s",
+ async (format, repository, destination) => {
+ const { input, normalized, original } = await snykRepositoryEvidence(
+ format,
+ repository,
+ );
+ const f = await fixture(input, destination);
+ const selected = { ...options, provider: "snyk" as const };
+ await expect(
+ prepareExternalPublication(f.file, selected, f.deps),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ await expect(
+ prepareNormalizedExternalPublication(normalized, selected, f.deps),
+ ).rejects.toThrow("does not match the selected Cloud repository");
+ expect(f.posts).toHaveLength(0);
+ expect(normalized.findings[0]!.evidence.source_data).toMatchObject(
+ original,
+ );
+ },
+);
+
+test("native Snyk JSON publishes selected dependency occurrences and replays their evidence", async () => {
+ const { snykJson } = await import("./support/snyk-import-fixtures.js");
+ const input = snykJson();
+ const f = await fixture(input);
+ const selected = {
+ ...options,
+ provider: "snyk" as const,
+ sourceKey: "example/project/main/root/native-sca",
+ };
+ const prepared = await prepareExternalPublication(f.file, selected, f.deps);
+ expect(prepared.preview.excluded).toEqual([]);
+ const first = await prepared.publish();
+ expect(first.counts.created).toBe(1);
+ expect(first.verified).toBe(1);
+ expect([...f.reports.values()][0]!.evidence).toMatchObject({
+ locations: [],
+ packages: [{ name: "@example/package", manifest_path: null }],
+ source_data: { vulnerability: input.vulnerabilities[0] },
+ });
+ const second = await (
+ await prepareExternalPublication(f.file, selected, f.deps)
+ ).publish();
+ expect(second.counts.unchanged).toBe(1);
+});
diff --git a/sdk/typescript/tests-ts/snyk-findings-local.test.ts b/sdk/typescript/tests-ts/snyk-findings-local.test.ts
new file mode 100644
index 000000000..ae3a22f68
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-findings-local.test.ts
@@ -0,0 +1,227 @@
+import { expect, test } from "bun:test";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { prepareLocalExternalImport } from "../src/external-findings-import.js";
+import { listLocalExternalFindings } from "../src/external-findings-local.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+import {
+ snykJson,
+ snykPluginExport,
+ snykSarif,
+} from "./support/snyk-import-fixtures.js";
+
+test.each(["plugin", "JSON", "SARIF"] as const)(
+ "Snyk %s findings persist locally and update without duplicating their identities",
+ async (format) => {
+ const fixture = await localFindingsFixture({
+ remote: "https://github.com/example/project",
+ });
+ try {
+ const input =
+ format === "plugin"
+ ? snykPluginExport()
+ : format === "JSON"
+ ? snykJson()
+ : snykSarif();
+ const path = join(fixture.root, "snyk.json");
+ const options = {
+ repository: fixture.repository,
+ provider: "snyk" as const,
+ sourceKey: `snyk-${format.toLowerCase()}`,
+ };
+ const dependencies = { environment: fixture.environment };
+ await writeFile(path, JSON.stringify(input));
+
+ const prepared = await prepareLocalExternalImport(
+ path,
+ options,
+ dependencies,
+ );
+ expect(prepared.preview.excluded).toEqual([]);
+ expect(prepared.preview.findings).toHaveLength(1);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ [],
+ );
+ expect((await prepared.import()).counts).toEqual({
+ created: 1,
+ updated: 0,
+ unchanged: 0,
+ });
+
+ const [stored] = await listLocalExternalFindings(options, dependencies);
+ expect(stored).toMatchObject({
+ repository: fixture.repository,
+ provider: "snyk",
+ sourceKey: options.sourceKey,
+ sourceFindingId: prepared.preview.findings[0]!.source_finding_id,
+ version: 1,
+ });
+ expect(stored!.evidence).toEqual(prepared.preview.findings[0]!.evidence);
+ expect(stored!.assessment).toEqual({ state: "not_assessed" });
+ expect(stored!.evidence).not.toHaveProperty("confidence");
+ if ("findings" in input) {
+ expect(stored!.evidence.locations).toEqual([]);
+ expect(stored!.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(stored!.evidence.source_data).toMatchObject({
+ collection: input.collection,
+ finding: input.findings[0],
+ });
+ } else if ("vulnerabilities" in input) {
+ expect(stored!.evidence.locations).toEqual([]);
+ expect(stored!.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(stored!.evidence.source_data).toMatchObject({
+ vulnerability: input.vulnerabilities[0],
+ });
+ } else {
+ expect(stored!.evidence.locations).toEqual([]);
+ expect(stored!.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(stored!.evidence.source_data).toMatchObject({
+ result: input.runs[0]!.results[0],
+ rule: input.runs[0]!.tool.driver.rules[0],
+ });
+ }
+
+ const repeated = await prepareLocalExternalImport(
+ path,
+ options,
+ dependencies,
+ );
+ expect((await repeated.import()).counts).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 1,
+ });
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual([
+ stored!,
+ ]);
+
+ if ("findings" in input) {
+ input.findings[0]!.severity.value = "low";
+ input.findings[0]!.nativeRecord.isIgnored = false;
+ } else if ("vulnerabilities" in input) {
+ input.vulnerabilities[0]!.severity = "low";
+ input.vulnerabilities[0]!.description = "Updated dependency evidence";
+ } else {
+ input.runs[0]!.tool.driver.rules[0]!.shortDescription.text =
+ "Low severity - synthetic vulnerability in @example/package";
+ input.runs[0]!.results[0]!.message.text = "Updated dependency evidence";
+ }
+ await writeFile(path, JSON.stringify(input));
+ const changed = await prepareLocalExternalImport(
+ path,
+ options,
+ dependencies,
+ );
+ expect((await changed.import()).counts).toEqual({
+ created: 0,
+ updated: 1,
+ unchanged: 0,
+ });
+ const updated = await listLocalExternalFindings(options, dependencies);
+ expect(updated).toHaveLength(1);
+ expect(updated[0]).toMatchObject({
+ id: stored!.id,
+ sourceFindingId: stored!.sourceFindingId,
+ createdAt: stored!.createdAt,
+ version: 2,
+ });
+ expect(updated[0]!.assessment).toEqual({ state: "not_assessed" });
+ expect(updated[0]!.evidence).toEqual(
+ changed.preview.findings[0]!.evidence,
+ );
+ expect(updated[0]!.evidence.severity).toBe("low");
+ expect(updated[0]!.evidence.source_data).not.toEqual(
+ stored!.evidence.source_data,
+ );
+ } finally {
+ await fixture.dispose();
+ }
+ },
+);
+
+test.each(["plugin", "SARIF"] as const)(
+ "Snyk %s repository provenance cannot be imported into a different local checkout",
+ async (format) => {
+ const fixture = await localFindingsFixture({
+ remote: "https://github.com/example/other",
+ });
+ try {
+ const sarif = snykSarif();
+ const input =
+ format === "plugin"
+ ? snykPluginExport()
+ : {
+ ...sarif,
+ runs: sarif.runs.map((run) => ({
+ ...run,
+ versionControlProvenance: [
+ { repositoryUri: "https://github.com/example/project" },
+ ],
+ })),
+ };
+ const path = join(fixture.root, "snyk.json");
+ await writeFile(path, JSON.stringify(input));
+ const options = {
+ repository: fixture.repository,
+ provider: "snyk" as const,
+ sourceKey: "snyk-sca",
+ };
+ const dependencies = { environment: fixture.environment };
+ await expect(
+ prepareLocalExternalImport(path, options, dependencies),
+ ).rejects.toThrow(/repository/iu);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ [],
+ );
+ } finally {
+ await fixture.dispose();
+ }
+ },
+);
+
+test.each([2222, 2223])(
+ "Snyk plugin repository matching preserves the SSH port (checkout port %i)",
+ async (port) => {
+ const fixture = await localFindingsFixture({
+ remote: `ssh://[email protected]:${port}/example/project.git`,
+ });
+ try {
+ const input = snykPluginExport();
+ input.collection.target.repository =
+ "ssh://[email protected]:2222/example/project.git";
+ const path = join(fixture.root, "snyk.json");
+ await writeFile(path, JSON.stringify(input));
+ const options = {
+ repository: fixture.repository,
+ provider: "snyk" as const,
+ sourceKey: "snyk-sca",
+ };
+ const dependencies = { environment: fixture.environment };
+ if (port !== 2222) {
+ await expect(
+ prepareLocalExternalImport(path, options, dependencies),
+ ).rejects.toThrow(/repository/iu);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ [],
+ );
+ return;
+ }
+
+ const prepared = await prepareLocalExternalImport(
+ path,
+ options,
+ dependencies,
+ );
+ expect((await prepared.import()).counts.created).toBe(1);
+ const records = await listLocalExternalFindings(options, dependencies);
+ expect(records).toHaveLength(1);
+ expect(records[0]!.evidence.source_data).toMatchObject({
+ collection: {
+ target: { repository: input.collection.target.repository },
+ },
+ });
+ } finally {
+ await fixture.dispose();
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/snyk-findings.test.ts b/sdk/typescript/tests-ts/snyk-findings.test.ts
new file mode 100644
index 000000000..9ce81d3f4
--- /dev/null
+++ b/sdk/typescript/tests-ts/snyk-findings.test.ts
@@ -0,0 +1,866 @@
+import { expect, test } from "bun:test";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { gzipSync } from "node:zlib";
+import {
+ normalizeSnykFindingsExport,
+ normalizeSnykJson,
+ normalizeSnykSarif,
+ readSnykFindings,
+ snykRepositoryUrls,
+} from "../src/snyk-findings.js";
+import {
+ snykJson,
+ snykPluginExport,
+ snykSarif,
+} from "./support/snyk-import-fixtures.js";
+
+test("Snyk retains the full selected result, rule, producer and unknown context", () => {
+ const input = snykSarif();
+ const before = structuredClone(input);
+ const output = normalizeSnykSarif(input);
+ expect(input).toEqual(before);
+ expect(output.read).toBe(1);
+ expect(output.excluded).toEqual([]);
+ const evidence = output.findings[0]!.evidence;
+ expect(evidence).toMatchObject({
+ severity: "critical",
+ advisory_ids: ["SNYK-EXAMPLE-1", "CVE-2099-0001"],
+ packages: [
+ {
+ name: "@example/package",
+ installed_version: "1.0.0",
+ ecosystem: "npm",
+ fixed_versions: [],
+ manifest_path: null,
+ },
+ ],
+ locations: [],
+ source_updated_at: null,
+ });
+ expect(evidence.source_data).toMatchObject({
+ rule: before.runs[0]!.tool.driver.rules[0],
+ result: before.runs[0]!.results[0],
+ driver: { name: "Snyk Open Source", semanticVersion: "1.0.0" },
+ run: { automationDetails: before.runs[0]!.automationDetails },
+ });
+ expect(evidence.description).toContain("Detailed paths");
+});
+
+test("severity and export time changes retain identity; manifests remain distinct", () => {
+ const input = snykSarif();
+ const original = normalizeSnykSarif(input).findings[0]!;
+ input.runs[0]!.automationDetails.id = "Snyk/Open Source/example/4/new-export";
+ input.runs[0]!.tool.driver.rules[0]!.shortDescription.text =
+ "Low severity - synthetic vulnerability";
+ const changed = normalizeSnykSarif(input).findings[0]!;
+ expect(changed.source_finding_id).toBe(original.source_finding_id);
+ expect(changed.evidence.severity).toBe("low");
+ expect(changed.evidence.source_data).not.toEqual(
+ original.evidence.source_data,
+ );
+ input.runs[0]!.results[0]!.locations[0]!.physicalLocation.artifactLocation.uri =
+ "other/package.json";
+ expect(normalizeSnykSarif(input).findings[0]!.source_finding_id).not.toBe(
+ original.source_finding_id,
+ );
+});
+
+test("unknown severity remains unknown, without inferring it from SARIF level or CVSS", () => {
+ const input = snykSarif();
+ input.runs[0]!.tool.driver.rules[0]!.shortDescription.text =
+ "Synthetic vulnerability";
+ expect(normalizeSnykSarif(input).findings[0]!.evidence.severity).toBe(
+ "unknown",
+ );
+});
+
+test("SARIF projects with the same advisory and manifest keep distinct, stable identities", () => {
+ const input = snykSarif();
+ input.runs = ["workspace/api", "@example/web"].map((project, index) => ({
+ ...structuredClone(input.runs[0]!),
+ automationDetails: {
+ id: `Snyk/Open Source/${project}/${index}/2026-01-01T00:00:00.000Z`,
+ },
+ }));
+ const original = structuredClone(input);
+ const before = normalizeSnykSarif(input);
+ expect(before.findings).toHaveLength(2);
+ expect(before.excluded).toEqual([]);
+ expect(new Set(before.findings.map((f) => f.source_finding_id)).size).toBe(2);
+ expect(input).toEqual(original);
+
+ input.runs.reverse();
+ input.runs.forEach((run, index) => {
+ run.automationDetails.id = run.automationDetails.id.replace(
+ /\/\d+\/[^/]+$/u,
+ `/${index}/2026-02-01T00:00:00.000Z`,
+ );
+ });
+ const after = normalizeSnykSarif(input);
+ expect(after.excluded).toEqual([]);
+ expect(after.findings.map((f) => f.source_finding_id).sort()).toEqual(
+ before.findings.map((f) => f.source_finding_id).sort(),
+ );
+});
+
+test.each(["example/", ""])(
+ "run indexes and export times do not distinguish duplicate project %j findings",
+ (project) => {
+ const input = snykSarif();
+ input.runs = ["2026-01-01T00:00:00.000Z", "2026-02-01T00:00:00.000Z"].map(
+ (timestamp, index) => ({
+ ...structuredClone(input.runs[0]!),
+ automationDetails: {
+ id: `Snyk/Open Source/${project}${index}/${timestamp}`,
+ },
+ }),
+ );
+ const output = normalizeSnykSarif(input);
+ expect(output.findings).toEqual([]);
+ expect(output.excluded.map((e) => e.position)).toEqual([1, 2]);
+ expect(output.excluded.every((e) => e.reason.includes("duplicate"))).toBe(
+ true,
+ );
+ },
+);
+
+test.each(["Snyk Code", "Snyk Container", "Snyk IaC", "Other"])(
+ "rejects unsupported producer %s",
+ (producer) => {
+ const input = snykSarif();
+ input.runs[0]!.tool.driver.name = producer;
+ expect(() => normalizeSnykSarif(input)).toThrow("Only Snyk Open Source");
+ },
+);
+
+test("licenses, malformed rules, conflicting references and external property files are not imported", () => {
+ const variants: Record<string, unknown>[] = [];
+ for (const mutate of [
+ (r: any) =>
+ (r.tool.driver.rules[0].help.markdown =
+ "* Package Manager: npm\n* Module: example"),
+ (r: any) => (r.results[0].ruleIndex = 1),
+ (r: any) => (r.results[0].rule = { id: "different" }),
+ (r: any) => (r.results[0].rule = { index: true }),
+ (r: any) => (r.results[0].rule = { toolComponent: { index: 0 } }),
+ (r: any) => (r.results[0].rule = { guid: "different" }),
+ (r: any) => (r.results[0].ruleId = "SNYK-MISSING"),
+ (r: any) =>
+ r.tool.driver.rules.push(structuredClone(r.tool.driver.rules[0])),
+ ]) {
+ const input = snykSarif();
+ mutate(input.runs[0]);
+ variants.push(input);
+ }
+ for (const input of variants) {
+ const result = normalizeSnykSarif(input);
+ expect(result.findings).toHaveLength(0);
+ expect(result.excluded).toHaveLength(1);
+ }
+ expect(() =>
+ normalizeSnykSarif({ ...snykSarif(), version: "2.0.0" }),
+ ).toThrow("2.1.0");
+ const input = snykSarif() as any;
+ input.runs[0].externalPropertyFileReferences = {
+ results: [{ location: { uri: "https://example.invalid/data" } }],
+ };
+ expect(() => normalizeSnykSarif(input)).toThrow("self-contained");
+});
+
+test("rule references use original indexes and ignore unrelated duplicate or missing IDs", () => {
+ const input = snykSarif();
+ const run = input.runs[0]!;
+ const rule = { ...run.tool.driver.rules[0]!, guid: "synthetic-guid" };
+ const report = {
+ ...input,
+ runs: [
+ {
+ ...run,
+ tool: {
+ ...run.tool,
+ driver: {
+ ...run.tool.driver,
+ rules: [{ id: "unrelated" }, rule, { id: "unrelated" }, {}],
+ },
+ },
+ results: [
+ {
+ ...run.results[0]!,
+ ruleIndex: 1,
+ rule: { id: rule.id, index: 1, guid: rule.guid },
+ },
+ ],
+ },
+ ],
+ };
+ const original = structuredClone(report);
+ const output = normalizeSnykSarif(report);
+ expect(output.findings).toHaveLength(1);
+ expect(output.excluded).toEqual([]);
+ expect(output.findings[0]!.evidence.source_data).toMatchObject({ rule });
+ expect(report).toEqual(original);
+});
+
+test("every ambiguous duplicate is excluded instead of keeping an arbitrary project", () => {
+ const input = snykSarif();
+ input.runs.push(structuredClone(input.runs[0]!));
+ const output = normalizeSnykSarif(input);
+ expect(output.findings).toEqual([]);
+ expect(output.excluded.map((e) => e.position)).toEqual([1, 2]);
+});
+
+test.each([
+ { index: 0 },
+ { uri: "package.json", index: 0 },
+ { uri: "package.json", uriBaseId: "ROOT" },
+])(
+ "unresolved SARIF artifact references cannot identify a Snyk manifest: %p",
+ (artifact) => {
+ for (const manifest of ["one/package.json", "two/package.json"]) {
+ const input: any = snykSarif();
+ input.runs[0].artifacts = [{ location: { uri: manifest } }];
+ input.runs[0].originalUriBaseIds = { ROOT: { uri: "file:///outside/" } };
+ input.runs[0].results[0].locations[0].physicalLocation.artifactLocation =
+ artifact;
+ const original = structuredClone(input);
+ const output = normalizeSnykSarif(input);
+ expect(output.findings).toEqual([]);
+ expect(output.excluded).toHaveLength(1);
+ expect(output.excluded[0]!.reason).toContain("artifact references");
+ expect(input).toEqual(original);
+ }
+ },
+);
+
+test.each([
+ "/tmp/package.json",
+ "C:\\work\\package.json",
+ "../package.json",
+ "https://example.invalid/package.json",
+])(
+ "retains %s as evidence without treating it as a repository path",
+ (path) => {
+ const input = snykSarif();
+ input.runs[0]!.results[0]!.locations[0]!.physicalLocation.artifactLocation.uri =
+ path;
+ const evidence = normalizeSnykSarif(input).findings[0]!.evidence;
+ expect(evidence.locations).toEqual([]);
+ expect(evidence.packages![0]!.manifest_path).toBeNull();
+ expect(JSON.stringify(evidence.source_data)).toContain(
+ JSON.stringify(path),
+ );
+ },
+);
+
+test.each([
+ "packages/my%20app/package.json",
+ "packages/name:variant/package.json",
+ "packages/100%/package.json",
+ "packages/%2e%2e/package.json",
+ "packages/%ZZ/package.json",
+ "packages/café/package.json",
+ "packages/my app/package.json",
+])("preserves the Snyk formatter's literal manifest path %s", (path) => {
+ // getArtifactLocationUri in Snyk CLI returns displayTargetFile verbatim.
+ // A percent sign belongs to the filename; it is not an encoded URI here.
+ const input = snykSarif();
+ input.runs[0]!.results[0]!.locations[0]!.physicalLocation.artifactLocation.uri =
+ path;
+ const original = structuredClone(input);
+ const finding = normalizeSnykSarif(input).findings[0]!;
+ expect(finding.evidence.locations).toEqual([]);
+ expect(finding.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(finding.evidence.source_data).toMatchObject({
+ result: original.runs[0]!.results[0],
+ });
+ expect(input).toEqual(original);
+});
+
+test("SARIF from a nested scan target retains manifest evidence without claiming a repository-root path", () => {
+ const input = snykSarif();
+ const run = input.runs[0]!;
+ const nested = {
+ ...input,
+ runs: [{ ...run, properties: { path: "/work/example/services/api" } }],
+ };
+ const original = structuredClone(nested);
+ const finding = normalizeSnykSarif(nested).findings[0]!;
+ expect(finding.evidence.locations).toEqual([]);
+ expect(finding.evidence.packages![0]!.manifest_path).toBeNull();
+ expect(finding.evidence.source_data).toMatchObject({
+ run: { properties: { path: "/work/example/services/api" } },
+ result: run.results[0],
+ });
+ expect(finding.source_finding_id).toBe(
+ normalizeSnykSarif(input).findings[0]!.source_finding_id,
+ );
+ expect(nested).toEqual(original);
+});
+
+test("500 independent advisory groups survive normalization with stable identities after reordering", () => {
+ const input = snykSarif();
+ const run = input.runs[0]!;
+ run.tool.driver.rules = Array.from({ length: 500 }, (_, i) => ({
+ ...structuredClone(run.tool.driver.rules[0]!),
+ id: `SNYK-EXAMPLE-${i}`,
+ }));
+ run.results = run.tool.driver.rules.map((rule) => ({
+ ...structuredClone(run.results[0]!),
+ ruleId: rule.id,
+ }));
+ const before = normalizeSnykSarif(input);
+ run.tool.driver.rules.reverse();
+ run.results.reverse();
+ const after = normalizeSnykSarif(input);
+ expect(before.findings).toHaveLength(500);
+ expect(after.excluded).toEqual([]);
+ expect(after.findings.map((f) => f.source_finding_id).sort()).toEqual(
+ before.findings.map((f) => f.source_finding_id).sort(),
+ );
+});
+
+test("BOM and gzip files use the same parser and malformed files fail", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "snyk-import-"));
+ try {
+ const path = join(dir, "report.sarif");
+ await writeFile(path, gzipSync("\uFEFF" + JSON.stringify(snykSarif())));
+ expect(await readSnykFindings(path)).toEqual(
+ normalizeSnykSarif(snykSarif()),
+ );
+ await writeFile(path, "{");
+ await expect(readSnykFindings(path)).rejects.toThrow("could not be parsed");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test.each([0xfe, 0xff])(
+ "malformed UTF-8 byte %p cannot alter a finding identity",
+ async (byte) => {
+ const dir = await mkdtemp(join(tmpdir(), "snyk-invalid-utf8-"));
+ try {
+ const path = join(dir, "report.sarif");
+ const report = JSON.stringify(snykSarif());
+ const marker = report.indexOf("package.json");
+ const bytes = Buffer.concat([
+ Buffer.from(report.slice(0, marker)),
+ Buffer.from([byte]),
+ Buffer.from(report.slice(marker)),
+ ]);
+ for (const encoded of [bytes, gzipSync(bytes)]) {
+ await writeFile(path, encoded);
+ await expect(readSnykFindings(path)).rejects.toThrow("UTF-8");
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ },
+);
+test("an invalid duplicate cannot make its sibling eligible for publication", () => {
+ for (const mutate of [
+ (run: any) => (run.tool.driver.rules[0].help.markdown += "x".repeat(65536)),
+ (run: any) => delete run.tool.driver.rules[0].shortDescription,
+ (run: any) => (run.results[0].ruleIndex = 99),
+ ]) {
+ const input = snykSarif();
+ input.runs.push(structuredClone(input.runs[0]!));
+ mutate(input.runs[1]);
+ const output = normalizeSnykSarif(input);
+ expect(output.findings).toEqual([]);
+ expect(output.excluded).toHaveLength(2);
+ expect(
+ output.excluded.every((item) => item.reason.includes("duplicate")),
+ ).toBe(true);
+ }
+});
+
+test("official Snyk plugin SCA bundles preserve MCP evidence and source limitations", () => {
+ const input = snykPluginExport();
+ const before = structuredClone(input);
+ const result = normalizeSnykFindingsExport(input);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings[0]!.evidence).toMatchObject({
+ title: "Synthetic vulnerability",
+ severity: "high",
+ advisory_ids: ["SNYK-EXAMPLE-1", "CVE-2099-0001"],
+ packages: [
+ {
+ name: "@example/package",
+ ecosystem: "npm",
+ installed_version: "1.0.0",
+ fixed_versions: ["1.0.1"],
+ manifest_path: null,
+ },
+ ],
+ locations: [],
+ code_revision: "synthetic-revision",
+ source_updated_at: null,
+ source_data: {
+ format: input.format,
+ collection: input.collection,
+ finding: input.findings[0],
+ },
+ });
+ expect(input).toEqual(before);
+});
+
+test("plugin finding identity ignores scan timestamps and preserves separate occurrences", () => {
+ const input = snykPluginExport();
+ const first = normalizeSnykFindingsExport(input).findings[0]!;
+ input.collection.finishedAt = "2026-01-02T00:01:00Z";
+ input.findings[0]!.severity.value = "Critical";
+ const updated = normalizeSnykFindingsExport(input).findings[0]!;
+ expect(updated.source_finding_id).toBe(first.source_finding_id);
+ expect(updated.evidence.severity).toBe("critical");
+ input.findings.push(structuredClone(input.findings[0]!));
+ input.findings[1]!.id.value += "|different-occurrence";
+ const distinct = normalizeSnykFindingsExport(input);
+ expect(distinct.findings).toHaveLength(2);
+ expect(
+ new Set(distinct.findings.map((item) => item.source_finding_id)).size,
+ ).toBe(2);
+ input.findings[1]!.id.value = input.findings[0]!.id.value;
+ const duplicate = normalizeSnykFindingsExport(input);
+ expect(duplicate.findings).toEqual([]);
+ expect(duplicate.excluded).toHaveLength(2);
+});
+
+test("mixed plugin bundles explicitly exclude other products and licenses", () => {
+ const input = snykPluginExport();
+ for (const [scanner, category, scan] of [
+ ["snyk-code", "code_weakness", "code"],
+ ["snyk-open-source", "license", "sca"],
+ ["snyk-open-source", "dependency_vulnerability", "sbom"],
+ ]) {
+ const unsupported = structuredClone(input.findings[0]!);
+ unsupported.id.value = `${scanner}/${category}/${scan}`;
+ unsupported.originatingScanner = scanner!;
+ unsupported.category = category!;
+ unsupported.observation.scan = scan!;
+ input.findings.push(unsupported);
+ }
+ const result = normalizeSnykFindingsExport(input);
+ expect(result.findings).toHaveLength(1);
+ expect(result.excluded.map((item) => item.position)).toEqual([2, 3, 4]);
+ expect(
+ result.excluded.every((item) =>
+ item.reason.includes("Only Snyk Open Source SCA"),
+ ),
+ ).toBe(true);
+});
+
+test("plugin imports keep dirty workspace context without asserting an exact revision", () => {
+ const input = snykPluginExport();
+ input.collection.target.workingTreeDirty = true;
+ input.collection.target.changedPaths = ["package.json"];
+ const evidence = normalizeSnykFindingsExport(input).findings[0]!.evidence;
+ expect(evidence.code_revision).toBeNull();
+ expect(evidence.source_data).toMatchObject({
+ collection: { target: input.collection.target },
+ });
+});
+
+test("plugin imports retain unknown severity and unsafe paths only as original evidence", () => {
+ const input = snykPluginExport();
+ input.findings[0]!.severity.value = "urgent";
+ input.findings[0]!.asset.manifest = "../package.json";
+ const evidence = normalizeSnykFindingsExport(input).findings[0]!.evidence;
+ expect(evidence.severity).toBe("unknown");
+ expect(evidence.locations).toEqual([]);
+ expect(evidence.packages![0]!.manifest_path).toBeNull();
+ expect(evidence.source_data).toMatchObject({ finding: input.findings[0] });
+});
+
+test("saved official plugin bundles are detected through the existing Snyk reader", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "snyk-plugin-import-"));
+ try {
+ const input = snykPluginExport();
+ const path = join(dir, "findings.json.gz");
+ await writeFile(path, gzipSync(JSON.stringify(input)));
+ expect(await readSnykFindings(path)).toEqual(
+ normalizeSnykFindingsExport(input),
+ );
+ expect(() =>
+ normalizeSnykFindingsExport({ ...input, provider: "other" }),
+ ).toThrow("from Snyk");
+ expect(() =>
+ normalizeSnykFindingsExport({
+ ...input,
+ format: "snyk-findings-export/v2",
+ }),
+ ).toThrow("v1");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("nested plugin scan targets do not become root-relative repository paths", () => {
+ const input = snykPluginExport();
+ input.collection.target.path = "/work/example/services/api";
+ input.findings[0]!.nativeRecord.filePath =
+ "/work/example/services/api/package.json";
+ const evidence = normalizeSnykFindingsExport(input).findings[0]!.evidence;
+ expect(evidence.locations).toEqual([]);
+ expect(evidence.packages![0]!.manifest_path).toBeNull();
+ expect(evidence.source_data).toMatchObject({
+ collection: { target: input.collection.target },
+ finding: {
+ asset: { manifest: "package.json" },
+ nativeRecord: input.findings[0]!.nativeRecord,
+ },
+ });
+});
+
+test("native Snyk JSON retains advisory, dependency path, remediation and project context", () => {
+ const input = snykJson();
+ input.path = "/work/example/services/api";
+ const original = structuredClone(input);
+ const result = normalizeSnykJson(input);
+ expect(result.excluded).toEqual([]);
+ expect(result.read).toBe(1);
+ const { vulnerabilities, ...project } = input;
+ expect(result.findings[0]!.evidence).toMatchObject({
+ title: "Synthetic vulnerability",
+ description: "Complete native advisory description",
+ severity: "high",
+ advisory_ids: ["SNYK-EXAMPLE-1", "CVE-2099-0001"],
+ packages: [
+ {
+ name: "@example/package",
+ ecosystem: "npm",
+ installed_version: "1.0.0",
+ fixed_versions: ["1.0.1"],
+ manifest_path: null,
+ },
+ ],
+ locations: [],
+ code_revision: null,
+ source_data: { project, vulnerability: vulnerabilities[0] },
+ });
+ expect(input).toEqual(original);
+});
+
+test("native identities preserve dependency occurrences and projects across report ordering and machine paths", () => {
+ const first = snykJson();
+ const originalId = normalizeSnykJson(first).findings[0]!.source_finding_id;
+ first.path = "/another/checkout";
+ first.summary = "Updated summary";
+ first.vulnerabilities[0]!.description = "Updated advisory";
+ first.vulnerabilities.push(structuredClone(first.vulnerabilities[0]!));
+ first.vulnerabilities[1]!.from.splice(1, 0, "[email protected]");
+ const second = structuredClone(first);
+ second.displayTargetFile = "services/worker/package.json";
+ const result = normalizeSnykJson([first, second]);
+ expect(result.excluded).toEqual([]);
+ expect(
+ new Set(result.findings.map((finding) => finding.source_finding_id)).size,
+ ).toBe(4);
+ expect(result.findings[0]!.source_finding_id).toBe(originalId);
+ const reordered = normalizeSnykJson([second, first]);
+ expect(
+ reordered.findings.map((finding) => finding.source_finding_id).sort(),
+ ).toEqual(result.findings.map((finding) => finding.source_finding_id).sort());
+ const duplicate = normalizeSnykJson([first, first]);
+ expect(duplicate.findings).toEqual([]);
+ expect(duplicate.excluded).toHaveLength(4);
+});
+
+test("native SCA JSON excludes license records and preserves the clean empty-result distinction", () => {
+ const license = {
+ ...snykJson().vulnerabilities[0]!,
+ id: "snyk:lic:npm:example:license",
+ type: "license",
+ };
+ const mixed = snykJson();
+ mixed.vulnerabilities.push(license);
+ const result = normalizeSnykJson(mixed);
+ expect(result.findings).toHaveLength(1);
+ expect(result.excluded).toHaveLength(1);
+ expect(result.excluded[0]!.reason).toContain(
+ "license findings are unsupported",
+ );
+ const licenseOnly = normalizeSnykJson({
+ ...mixed,
+ vulnerabilities: [license],
+ });
+ expect(licenseOnly.read).toBe(1);
+ expect(licenseOnly.findings).toEqual([]);
+ expect(licenseOnly.excluded).toHaveLength(1);
+ expect(
+ normalizeSnykJson({ ...snykJson(), ok: true, vulnerabilities: [] }),
+ ).toEqual({ read: 0, findings: [], excluded: [] });
+});
+
+test("native project errors stop import, including partial all-projects output", () => {
+ const failed = {
+ ok: false,
+ error: "Synthetic dependency resolution failed",
+ path: "/work/example/worker",
+ };
+ for (const input of [failed, [snykJson(), failed]]) {
+ expect(() => normalizeSnykJson(input)).toThrow(
+ "Synthetic dependency resolution failed",
+ );
+ }
+ for (const input of [
+ { ...snykJson(), docker: { baseImage: "example-image" } },
+ { ...snykJson(), docker: {} },
+ { ...snykJson(), applications: [] },
+ { infrastructureAsCodeIssues: [], ok: true },
+ { version: "2.1.0", runs: [] },
+ { data: [] },
+ ]) {
+ expect(() => normalizeSnykJson(input)).toThrow();
+ }
+});
+
+test("native grouped JSON cannot silently collapse package occurrences", () => {
+ const input = snykJson();
+ const grouped = {
+ ...input,
+ vulnerabilities: input.vulnerabilities.map((item) => ({
+ ...item,
+ from: [item.from],
+ name: [item.name],
+ })),
+ };
+ expect(normalizeSnykJson(grouped).findings).toEqual([]);
+ expect(normalizeSnykJson(grouped).excluded).toHaveLength(1);
+});
+
+test("native JSON object and array exports are read through the existing Snyk provider", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "snyk-native-import-"));
+ try {
+ const path = join(dir, "findings.json.gz");
+ for (const input of [snykJson(), [snykJson()]]) {
+ await writeFile(path, gzipSync("\uFEFF" + JSON.stringify(input)));
+ expect(await readSnykFindings(path)).toEqual(normalizeSnykJson(input));
+ }
+ const ids = [
+ normalizeSnykJson(snykJson()),
+ normalizeSnykFindingsExport(snykPluginExport()),
+ normalizeSnykSarif(snykSarif()),
+ ].map((result) => result.findings[0]!.source_finding_id);
+ expect(new Set(ids).size).toBe(3);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+function selfContainedSnykSarif() {
+ const input: any = snykSarif();
+ const run = input.runs[0];
+ run.tool.driver.rules[0].help.text = run.tool.driver.rules[0].help.markdown;
+ delete run.results[0].fixes;
+ return input;
+}
+
+test("unrelated SARIF artifact inventories do not change direct-location findings", () => {
+ const input = selfContainedSnykSarif();
+ const expected = normalizeSnykSarif(input);
+ input.runs[0].artifacts = Array.from({ length: 5000 }, (_, index) => ({
+ location: { uri: `unrelated/project-${index}/package.json` },
+ }));
+ expect(
+ Buffer.byteLength(JSON.stringify(input.runs[0].artifacts)),
+ ).toBeGreaterThan(256 * 1024);
+ const original = structuredClone(input);
+ expect(normalizeSnykSarif(input)).toEqual(expected);
+ expect(input).toEqual(original);
+});
+
+test.each([{}, { artifacts: [], results: [] }])(
+ "self-contained SARIF permits empty external references %j",
+ (externalPropertyFileReferences) => {
+ const input = selfContainedSnykSarif();
+ input.runs[0].externalPropertyFileReferences =
+ externalPropertyFileReferences;
+ const original = structuredClone(input);
+ const output = normalizeSnykSarif(input);
+ expect(output.excluded).toEqual([]);
+ expect(output.findings).toHaveLength(1);
+ expect(output.findings[0]!.evidence.source_data).toMatchObject({
+ run: { externalPropertyFileReferences },
+ result: input.runs[0].results[0],
+ });
+ expect(input).toEqual(original);
+ },
+);
+
+test.each(["code flow", "fix", "invocation"] as const)(
+ "SARIF artifact indexes in retained %s evidence keep their original inventory",
+ (context) => {
+ const input = selfContainedSnykSarif();
+ const run = input.runs[0];
+ const result = run.results[0];
+ run.artifacts = [
+ { location: { uri: "parent" } },
+ { location: { uri: "referenced/package.json" }, parentIndex: 0 },
+ ];
+ if (context === "code flow") {
+ result.codeFlows = [
+ {
+ threadFlows: [
+ {
+ locations: [
+ {
+ location: {
+ physicalLocation: {
+ artifactLocation: { index: 1 },
+ region: { startLine: 1 },
+ },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ];
+ } else if (context === "fix") {
+ result.fixes = [
+ {
+ description: { text: "Synthetic dependency update" },
+ artifactChanges: [
+ {
+ artifactLocation: { index: 1 },
+ replacements: [
+ {
+ deletedRegion: { startLine: 1 },
+ insertedContent: { text: "synthetic update" },
+ },
+ ],
+ },
+ ],
+ },
+ ];
+ } else {
+ run.invocations = [
+ { executionSuccessful: true, executableLocation: { index: 1 } },
+ ];
+ }
+ const original = structuredClone(input);
+ const output = normalizeSnykSarif(input);
+ expect(output.excluded).toEqual([]);
+ expect(output.findings).toHaveLength(1);
+ expect(output.findings[0]!.evidence.source_data).toMatchObject({
+ run: {
+ artifacts: run.artifacts,
+ ...(run.invocations ? { invocations: run.invocations } : {}),
+ },
+ result,
+ rule: run.tool.driver.rules[0],
+ });
+ expect(input).toEqual(original);
+ },
+);
+
+test("direct SARIF manifest locations retain matching artifact metadata", () => {
+ const input = selfContainedSnykSarif();
+ const artifact = {
+ location: { uri: "package.json" },
+ contents: { text: '{"name":"synthetic-project"}' },
+ };
+ input.runs[0].artifacts = [artifact];
+ const original = structuredClone(input);
+ const output = normalizeSnykSarif(input);
+ expect(output.excluded).toEqual([]);
+ expect(output.findings[0]!.evidence.source_data).toMatchObject({
+ run: { artifacts: [artifact] },
+ result: input.runs[0].results[0],
+ });
+ expect(input).toEqual(original);
+});
+
+const snykRepositoryContexts: [string, string][] = [
+ [
+ "[email protected]:example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://git.example.test/example/project",
+ ],
+ [
+ "[email protected]:example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+ [
+ "ssh://[email protected]:22/example/project.git",
+ "https://tenant.ghe.com/example/project",
+ ],
+];
+
+test.each(["\t", "\r", "\n"])(
+ "SSH repository claims retain literal hostname and path bytes: %j",
+ (control) => {
+ const repository = `ssh://git@github.${control}com/example/pro${control}ject.git`;
+ const input = snykPluginExport();
+ input.collection.target.repository = repository;
+ const source =
+ normalizeSnykFindingsExport(input).findings[0]!.evidence.source_data;
+ expect(
+ snykRepositoryUrls(source, {
+ cloudRepositoryUrl: "https://github.com/example/project",
+ }),
+ ).toEqual([repository]);
+ expect(snykRepositoryUrls(source)).toEqual([repository]);
+ expect(snykRepositoryUrls(source, { normalizeGitRemote: false })).toEqual([
+ repository,
+ ]);
+ expect(source).toMatchObject({ collection: input.collection });
+ },
+);
+
+test.each(snykRepositoryContexts)(
+ "Plugin repository claims stay raw without Cloud context or when normalization is disabled: %s",
+ (repository, cloudRepositoryUrl) => {
+ const input = snykPluginExport();
+ input.collection.target.repository = repository;
+ const source =
+ normalizeSnykFindingsExport(input).findings[0]!.evidence.source_data;
+ expect(snykRepositoryUrls(source)).toEqual([repository]);
+ expect(
+ snykRepositoryUrls(source, {
+ normalizeGitRemote: false,
+ cloudRepositoryUrl,
+ }),
+ ).toEqual([repository]);
+ expect(source).toMatchObject({ collection: input.collection });
+ },
+);
+
+test.each(snykRepositoryContexts)(
+ "SARIF repository claims stay raw without Cloud context or when normalization is disabled: %s",
+ (repository, cloudRepositoryUrl) => {
+ const sarif = snykSarif();
+ const provenance = [{ repositoryUri: repository }];
+ const input = {
+ ...sarif,
+ runs: sarif.runs.map((run) => ({
+ ...run,
+ versionControlProvenance: provenance,
+ })),
+ };
+ const source = normalizeSnykSarif(input).findings[0]!.evidence.source_data;
+ expect(snykRepositoryUrls(source)).toEqual([repository]);
+ expect(
+ snykRepositoryUrls(source, {
+ normalizeGitRemote: false,
+ cloudRepositoryUrl,
+ }),
+ ).toEqual([repository]);
+ expect(source).toMatchObject({
+ run: { versionControlProvenance: provenance },
+ });
+ },
+);
diff --git a/sdk/typescript/tests-ts/support/snyk-import-fixtures.ts b/sdk/typescript/tests-ts/support/snyk-import-fixtures.ts
new file mode 100644
index 000000000..a5555fca3
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/snyk-import-fixtures.ts
@@ -0,0 +1,188 @@
+// Synthetic field shapes from Snyk CLI's Open Source SARIF formatter.
+export function snykSarif() {
+ return {
+ version: "2.1.0",
+ runs: [
+ {
+ automationDetails: { id: "Snyk/Open Source/example/0/export-time" },
+ tool: {
+ driver: {
+ name: "Snyk Open Source",
+ semanticVersion: "1.0.0",
+ rules: [
+ {
+ id: "SNYK-EXAMPLE-1",
+ shortDescription: {
+ text: "Critical severity - synthetic vulnerability in @example/package",
+ },
+ fullDescription: {
+ text: "(CVE-2099-0001) @example/[email protected]",
+ },
+ help: {
+ markdown:
+ "* Package Manager: npm\n* Vulnerable module: @example/package\n* Introduced through: example\n#### Detailed paths\n* _Introduced through_: example › @example/[email protected]\nSynthetic evidence",
+ },
+ properties: {
+ tags: ["security", "npm"],
+ "security-severity": "9.8",
+ unknown_numeric: 40000,
+ },
+ },
+ ],
+ },
+ },
+ results: [
+ {
+ ruleId: "SNYK-EXAMPLE-1",
+ level: "error",
+ message: { text: "Synthetic dependency vulnerability" },
+ locations: [
+ {
+ physicalLocation: {
+ artifactLocation: { uri: "package.json" },
+ region: { startLine: 1 },
+ },
+ logicalLocations: [
+ { fullyQualifiedName: "@example/[email protected]" },
+ ],
+ },
+ ],
+ fixes: [
+ { description: { text: "Upgrade the introducing dependency" } },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+}
+
+// Synthetic example of the official snyk-findings-export/v1 bundle contract.
+export function snykPluginExport() {
+ return {
+ format: "snyk-findings-export/v1",
+ provider: "snyk",
+ collection: {
+ collector: { skill: "snyk-findings-export", pluginVersion: "0.1.0" },
+ scanner: { name: "snyk-cli", version: "1.0.0", via: "snyk mcp -t stdio" },
+ startedAt: "2026-01-01T00:00:00Z",
+ finishedAt: "2026-01-01T00:01:00Z",
+ target: {
+ path: "/work/example",
+ repository: "https://github.com/example/project.git",
+ revision: "synthetic-revision",
+ workingTreeDirty: false,
+ changedPaths: [] as string[],
+ },
+ org: {
+ state: "unknown",
+ reason: "snyk_sca_scan does not report the org",
+ },
+ scans: [
+ {
+ category: "sca",
+ tool: "snyk_sca_scan",
+ outcome: "succeeded",
+ issueCount: 1,
+ },
+ ],
+ completeness: { collection: "complete", analysis: "SCA succeeded" },
+ limitations: [
+ "Local workspace scan; not a Snyk platform project export.",
+ ],
+ },
+ findings: [
+ {
+ id: {
+ value:
+ "sca:SNYK-EXAMPLE-1|npm:@example/[email protected]|package.json|[email protected] > @example/[email protected]",
+ kind: "composite",
+ basis: "sca composite",
+ scope: "collection.target.repository",
+ },
+ category: "dependency_vulnerability",
+ originatingScanner: "snyk-open-source",
+ title: "Synthetic vulnerability",
+ description: { text: "Partial scanner description" },
+ rule: {
+ id: "SNYK-EXAMPLE-1",
+ aliases: { cve: ["CVE-2099-0001"], cwe: ["CWE-79"] },
+ },
+ severity: {
+ value: "high",
+ scale: "low | medium | high | critical",
+ authority: "snyk",
+ },
+ status: {
+ value: "ignored",
+ meaning: "Suppressed by policy",
+ authority: "snyk-cli",
+ },
+ asset: {
+ type: "package_occurrence",
+ package: {
+ ecosystem: "npm",
+ name: "@example/package",
+ version: "1.0.0",
+ },
+ manifest: "package.json",
+ transitive: true,
+ },
+ remediation: {
+ fixedIn: ["1.0.1"],
+ advice: "Upgrade the direct dependency",
+ },
+ evidence: {
+ introducedThrough: ["[email protected]", "@example/[email protected]"],
+ },
+ observation: { scan: "sca", observedAt: "2026-01-01T00:01:00Z" },
+ unavailable: {
+ description: {
+ state: "truncated",
+ reason: "snyk_sca_scan truncates messages",
+ },
+ },
+ nativeRecord: {
+ id: "SNYK-EXAMPLE-1",
+ packageName: "@example/package",
+ version: "1.0.0",
+ filePath: "/work/example/package.json",
+ isIgnored: true,
+ unknownField: "retained",
+ },
+ },
+ ],
+ };
+}
+
+// Synthetic fields from Snyk CLI's TestResult/AnnotatedIssue native JSON output.
+export function snykJson() {
+ return {
+ ok: false,
+ vulnerabilities: [
+ {
+ id: "SNYK-EXAMPLE-1",
+ title: "Synthetic vulnerability",
+ description: "Complete native advisory description",
+ severity: "high",
+ name: "@example/package",
+ packageName: "@example/package",
+ version: "1.0.0",
+ identifiers: { CVE: ["CVE-2099-0001"], CWE: ["CWE-79"] },
+ from: ["[email protected]", "@example/[email protected]"],
+ upgradePath: [false, "@example/[email protected]"],
+ fixedIn: ["1.0.1"],
+ isUpgradable: true,
+ isPatchable: false,
+ },
+ ],
+ dependencyCount: 1,
+ packageManager: "npm",
+ targetFile: "package.json",
+ displayTargetFile: "package.json",
+ projectName: "example",
+ path: "/work/example",
+ policy: "synthetic policy context",
+ summary: "1 vulnerability",
+ };
+}