OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(endor): import findings (#1689)
Michael D'Angelo8f18784d94ef
diff --git a/docs/scanner-imports/endor.md b/docs/scanner-imports/endor.mdnew file mode 100644index 000000000..233efb7cb--- /dev/null+++ b/docs/scanner-imports/endor.md@@ -0,0 +1,81 @@+# Import Endor Labs findings++Use authenticated `endorctl` to export complete native Finding JSON through the+[official CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api).+Scope the export to one project and context, omit `--field-mask`, and use+`--list-all` to fetch every page. Replace the namespace and project UUID below+to select the project's default-branch findings:++```sh+endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \+ --filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \+ --list-all --output-type json > endor-findings.json++codex-security publish findings endor-findings.json --to local \+ --provider endor --repository ./project \+ --source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run+```++Use `--to local` with a local repository path to store unassessed source evidence+without a Cloud login or model call. After reviewing the preview, remove+`--dry-run` to confirm the import. Read the stored records with+`codex-security findings imported ./project --format json`.++To publish the same export to Cloud, select its connected repository instead:++```sh+codex-security publish findings endor-findings.json --to cloud \+ --provider endor --repository "CLOUD_REPOSITORY_ID" \+ --source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run+```++Confirm that the selected Endor project and context correspond to the destination+repository. Native JSON retains the project UUID, but the importer does not look+it up to verify that association. For another branch or scan context, change the+Endor filter and use a distinct, stable source key. An unfinished paginated+response is rejected by the importer. Remove `--dry-run` to review and confirm+the upload.++The official [Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit)+can help with setup and interactive investigation. Its Findings Browser summaries,+counts and field-masked results do not replace the complete Finding objects used+here. `endorctl` reads the Endor API; the Codex Security importer reads the saved+export. It does not establish a persistent API connection or write changes back+to Endor.++Native JSON is the preferred import format: it preserves Endor severity,+dependency and advisory details, the scanned commit SHA, primary SAST/AI SAST+locations, and the complete original Finding. The importer accepts a single+Finding, an array, or a `ListFindingsResponse` containing `list.objects`. Mapping+follows Endor's public [Finding model](https://github.com/endorlabs/endorlabs-sdk/blob/8a41756890c2dee3bb089fee881cae4f2adbde03/src/endorlabs/generated/models/finding_service.py).++Existing self-contained `endorctl` SARIF 2.1.0 reports are accepted as a lossy+compatibility format. The importer retains finding UUIDs and links but does not+infer native Endor severity or scanned revisions from SARIF. Diagnostic levels+and CVSS stay in the original evidence;+displayed severity remains unknown. Direct repository paths and reported SAST or+Secrets lines are mapped. Indexed or base-relative artifact references remain in+the original evidence. Run artifact inventories that are unrelated to the selected+finding are omitted from its evidence. Declared SARIF repository URLs must+match the selected Cloud repository for a new upload. For local imports, those+URLs must match a configured Git remote when the checkout has remotes.++Both formats use the native finding UUID as identity within the selected+repository and source key. Keep the source key stable across repeated imports.+Importing the same UUID from SARIF after native JSON updates the same source+record: it replaces the evidence snapshot rather than merging it. Severity can+become unknown, and commit, package, advisory and other native detail absent from+SARIF is no longer present in that snapshot. Importing native JSON again replaces+it with the richer native evidence. Use native JSON consistently for ongoing+imports.++Recommended upgrades, reachability, dismissals and other Endor assessments remain+source claims. Local records remain unassessed and separate from completed scans;+imports do not automatically investigate or patch them. Records omitted from a+later local import remain stored. Saved Cloud requests retain their destination+repository ID when resumed.++The adapter can be tested with synthetic records and the public SARIF sample.+Verifying acquisition requires an authenticated Endor namespace with findings.+Verifying Cloud publication also requires a Cloud environment that supports+finding imports.diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex 6a89b36fa..f92a00fcb 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 Snyk Open Source findings, Semgrep Code CLI/CI reports, 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, Snyk Open Source and Semgrep Code 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.+description: Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs 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, Snyk Open Source and Semgrep Code SARIF, endorctl 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@@ -29,6 +29,23 @@ Show the repository, source namespace, normalized evidence, and exclusions. AfteLocal records remain unassessed source evidence, separate from `findings list` and completed scans. Retain unknown metadata without inventing scanner revisions, assessment fields, or patch results. Report the created, updated, unchanged, and excluded counts. Repeated imports use the same repository/provider/source-key/source-ID identity; omitted records remain stored. When a source repository URL and local Git remotes are available, the source URL must match one of those remotes. Local import does not publish to Cloud or automatically investigate or patch findings.+## Endor Labs findings++For Endor Labs imports, prefer native Finding JSON from authenticated `endorctl`, scoped to one project and context. Omit `--field-mask` and fetch all pages with `--list-all`:++```sh+endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \+ --filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \+ --list-all --output-type json > endor-findings.json+codex-security publish findings endor-findings.json --to local \+ --provider endor --repository /path/to/project \+ --source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run --format json+```++Choose a project that corresponds to the selected local checkout or Cloud repository. To publish the same export to Cloud, use `--to cloud --repository "CLOUD_REPOSITORY_ID"`. For a different branch or scan context, change the Endor filter and keep a distinct, stable source key. The [official Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit) can help with setup and investigation; its summaries, counts and field-masked results do not replace complete Finding objects. The [CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api) supplies the export. The importer reads that saved file; it does not maintain an Endor API connection or write changes back to Endor.++Native JSON retains severity, scanned commit, package and advisory data, and primary SAST/AI SAST locations. Existing self-contained endorctl SARIF is a lossy compatibility format that retains finding UUIDs and links; unavailable severity or revisions stay unknown. Both formats use the Endor UUID within the selected repository and source key as identity. Importing SARIF after native JSON updates the same record by replacing its evidence snapshot, not merging it: native detail absent from SARIF is removed from that snapshot. Use native JSON consistently for ongoing imports. Keep the original evidence and inspect exclusions. Imported records remain unassessed source evidence. For local imports, use the preview and readback procedure above; for Cloud, use the publication procedure below.+## Wiz findingsUse an authorized [Wiz MCP](https://www.wiz.io/blog/introducing-wiz-mcp) or Wiz API connection to acquire selected findings and save the supported native JSON with its original occurrence IDs and evidence. A configured plugin may provide that connection; do not assume an official Codex plugin is available. Inspect the returned fields: a summary, Wiz Issue, or local Wiz CLI scan result is not automatically a supported finding record. Do not invent fields to make a response fit the mapper.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex a88a739ee..4b8e1a6c1 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -684,6 +684,10 @@ Open Source SARIF. Prefer JSON, and keep one format and stable source key per sctarget; switching formats creates separate source identities. See[local imports](docs/cli.md#import-vendor-findings-locally).+Use `--provider endor` with native Endor Finding JSON; existing endorctl SARIF is+accepted as a lossy compatibility format. See+[Endor imports](docs/cli.md#import-endor-labs-findings).+The SDK's `prepareLocalExternalImport(file, options)` returns a `preview` and aseparate `import()` operation. `prepareNormalizedLocalImport(findings,options)` accepts already normalized evidence, anddiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex d03068835..6ae9ccf98 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1250,6 +1250,45 @@ supported vendor formats and evidence requirements apply locally and in Cloud.Codex Security's findings schema as a saved scan; they do not accept vendorexports.+## Import Endor Labs findings++For local or Cloud import, prefer complete native Finding JSON from authenticated+`endorctl`, scoped to one project and context. Omit `--field-mask` and use+`--list-all` to finish pagination:++```sh+endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \+ --filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \+ --list-all --output-type json > endor-findings.json+codex-security publish findings endor-findings.json --to local \+ --provider endor --repository ./project \+ --source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run+```++Replace the example namespace, project UUID and local repository with your selection.+Review the preview, remove `--dry-run` to confirm, then read the stored evidence+with `codex-security findings imported ./project --format json`. To publish to+Cloud instead, use `--to cloud --repository "CLOUD_REPOSITORY_ID"` with the same+file, provider and source key. The official+[Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit)+can help with setup and investigation, but summaries, counts and field-masked+results do not replace complete Finding objects. `endorctl` reads the Endor API;+the importer reads the saved export without maintaining an API connection or+writing changes back to Endor.++Native JSON retains severity, package and advisory data, primary SAST/AI SAST+locations and the scanned commit. Existing self-contained endorctl SARIF 2.1.0+reports are a lossy compatibility format, retaining finding links and UUIDs;+unavailable severity and revisions stay unknown. Both formats use the Endor UUID+within the selected repository and stable source key as identity. Importing SARIF+after native JSON for that UUID updates the same record by replacing its evidence+snapshot, not merging it. Native detail absent from SARIF is removed from the+snapshot. Use native JSON consistently for ongoing imports.++Local and Cloud records remain unassessed source evidence. Local imports use the+SQLite readback described above; Cloud imports use the login, preview,+confirmation and retry flow below.+## Publish findings to Cloud### Import Snyk Open Source findingsdiff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex 93f335eda..752f452a1 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -33,6 +33,7 @@ const distModules = ["external-findings-publish","external-import-contract","external-import-models",+ "endor-findings","wiz-csv","wiz-findings","codex-prompt",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 7334ba6e3..4026200ae 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, Snyk, or Semgrep Code 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 Semgrep Code, supply native JSON or SARIF and --source-repository-url. 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",+ "Preview and import selected Wiz, Snyk, Semgrep Code, or Endor 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 Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. 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(- "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",+ "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl 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- .enum(["wiz", "snyk", "semgrep"])+ .enum(["wiz", "snyk", "semgrep", "endor"]).describe("Vendor that produced these findings."),sourceRepositoryUrl: optionValue("--source-repository-url").optional()diff --git a/sdk/typescript/src/endor-findings.ts b/sdk/typescript/src/endor-findings.tsnew file mode 100644index 000000000..9568566be--- /dev/null+++ b/sdk/typescript/src/endor-findings.ts@@ -0,0 +1,351 @@+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,+ relativePath,+ requiredText,+ sarifRunContextForResult,+ strings,+ text,+} from "./scanner-import.js";++/** @internal Repository claims retained in the adapter's original SARIF context. */+export function endorRepositoryUrls(sourceData: unknown): string[] {+ if (!isRecord(sourceData)) return [];+ const run = sourceData["runContext"];+ if (run == null) return [];+ return array(+ record(run, "Endor run context")["versionControlProvenance"] ?? [],+ "Endor version control provenance",+ ).map((entry) =>+ requiredText(+ record(entry, "Endor repository provenance")["repositoryUri"],+ "Endor repository URI",+ ),+ );+}++/** Saved Endor Finding objects, an array, or an unmasked ListFindingsResponse. */+export function normalizeEndorFindings(input: unknown): ExternalFindings {+ const root = Array.isArray(input) ? null : record(input, "Endor report");+ if (root?.["version"] === "2.1.0" && root["runs"] !== undefined)+ return normalizeEndorSarif(root);+ const list =+ root?.["list"] === undefined ? null : record(root["list"], "Endor list");+ if (list) {+ const response = record(list["response"] ?? {}, "Endor list response");+ const token = response["next_page_token"];+ if (+ text(response["next_page_id"]) ||+ (token != null && token !== 0 && token !== "0" && token !== "")+ ) {+ throw new Error(+ "The Endor list response has another page. Supply a complete export or an explicitly selected array.",+ );+ }+ }+ const values = list+ ? array(list["objects"] ?? [], "Endor list.objects")+ : Array.isArray(input)+ ? input+ : [input];+ return normalizeRecords(+ values,+ (value, id) => {+ const finding = record(value, "Endor finding");+ const meta = record(finding["meta"], "Endor meta");+ const spec = record(finding["spec"], "Endor spec");+ requiredText(spec["project_uuid"], "Endor project_uuid");+ const name = text(spec["target_dependency_name"]);+ const paths = [+ ...new Set(+ strings(spec["dependency_file_paths"])+ .map(relativePath)+ .filter((p): p is string => p !== null),+ ),+ ];+ const metadata = record(+ spec["finding_metadata"] ?? {},+ "Endor finding_metadata",+ );+ const codeLocations = ["sast_data", "ai_sast_data"].flatMap((field) => {+ const data = record(metadata[field] ?? {}, `Endor ${field}`);+ const location = record(+ data["location"] ?? {},+ `Endor ${field} location`,+ );+ const path = relativePath(location["relative_path"]);+ if (path === null) return [];+ const line = location["start_line"];+ return [+ {+ path,+ line:+ typeof line === "number" && Number.isSafeInteger(line) && line > 0+ ? line+ : null,+ },+ ];+ });+ const locations = [+ ...paths+ .filter(+ (path) => !codeLocations.some((location) => location.path === path),+ )+ .map((path) => ({ path })),+ ...new Map(+ codeLocations.map((location) => [JSON.stringify(location), location]),+ ).values(),+ ];+ const vulnerability = record(+ metadata["vulnerability"] ?? {},+ "Endor vulnerability",+ );+ const advisory = text(+ record(vulnerability["meta"] ?? {}, "Vulnerability meta")["name"],+ );+ const aliases = strings(+ record(vulnerability["spec"] ?? {}, "Vulnerability spec")["aliases"],+ );+ const level = text(spec["level"])+ ?.replace(/^FINDING_LEVEL_/u, "")+ .toLowerCase();+ const severity =+ level && ["critical", "high", "medium", "low"].includes(level)+ ? level+ : "unknown";+ // A recommended version can refer to an introducing dependency; retain it in source_data.+ const packages = name+ ? (paths.length ? paths : [null]).map((path) => ({+ name,+ ecosystem:+ text(spec["ecosystem"])+ ?.replace(/^ECOSYSTEM_/u, "")+ .toLowerCase() ?? null,+ installed_version: text(spec["target_dependency_version"]),+ manifest_path: path,+ fixed_versions: [],+ }))+ : [];+ const context = record(finding["context"] ?? {}, "Endor context");+ const updated = text(meta["update_time"]);+ return {+ source_finding_id: id,+ evidence: validateExternalEvidence({+ title: requiredText(meta["name"], "Endor finding title"),+ description:+ [+ text(spec["summary"]),+ text(spec["explanation"]),+ text(spec["remediation"]),+ ]+ .filter(Boolean)+ .join("\n\n") || text(meta["description"]),+ severity,+ branch:+ context["type"] === "CONTEXT_TYPE_REF" ? text(context["id"]) : null,+ code_revision: text(+ record(+ spec["source_code_version"] ?? {},+ "Endor source code version",+ )["sha"],+ ),+ source_updated_at:+ updated === null ? null : Math.floor(Date.parse(updated) / 1000),+ advisory_ids: [+ ...new Set([...(advisory ? [advisory] : []), ...aliases]),+ ],+ packages,+ locations,+ source_data: structuredClone(finding),+ }),+ };+ },+ (value) =>+ requiredText(+ record(value, "Endor finding")["uuid"],+ "Endor finding uuid",+ ),+ );+}++/** Endor's documented SARIF producer uses properties.finding-uuid, not its rule name. */+export function normalizeEndorSarif(input: unknown): ExternalFindings {+ const document = record(input, "Endor SARIF");+ if (document["version"] !== "2.1.0")+ throw new Error("Expected Endor SARIF 2.1.0.");+ const entries = array(document["runs"], "SARIF runs").flatMap((value) => {+ const run = record(value, "SARIF run");+ const tool = record(run["tool"], "SARIF tool");+ const driver = record(tool["driver"], "SARIF driver");+ if (driver["name"] !== "endorctl")+ throw new Error("Expected the endorctl SARIF producer.");+ if (+ hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])+ )+ throw new Error("Use a self-contained Endor SARIF report.");+ const rules = array(driver["rules"] ?? [], "Endor rules").map((r) =>+ record(r, "Endor rule"),+ );+ const rulesById = new Map<+ unknown,+ { rule: Record<string, unknown>; index: number } | null+ >();+ for (const [index, rule] of rules.entries()) {+ const id = rule["id"];+ rulesById.set(id, rulesById.has(id) ? null : { rule, index });+ }+ const { runs: _runs, ...documentContext } = document;+ const { results: _results, tool: _tool, ...runContext } = run;+ const { rules: _rules, ...driverContext } = driver;+ const { driver: _driver, ...toolContext } = tool;+ return array(run["results"] ?? [], "Endor results").map((result) => ({+ result,+ rulesById,+ documentContext,+ runContext,+ driverContext,+ toolContext,+ }));+ });+ return normalizeRecords(+ entries,+ ({ result: value, rulesById, ...context }, id) => {+ const result = record(value, "Endor result");+ const properties = record(+ result["properties"],+ "Endor result properties",+ );+ requiredText(properties["project-uuid"], "Endor project-uuid");+ const ruleId = requiredText(result["ruleId"], "Endor ruleId");+ const selectedRule = rulesById.get(ruleId);+ if (!selectedRule)+ throw new Error(+ "Endor result must reference exactly one rule in its run.",+ );+ const { rule, index: ruleIndex } = selectedRule;+ if (+ result["ruleIndex"] !== undefined &&+ result["ruleIndex"] !== ruleIndex+ )+ throw new Error("Endor ruleIndex and ruleId disagree.");+ if (result["rule"] !== undefined) {+ const reference = record(result["rule"], "Endor rule reference");+ if (+ reference["toolComponent"] !== undefined ||+ (reference["id"] !== undefined && reference["id"] !== ruleId) ||+ (reference["index"] !== undefined &&+ reference["index"] !== ruleIndex) ||+ (reference["guid"] !== undefined &&+ reference["guid"] !== rule["guid"])+ )+ throw new Error("Inconsistent or external Endor rule reference.");+ }+ const message = record(result["message"], "Endor message");+ const short = record(+ rule["shortDescription"] ?? {},+ "Endor shortDescription",+ );+ const full = record(+ rule["fullDescription"] ?? {},+ "Endor fullDescription",+ );+ const help = record(rule["help"] ?? {}, "Endor help");+ const hasCodeLocations = strings(properties["categories"]).some(+ (category) => category === "SAST" || category === "SECRETS",+ );+ const locations = array(+ result["locations"] ?? [],+ "Endor locations",+ ).flatMap((v) => {+ const physical = record(+ record(v, "Endor location")["physicalLocation"] ?? {},+ "Physical location",+ );+ const artifact = record(+ physical["artifactLocation"] ?? {},+ "Artifact location",+ );+ if (+ artifact["index"] !== undefined ||+ artifact["uriBaseId"] !== undefined+ )+ return [];+ const uri = text(artifact["uri"]);+ if (uri === null || /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(uri)) return [];+ let path: string | null;+ try {+ path = relativePath(decodeURIComponent(uri));+ } catch {+ return [];+ }+ if (path === null) return [];+ const line = hasCodeLocations+ ? record(physical["region"] ?? {}, "Endor region")["startLine"]+ : null;+ return [+ {+ path,+ line:+ typeof line === "number" && Number.isSafeInteger(line) && line > 0+ ? line+ : null,+ },+ ];+ });+ return {+ source_finding_id: id,+ evidence: validateExternalEvidence({+ title: text(short["text"]) ?? text(rule["name"]) ?? ruleId,+ url: text(properties["finding-url"]),+ description: [+ text(message["markdown"]) ?? text(message["text"]),+ text(full["text"]),+ text(help["markdown"]) ?? text(help["text"]),+ ]+ .filter(Boolean)+ .join("\n\n"),+ // Diagnostic level and CVSS are not Endor's finding severity. Keep both as source evidence.+ severity: "unknown",+ locations: [+ ...new Map(+ locations.map((location) => [JSON.stringify(location), location]),+ ).values(),+ ],+ source_data: structuredClone({+ ...context,+ runContext: sarifRunContextForResult(+ context.runContext,+ result,+ rule,+ context.documentContext,+ context.driverContext,+ context.toolContext,+ ),+ rule,+ result,+ }),+ }),+ };+ },+ ({ result }) =>+ requiredText(+ record(+ record(result, "Endor result")["properties"],+ "Endor result properties",+ )["finding-uuid"],+ "Endor finding-uuid",+ ),+ );+}++export async function readEndorFindings(+ path: string,+): Promise<ExternalFindings> {+ return normalizeEndorFindings(await readScannerJson(path));+}diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 1efa09017..c617b8234 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -30,6 +30,7 @@ import {} from "./external-findings-read.js";import { wizCsvRepositoryUrl } from "./wiz-csv.js";import { snykRepositoryUrls } from "./snyk-findings.js";+import { endorRepositoryUrls } from "./endor-findings.js";import type {ExternalFindings,ExternalPublicationInput,@@ -717,6 +718,9 @@ async function preparePublicationInput(cloudRepositoryUrl: destination.url,}): []),+ ...(options.provider === "endor"+ ? endorRepositoryUrls(finding.evidence.source_data)+ : []),];for (const sourceRepository of sourceRepositories)if (diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex 3b64918bb..5ae308d1d 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -6,13 +6,14 @@ import type {import { wizCsvRepositoryUrl } from "./wiz-csv.js";import { readSnykFindings, snykRepositoryUrls } from "./snyk-findings.js";import { readSemgrepFindings } from "./semgrep-findings.js";+import { readEndorFindings, endorRepositoryUrls } from "./endor-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" | "snyk" | "semgrep";+ provider: "wiz" | "snyk" | "semgrep" | "endor";sourceRepositoryUrl?: string;}@@ -61,6 +62,17 @@ export async function readExternalFindings(});return { findings, sourceRepositories };}+ if (options.provider === "endor") {+ const parsed = await readEndorFindings(path);+ return {+ findings: parsed,+ sourceRepositories: parsed.findings.flatMap((finding) =>+ endorRepositoryUrls(finding.evidence.source_data).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.tsindex ca670f3ae..3aa812715 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -324,3 +324,8 @@ export {readSemgrepFindings,type SemgrepImportOptions,} from "./semgrep-findings.js";+export {+ normalizeEndorFindings,+ normalizeEndorSarif,+ readEndorFindings,+} from "./endor-findings.js";diff --git a/sdk/typescript/tests-ts/endor-findings-local.test.ts b/sdk/typescript/tests-ts/endor-findings-local.test.tsnew file mode 100644index 000000000..63b3b89d5--- /dev/null+++ b/sdk/typescript/tests-ts/endor-findings-local.test.ts@@ -0,0 +1,276 @@+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 { endorFinding, endorSarif } from "./support/endor-import-fixtures.js";++test.each(["native JSON", "SARIF"] as const)(+ "Endor %s findings persist locally and update the same source identity",+ async (format) => {+ const fixture = await localFindingsFixture();+ try {+ const input = format === "native JSON" ? endorFinding() : endorSarif();+ const path = join(fixture.root, "endor.json");+ const options = {+ repository: fixture.repository,+ provider: "endor" as const,+ sourceKey: "endor-project-example",+ };+ 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: "endor",+ sourceKey: options.sourceKey,+ sourceFindingId: "finding-example-1",+ version: 1,+ });+ expect(stored!.evidence).toEqual(prepared.preview.findings[0]!.evidence);+ expect(stored!.assessment).toEqual({ state: "not_assessed" });+ expect(stored!.evidence).not.toHaveProperty("confidence");+ expect(stored!.evidence.locations).toEqual(+ "spec" in input+ ? [+ { path: "package.json", line: null },+ { path: "package-lock.json", line: null },+ ]+ : [{ path: "package.json", line: null }],+ );+ if ("spec" in input) {+ expect(stored!.evidence.source_data).toEqual(input);+ expect(stored!.evidence.packages![0]!.fixed_versions).toEqual([]);+ } else {+ expect(stored!.evidence.severity).toBe("unknown");+ 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 ("spec" in input) {+ input.spec.dismiss = true;+ input.spec.target_dependency_version = "1.1.0";+ } else {+ input.runs[0]!.results[0]!.message.text = "Updated source explanation";+ input.runs[0]!.results[0]!.properties.tags = [];+ }+ 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.source_data).not.toEqual(+ stored!.evidence.source_data,+ );+ } finally {+ await fixture.dispose();+ }+ },+);++test("switching Endor JSON and SARIF replaces the same local source snapshot without merging evidence", async () => {+ const fixture = await localFindingsFixture();+ try {+ const finding = endorFinding();+ const native = {+ ...finding,+ spec: {+ ...finding.spec,+ source_code_version: { sha: "a".repeat(40) },+ },+ };+ const sarif = endorSarif();+ const path = join(fixture.root, "endor.json");+ const options = {+ repository: fixture.repository,+ provider: "endor" as const,+ sourceKey: "endor-project-example",+ };+ const dependencies = { environment: fixture.environment };+ const importAndRead = async (input: unknown) => {+ await writeFile(path, JSON.stringify(input));+ const prepared = await prepareLocalExternalImport(+ path,+ options,+ dependencies,+ );+ const result = await prepared.import();+ const records = await listLocalExternalFindings(options, dependencies);+ expect(prepared.preview.excluded).toEqual([]);+ expect(records).toHaveLength(1);+ expect(records[0]!.evidence).toEqual(+ prepared.preview.findings[0]!.evidence,+ );+ expect(records[0]!.assessment).toEqual({ state: "not_assessed" });+ return { record: records[0]!, counts: result.counts };+ };++ const original = await importAndRead({ list: { objects: [native] } });+ expect(original.counts).toEqual({ created: 1, updated: 0, unchanged: 0 });+ expect(original.record.evidence).toMatchObject({+ severity: "critical",+ code_revision: native.spec.source_code_version.sha,+ advisory_ids: ["CVE-2099-0001", "GHSA-2222-3333-4444"],+ source_data: native,+ });+ expect(original.record.evidence.packages).toHaveLength(2);+ expect(original.record.evidence.packages![0]).toMatchObject({+ name: "@example/package",+ installed_version: "1.0.0",+ });++ const replaced = await importAndRead(sarif);+ expect(replaced.counts).toEqual({ created: 0, updated: 1, unchanged: 0 });+ expect(replaced.record).toMatchObject({+ id: original.record.id,+ sourceFindingId: native.uuid,+ sourceKey: options.sourceKey,+ createdAt: original.record.createdAt,+ version: 2,+ });+ expect(replaced.record.evidence.severity).toBe("unknown");+ expect(replaced.record.evidence.code_revision).toBeNull();+ expect(replaced.record.evidence.advisory_ids).toEqual([]);+ expect(replaced.record.evidence.packages).toEqual([]);+ expect(replaced.record.evidence.source_data).not.toHaveProperty("spec");+ expect(replaced.record.evidence.source_data).toMatchObject({+ result: sarif.runs[0]!.results[0],+ });++ const restored = await importAndRead(native);+ expect(restored.counts).toEqual({ created: 0, updated: 1, unchanged: 0 });+ expect(restored.record).toMatchObject({+ id: original.record.id,+ createdAt: original.record.createdAt,+ version: 3,+ evidence: original.record.evidence,+ });+ expect(restored.record.evidence.source_data).not.toHaveProperty("result");+ } finally {+ await fixture.dispose();+ }+});++test("sparse Endor findings remain unassessed without invented locations or remediation", async () => {+ const fixture = await localFindingsFixture();+ try {+ const input = {+ uuid: "sparse-finding",+ meta: { name: "Synthetic sparse finding" },+ spec: { project_uuid: "project-example" },+ };+ const path = join(fixture.root, "endor.json");+ await writeFile(path, JSON.stringify({ list: { objects: [input] } }));+ const options = {+ repository: fixture.repository,+ provider: "endor" as const,+ sourceKey: "endor-project-example",+ };+ const dependencies = { environment: fixture.environment };+ 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]!.assessment).toEqual({ state: "not_assessed" });+ expect(records[0]!.evidence).toMatchObject({+ severity: "unknown",+ description: null,+ locations: [],+ packages: [],+ code_revision: null,+ source_data: input,+ });+ expect(records[0]!.evidence).not.toHaveProperty("confidence");+ expect(records[0]!.evidence).not.toHaveProperty("remediation");+ } finally {+ await fixture.dispose();+ }+});++test("Endor SARIF repository provenance cannot be imported into a different local checkout", async () => {+ const fixture = await localFindingsFixture({+ remote: "https://github.com/example/other",+ });+ try {+ const sarif = endorSarif();+ const input = {+ ...sarif,+ runs: sarif.runs.map((run) => ({+ ...run,+ versionControlProvenance: [+ { repositoryUri: "https://github.com/example/project" },+ ],+ })),+ };+ const path = join(fixture.root, "endor.json");+ await writeFile(path, JSON.stringify(input));+ const options = {+ repository: fixture.repository,+ provider: "endor" as const,+ sourceKey: "endor-project-example",+ };+ 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();+ }+});diff --git a/sdk/typescript/tests-ts/endor-findings.test.ts b/sdk/typescript/tests-ts/endor-findings.test.tsnew file mode 100644index 000000000..ae614cb34--- /dev/null+++ b/sdk/typescript/tests-ts/endor-findings.test.ts@@ -0,0 +1,603 @@+import { expect, test } from "bun:test";+import {+ normalizeEndorFindings,+ normalizeEndorSarif,+} from "../src/endor-findings.js";+import { endorFinding, endorSarif } from "./support/endor-import-fixtures.js";++test("Endor JSON preserves the complete source, UUID, severity, aliases and repository manifests", () => {+ const input = endorFinding();+ const original = structuredClone(input);+ const output = normalizeEndorFindings(input);+ expect(input).toEqual(original);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]).toMatchObject({+ source_finding_id: input.uuid,+ evidence: {+ title: input.meta.name,+ severity: "critical",+ branch: "main",+ source_updated_at: 1767225600,+ advisory_ids: ["CVE-2099-0001", "GHSA-2222-3333-4444"],+ locations: [+ { path: "package.json", line: null },+ { path: "package-lock.json", line: null },+ ],+ source_data: original,+ },+ });+ expect(output.findings[0]!.evidence.packages).toHaveLength(2);+ expect(output.findings[0]!.evidence.packages![0]).toMatchObject({+ name: "@example/package",+ installed_version: "1.0.0",+ fixed_versions: [],+ });+});++test("arrays and ListFindingsResponse use the same identities and empty lists are empty", () => {+ const input = endorFinding();+ expect(normalizeEndorFindings([input])).toEqual(+ normalizeEndorFindings({ list: { objects: [input] } }),+ );+ expect(normalizeEndorFindings({ list: { objects: [] } })).toEqual({+ read: 0,+ findings: [],+ excluded: [],+ });+});++test.each(["sast_data", "ai_sast_data"])(+ "Endor %s preserves the primary source location and original evidence",+ (field) => {+ const base = endorFinding();+ const input = {+ ...base,+ spec: {+ ...base.spec,+ target_dependency_name: "",+ dependency_file_paths: ["src/example.ts", "package.json"],+ finding_metadata: {+ [field]: {+ location: {+ relative_path: "src/example.ts",+ start_line: 12,+ end_line: 14,+ },+ },+ },+ },+ };+ const original = structuredClone(input);+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.source_finding_id).toBe(input.uuid);+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "package.json", line: null },+ { path: "src/example.ts", line: 12 },+ ]);+ expect(output.findings[0]!.evidence.source_data).toEqual(original);+ expect(input).toEqual(original);+ },+);++test.each([12, 24])(+ "Endor retains distinct code locations without duplicating identical locations (line %i)",+ (secondLine) => {+ const base = endorFinding();+ const location = { relative_path: "src/example.ts", start_line: 12 };+ const input = {+ ...base,+ spec: {+ ...base.spec,+ dependency_file_paths: [],+ finding_metadata: {+ sast_data: { location },+ ai_sast_data: { location: { ...location, start_line: secondLine } },+ },+ },+ };+ const expected = [{ path: "src/example.ts", line: 12 }];+ if (secondLine !== 12)+ expected.push({ path: "src/example.ts", line: secondLine });+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual(expected);+ },+);++test.each([null, 0, -1, 1.5, "12"])(+ "Endor retains a code path without inventing a line from %p",+ (start_line) => {+ const base = endorFinding();+ const input = {+ ...base,+ spec: {+ ...base.spec,+ dependency_file_paths: [],+ finding_metadata: {+ ai_sast_data: {+ location: { relative_path: "src/example.ts", start_line },+ },+ },+ },+ };+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "src/example.ts", line: null },+ ]);+ expect(output.findings[0]!.evidence.source_data).toEqual(input);+ },+);++test("unsafe code locations remain only in the original Endor evidence", () => {+ const base = endorFinding();+ const input = {+ ...base,+ spec: {+ ...base.spec,+ dependency_file_paths: [],+ finding_metadata: {+ sast_data: {+ location: { relative_path: "../outside.ts", start_line: 12 },+ },+ ai_sast_data: {+ location: { relative_path: "C:\\private\\source.ts", start_line: 24 },+ },+ },+ },+ };+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual([]);+ expect(output.findings[0]!.evidence.source_data).toEqual(input);+});++test("changed severity, reachability, dismissal and dependency version retain UUID", () => {+ const input = endorFinding();+ const original = normalizeEndorFindings(input).findings[0]!;+ input.spec.level = "FINDING_LEVEL_LOW";+ input.spec.dismiss = true;+ input.spec.target_dependency_version = "1.1.0";+ input.spec.reachable_paths = [];+ const changed = normalizeEndorFindings(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,+ );+});++test("Endor imports the scanned commit while preserving identity across revisions", () => {+ const finding = {+ ...endorFinding(),+ spec: {+ ...endorFinding().spec,+ source_code_version: { ref: "release", sha: "a".repeat(40) },+ },+ };+ const first = normalizeEndorFindings(finding).findings[0]!;+ expect(first.evidence.code_revision).toBe("a".repeat(40));+ finding.spec.source_code_version.sha = "b".repeat(40);+ const updated = normalizeEndorFindings(finding).findings[0]!;+ expect(updated.source_finding_id).toBe(first.source_finding_id);+ expect(updated.evidence.code_revision).toBe("b".repeat(40));+ expect(updated.evidence.source_data).toEqual(finding);++ const withoutSha = {+ ...finding,+ spec: { ...finding.spec, source_code_version: { ref: "release" } },+ };+ expect(+ normalizeEndorFindings(withoutSha).findings[0]!.evidence.code_revision,+ ).toBeNull();+});++test("unknown levels stay unknown and main-context default is not mistaken for a branch", () => {+ const input = endorFinding();+ input.spec.level = "FINDING_LEVEL_UNSPECIFIED";+ input.context = { type: "CONTEXT_TYPE_MAIN", id: "default" };+ expect(normalizeEndorFindings(input).findings[0]!.evidence).toMatchObject({+ severity: "unknown",+ branch: null,+ });+});++test("duplicate UUIDs, masked records, bad timestamps and oversized evidence are excluded", () => {+ const input = endorFinding();+ const duplicate = normalizeEndorFindings([input, input]);+ expect(duplicate.findings).toEqual([]);+ expect(duplicate.excluded).toHaveLength(2);+ for (const invalid of [+ { ...input, uuid: "" },+ { uuid: "invalid-finding" },+ {+ ...input,+ uuid: "invalid-finding",+ meta: { ...input.meta, update_time: "invalid" },+ },+ {+ ...input,+ uuid: "invalid-finding",+ spec: { ...input.spec, summary: "é".repeat(65536) },+ },+ ]) {+ const output = normalizeEndorFindings([input, invalid]);+ expect(output.findings.map((finding) => finding.source_finding_id)).toEqual(+ [input.uuid],+ );+ expect(output.excluded).toHaveLength(1);+ }+});++test("unsafe dependency paths remain in raw evidence", () => {+ const input = endorFinding();+ input.spec.dependency_file_paths = [+ "../outside",+ "/tmp/absolute",+ "C:\\private\\manifest",+ "safe/manifest.json",+ ];+ const evidence = normalizeEndorFindings(input).findings[0]!.evidence;+ expect(evidence.locations).toEqual([+ { path: "safe/manifest.json", line: null },+ ]);+ expect(evidence.source_data).toEqual(input);+});++test("native and SARIF Endor locations preserve repository filenames containing colons", () => {+ const native = endorFinding();+ native.spec.dependency_file_paths = ["src/schema:prod.ts"];+ const sarif = endorSarif();+ sarif.runs[0]!.results[0]!.locations[0]!.physicalLocation.artifactLocation.uri =+ "src/schema%3Aprod.ts";+ const nativeResult = normalizeEndorFindings(native);+ const sarifResult = normalizeEndorFindings(sarif);+ expect(nativeResult.excluded).toEqual([]);+ expect(sarifResult.excluded).toEqual([]);+ expect(nativeResult.findings[0]!.evidence.locations).toEqual([+ { path: "src/schema:prod.ts", line: null },+ ]);+ expect(sarifResult.findings[0]!.evidence.locations).toEqual(+ nativeResult.findings[0]!.evidence.locations,+ );+ expect(nativeResult.findings[0]!.evidence.source_data).toEqual(native);+ expect(sarifResult.findings[0]!.evidence.source_data).toMatchObject({+ result: sarif.runs[0]!.results[0],+ });+});++test("Endor SARIF UUID matches JSON and retains all source assertions without promoting them to Cloud assessments", () => {+ const input = endorSarif();+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.source_finding_id).toBe(+ normalizeEndorFindings(endorFinding()).findings[0]!.source_finding_id,+ );+ expect(output.findings[0]!.evidence).toMatchObject({+ severity: "unknown",+ url: input.runs[0]!.results[0]!.properties["finding-url"],+ locations: [{ path: "package.json", line: null }],+ source_data: {+ result: input.runs[0]!.results[0],+ rule: input.runs[0]!.tool.driver.rules[0],+ },+ });+});++test("Endor SARIF does not duplicate unrelated artifact inventories into a direct-URI finding", () => {+ const input: any = endorSarif();+ const run = input.runs[0];+ run.artifacts = Array.from({ length: 5_000 }, (_, index) => ({+ location: { uri: `unrelated/source-file-${index}.ts` },+ }));+ run.versionControlProvenance = [+ { repositoryUri: "https://github.com/example/project" },+ ];+ const original = structuredClone(input);+ const output = normalizeEndorSarif(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings).toHaveLength(1);+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "package.json", line: null },+ ]);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({+ result: original.runs[0].results[0],+ rule: original.runs[0].tool.driver.rules[0],+ runContext: {+ versionControlProvenance: original.runs[0].versionControlProvenance,+ },+ });+ expect(+ output.findings[0]!.evidence.source_data!["runContext"],+ ).not.toHaveProperty("artifacts");+ expect(input).toEqual(original);+});++test("Endor SARIF retains artifact metadata for the selected direct-URI location", () => {+ const input: any = endorSarif();+ input.runs[0].artifacts = [+ { location: { uri: "unrelated.ts" } },+ {+ location: { uri: "package.json" },+ contents: { text: "synthetic package contents" },+ },+ ];+ const original = structuredClone(input);+ const output = normalizeEndorSarif(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({+ result: original.runs[0].results[0],+ runContext: { artifacts: original.runs[0].artifacts },+ });+ expect(input).toEqual(original);+});++test.each([+ {},+ { artifacts: [], results: [] },+ { properties: { producer: "synthetic-exporter" }, artifacts: [] },+])("Endor SARIF accepts an empty external-property map: %p", (references) => {+ const input: any = endorSarif();+ input.runs[0].externalPropertyFileReferences = references;+ const original = structuredClone(input);+ const output = normalizeEndorSarif(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings).toHaveLength(1);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({+ result: original.runs[0].results[0],+ runContext: { externalPropertyFileReferences: references },+ });+ expect(input).toEqual(original);+});++test.each(["artifacts", "results"])(+ "Endor SARIF still rejects external %s references",+ (property) => {+ const input: any = endorSarif();+ input.runs[0].externalPropertyFileReferences = {+ [property]: [{ location: { uri: "external-results.sarif" } }],+ };+ expect(() => normalizeEndorSarif(input)).toThrow("self-contained");+ },+);++test.each([+ ["packages/my%20app/package.json", "packages/my app/package.json"],+ ["packages/%E6%97%A5%E6%9C%AC/package.json", "packages/日本/package.json"],+ ["packages/my%23app/package.json", "packages/my#app/package.json"],+ ["packages/my%2520app/package.json", "packages/my%20app/package.json"],+ ["%2e%2e/outside/package.json", null],+ ["%2Ftmp/package.json", null],+ ["C%3A%5Cprivate%5Cpackage.json", null],+ ["file:src/package.json", null],+ ["https:src/package.json", null],+ ["packages/invalid%ZZ/package.json", null],+])("Endor SARIF decodes safe repository paths once (%s)", (uri, path) => {+ const input = endorSarif();+ const result = input.runs[0]!.results[0]!;+ result.locations[0]!.physicalLocation.artifactLocation.uri = uri!;+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual(+ path === null ? [] : [{ path, line: null }],+ );+ expect(output.findings[0]!.evidence.source_data).toMatchObject({ result });+ expect(result.locations[0]!.physicalLocation.artifactLocation.uri).toBe(uri);+});++test.each(["SAST", "SECRETS"])(+ "Endor SARIF retains distinct reported code lines for %s findings",+ (category) => {+ const input = endorSarif();+ const result = input.runs[0]!.results[0]!;+ result.properties.categories = [category];+ result.locations = [1, 42, 42].map((startLine) => ({+ physicalLocation: {+ artifactLocation: { uri: "src/my%20module.ts" },+ region: { startLine },+ },+ }));+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "src/my module.ts", line: 1 },+ { path: "src/my module.ts", line: 42 },+ ]);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({ result });+ },+);++test.each([0, -1, 1.5, "42", null, undefined])(+ "Endor SARIF keeps unknown or invalid code lines as null (%p)",+ (startLine) => {+ const input = endorSarif();+ const result: any = input.runs[0]!.results[0]!;+ result.properties.categories = ["SAST"];+ result.locations[0].physicalLocation.region = { startLine };+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "package.json", line: null },+ ]);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({ result });+ },+);++test("SARIF requires vendor identity, producer and consistent rule references", () => {+ for (const mutate of [+ (r: any) => delete r.results[0].properties["finding-uuid"],+ (r: any) => delete r.results[0].properties["project-uuid"],+ (r: any) => (r.results[0].ruleIndex = 1),+ (r: any) => (r.results[0].rule = { id: "other" }),+ (r: any) => (r.results[0].rule = { index: 1 }),+ (r: any) => (r.results[0].rule = { guid: "other" }),+ (r: any) => (r.tool.driver.rules = []),+ (r: any) =>+ r.tool.driver.rules.push(structuredClone(r.tool.driver.rules[0])),+ ]) {+ const input = endorSarif();+ mutate(input.runs[0]);+ expect(normalizeEndorSarif(input).findings).toEqual([]);+ }+ const input = endorSarif();+ input.runs[0]!.tool.driver.name = "other";+ expect(() => normalizeEndorSarif(input)).toThrow("endorctl");+});++test("Endor SARIF selects exact rule IDs and original indexes within each run", () => {+ const input = endorSarif();+ const originalRun = input.runs[0]!;+ const originalRule = originalRun.tool.driver.rules[0]!;+ const originalResult = originalRun.results[0]!;+ const runs = [0, 1].map((index) => {+ const rule = {+ ...originalRule,+ guid: `rule-guid-${index}`,+ shortDescription: { text: `Finding from run ${index}` },+ };+ const otherRule = { ...originalRule, id: ` ${originalRule.id} ` };+ return {+ ...originalRun,+ tool: {+ driver: {+ ...originalRun.tool.driver,+ rules: index === 0 ? [rule, otherRule] : [otherRule, rule],+ },+ },+ results: [+ {+ ...originalResult,+ ruleIndex: index,+ rule: { id: rule.id, index, guid: rule.guid },+ properties: {+ ...originalResult.properties,+ "finding-uuid": `finding-from-run-${index}`,+ },+ },+ ],+ };+ });+ const output = normalizeEndorSarif({ ...input, runs });+ expect(output.excluded).toEqual([]);+ expect(output.findings).toHaveLength(2);+ for (const [index, finding] of output.findings.entries()) {+ expect(finding.source_finding_id).toBe(`finding-from-run-${index}`);+ expect(finding.evidence.title).toBe(`Finding from run ${index}`);+ expect(finding.evidence.source_data!["rule"]).toEqual(+ runs[index]!.tool.driver.rules[index],+ );+ }+});++test("distinct finding UUIDs survive a reordered export", () => {+ const input = Array.from({ length: 3 }, (_, i) => ({+ ...endorFinding(),+ uuid: `finding-example-${i}`,+ }));+ const first = normalizeEndorFindings(input);+ const second = normalizeEndorFindings(input.reverse());+ expect(first.findings).toHaveLength(input.length);+ expect(second.excluded).toEqual([]);+ expect(second.findings.map((f) => f.source_finding_id).sort()).toEqual(+ first.findings.map((f) => f.source_finding_id).sort(),+ );+});++test.each(["2026-01-01T00:00:00.123Z", "2026-01-01T00:00:00.123456789Z"])(+ "fractional Endor timestamps retain precise source evidence (%s)",+ (timestamp) => {+ const finding = endorFinding();+ finding.meta.update_time = timestamp;+ const result = normalizeEndorFindings({+ list: { objects: [finding], response: { next_page_token: 0 } },+ });+ expect(result.excluded).toEqual([]);+ expect(result.findings[0]!.evidence.source_updated_at).toBe(1767225600);+ expect(result.findings[0]!.evidence.source_data).toMatchObject({+ meta: { update_time: timestamp },+ });+ },+);++test.each([1, "1", "opaque-next-page", -1, true])(+ "rejects unfinished or invalid Endor page tokens (%p)",+ (next_page_token) => {+ expect(() =>+ normalizeEndorFindings({+ list: { objects: [endorFinding()], response: { next_page_token } },+ }),+ ).toThrow("another page");+ },+);++test("rejects Endor cursor pages while accepting complete exports and selected arrays", () => {+ const finding = endorFinding();+ expect(() =>+ normalizeEndorFindings({+ list: { objects: [finding], response: { next_page_id: "next-finding" } },+ }),+ ).toThrow("another page");+ for (const next_page_token of [undefined, null, 0, "0", ""]) {+ expect(+ normalizeEndorFindings({+ list: {+ objects: [finding],+ response: { next_page_token, next_page_id: "" },+ },+ }).findings,+ ).toHaveLength(1);+ }+ expect(normalizeEndorFindings([finding]).findings).toHaveLength(1);+});++test.each([+ {+ artifact: { uri: "src/query.ts", uriBaseId: "ROOT" },+ base: "file:///outside/",+ },+ { artifact: { uri: "src/query.ts", uriBaseId: "ROOT" }, base: "subproject/" },+ { artifact: { uri: "src/query.ts", index: 0 }, base: "subproject/" },+ { artifact: { index: 0 }, base: "subproject/" },+])(+ "Endor SARIF leaves unsupported artifact references unmapped: %p",+ ({ artifact, base }) => {+ const input: any = endorSarif();+ const run = input.runs[0];+ run.originalUriBaseIds = { ROOT: { uri: base } };+ run.artifacts = [{ location: { uri: "src/actual.ts" } }];+ const result = run.results[0];+ result.properties.categories = ["SAST"];+ result.locations = [+ {+ physicalLocation: {+ artifactLocation: artifact,+ region: { startLine: 42 },+ },+ },+ {+ physicalLocation: {+ artifactLocation: { uri: "src/direct.ts" },+ region: { startLine: 8 },+ },+ },+ ];+ const original = structuredClone(input);+ const output = normalizeEndorFindings(input);+ expect(output.excluded).toEqual([]);+ expect(output.findings[0]!.source_finding_id).toBe(+ result.properties["finding-uuid"],+ );+ expect(output.findings[0]!.evidence.locations).toEqual([+ { path: "src/direct.ts", line: 8 },+ ]);+ expect(output.findings[0]!.evidence.source_data).toMatchObject({+ result: original.runs[0].results[0],+ runContext: {+ originalUriBaseIds: run.originalUriBaseIds,+ artifacts: run.artifacts,+ },+ });+ expect(input).toEqual(original);+ },+);diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 8a2043f29..7c93670df 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -3467,3 +3467,132 @@ test("Semgrep CLI dry-run preserves explicit source repository and does not uploexpect(await cli.runCli(command, f.cliDeps)).toBe(0);expect(f.posts).toHaveLength(0);});++test("Endor JSON and SARIF reuse UUID identity through Cloud publication", async () => {+ const { endorFinding, endorSarif } =+ await import("./support/endor-import-fixtures.js");+ const input = endorFinding();+ const f = await fixture(input);+ const settings = {+ ...options,+ provider: "endor" as const,+ sourceKey: "namespace/project/main",+ };+ const first = await (+ await prepareExternalPublication(f.file, settings, f.deps)+ ).publish();+ expect(first.counts.created).toBe(1);+ const original = structuredClone([...f.reports.values()][0]!);+ expect(+ (+ await (+ await prepareExternalPublication(f.file, settings, f.deps)+ ).publish()+ ).counts.unchanged,+ ).toBe(1);+ const sarif = endorSarif();+ await writeFile(f.file, JSON.stringify(sarif));+ const changed = await (+ await prepareExternalPublication(f.file, settings, f.deps)+ ).publish();+ expect(changed.counts.updated).toBe(1);+ expect(changed.verified).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.evidence.source_data).toMatchObject({+ result: sarif.runs[0]!.results[0],+ });+});+test("Endor CLI dry-run recognizes SARIF without writing imports", async () => {+ const { endorSarif } = await import("./support/endor-import-fixtures.js");+ const f = await fixture(endorSarif());+ const command = [...f.command, "--dry-run"];+ command[command.indexOf("--provider") + 1] = "endor";+ 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"] },+])(+ "Endor source repository provenance binds both publication entrypoints: %p",+ async ({ uris }) => {+ const { endorSarif } = await import("./support/endor-import-fixtures.js");+ const { normalizeEndorFindings } = await import("../src/endor-findings.js");+ const input: any = endorSarif();+ input.runs[0].versionControlProvenance = uris.map((repositoryUri) => ({+ repositoryUri,+ }));+ const f = await fixture(input);+ const selected = { ...options, provider: "endor" as const };+ await expect(+ prepareExternalPublication(f.file, selected, f.deps),+ ).rejects.toThrow("does not match the selected Cloud repository");+ await expect(+ prepareNormalizedExternalPublication(+ normalizeEndorFindings(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("Endor source repository binding preserves immutable requests across a repository rename", async () => {+ const { endorSarif } = await import("./support/endor-import-fixtures.js");+ const input: any = endorSarif();+ 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: "endor" as const };+ f.state.loseResponse = true;+ const first = await prepareExternalPublication(f.file, selected, f.deps);+ await expect(first.publish()).rejects.toThrow("resume the saved request");+ 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 retry = await prepareExternalPublication(+ f.file,+ selected,+ changedDestination,+ );+ expect(retry.preview.resumed).toBe(true);+ expect((await retry.publish()).status).toBe("complete");+ expect(f.posts[1]).toBe(f.posts[0]);+ expect([...f.reports.values()][0]!.evidence.source_data).toMatchObject({+ runContext: {+ versionControlProvenance: original.runs[0].versionControlProvenance,+ },+ });+ 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);+});diff --git a/sdk/typescript/tests-ts/support/endor-import-fixtures.ts b/sdk/typescript/tests-ts/support/endor-import-fixtures.tsnew file mode 100644index 000000000..c19d0cc44--- /dev/null+++ b/sdk/typescript/tests-ts/support/endor-import-fixtures.ts@@ -0,0 +1,77 @@+// Synthetic records shaped after Endor's Finding model and its published SARIF sample.+export function endorFinding() {+ return {+ uuid: "finding-example-1",+ meta: {+ name: "Synthetic vulnerable dependency",+ update_time: "2026-01-01T00:00:00Z",+ },+ context: { type: "CONTEXT_TYPE_REF", id: "main" },+ spec: {+ project_uuid: "project-example",+ level: "FINDING_LEVEL_CRITICAL",+ summary: "Synthetic dependency finding",+ ecosystem: "ECOSYSTEM_NPM",+ target_dependency_name: "@example/package",+ target_dependency_version: "1.0.0",+ proposed_version: "2.0.0",+ dependency_file_paths: ["package.json", "package-lock.json"],+ finding_categories: ["FINDING_CATEGORY_VULNERABILITY"],+ finding_metadata: {+ vulnerability: {+ meta: { name: "CVE-2099-0001" },+ spec: { aliases: ["GHSA-2222-3333-4444"] },+ },+ },+ reachable_paths: [{ nodes: [{ function: "syntheticFunction" }] }],+ dismiss: false,+ },+ };+}++export function endorSarif() {+ return {+ version: "2.1.0",+ runs: [+ {+ tool: {+ driver: {+ name: "endorctl",+ semanticVersion: "1.0.0",+ rules: [+ {+ id: "synthetic-rule",+ shortDescription: { text: "Synthetic finding" },+ fullDescription: { text: "Synthetic explanation" },+ help: { text: "Synthetic remediation" },+ },+ ],+ },+ },+ results: [+ {+ ruleId: "synthetic-rule",+ message: { text: "Synthetic result" },+ properties: {+ "finding-uuid": "finding-example-1",+ "project-uuid": "project-example",+ categories: ["VULNERABILITY"],+ tags: ["REACHABLE_FUNCTION"],+ "cvss-score": 9.8,+ "finding-url":+ "https://example.invalid/findings/finding-example-1",+ },+ locations: [+ {+ physicalLocation: {+ artifactLocation: { uri: "package.json" },+ region: { startLine: 1 },+ },+ },+ ],+ },+ ],+ },+ ],+ };+}