OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(import): track Amazon Inspector repository vulnerabilities (#2097)
Michael D'Angelocaf913cbef91
diff --git a/docs/scanner-imports/inspector.md b/docs/scanner-imports/inspector.mdnew file mode 100644index 000000000..e4942e917--- /dev/null+++ b/docs/scanner-imports/inspector.md@@ -0,0 +1,78 @@+# Import Amazon Inspector repository findings++Import package and code vulnerabilities from one Amazon Inspector Code Security+repository. Each finding ARN identifies one occurrence within your source key.++## Export one repository++In Inspector coverage, find the account, Region and full resource ID for the+repository. A project name alone can match several integrations. With+`inspector2:ListFindings` permission, export the findings outside the checkout.++```bash+set -eu+umask 077+out=$(mktemp -d)+aws inspector2 list-findings --region us-east-1 --output json \+ --filter-criteria '{+ "awsAccountId":[{"comparison":"EQUALS","value":"ACCOUNT_ID"}],+ "resourceType":[{"comparison":"EQUALS","value":"CODE_REPOSITORY"}],+ "resourceId":[{"comparison":"EQUALS","value":"REPOSITORY_RESOURCE_ID"}]+ }' > "$out/inspector.json.tmp"+mv "$out/inspector.json.tmp" "$out/inspector.json"+```++Start at the first page with automatic pagination enabled. Omit+`--starting-token`, `--no-paginate`, `--max-items` and `--query`. The+importer rejects continuation tokens but cannot distinguish a final page+saved on its own from a complete export.++## Bind the Inspector project to a Git repository++Inspector often reports a project ARN and a name such as `example/project`.+That name can exist on multiple Git hosts. Verify the project ARN and its+canonical Git URL in your SCM integration setup. Set `VERIFIED_PROJECT_ARN`+to that ARN and pass the pair explicitly.+Copying an ARN from the report alone cannot verify who owns the repository.+When the findings already include a matching native Git URL, omit+`--inspector-project-arn`.++## Preview, import and read back++```bash+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1+codex-security publish findings "$out/inspector.json" \+ --to local --repository ./project --provider inspector \+ --source-repository-url https://github.com/example/project \+ --inspector-project-arn "$VERIFIED_PROJECT_ARN" \+ --source-key inspector/account-alias/us-east-1/example/project \+ --dry-run --format json+```++Review the destination, ready findings and exclusions. Remove `--dry-run` to+import, then run `codex-security findings imported ./project --format json`.+Reuse the source key across exports. Reimport updates an existing ARN.+Omitted findings and empty exports leave earlier occurrences in place.++For Cloud, use `--to cloud --repository CLOUD_REPOSITORY_ID` on a deployment+that accepts the Inspector provider. Cloud checks the authorized GitHub+destination. Custom GitHub hosts need a native GitHub provider hint.+Self-managed GitLab is supported locally. If the GitLab web URL includes an+installation prefix that the SSH clone URL omits, use the verified HTTPS clone+URL as a checkout remote. Use the verified URL’s path casing on custom hosts.+For home-relative SSH paths, verify the account when a URL omits the login.++Supply the same verified ARN and URL when resuming a Cloud submission prepared+with that binding. SDK callers can pass verified ARN-to-URL pairs through the+`inspectorProjectMap` option on raw and normalized imports.++## Evidence++Package findings retain the advisory and reported dependency versions. Code+findings retain detector details and safe repository-relative locations when+available. Native status, severity and remediation remain source evidence.+A closed or suppressed finding stays unassessed. EC2, ECR, Lambda and network+findings are excluded.++[AWS CLI export](https://docs.aws.amazon.com/cli/latest/reference/inspector2/list-findings.html)+and [repository fields](https://docs.aws.amazon.com/inspector/v2/APIReference/API_CodeRepositoryDetails.html).diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.mdindex 221a122c7..3c075e858 100644--- a/docs/scanner-imports/schema-guide.md+++ b/docs/scanner-imports/schema-guide.md@@ -23,6 +23,7 @@ to investigate records together, not instructions to merge them.| [Wiz package JSON or detailed CSV](../../sdk/typescript/docs/cli.md#package-vulnerability-inputs); CSV requires `CloudPlatform=GitHub` and `CloudProviderURL` for a GitHub repository `/tree/<ref>` | Vendor occurrence `id` (CSV: `ID`), not the CVE | Tenant and finding family || [Wiz named repository collections](../../sdk/typescript/docs/cli.md#sast-repository-secrets-and-iac-inputs) | `sast:<id>`, `secret:<id>`, `iac:<id>` | Tenant and finding family || [Endor Finding JSON or endorctl SARIF](endor.md) | Finding `uuid` or SARIF `properties["finding-uuid"]` | Namespace, project and context |+| [Amazon Inspector Code Security ListFindings JSON](inspector.md) | Full Inspector finding ARN | AWS account, Region and repository project || [Snyk Open Source CLI JSON, plugin v1 or SARIF](snyk.md) | CLI: manager, manifest, advisory, package/version and dependency path; plugin: supplied composite; SARIF: advisory, manifest set and project when known | Repository, branch, scan target and format || [Semgrep Code CLI/CI JSON or SARIF](semgrep.md) | Fingerprint; otherwise rule, literal path and start/end lines and columns | Organization, project and branch || [GitHub Dependabot repository REST alerts](github-dependabot.md) | Host, repository and alert number | Host, repository and Dependabot family |@@ -55,6 +56,11 @@ before preparing a fresh submission.normalized JSONL: supply the reviewed `source_finding_id` and `evidence`,retaining the raw row. The reader does not infer a mapping for other CSVprofiles.+- **Amazon Inspector.** Supply a complete export for one repository project.+ A matching native URL or the operator's full project ARN mapping establishes+ the Git host. Local import and Cloud replay check the destination again.+ Each finding ARN identifies one occurrence. Duplicate ARNs exclude all+ colliding rows. Package and code evidence retain the native finding.- **Endor Labs:** Prefer a complete native Finding, array or `list.objects`.`spec.level`, dependency paths/versions, advisory aliases, source SHA andprimary SAST/AI SAST locations map when present. The project UUID does not@@ -78,6 +84,8 @@ before preparing a fresh submission.Critical from High; both become diagnostic `error`, mapped to High, in SemgrepSARIF. Inspect the selected result for trace/fix details. Platform/MCPenvelopes and general Supply Chain/Secrets feeds are not Code CLI or SARIF exports.+- **OpenGrep.** Use native JSON and supply `--source-repository-url`. The+ [OpenGrep guide](opengrep.md) covers export and occurrence identity.- **GitHub:** For code scanning, the selected instance supplies path/range, refand commit. The rule's `security_severity_level` supplies severity; diagnostic`error` alone means `unknown`. An alert-wide dismissal takes precedence overdiff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex 24965a420..b675898f0 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -31,6 +31,10 @@ Read the stored evidence with `codex-security findings imported /path/to/projectLocal records remain unassessed source evidence, separate from `findings list` and completed scans. Repeated imports use the same repository/provider/source-key/source-ID identity; omitted records remain stored. When a source repository URL and local Git remotes are available, the URL must match a remote. Local import does not publish to Cloud or automatically investigate or patch findings.+## Amazon Inspector repository findings++Use `--provider inspector` and `--source-repository-url` with a complete Inspector2 ListFindings export for one Code Security repository. If it contains only a project ARN and name, pass the full `--inspector-project-arn ARN` verified for that Git URL in the SCM integration. Supply the same ARN when resuming a pending Cloud submission. Self-managed GitLab is supported locally.+## Endor Labs findingsFor Endor Labs imports, prefer native Finding JSON from authenticated `endorctl`, scoped to one project and context. Omit `--field-mask` and fetch all pages with `--list-all`:diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex f61a4f885..e701623cb 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -667,6 +667,12 @@ options where supported, and changing formats can change record identities orreplace richer evidence with less detail. See the[import guide](docs/cli.md#import-vendor-findings-locally) for format selection.+For Amazon Inspector Code Security, use `--provider inspector` with a complete+ListFindings JSON export and `--source-repository-url`. When the export identifies+the repository by an ARN and name, pass `--inspector-project-arn ARN` with the ARN+you verified for that Git URL in the SCM integration. See the+[Inspector guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/inspector.md).+For OpenGrep, use `--provider opengrep` with native JSON or gzip and an explicit`--source-repository-url`. Local and Cloud imports retain unassessed OpenGrepevidence through the existing Semgrep source-provider contract. See thediff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 564bb0bdf..faac0880e 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1305,6 +1305,7 @@ Use the same vendor input and parser as Cloud publication, selecting a localrepository path instead of a Cloud repository ID or URL. Supported inputs includeWiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-findings),[Endor Labs Finding JSON and SARIF](#import-endor-labs-findings),+[Amazon Inspector repository findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/inspector.md),[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),[OpenGrep native JSON](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md),[GitHub Dependabot repository alerts](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md),diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.jsonindex f04ad771b..8add329f4 100644--- a/sdk/typescript/schemas/external-findings.schema.json+++ b/sdk/typescript/schemas/external-findings.schema.json@@ -378,7 +378,7 @@"additionalProperties": false,"properties": {"provider": {- "enum": ["wiz", "endor", "snyk", "github", "semgrep"],+ "enum": ["wiz", "endor", "snyk", "github", "semgrep", "inspector"],"title": "Provider","type": "string"},diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.tsindex dd0f46dda..94b194534 100644--- a/sdk/typescript/scripts/fixtures/package-consumer.ts+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts@@ -13,6 +13,7 @@ import {normalizeSnykFindingsExport,prepareNormalizedExternalPublication,type ExternalFindings,+ type FindingImportRequest,type ExternalPublicationOptions,type NormalizedExternalPublicationOptions,type ExternalPublicationResult,@@ -305,7 +306,7 @@ export async function externalPublication(): Promise<ExternalPublicationResult> {const fromFile = await prepareExternalPublication(file, options);fromFile.preview.requests[0]?.source.provider satisfies- "wiz" | "endor" | "snyk" | "github" | "semgrep" | undefined;+ FindingImportRequest["source"]["provider"] | undefined;const prepared = await prepareNormalizedExternalPublication(input, {...options,provider: fromFile.preview.source.provider,diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex c43434cd9..69af86328 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",+ "inspector-findings","snyk-findings","semgrep-findings","native-json-findings",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 24468acfc..7ac811827 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -114,6 +114,7 @@ import {type ExternalPublicationResult,} from "./external-findings-publish.js";import { prepareLocalExternalImport } from "./external-findings-import.js";+import { validateInspectorProjectMapping } from "./inspector-findings.js";import {externalImportsDisabledMessage,externalImportsEnabled,@@ -3572,7 +3573,12 @@ export async function main(sourceRepositoryUrl: optionValue("--source-repository-url").optional().describe(- "Required for Semgrep and OpenGrep: source repository URL, checked against the Cloud destination or configured local Git remotes.",+ "Source repository URL when required by the selected reader. Checked against the Cloud destination or configured local Git remotes.",+ ),+ inspectorProjectArn: optionValue("--inspector-project-arn")+ .optional()+ .describe(+ "Full Inspector project ARN independently verified for --source-repository-url. Required when the report does not identify its repository by URL.",),sourceKey: optionValue("--source-key").describe("Stable vendor tenant and finding namespace; not a project selection filter.",@@ -3674,24 +3680,38 @@ export async function main(try {if (!importsEnabled)throw new CodexSecurityError(externalImportsDisabledMessage);+ const { inspectorProjectArn, ...readerOptions } = options;+ let inspectorProjectMap: Map<string, string> | undefined;+ if (inspectorProjectArn !== undefined) {+ if (options.provider !== "inspector")+ throw new CodexSecurityError(+ "--inspector-project-arn requires --provider inspector.",+ );+ const url = validateInspectorProjectMapping(+ inspectorProjectArn,+ options.sourceRepositoryUrl,+ );+ inspectorProjectMap = new Map([[inspectorProjectArn, url]]);+ }+ const directory = dependencies.currentDirectory();+ const report = resolveCliPath(directory, args.file);+ const repository =+ options.to === "local"+ ? resolveCliPath(directory, options.repository)+ : options.repository;+ const publicationOptions = {+ ...readerOptions,+ repository,+ inspectorProjectMap,+ };if (options.to === "local") {const prepared = await (dependencies.prepareLocalExternalImport ??prepareLocalExternalImport- )(- resolveCliPath(dependencies.currentDirectory(), args.file),- {- ...options,- repository: resolveCliPath(- dependencies.currentDirectory(),- options.repository,- ),- },- {- environment: dependencies.environment,- signal: controller.signal,- },- );+ )(report, publicationOptions, {+ environment: dependencies.environment,+ signal: controller.signal,+ });const { preview } = prepared;const showPreview = () => {showScannerReport(preview);@@ -3728,8 +3748,8 @@ export async function main(return { ...result };}const prepared = await prepareExternalPublication(- resolveCliPath(dependencies.currentDirectory(), args.file),- options,+ report,+ publicationOptions,{environment: dependencies.environment,fetch: dependencies.cloudFetch,diff --git a/sdk/typescript/src/external-findings-import.ts b/sdk/typescript/src/external-findings-import.tsindex 3975eb5b7..f2a402522 100644--- a/sdk/typescript/src/external-findings-import.ts+++ b/sdk/typescript/src/external-findings-import.ts@@ -8,9 +8,10 @@ import {readExternalFindings,} from "./external-findings-read.js";import {- prepareNormalizedLocalImport,+ prepareLocalImport,type LocalExternalImportDependencies,} from "./external-findings-local.js";+import { snapshotImportOptions } from "./external-findings.js";import { abortable } from "./targets.js";import { requireExternalImports } from "./external-imports-feature.js";@@ -22,19 +23,20 @@ export async function prepareLocalExternalImport() {dependencies.signal?.throwIfAborted();requireExternalImports(dependencies.environment);+ const settings = snapshotImportOptions(options);const parsed = await abortable(- () => readExternalFindings(path, options, "local"),+ () => readExternalFindings(path, settings, "local"),dependencies.signal,);const normalizedOptions = {- ...options,- provider: EXTERNAL_FINDINGS_PROVIDERS[options.provider],+ ...settings,+ provider: EXTERNAL_FINDINGS_PROVIDERS[settings.provider],};let sourceRepositories = parsed.sourceRepositories ?? [];if (normalizedOptions.provider === "semgrep") {// The Cloud reader allows custom GitHub casing. Local provenance must also// agree with the caller's source URL when the checkout has no remote.- const source = options.sourceRepositoryUrl!;+ const source = settings.sourceRepositoryUrl!;const knownGitHub = dependencies.sourceRepositories?.some(({ url, platform }) =>platform === "github" &&@@ -57,7 +59,7 @@ export async function prepareLocalExternalImport(];}const { environment, ...workbench } = dependencies;- return prepareNormalizedLocalImport(parsed.findings, normalizedOptions, {+ return prepareLocalImport(parsed.findings, normalizedOptions, {...workbench,environment,sourceRepositories: [diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex 4163473cc..1916e8897 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -7,9 +7,10 @@ import {forwardExternalImportSetting,requireExternalImports,} from "./external-imports-feature.js";-import type {- ExternalFindings,- ExternalSourceRepository,+import {+ snapshotImportOptions,+ type ExternalFindings,+ type ExternalSourceRepository,} from "./external-findings.js";import {cloudRepositoryUrlKey,@@ -20,7 +21,8 @@ import type {ExternalFindingEvidence,Provider,} from "./external-import-models.js";-import { parseGitRemote } from "./git-remote.js";+import { isGitHubCloudHost, parseGitRemote } from "./git-remote.js";+import { inspectorReportRepository } from "./inspector-findings.js";import { isRecord } from "./record.js";import { dependabotRepository } from "./github-dependabot-findings.js";import {@@ -62,6 +64,8 @@ export interface NormalizedLocalImportOptions {provider: Provider;/** Stable scanner organization/project/branch namespace across imports. */sourceKey: string;+ /** Full Inspector project ARNs mapped to independently verified repository URLs. */+ inspectorProjectMap?: ReadonlyMap<string, string>;}export interface LocalExternalImportDependencies {@@ -102,34 +106,47 @@ function requireIdentity();}+const gitTransportPorts: Readonly<Record<string, string>> = {+ "http:": "80",+ "https:": "443",+ "ssh:": "22",+ "git+ssh:": "22",+ "ssh+git:": "22",+ "git:": "9418",+ "ftp:": "21",+ "ftps:": "990",+};+/** Compare transport forms without changing retained scanner evidence. */-function remoteRepositoryKey(+function remoteRepository(value: string,provider: Provider,-): string | undefined {+ bound: boolean,+): { key: string; account?: string; homeRelative?: boolean } | undefined {if (/^[A-Za-z]:[\\/]/u.test(value)) return undefined;+ const transport = bound+ ? /^(?:ssh|git\+ssh|ssh\+git|git):\/\/([^/]*)(.*)$/isu.exec(value)+ : null;+ const authority = transport?.[1];+ const http = bound && /^https?:\/\//iu.test(value.trimStart());+ // Git decodes the authority before locating its path. An encoded delimiter+ // cannot prove a match to another spelling through WHATWG URL's hostname.+ if (+ authority &&+ (/%2f|[?#]/iu.test(authority) ||+ authority.slice(authority.lastIndexOf("@") + 1).includes("%"))+ )+ return { key: value };let remote;try {remote = parseGitRemote(value);} catch {- return undefined;+ return transport || http ? { key: "\0" + value } : undefined;}- if (- !remote ||- ![- "http:",- "https:",- "ssh:",- "git:",- "ftp:",- "ftps:",- "git+ssh:",- "ssh+git:",- ].includes(remote.url.protocol)- )+ if (!remote || !Object.hasOwn(gitTransportPorts, remote.url.protocol))return undefined;- const url = remote.url;- const ssh = ["ssh:", "git+ssh:", "ssh+git:"].includes(url.protocol);+ const { url, path, scpStyle } = remote;+ const ssh = url.protocol.includes("ssh");const protocol = url.protocol === "http:" ? "http:" : "https:";const githubSshOverHttps =ssh &&@@ -137,19 +154,74 @@ function remoteRepositoryKey(url.port === "443";const hostname = githubSshOverHttps ? "github.com" : url.hostname;const port =- githubSshOverHttps ||- (ssh && url.port === "22") ||- (url.protocol === "git:" && url.port === "9418") ||- (url.protocol === "ftp:" && url.port === "21") ||- (url.protocol === "ftps:" && url.port === "990")+ githubSshOverHttps || url.port === gitTransportPorts[url.protocol]? "": url.port;// A GitHub source identifies a case-insensitive repository on custom Enterprise// hosts too; other providers can refer to VCS hosts with case-sensitive paths.const key = provider === "github" ? cloudRepositoryUrlKey : repositoryUrlKey;- return key(- `${protocol}//${hostname}${port ? `:${port}` : ""}/${remote.path}`,- );+ const origin = `${protocol}//${hostname}${port ? `:${port}` : ""}/`;+ if (!bound) return { key: key(origin + path) };++ if (!ssh && url.protocol !== "git:") {+ if (url.protocol === "http:" || url.protocol === "https:") {+ // libcurl and WHATWG differ on backslashes and encoded dot segments.+ const raw = /^https?:\/\/[^/\\?#\s]+(\/[^\\?#]*)?(?:[?#].*)?$/iu.exec(+ value,+ );+ if (!raw || /\/(?:%2e|\.%2e|%2e\.|%2e%2e)(?:\/|$)/iu.test(raw[1] ?? ""))+ return { key: "\0" + value };+ }+ const suffix = /[?#].*$/su.exec(value)?.[0] ?? "";+ // HTTP sends the query and omits fragment text from repository requests.+ if (suffix && !["http:", "https:"].includes(url.protocol))+ return { key: key(origin + path) + "\0" };+ return {+ key:+ key(origin + path) + suffix.replace(/#.*$/su, "#").replace(/\/$/u, ""),+ };+ }++ // Git passes the original path (including dot segments, '?' and '#') to upload-pack.+ const literal = (raw: string) => {+ const bytes = Buffer.from(raw).toString("latin1");+ return scpStyle+ ? bytes+ : bytes.replace(/%(?!00)([\da-f]{2})/giu, (_, hex: string) =>+ String.fromCharCode(parseInt(hex, 16)),+ );+ };+ if (!scpStyle && !transport) return { key: value };+ const gitPath = literal(transport?.[2] ?? path);+ const login = scpStyle+ ? /^([^@/:\s?#]+)@/u.exec(value)?.[1]+ : /^(.*)@/u.exec(authority ?? "")?.[1];+ const homeRelative =+ /^\/?~(?:\/|$)/u.test(gitPath) || (scpStyle && !/^[~/]/u.test(gitPath));+ const suffix = /[?#].*$/su.exec(gitPath);+ // Express upload-pack bytes as a URL path for comparison with the HTTP source.+ const name = gitPath+ .slice(0, suffix?.index)+ .replace(/^\//u, "")+ .replace(+ /[%\x00-\x20\x7f-\xff]/gu,+ (byte) =>+ "%" + byte.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"),+ );+ const repository = suffix+ ? key(origin + name + "?") ++ "\0" ++ suffix[0].replace(/\/$/u, "").replace(/\.git$/u, "")+ : key(origin + name);+ return {+ key: repository,+ account: ssh && login ? literal(login) : undefined,+ // GitHub serves the same repository path through its SCP and SSH URLs.+ homeRelative:+ ssh && provider !== "github" && !isGitHubCloudHost(hostname.toLowerCase())+ ? homeRelative+ : undefined,+ };}async function bareMetadataRoots(@@ -397,29 +469,41 @@ async function requireMatchingRepository(const urls = await readGit(["remote", "get-url", "--all", "--", name]);remotes.push(...urls.split(/\r?\n/u));}+ const identity = (value: string, platform: Provider) =>+ remoteRepository(value, platform, provider === "inspector");const githubRepositories = new Set(sources.flatMap((source) => {if (source.platform !== "github") return [];- const key = remoteRepositoryKey(source.url, "github");+ const key = identity(source.url, "github")?.key;return key === undefined ? [] : [key];}),);for (const source of sources) {- const githubKey = remoteRepositoryKey(source.url, "github");+ const githubKey = identity(source.url, "github")?.key;const sourceProvider =source.platform === "github" ||(githubKey !== undefined && githubRepositories.has(githubKey))? "github": provider;- const remoteKeys = new Set(- remotes.flatMap((remote) => {- const key = remoteRepositoryKey(remote, sourceProvider);- return key === undefined ? [] : [key];- }),+ const targets = remotes.flatMap(+ (remote) => identity(remote, sourceProvider) ?? [],);- if (remoteKeys.size === 0) continue;- const key = remoteRepositoryKey(source.url, sourceProvider);- if (key === undefined || !remoteKeys.has(key))+ if (!targets.length) continue;+ const target = identity(source.url, sourceProvider);+ if (+ !target ||+ !targets.some(+ ({ key, account, homeRelative }) =>+ key === target.key &&+ (homeRelative === undefined ||+ target.homeRelative === undefined ||+ homeRelative === target.homeRelative) &&+ ((homeRelative === false && target.homeRelative === false) ||+ account === undefined ||+ target.account === undefined ||+ account === target.account),+ )+ )throw new CodexSecurityError(`Imported repository ${JSON.stringify(source.url)} does not match a configured remote of ${repository}. Select the matching local repository.`,);@@ -490,6 +574,19 @@ export async function prepareNormalizedLocalImport(): Promise<PreparedLocalExternalImport> {dependencies.signal?.throwIfAborted();requireExternalImports(dependencies.environment);+ return prepareLocalImport(+ input,+ snapshotImportOptions(options),+ dependencies,+ );+}++/** @internal Prepare evidence using settings captured by either local import entrypoint. */+export async function prepareLocalImport(+ input: ExternalFindings,+ options: NormalizedLocalImportOptions,+ dependencies: LocalExternalImportDependencies,+): Promise<PreparedLocalExternalImport> {requireIdentity(options.sourceKey, "Source key");const current = structuredClone(input);validateExternalReport(current.report);@@ -526,14 +623,36 @@ export async function prepareNormalizedLocalImport(dependencies,);const sources = new Map<string, ExternalSourceRepository>();- for (const { evidence } of current.findings) {- const url = evidence.details?.repository?.url;+ for (const finding of current.findings) {+ const url = finding.evidence.details?.repository?.url;if (url) sources.set(url, { url });}- for (const source of dependencies.sourceRepositories ?? []) {- // A reader's explicit platform also applies to the same URL in typed evidence.+ const inspector = inspectorReportRepository(+ options.provider,+ current.findings,+ "local",+ options.inspectorProjectMap,+ );+ if (inspector) {+ const platform = inspector.platform ?? options.provider;+ const native = remoteRepository(inspector.url, platform, true);+ for (const url of sources.keys()) {+ if (!native || remoteRepository(url, platform, true)?.key !== native.key)+ throw new CodexSecurityError(+ `Imported repository ${JSON.stringify(url)} does not match the retained Inspector repository ${JSON.stringify(inspector.url)}.`,+ );+ }+ }+ for (const source of [+ ...(inspector ? [inspector] : []),+ ...(dependencies.sourceRepositories ?? []),+ ]) {+ // A reader's platform must not loosen an operator-supplied Inspector map.if (sources.get(source.url)?.platform !== "github")- sources.set(source.url, source);+ sources.set(+ source.url,+ options.inspectorProjectMap ? { url: source.url } : source,+ );}if (dependabotSource)sources.set(dependabotSource, {diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 19db12b22..a47ab0e95 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -35,9 +35,11 @@ import { wizCsvRepositoryUrl } from "./wiz-csv.js";import { dependabotRepository } from "./github-dependabot-findings.js";import { snykRepositoryUrls } from "./snyk-findings.js";import { endorRepositoryUrls } from "./endor-findings.js";-import type {- ExternalFindings,- ExternalPublicationInput,+import { inspectorReportRepository } from "./inspector-findings.js";+import {+ snapshotImportOptions,+ type ExternalFindings,+ type ExternalPublicationInput,} from "./external-findings.js";import {cloudRepositoryUrlKey,@@ -63,6 +65,8 @@ export interface NormalizedExternalPublicationOptions {repository: string;provider: FindingImportRequest["source"]["provider"];sourceKey: string;+ /** Full Inspector project ARNs mapped to independently verified repository URLs. */+ inspectorProjectMap?: ReadonlyMap<string, string>;}/** File readers accept the vendor formats installed in this SDK. */@@ -129,6 +133,7 @@ interface SavedSubmission {requests: FindingImportRequest[];receipts?: FindingImportReceipt[];inputProjection?: { inputDigest: string; savedEvidenceDigest: string };+ inspectorProjectMapRequired?: true;}export interface ExternalPublicationPreview extends ExternalFindings {@@ -171,6 +176,7 @@ function sameSubmission(): boolean {return (left.accountId === right.accountId &&+ left.inspectorProjectMapRequired === right.inspectorProjectMapRequired &&canonicalJson(left.requests) === canonicalJson(right.requests));}@@ -348,22 +354,13 @@ export async function prepareExternalPublication(dependencies: ExternalPublicationDependencies = {},): Promise<PreparedExternalPublication> {requireExternalImports(dependencies.environment);- const parsed = await readExternalFindings(path, options);- const normalizedOptions = {- ...options,- provider: EXTERNAL_FINDINGS_PROVIDERS[options.provider],- };- return parsed.publication- ? preparePublicationInput(- parsed.publication,- normalizedOptions,- dependencies,- )- : prepareNormalizedExternalPublication(- parsed.findings,- normalizedOptions,- dependencies,- );+ const settings = snapshotImportOptions(options);+ const parsed = await readExternalFindings(path, settings);+ return preparePublicationInput(+ parsed.publication ?? normalizedPublicationInput(parsed.findings),+ { ...settings, provider: EXTERNAL_FINDINGS_PROVIDERS[settings.provider] },+ dependencies,+ );}/** Prepare normalized provider evidence without reading a vendor export. */@@ -373,6 +370,17 @@ export async function prepareNormalizedExternalPublication(dependencies: ExternalPublicationDependencies = {},): Promise<PreparedExternalPublication> {requireExternalImports(dependencies.environment);+ const settings = snapshotImportOptions(options);+ return preparePublicationInput(+ normalizedPublicationInput(input),+ settings,+ dependencies,+ );+}++function normalizedPublicationInput(+ input: ExternalFindings,+): ExternalPublicationInput {// Validation adds Cloud defaults; leave the caller's objects unchanged.const { report, ...parsed } = input;const current: ExternalFindings = structuredClone(parsed);@@ -405,16 +413,12 @@ export async function prepareNormalizedExternalPublication(current.report === undefined? current.findings: { findings: current.findings, report: reportForJson(current.report) };- return preparePublicationInput(- {- current,- legacy: current,- currentIdentity: identity,- legacyIdentity: identity,- },- options,- dependencies,- );+ return {+ current,+ legacy: current,+ currentIdentity: identity,+ legacyIdentity: identity,+ };}async function preparePublicationInput(@@ -422,6 +426,7 @@ async function preparePublicationInput(options: NormalizedExternalPublicationOptions,dependencies: ExternalPublicationDependencies,): Promise<PreparedExternalPublication> {+ const { inspectorProjectMap } = options;const progress = (event: ExternalPublicationProgress): void => {try {dependencies.onProgress?.(event);@@ -727,36 +732,56 @@ async function preparePublicationInput(}}}- let requests = saved?.requests;- if (!requests) {- for (const finding of parsed.findings) {- const sourceRepositories = [- finding.evidence.details?.repository?.url,- ...(options.provider === "wiz"- ? [wizCsvRepositoryUrl(finding.evidence)]- : []),+ if (saved?.inspectorProjectMapRequired && !inspectorProjectMap)+ throw new CodexSecurityError(+ "Supply the verified Inspector project binding again to resume.",+ );++ function checkRepositories(findings: ExternalFindings["findings"]) {+ // Validated non-Inspector checkpoints retain their original provider and repository ID.+ if (saved && options.provider !== "inspector") return;+ const binding = inspectorReportRepository(+ options.provider,+ findings,+ "cloud",+ inspectorProjectMap,+ );+ function requireDestination(id: string, url: string | null | undefined) {+ if (+ url &&+ cloudRepositoryUrlKey(url) !== cloudRepositoryUrlKey(destination.url)+ )+ throw new CodexSecurityError(+ `Finding ${JSON.stringify(id)} belongs to ${JSON.stringify(url)}, which does not match the selected Cloud repository ${JSON.stringify(destination.url)}. Verify the source repository mapping before publishing.`,+ );+ }+ if (binding) requireDestination(binding.findingId, binding.url);+ for (const finding of findings) {+ const { source_finding_id: id, evidence } = finding;+ const urls = [+ evidence.details?.repository?.url,+ ...(options.provider === "wiz" ? [wizCsvRepositoryUrl(evidence)] : []),...(options.provider === "snyk"- ? snykRepositoryUrls(finding.evidence.source_data, {+ ? snykRepositoryUrls(evidence.source_data, {cloudRepositoryUrl: destination.url,}): []),...(options.provider === "endor"- ? endorRepositoryUrls(finding.evidence.source_data)+ ? endorRepositoryUrls(evidence.source_data): []),options.provider === "github"? dependabotRepository(finding): undefined,];- for (const sourceRepository of sourceRepositories)- if (- sourceRepository &&- cloudRepositoryUrlKey(sourceRepository) !==- cloudRepositoryUrlKey(destination.url)- )- throw new CodexSecurityError(- `Finding ${JSON.stringify(finding.source_finding_id)} belongs to ${JSON.stringify(sourceRepository)}, which does not match the selected Cloud repository ${JSON.stringify(destination.url)}. Verify the source repository mapping before publishing.`,- );+ for (const url of urls) requireDestination(id, url);}+ }+ checkRepositories(parsed.findings);+ // A retry sends its saved projection, which may differ from today's reader.+ if (saved) checkRepositories(submissionFindings(saved.requests));++ let requests = saved?.requests;+ if (!requests) {let preparedCount = 0;progress({phase: "preparing",@@ -859,6 +884,7 @@ async function preparePublicationInput(),},};+ if (inspectorProjectMap) submission.inspectorProjectMapRequired = true;const preview: ExternalPublicationPreview = {...parsed,findings: submissionFindings(requests),@@ -927,6 +953,10 @@ async function preparePublicationInput(pending === undefined? submission: (JSON.parse(pending) as SavedSubmission);+ const adoptProjectMap =+ submission.inspectorProjectMapRequired &&+ current.inspectorProjectMapRequired === undefined;+ if (adoptProjectMap) current.inspectorProjectMapRequired = true;if (!sameSubmission(current, submission))throw new CodexSecurityError("Another publication prepared this input. Run the command again to review and resume that saved request.",@@ -940,8 +970,8 @@ async function preparePublicationInput(let verified = 0;let persisted = pending !== undefined;try {- if (pending === undefined) {- await writeAtomicJson(pendingPath, submission);+ if (pending === undefined || adoptProjectMap) {+ await writeAtomicJson(pendingPath, current);persisted = true;}progress({diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex d9b43d2fe..36c8a731f 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -11,6 +11,7 @@ import { readSemgrepFindings } from "./semgrep-findings.js";import { readOpenGrepFindings } from "./opengrep-findings.js";import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";import { readGitHubFindings } from "./github-findings.js";+import { readInspectorFindings } from "./inspector-findings.js";import { isGitHubCloudHost } from "./git-remote.js";import { isRecord } from "./record.js";import { readVendorFindingsForPublication } from "./wiz-findings.js";@@ -24,6 +25,7 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {opengrep: "semgrep",endor: "endor",github: "github",+ inspector: "inspector",} as const satisfies Record<string, Provider>;export type ExternalFindingsReader = keyof typeof EXTERNAL_FINDINGS_PROVIDERS;@@ -36,6 +38,7 @@ export const EXTERNAL_FINDINGS_READERS = Object.keys(export interface ExternalFindingsReaderOptions {provider: ExternalFindingsReader;sourceRepositoryUrl?: string;+ inspectorProjectMap?: ReadonlyMap<string, string>;}/** @internal Shared parser output, including immutable Cloud retry projections. */@@ -112,6 +115,18 @@ export async function readExternalFindings(}if (options.provider === "github")return { findings: await readGitHubFindings(path, target) };+ if (options.provider === "inspector") {+ const url = options.sourceRepositoryUrl ?? "";+ return {+ findings: await readInspectorFindings(+ path,+ url,+ target,+ options.inspectorProjectMap,+ ),+ sourceRepositories: [{ url }],+ };+ }const publication = await readVendorFindingsForPublication(path, target);// Raw package exports keep repository-branch URLs in retained source data.const sourceRepositories = publication.current.findings.flatMap(diff --git a/sdk/typescript/src/external-findings.ts b/sdk/typescript/src/external-findings.tsindex 113d3e907..1b717a16d 100644--- a/sdk/typescript/src/external-findings.ts+++ b/sdk/typescript/src/external-findings.ts@@ -1,3 +1,5 @@+import { CodexSecurityError } from "./errors.js";+import type { ExternalPublicationOptions } from "./external-findings-publish.js";import type { ExternalFindingEvidence } from "./external-import-models.js";/** A provider occurrence and its evidence, independent of a Codex assessment. */@@ -31,3 +33,26 @@ export interface ExternalPublicationInput {currentIdentity: unknown;legacyIdentity: unknown;}++/** Capture the caller's import settings before reading an export or resolving its destination. */+export function snapshotImportOptions<+ P extends ExternalPublicationOptions["provider"],+>({+ repository,+ provider,+ sourceKey,+ sourceRepositoryUrl,+ inspectorProjectMap,+}: ExternalPublicationOptions & { provider: P }) {+ if (inspectorProjectMap !== undefined && provider !== "inspector")+ throw new CodexSecurityError(+ "An Inspector project map requires the inspector provider.",+ );+ return {+ repository,+ provider,+ sourceKey,+ sourceRepositoryUrl,+ inspectorProjectMap: inspectorProjectMap && new Map(inspectorProjectMap),+ };+}diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.tsindex 1f55518c0..8ea786f61 100644--- a/sdk/typescript/src/external-import-models.ts+++ b/sdk/typescript/src/external-import-models.ts@@ -5,7 +5,8 @@ export type Id = string;export type RepoConnectorId = string;export type EnvironmentId = string;export type ResetMarker = string;-export type Provider = "wiz" | "endor" | "snyk" | "github" | "semgrep";+export type Provider =+ "wiz" | "endor" | "snyk" | "github" | "semgrep" | "inspector";export type SourceKey = string;export type ClientId = string;export type SourceFindingId = string;diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 7d5cadd70..f3d752e32 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -331,6 +331,10 @@ export {readOpenGrepFindings,type OpenGrepImportOptions,} from "./opengrep-findings.js";+export {+ normalizeInspectorFindings,+ readInspectorFindings,+} from "./inspector-findings.js";export {normalizeSnykFindingsExport,normalizeSnykJson,diff --git a/sdk/typescript/src/inspector-findings.ts b/sdk/typescript/src/inspector-findings.tsnew file mode 100644index 000000000..e81782df6--- /dev/null+++ b/sdk/typescript/src/inspector-findings.ts@@ -0,0 +1,728 @@+import { posix } from "node:path";+import { z } from "zod";+import validSemver from "semver/functions/valid.js";+import type {+ ExternalFinding,+ ExternalFindings,+ ExternalSourceRepository,+} from "./external-findings.js";+import {+ cloudRepositoryUrlKey,+ repositoryUrlKey,+ validateExternalEvidence,+ type ExternalImportTarget,+} from "./external-import-contract.js";+import { isGitHubCloudHost } from "./git-remote.js";+import { CodexSecurityError, errorMessage } from "./errors.js";+import type { Provider } from "./external-import-models.js";+import { isRecord } from "./record.js";+import {+ normalizeRecords,+ readScannerJson,+ record,+ relativePath,+ requiredText,+ text,+} from "./scanner-import.js";++type Native = Record<string, unknown>;++const listFindings = z.strictObject({ findings: z.array(z.unknown()) });+const format = "aws-inspector2-list-findings/v1";+const findingArn =+ /^(arn:(aws[a-zA-Z-]*):inspector2:([a-z]{2}(?:-gov)?-[a-z]+-\d):(\d{12})):finding\/[a-f0-9]{32}$/u;+const integrationArn =+ /^arn:aws[a-zA-Z-]*:inspector2:[a-z]{2}(?:-gov)?-[a-z]+-\d:\d{12}:codesecurity-integration\/[a-f0-9-]{36}$/u;+const projectSuffix =+ /^project-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u;+const absoluteUrl = /^[a-z][a-z\d+.-]*:\/\//iu;++function repositoryUrl(value: unknown): string {+ const raw = requiredText(value, "Inspector --source-repository-url");+ const url = URL.parse(raw);+ const path = /^https?:\/\/[^/?#]+(\/[^?#]+)$/iu.exec(raw)?.[1];+ if (+ !url ||+ !path ||+ url.username ||+ url.password ||+ /[\s\\?#]|%(?:2f|5c)/iu.test(raw) ||+ path !== url.pathname ||+ !/^\/[^/]+(?:\/[^/]+)+\/?$/u.test(path)+ )+ throw new Error(+ "Use a complete HTTP(S) Inspector source repository URL with a namespace and repository, without credentials, query or fragment.",+ );+ return raw;+}++function projectIntegration(projectArn: string): string {+ const separator = projectArn.lastIndexOf("/");+ const parent = projectArn.slice(0, separator);+ if (+ !integrationArn.test(parent) ||+ !projectSuffix.test(projectArn.slice(separator + 1))+ )+ throw new Error("Expected a full Inspector repository project ARN.");+ return parent;+}++/** @internal Validate an operator-supplied project binding. */+export function validateInspectorProjectMapping(+ projectArn: string,+ canonicalUrl: unknown,+): string {+ projectIntegration(projectArn);+ return repositoryUrl(canonicalUrl);+}++function identity(finding: Native) {+ const arn = requiredText(finding["findingArn"], "Inspector finding ARN");+ const match = findingArn.exec(arn);+ if (!match) throw new Error("Expected an Inspector2 finding ARN.");+ if (finding["awsAccountId"] !== match[4])+ throw new Error("Inspector finding ARN and AWS account do not match.");+ return {+ arn,+ issuer: match[1]!,+ partition: match[2]!,+ region: match[3]!,+ account: match[4]!,+ };+}++function repositoryClaim(+ { issuer, partition, region, account }: ReturnType<typeof identity>,+ resource: Native,+) {+ for (const [field, expected] of Object.entries({+ partition,+ region,+ provider: "AWS",+ providerAccountId: account,+ })) {+ if (resource[field] !== undefined && resource[field] !== expected)+ throw new Error(+ "Inspector repository resource and finding scope do not match.",+ );+ }+ const { codeRepository } = record(+ resource["details"] ?? {},+ "Inspector resource details",+ );+ const repo = record(codeRepository ?? {}, "Inspector codeRepository");+ const optional = (field: string) =>+ repo[field] === undefined+ ? undefined+ : requiredText(repo[field], `Inspector codeRepository.${field}`);+ const nativeId = requiredText(+ resource["id"],+ "Inspector repository resource ID",+ );+ let integration = optional("integrationArn");+ if (+ integration !== undefined &&+ (!integration.startsWith(issuer + ":") || !integrationArn.test(integration))+ )+ throw new Error(+ "Inspector integration ARN does not match the finding scope.",+ );+ if (nativeId.startsWith("arn:")) {+ const parent = projectIntegration(nativeId);+ if (+ !parent.startsWith(issuer + ":") ||+ (integration !== undefined && parent !== integration)+ )+ throw new Error(+ "Inspector repository resource ARN does not match its project or integration.",+ );+ integration = parent;+ }+ return {+ project: JSON.stringify([issuer, nativeId]),+ integration,+ provider: optional("providerType"),+ nativeId,+ name: optional("projectName"),+ };+}++function checkRepositoryMapping(+ { nativeId, name }: ReturnType<typeof repositoryClaim>,+ source: string,+ provider: string | undefined,+ target: ExternalImportTarget,+ projectMap?: ReadonlyMap<string, string>,+) {+ const hostname = new URL(source).hostname;+ const knownGitHub = isGitHubCloudHost(hostname);+ const gitlab = provider === "GITLAB_SELF_MANAGED";+ const github = provider === "GITHUB" || knownGitHub;+ if (+ hostname === "gitlab.com" ||+ (gitlab && knownGitHub) ||+ (provider !== undefined && !gitlab && provider !== "GITHUB")+ )+ throw new Error(+ "Inspector repository provider does not match the selected mapping.",+ );+ if (target === "cloud" && !github)+ throw new Error(+ "Inspector Cloud requires a GitHub repository provider; self-managed GitLab is local only.",+ );+ const urls = [nativeId, name].filter(+ (url): url is string => !!url && absoluteUrl.test(url),+ );+ const key = github && !projectMap ? cloudRepositoryUrlKey : repositoryUrlKey;+ const path = new URL(+ (github ? cloudRepositoryUrlKey : repositoryUrlKey)(source),+ ).pathname.slice(1);+ const slug = github ? name?.toLowerCase() : name;+ const matchesSlug =+ !slug ||+ absoluteUrl.test(slug) ||+ slug === path ||+ slug === posix.basename(path) ||+ (gitlab && projectMap && path.endsWith("/" + slug));+ if (+ !matchesSlug ||+ urls.some((url) => key(repositoryUrl(url)) !== key(source))+ )+ throw new Error(+ "Inspector native repository does not match --source-repository-url.",+ );+ if (projectMap) {+ // repositoryClaim validated this ARN and its issuer before the lookup.+ const trustedUrl = nativeId.startsWith("arn:")+ ? projectMap.get(nativeId)+ : undefined;+ if (trustedUrl === undefined)+ throw new Error(+ "Inspector project ARN is missing from the trusted mapping.",+ );+ if (+ repositoryUrlKey(repositoryUrl(trustedUrl)) !== repositoryUrlKey(source)+ )+ throw new Error(+ "Inspector project ARN mapping does not match the source repository URL.",+ );+ return true;+ }+ return urls.length > 0;+}++function repositoryClaims(finding: unknown) {+ if (!isRecord(finding) || !Array.isArray(finding["resources"])) return [];+ const claims = [];+ let origin: ReturnType<typeof identity> | undefined;+ for (const resource of finding["resources"]) {+ if (!isRecord(resource) || resource["type"] !== "CODE_REPOSITORY") continue;+ origin ??= identity(finding);+ claims.push(repositoryClaim(origin, resource));+ }+ return claims;+}++/** Claims from the whole export must identify one project, including excluded rows. */+function checkReportScope<+ T extends { claims: ReturnType<typeof repositoryClaims>; source: string },+>(+ rows: readonly T[],+ target: ExternalImportTarget,+ projectMap?: ReadonlyMap<string, string>,+ exclude: (row: T, error: unknown) => void = (_, error) => {+ throw error;+ },+): string | undefined {+ const claims = rows.flatMap((row) => row.claims);+ function shared(field: "project" | "integration" | "provider") {+ const values = new Set(claims.map((claim) => claim[field]));+ values.delete(undefined);+ if (values.size > 1)+ throw new Error(+ "Inspector export identifies more than one repository project or integration.",+ );+ return values.values().next().value;+ }+ shared("project");+ shared("integration");+ const provider = shared("provider");+ type Claim = ReturnType<typeof repositoryClaim>;+ // A bare project ID can recur across integrations in the same account and Region.+ const sharedProvider = claims.find(+ (claim) => claim.integration && claim.provider,+ )?.provider;+ const providerFor = (claim: Claim) =>+ claim.provider ?? (claim.integration ? sharedProvider : undefined);+ const missingHost = () =>+ new Error(+ "Inspector needs a matching native repository URL or a trusted project ARN mapping to identify the Git host.",+ );+ const needHost = [];+ let sharedHost = false;+ for (const row of rows) {+ try {+ // Only a fully verified row can supply evidence to another row.+ const scopedMatches = row.claims.flatMap((claim) => {+ const proven = checkRepositoryMapping(+ claim,+ row.source,+ providerFor(claim),+ target,+ projectMap,+ );+ if (claim.integration) return [proven];+ if (!proven) throw missingHost();+ return [];+ });+ if (scopedMatches.includes(true)) sharedHost = true;+ else if (scopedMatches.length) needHost.push(row);+ } catch (error) {+ exclude(row, error);+ }+ }+ if (!sharedHost) for (const row of needHost) exclude(row, missingHost());+ return claims.every((claim) => providerFor(claim) === provider)+ ? provider+ : undefined;+}++const nonempty = z.string().regex(/\S/u, "Expected nonempty text.");+const optionalValue = z.unknown().optional();+const absent = z.never().optional();+const vulnerablePackage = z.object({+ name: nonempty,+ version: nonempty,+ packageManager: optionalValue,+ epoch: optionalValue,+ release: optionalValue,+ fixedInVersion: optionalValue,+ filePath: optionalValue,+ sourceLayerHash: absent,+ sourceLambdaLayerArn: absent,+});+const repositoryFinding = z.object({+ type: z.enum(["PACKAGE_VULNERABILITY", "CODE_VULNERABILITY"]),+ resources: z+ .array(+ z.object({+ type: z.literal("CODE_REPOSITORY"),+ details: z.strictObject({ codeRepository: optionalValue }).nullish(),+ }),+ )+ .min(1),+ networkReachabilityDetails: absent,+ packageVulnerabilityDetails: z+ .object({+ vulnerabilityId: nonempty,+ source: nonempty,+ sourceUrl: optionalValue,+ relatedVulnerabilities: z.array(nonempty).nullish(),+ vulnerablePackages: z.array(vulnerablePackage).nullish(),+ })+ .optional(),+ codeVulnerabilityDetails: z+ .object({+ detectorName: nonempty,+ detectorId: nonempty,+ cwes: z.array(z.unknown()),+ filePath: z.object({+ fileName: optionalValue,+ filePath: optionalValue,+ startLine: optionalValue,+ }),+ sourceLambdaLayerArn: absent,+ })+ .optional(),+});+function selectedFinding(value: unknown) {+ const native = record(value, "Inspector finding");+ const parsed = repositoryFinding.safeParse(native);+ if (!parsed.success)+ throw new Error(+ `Expected an Inspector vulnerability on CODE_REPOSITORY resources. ${z.prettifyError(parsed.error)}`,+ );+ const {+ type,+ packageVulnerabilityDetails: pkg,+ codeVulnerabilityDetails: code,+ } = parsed.data;+ if (+ (pkg && type !== "PACKAGE_VULNERABILITY") ||+ (code && type !== "CODE_VULNERABILITY")+ )+ throw new Error(+ "Inspector finding contains details for a different finding type.",+ );+ return { native, pkg, code };+}++function isInspectorFinding(value: unknown, occurrenceId?: string): boolean {+ return (+ isRecord(value) &&+ typeof value["findingArn"] === "string" &&+ findingArn.test(value["findingArn"]) &&+ (occurrenceId === undefined || value["findingArn"] === occurrenceId) &&+ Array.isArray(value["resources"])+ );+}++function hasInspectorEvidence(+ sourceData: unknown,+ occurrenceId?: string,+): boolean {+ return (+ isRecord(sourceData) &&+ (sourceData["format"] === format ||+ isInspectorFinding(sourceData["finding"], occurrenceId) ||+ isInspectorFinding(sourceData, occurrenceId))+ );+}++export function inspectorReportRepository(+ provider: Provider,+ findings: readonly ExternalFinding[],+ target: ExternalImportTarget,+ projectMap?: ReadonlyMap<string, string>,+): (ExternalSourceRepository & { findingId: string }) | undefined {+ if (provider !== "inspector") {+ if (+ findings.some(({ evidence, source_finding_id }) =>+ hasInspectorEvidence(evidence.source_data, source_finding_id),+ )+ )+ throw new CodexSecurityError(+ "Retained Inspector evidence requires the inspector provider.",+ );+ return undefined;+ }+ const retained = [];+ for (const { source_finding_id: id, evidence } of findings) {+ const data = evidence.source_data;+ if (!isRecord(data) || data["format"] !== format) {+ if (projectMap || hasInspectorEvidence(data) || findingArn.test(id))+ throw new Error(+ "Expected retained Inspector ListFindings evidence for the finding ARN.",+ );+ continue;+ }+ const source = repositoryUrl(data["sourceRepositoryUrl"]);+ const { native: finding } = selectedFinding(data["finding"]);+ if (finding["findingArn"] !== id)+ throw new Error(+ "Inspector source_finding_id does not match the retained finding ARN.",+ );+ retained.push({+ source,+ claims: repositoryClaims(finding),+ id,+ declared: evidence.details?.repository?.url,+ });+ }+ const first = retained[0];+ if (!first) return undefined;+ // A supplied map owns the path casing on custom hosts.+ const github =+ checkReportScope(retained, target, projectMap) === "GITHUB" && !projectMap;+ const key =+ github || target === "cloud" ? cloudRepositoryUrlKey : repositoryUrlKey;+ const repository = key(first.source);+ for (const { source, declared } of retained) {+ if (key(source) !== repository)+ throw new Error(+ "Inspector export identifies more than one source repository.",+ );+ if (declared && key(declared) !== repository)+ throw new Error(+ "Retained scanner repository does not match the normalized evidence repository.",+ );+ }+ return {+ findingId: first.id,+ url: first.source,+ ...(github && { platform: "github" }),+ };+}++function repoFile(value: unknown): string | null {+ const relative = relativePath(value);+ if (!relative) return null;+ const path = posix.normalize(relative);+ return path === "." ||+ path.endsWith("/") ||+ /^(?:[a-z][a-z\d+.-]*:|~[^/]*(?:\/|$)|[^/]+@[^/]+:)/iu.test(path)+ ? null+ : path;+}++function timestamp(value: unknown): number {+ const seconds =+ typeof value === "number"+ ? value+ : typeof value === "string" &&+ /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/u.test(+ value,+ )+ ? Date.parse(value) / 1000+ : NaN;+ if (!Number.isFinite(seconds))+ throw new Error("Invalid Inspector timestamp.");+ return Math.floor(seconds);+}++const ecosystems = new Map(+ Object.entries({+ BUNDLER: "rubygems",+ GEMSPEC: "rubygems",+ CARGO: "cargo",+ COMPOSER: "composer",+ NPM: "npm",+ YARN: "npm",+ NODEPKG: "npm",+ NUGET: "nuget",+ DOTNET_CORE: "nuget",+ GOBINARY: "go",+ GOMOD: "go",+ JAR: "java",+ POM: "maven",+ PIP: "pypi",+ PIPENV: "pypi",+ POETRY: "pypi",+ PYTHONPKG: "pypi",+ }),+);++const manifests = new Set([+ "package.json",+ "package-lock.json",+ "npm-shrinkwrap.json",+ "yarn.lock",+ "pnpm-lock.yaml",+ "Cargo.toml",+ "Cargo.lock",+ "composer.json",+ "composer.lock",+ "Gemfile",+ "Gemfile.lock",+ "go.mod",+ "go.sum",+ "pom.xml",+ "build.gradle",+ "build.gradle.kts",+ "gradle.lockfile",+ "Pipfile",+ "Pipfile.lock",+ "poetry.lock",+ "pyproject.toml",+ "uv.lock",+ "packages.config",+ "packages.lock.json",+]);++function manifestPath(path: string | null): string | null {+ if (!path) return null;+ const name = posix.basename(path);+ return manifests.has(name) ||+ /^requirements(?:[-_.].*)?\.txt$/u.test(name) ||+ /\.(?:csproj|fsproj|vbproj|gemspec)$/u.test(name)+ ? path+ : null;+}++function concreteVersion(+ value: unknown,+ ecosystem: string | null,+ osPackage: boolean,+): string | null {+ const version = text(value);+ if (!version) return null;+ // Debian versions use internal tildes for prereleases and backports.+ if (osPackage && version.includes("~"))+ return /^(?:\d+:)?\d[a-z\d.+~]*(?:-[a-z\d.+~]+)*$/iu.test(version)+ ? version+ : null;+ if (validSemver(version)) return version;+ if (ecosystem === "npm" || ecosystem === "cargo") return null;+ if (ecosystem === "java" || ecosystem === "maven") {+ if (+ version === "LATEST" ||+ version === "RELEASE" ||+ version.startsWith("latest.")+ )+ return null;+ return /^[a-z\d][\w.+-]*$/iu.test(version) && !version.endsWith("+")+ ? version+ : null;+ }+ if (!ecosystem && version.endsWith("+")) return null;+ const publicVersion =+ ecosystem === "pypi" ? version.split("+", 1)[0]! : version;+ return /\d/u.test(version) &&+ /^(?:\d+:)?[a-z\d][\w.+!-]*$/iu.test(version) &&+ !/(?:^|\.)x(?:\.|$)/iu.test(publicVersion)+ ? version+ : null;+}++function evidence(+ { native: finding, pkg, code }: ReturnType<typeof selectedFinding>,+ id: string,+ source: string,+ target: ExternalImportTarget,+) {+ const {+ description,+ severity,+ remediation,+ firstObservedAt,+ lastObservedAt,+ updatedAt,+ status,+ } = finding;+ const { recommendation } = record(remediation, "Inspector remediation");+ record(recommendation ?? {}, "Inspector recommendation");+ requiredText(status, "Inspector status");+ timestamp(firstObservedAt);+ timestamp(lastObservedAt);+ const level = requiredText(severity, "Inspector severity").toLowerCase();+ const paths = new Set<string>();+ const packages = (pkg?.vulnerablePackages ?? []).map((item) => {+ const path = repoFile(item.filePath);+ if (path) paths.add(path);+ const ecosystem = ecosystems.get(text(item.packageManager) ?? "") ?? null;+ const version = (value: unknown) =>+ concreteVersion(value, ecosystem, item.packageManager === "OS");+ const fixed = version(item.fixedInVersion);+ const splitVersion =+ item.packageManager === "OS" &&+ (item.epoch != null || item.release != null);+ return {+ name: item.name,+ ecosystem,+ installed_version: splitVersion ? null : version(item.version),+ manifest_path: manifestPath(path),+ fixed_versions: fixed ? [fixed] : [],+ };+ });+ const locations: { path: string; line: number | null }[] = [...paths].map(+ (path) => ({ path, line: null }),+ );+ if (code) {+ const { fileName, filePath, startLine } = code.filePath;+ const path = repoFile(filePath);+ if (path && posix.basename(path) === fileName)+ locations.push({+ path,+ line:+ typeof startLine === "number" &&+ Number.isSafeInteger(startLine) &&+ startLine > 0+ ? startLine+ : null,+ });+ }+ return validateExternalEvidence(+ {+ title:+ text(finding["title"]) ??+ pkg?.vulnerabilityId ??+ code?.detectorName ??+ id,+ description: requiredText(description, "Inspector description"),+ severity: ["critical", "high", "medium", "low", "informational"].includes(+ level,+ )+ ? level+ : "unknown",+ url: text(pkg?.sourceUrl),+ advisory_ids: pkg+ ? [+ ...new Set([+ pkg.vulnerabilityId,+ ...(pkg.relatedVulnerabilities ?? []),+ ]),+ ]+ : [],+ packages,+ locations,+ source_updated_at: updatedAt === undefined ? null : timestamp(updatedAt),+ source_data: {+ format,+ sourceRepositoryUrl: source,+ finding: structuredClone(finding),+ },+ },+ target,+ );+}++export function normalizeInspectorFindings(+ input: unknown,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+ projectMap?: ReadonlyMap<string, string>,+): ExternalFindings {+ const source = repositoryUrl(sourceRepositoryUrl);+ if (+ isRecord(input) &&+ (Object.hasOwn(input, "NextToken") || Object.hasOwn(input, "nextToken"))+ )+ throw new Error(+ "Inspector export has a continuation key; supply the complete paginated CLI JSON output.",+ );+ const report = listFindings.safeParse(input);+ if (!report.success)+ throw new Error(+ "Expected only a complete native Inspector ListFindings response with a findings array.",+ );+ const rows = report.data.findings.map((finding, i) => ({+ finding,+ source,+ position: i + 1,+ claims: repositoryClaims(finding),+ }));+ checkReportScope(rows, target, projectMap);+ const result = normalizeRecords(+ rows,+ ({ finding }, id) => ({+ source_finding_id: id,+ evidence: evidence(selectedFinding(finding), id, source, target),+ }),+ ({ finding }) => identity(record(finding, "Inspector finding")).arn,+ target,+ );+ if (result.excluded.length && result.findings.length) {+ // Only surviving rows can supply shared provider and host evidence on replay.+ const skipped = new Set(result.excluded.map((row) => row.position));+ const retained = rows.filter((row) => !skipped.has(row.position));+ checkReportScope(retained, target, projectMap, (row, error) => {+ skipped.add(row.position);+ result.excluded.push({+ position: row.position,+ source_finding_id: identity(record(row.finding, "Inspector finding"))+ .arn,+ reason: errorMessage(error),+ });+ });+ result.findings = result.findings.filter(+ (_, i) => !skipped.has(retained[i]!.position),+ );+ result.excluded.sort((a, b) => a.position - b.position);+ }+ return result;+}++export async function readInspectorFindings(+ path: string,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+ projectMap?: ReadonlyMap<string, string>,+): Promise<ExternalFindings> {+ const mapping = projectMap && new Map(projectMap);+ return normalizeInspectorFindings(+ await readScannerJson(path),+ sourceRepositoryUrl,+ target,+ mapping,+ );+}diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.tsindex 2f3ba4e13..bcca60e46 100644--- a/sdk/typescript/tests-ts/cli-local-import.test.ts+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts@@ -17,6 +17,10 @@ import {} from "./cli-fixtures.js";import { createCliTest } from "./support/cli-run.js";import { opengrepJson } from "./support/opengrep-import-fixtures.js";+import {+ inspectorReport,+ inspectorRepositoryUrl,+} from "./support/inspector-import-fixtures.js";const dependencies: typeof cliDependencies = (options = {}) => {const result = cliDependencies(options);@@ -203,6 +207,66 @@ test("CLI imports a vendor report, reads local evidence, and updates the same soexpect(result.findings[0].evidence.confidence).toBeUndefined();});+test("Inspector CLI binds an opaque project to the operator's ARN and repository URL", async () => {+ const f = await fixture();+ const report = inspectorReport();+ const finding = report.findings[0]!;+ const resource = finding.resources[0]!;+ const source = ["--source-repository-url", inspectorRepositoryUrl];+ const arn = ["--inspector-project-arn", resource.id];+ const run = async (args: string[], provider = "inspector") => {+ const cli = createCliTest(main);+ const code = await cli.runCli(+ [+ ...f.command.map((value) => (value === "wiz" ? provider : value)),+ "--dry-run",+ ...args,+ ],+ f.deps,+ );+ return { code, stdout: cli.stdout.text(), stderr: cli.stderr.text() };+ };++ await writeFile(f.file, JSON.stringify(report));+ expect((await run(source)).code).toBe(0);+ expect(+ (+ await run([+ "--source-repository-url",+ "https://other.invalid/example/project",+ ...arn,+ ])+ ).stderr,+ ).toMatch(/does not match|disagree/iu);++ resource.details.codeRepository.projectName = "example/project";+ await writeFile(f.file, JSON.stringify(report));+ const preview = await run([...source, ...arn]);+ expect(preview.code).toBe(0);+ expect(JSON.parse(preview.stdout).findings[0].source_finding_id).toBe(+ finding.findingArn,+ );+ expect((await run(source)).code).not.toBe(0);+ expect(+ (+ await run([+ ...source,+ "--inspector-project-arn",+ resource.id.replace("project-2", "project-3"),+ ])+ ).stderr,+ ).toMatch(/project (?:map|ARN)|mapping/iu);+ expect((await run(arn, "wiz")).stderr).toContain(+ "requires --provider inspector",+ );++ await writeFile(f.file, JSON.stringify({ findings: [] }));+ expect((await run(arn)).stderr).toContain("--source-repository-url");+ expect(+ (await run([...source, "--inspector-project-arn", "not-an-arn"])).stderr,+ ).toContain("full Inspector repository project ARN");+});+test("CLI imports OpenGrep evidence locally without assessing it", async () => {const f = await fixture();const report = opengrepJson();diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 8f251cf36..0bb6cef00 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -21,7 +21,9 @@ import {ExternalPublicationError,prepareExternalPublication,prepareNormalizedExternalPublication,+ type ExternalPublicationOptions,type ExternalPublicationProgress,+ type PreparedExternalPublication,} from "../src/external-findings-publish.js";import { snykRepositoryUrls } from "../src/snyk-findings.js";import { readGitHubFindings } from "../src/github-findings.js";@@ -45,6 +47,10 @@ import {importedAdvisory,} from "./support/github-import-fixtures.js";import { createCliTest } from "./support/cli-run.js";+import {+ inspectorPackageFinding,+ inspectorRepositoryUrl,+} from "./support/inspector-import-fixtures.js";const cleanups: (() => Promise<void>)[] = [];afterEach(async () => {@@ -97,7 +103,7 @@ test("external publication requires opt-in before reading input or accessing Cloawait expect(readdir(state)).rejects.toThrow("ENOENT");});-test("concurrent external publications use their own opt-in environments", async () => {+test("concurrent external publications enforce opt-in and provider options before Cloud access", async () => {const f = await fixture();const parsed = await readVendorFindings(f.file);let disabledSideEffects = 0;@@ -137,6 +143,19 @@ test("concurrent external publications use their own opt-in environments", async);}}+ const incompatible = { ...options, inspectorProjectMap: new Map() };+ const enabled = { ...disabled, environment: f.environment };+ const message = "map requires the inspector provider";+ await expect(+ prepareNormalizedExternalPublication(parsed, incompatible, enabled),+ ).rejects.toThrow(message);+ await expect(+ prepareExternalPublication(+ join(f.root, "missing.json"),+ incompatible,+ enabled,+ ),+ ).rejects.toThrow(message);expect(disabledSideEffects).toBe(0);expect(f.posts).toHaveLength(0);});@@ -385,6 +404,7 @@ async function fixture(const receipts = new Map<string, FindingImportReceipt>();const posts: string[] = [];const state = {+ repositoryUrl,marker: "generation-1",environmentId: "environment-example" as string | null,materializeDefaults: false,@@ -399,7 +419,7 @@ async function fixture(id: options.repository,object: "security.repository",repo_connector_id: repoConnectorId,- url: repositoryUrl,+ url: state.repositoryUrl,default_branch: "main",reset_marker: state.marker,import_environment_id: state.environmentId,@@ -967,6 +987,212 @@ test("request and pagination metadata retain Cloud byte limits and distinct iden).toThrow("4096 UTF-8");});+const inspectorOptions = {+ ...options,+ provider: "inspector" as const,+ sourceRepositoryUrl: inspectorRepositoryUrl,+};++async function inspectorPublicationFixture(name = inspectorRepositoryUrl) {+ const input = inspectorPackageFinding();+ const project = input.resources[0]!;+ project.details.codeRepository.projectName = name;+ const f = await fixture({ findings: [input] });+ const map = new Map([[project.id, inspectorRepositoryUrl]]);+ const prepare = (settings: ExternalPublicationOptions = inspectorOptions) =>+ prepareExternalPublication(f.file, settings, f.deps);+ async function loseResponse(prepared: PreparedExternalPublication) {+ f.state.loseResponse = true;+ await expect(prepared.publish()).rejects.toThrow(+ "resume the saved request",+ );+ return f.posts.at(-1)!;+ }+ return { f, input, project, map, prepare, loseResponse };+}++test("Inspector publication checks its source and reuses the finding ARN", async () => {+ const { f, input, prepare } = await inspectorPublicationFixture();+ const prepared = await prepare();+ expect(prepared.preview.source.provider).toBe("inspector");+ expect((await prepared.publish()).counts.created).toBe(1);+ expect((await (await prepare()).publish()).counts.unchanged).toBe(1);+ expect(f.reports.has(input.findingArn)).toBe(true);++ const row = prepared.preview.findings[0]!;+ const opaque = structuredClone(row);+ opaque.source_finding_id = "typed-only";+ delete opaque.evidence.source_data;+ const other = "https://github.com/example/other";+ opaque.evidence.details = { kind: "sast", repository: { url: other } };+ await expect(+ prepareNormalizedExternalPublication(+ { ...prepared.preview, findings: [row, opaque] },+ inspectorOptions,+ f.deps,+ ),+ ).rejects.toThrow(/typed-only.*does not match/i);++ f.state.repositoryUrl = other;+ await expect(prepare()).rejects.toThrow(/does not match/i);+ for (const source_data of [row.evidence.source_data, { finding: input }]) {+ row.evidence.source_data = source_data;+ await expect(+ prepareNormalizedExternalPublication(prepared.preview, options, f.deps),+ ).rejects.toThrow("requires the inspector provider");+ }+ expect(f.posts).toHaveLength(2);+});++test("Wiz can import, resume and update its own occurrence with upstream Inspector evidence", async () => {+ const record = {+ id: "wiz-vulnerability-1",+ name: "CVE-2099-1234",+ detailedName: "example-package",+ vendorSeverity: "HIGH",+ vulnerableAsset: { id: "example-asset" },+ finding: inspectorPackageFinding(),+ };+ const f = await fixture([record]);+ const prepare = () => prepareExternalPublication(f.file, options, f.deps);+ const first = await prepare();+ f.state.loseResponse = true;+ const error = await first.publish().catch((error: unknown) => error);+ if (!(error instanceof ExternalPublicationError)) throw error;+ expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);++ // A pre-Inspector checkpoint can contain the original requests without their input projection.+ const path = error.result.savedSubmission!;+ const saved = JSON.parse(await readFile(path, "utf8"));+ delete saved.inputProjection;+ await writeFile(path, JSON.stringify(saved));+ const retry = await prepare();+ expect(retry.preview.resumed).toBe(true);+ expect((await retry.publish()).verified).toBe(1);+ expect(f.posts).toEqual([f.posts[0]!, f.posts[0]!]);++ record.vendorSeverity = "MEDIUM";+ await writeFile(f.file, JSON.stringify([record]));+ const updated = await prepareNormalizedExternalPublication(+ await readVendorFindings(f.file),+ options,+ f.deps,+ );+ expect((await updated.publish()).counts.updated).toBe(1);+ expect(f.reports.get(record.id)?.evidence.source_data).toEqual(record);+});++test.each(["example/project", inspectorRepositoryUrl])(+ "pending Inspector requests for %s recheck their project mapping and destination host",+ async (name) => {+ const { f, project, map, prepare, loseResponse } =+ await inspectorPublicationFixture(name);+ const otherUrl = "https://git.example.test/example/project";+ const supplied = new Map(map);+ const settings: ExternalPublicationOptions = {+ ...inspectorOptions,+ inspectorProjectMap: supplied,+ };+ const preparing = prepare(settings);+ if (name === inspectorRepositoryUrl) delete settings.inspectorProjectMap;+ else supplied.clear();+ const prepared = await preparing;+ const firstBody = await loseResponse(prepared);+ const resume = (inspectorProjectMap?: ReadonlyMap<string, string>) =>+ prepareNormalizedExternalPublication(+ prepared.preview,+ { ...inspectorOptions, inspectorProjectMap },+ f.deps,+ );++ await expect(resume()).rejects.toThrow(/project|repository/i);+ await expect(resume(new Map([[project.id, otherUrl]]))).rejects.toThrow(+ /project|repository/i,+ );+ // Connector and repository IDs stay stable while the host changes.+ f.state.repositoryUrl = otherUrl;+ await expect(resume(map)).rejects.toThrow(/repository/i);+ expect(f.posts).toHaveLength(1);++ f.state.repositoryUrl = inspectorRepositoryUrl;+ const retry = await resume(map);+ expect(retry.preview.resumed).toBe(true);+ retry.preview.requests[0]!.items[0]!.evidence.source_data![+ "sourceRepositoryUrl"+ ] = otherUrl;+ expect((await retry.publish()).verified).toBe(1);+ expect(f.posts).toEqual([firstBody, firstBody]);+ },+);++test("a repository reset retires an Inspector request even when the destination URL changed", async () => {+ const { f, map, prepare, loseResponse } = await inspectorPublicationFixture();+ const first = await prepare({+ ...inspectorOptions,+ inspectorProjectMap: map,+ });+ await loseResponse(first);+ f.state.marker = "generation-2";+ f.state.repositoryUrl = "https://github.com/example/new-destination";+ await expect(prepare()).rejects.toThrow("retired without uploading");+ await expect(prepare()).rejects.toThrow("does not match");+ expect(f.posts).toHaveLength(1);++ f.state.repositoryUrl = inspectorRepositoryUrl;+ const fresh = await prepare();+ expect(fresh.preview.resumed).toBe(false);+ const request = fresh.preview.requests[0]!;+ expect(request.repository.reset_marker).toBe("generation-2");+ expect(request.request_id).not.toBe(first.preview.requests[0]!.request_id);+});++test("publishing an Inspector retry adopts its project map without changing the pending request", async () => {+ const { f, map, prepare, loseResponse } = await inspectorPublicationFixture();+ const mappedOptions = { ...inspectorOptions, inspectorProjectMap: map };+ const body = await loseResponse(await prepare());+ const mapped = await prepare(mappedOptions);+ const withoutMap = await prepare(); // Previewing the map does not change the checkpoint.+ await loseResponse(mapped);+ await expect(prepare()).rejects.toThrow(+ "Supply the verified Inspector project binding",+ );+ await expect(withoutMap.publish()).rejects.toThrow(+ "Another publication prepared this input",+ );+ expect((await (await prepare(mappedOptions)).publish()).verified).toBe(1);+ expect(f.posts).toEqual([body, body, body]);+});++test("a normalized Inspector retry checks its typed repository without native evidence", async () => {+ const f = await fixture();+ const finding = {+ source_finding_id: "vendor-1",+ evidence: {+ title: "Synthetic code finding",+ severity: "high" as const,+ details: {+ kind: "sast" as const,+ repository: { url: inspectorRepositoryUrl },+ },+ },+ };+ const prepare = () =>+ prepareNormalizedExternalPublication(+ { read: 1, findings: [finding], excluded: [] },+ inspectorOptions,+ f.deps,+ );+ f.state.loseResponse = true;+ await expect((await prepare()).publish()).rejects.toThrow(+ "resume the saved request",+ );+ f.state.repositoryUrl = "https://github.com/different/project";+ await expect(prepare()).rejects.toThrow(+ "does not match the selected Cloud repository",+ );+ expect(f.posts).toHaveLength(1);+});+test("CLI preview and rejected confirmation never POST or persist an upload", async () => {const f = await fixture();const cli = createCliTest(main);@@ -2904,7 +3130,7 @@ test("normalized SDK publication preserves caller evidence and exclusion accountconst original = structuredClone(input);const prepared = await prepareNormalizedExternalPublication(input as Parameters<typeof prepareNormalizedExternalPublication>[0],- options,+ Object.create(options) as typeof options,f.deps,);expect(input).toEqual(original);diff --git a/sdk/typescript/tests-ts/inspector-findings.test.ts b/sdk/typescript/tests-ts/inspector-findings.test.tsnew file mode 100644index 000000000..da5716aae--- /dev/null+++ b/sdk/typescript/tests-ts/inspector-findings.test.ts@@ -0,0 +1,741 @@+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 type { ExternalImportTarget } from "../src/external-import-contract.js";+import {+ inspectorReportRepository,+ normalizeInspectorFindings,+ readInspectorFindings,+} from "../src/inspector-findings.js";+import {+ inspectorIntegrationArn,+ inspectorPackageFinding,+ inspectorProjectId,+ inspectorReport,+ inspectorRepositoryUrl,+} from "./support/inspector-import-fixtures.js";++function normalize(+ findings: unknown[],+ source = inspectorRepositoryUrl,+ target: ExternalImportTarget = "cloud",+ projectMap?: ReadonlyMap<string, string>,+) {+ return normalizeInspectorFindings({ findings }, source, target, projectMap);+}++function codeFinding(+ filePath = "src/example.ts",+ fileName = "example.ts",+ startLine = 8,+) {+ const { packageVulnerabilityDetails: _packages, ...common } =+ inspectorPackageFinding();+ return {+ ...common,+ type: "CODE_VULNERABILITY",+ findingArn: common.findingArn.replace(/a{32}$/u, "b".repeat(32)),+ title: "Synthetic code finding",+ codeVulnerabilityDetails: {+ detectorId: "synthetic-detector",+ detectorName: "Synthetic detector",+ cwes: ["CWE-79"],+ detectorTags: ["example-tag"],+ filePath: { fileName, filePath, startLine, endLine: 12 },+ },+ };+}++function projectFinding(+ repoChanges: Record<string, unknown>,+ resourceChanges: Record<string, unknown> = {},+) {+ const finding = inspectorPackageFinding();+ const resource = finding.resources[0]!;+ Object.assign(resource.details.codeRepository, repoChanges);+ Object.assign(resource, resourceChanges);+ return finding;+}++const projectArn = `${inspectorIntegrationArn}/${inspectorProjectId}`;+const enterprise = "https://scm.example.test/example/project";++test("preserves the native package finding and projects only reported dependency evidence", () => {+ const native = projectFinding({ projectName: "example/project" });+ const map = new Map([[projectArn, inspectorRepositoryUrl]]);+ const read = () =>+ normalize([native], inspectorRepositoryUrl, "cloud", map).findings[0]!;+ const row = read();+ expect(row.source_finding_id).toBe(native.findingArn);+ expect(row.evidence).toMatchObject({+ title: native.title,+ severity: "high",+ description: native.description,+ advisory_ids: ["CVE-2099-1234", "GHSA-2345-6789-cfgh"],+ url: native.packageVulnerabilityDetails.sourceUrl,+ packages: [+ {+ name: "example-package",+ ecosystem: "npm",+ installed_version: "1.0.0",+ fixed_versions: ["1.0.1"],+ manifest_path: "apps/web/package.json",+ },+ ],+ locations: [{ path: "apps/web/package.json", line: null }],+ source_updated_at: Date.parse(native.updatedAt) / 1000,+ source_data: {+ sourceRepositoryUrl: inspectorRepositoryUrl,+ finding: native,+ },+ });+ for (const field of [+ "branch",+ "code_revision",+ "source_scan_id",+ "details",+ ] as const)+ expect(row.evidence[field] ?? null).toBeNull();++ native.status = "CLOSED";+ native.packageVulnerabilityDetails.vulnerablePackages[0]!.version = "^1.0.0";+ const updated = read();+ expect(updated.source_finding_id).toBe(row.source_finding_id);+ expect(updated.evidence.packages![0]!.installed_version).toBeNull();+ expect(updated).not.toHaveProperty("assessment");+ expect(row.evidence.source_data?.["finding"]).toMatchObject({+ status: "ACTIVE",+ });+});++test.each([+ ["NPM", "1.2.3+build.x.1", "2.x", "1.2.3+build.x.1", []],+ ["YARN", "workspace:1.2.3", "1.2.3-rc.x.1", null, ["1.2.3-rc.x.1"]],+ ["CARGO", "1.2", "2", null, []],+ ["CARGO", "1.2.3", "2.0.0", "1.2.3", ["2.0.0"]],+ ["JAR", "1.+", "1.3", null, ["1.3"]],+ ["POM", "First.RELEASE", "Next.RELEASE", "First.RELEASE", ["Next.RELEASE"]],+ ["POM", "LATEST", "RELEASE", null, []],+ ["JAR", "latest.integration", "[1.3,2.0)", null, []],+ [+ "PYTHONPKG",+ "1.0+linux.x.1",+ "1!2.3rc1+lab",+ "1.0+linux.x.1",+ ["1!2.3rc1+lab"],+ ],+ ["OS", "1:2.3-4", "1:2.3-5", "1:2.3-4", ["1:2.3-5"]],+ ["OS", "1.2.3~rc1-1", "1.2.3~rc2-1", "1.2.3~rc1-1", ["1.2.3~rc2-1"]],+] as const)(+ "projects exact %s versions from %s and %s",+ (+ packageManager,+ version,+ fixedInVersion,+ installed_version,+ fixed_versions,+ ) => {+ const finding = inspectorPackageFinding();+ Object.assign(finding.packageVulnerabilityDetails.vulnerablePackages[0]!, {+ packageManager,+ version,+ fixedInVersion,+ });+ expect(normalize([finding]).findings[0]!.evidence.packages).toMatchObject([+ { installed_version, fixed_versions },+ ]);+ },+);++test("retains separate package version components without projecting a partial installed version", () => {+ const finding = inspectorPackageFinding();+ const item = finding.packageVulnerabilityDetails.vulnerablePackages[0]!;+ const fixed = "1:1.2.3-5.el9";+ Object.assign(item, {+ packageManager: "OS",+ epoch: 1,+ version: "1.2.3",+ release: "4.el9",+ fixedInVersion: fixed,+ });+ const { evidence } = normalize([finding]).findings[0]!;+ expect(evidence.packages).toMatchObject([+ { installed_version: null, fixed_versions: [fixed] },+ ]);+ expect(evidence.source_data?.["finding"]).toEqual(finding);+});++test("distinguishes dependency manifests from source files and unsafe paths", () => {+ const finding = inspectorPackageFinding();+ const pkg = { name: "synthetic", version: "1.2.x" };+ const vulnerablePackages = [+ { ...pkg, filePath: "src/example.ts" },+ {+ ...pkg,+ filePath: "api/requirements-dev.txt",+ packageManager: "PIP",+ version: "1.2",+ },+ { ...pkg, filePath: "../package.json" },+ ];+ const { evidence } = normalize([+ {+ ...finding,+ severity: "UNTRIAGED",+ updatedAt: undefined,+ packageVulnerabilityDetails: {+ ...finding.packageVulnerabilityDetails,+ vulnerablePackages,+ },+ },+ ]).findings[0]!;+ expect(evidence.packages).toMatchObject([+ {+ ecosystem: null,+ installed_version: null,+ fixed_versions: [],+ manifest_path: null,+ },+ { ecosystem: "pypi", manifest_path: "api/requirements-dev.txt" },+ { manifest_path: null },+ ]);+ expect(evidence.locations).toEqual([+ { path: "src/example.ts", line: null },+ { path: "api/requirements-dev.txt", line: null },+ ]);+ expect(evidence.severity).toBe("unknown");+ expect(evidence.source_updated_at ?? null).toBeNull();+});++test("projects only repository-relative code locations with a matching filename", () => {+ const evidence = (finding: ReturnType<typeof codeFinding>) =>+ normalize([finding]).findings[0]!.evidence;+ const code = codeFinding();+ expect(evidence(code).locations).toEqual([+ { path: "src/example.ts", line: 8 },+ ]);+ expect(evidence(code).source_data?.["finding"]).toEqual(code);+ for (const path of [+ "/tmp/example.ts",+ "C:\\work\\example.ts",+ "src/../example.ts",+ "file:///tmp/example.ts",+ "https://example.invalid/example.ts",+ "~/example.ts",+ "./C:/work/example.ts",+ "src/",+ "src/other.ts",+ ])+ expect(evidence(codeFinding(path)).locations).toEqual([]);+ expect(+ evidence(codeFinding("src\\example.ts", "example.ts", 0)).locations,+ ).toEqual([{ path: "src/example.ts", line: null }]);+});++test("accepts Unix and timezone-qualified ISO timestamps", () => {+ const native = inspectorPackageFinding();+ const epoch = Date.parse(native.updatedAt) / 1000;+ for (const updatedAt of [+ epoch + 0.125,+ native.updatedAt,+ "2026-01-04T06:06:07.125+01:00",+ ]) {+ const { evidence } = normalize([+ {+ ...native,+ firstObservedAt: epoch - 2,+ lastObservedAt: epoch - 1,+ updatedAt,+ },+ ]).findings[0]!;+ expect(evidence.source_updated_at).toBe(epoch);+ expect(evidence.source_data?.["finding"]).toMatchObject({ updatedAt });+ }+ for (const updatedAt of [+ "January 4",+ "2026-01-04T05:06:07",+ String(epoch),+ null,+ ])+ expect(normalize([{ ...native, updatedAt }]).excluded[0]?.reason).toContain(+ "timestamp",+ );+});++test("accepts a complete native ListFindings envelope, including an empty export", () => {+ expect(normalize([])).toEqual({ read: 0, findings: [], excluded: [] });+ const parse = (input: unknown) =>+ normalizeInspectorFindings(input, inspectorRepositoryUrl);+ for (const invalid of [+ null,+ [],+ {},+ { Findings: [] },+ { findings: null },+ { findings: [], Error: { Code: "AccessDenied" } },+ { detail: inspectorReport() },+ inspectorPackageFinding(),+ ])+ expect(() => parse(invalid)).toThrow();+ for (const key of ["nextToken", "NextToken"])+ for (const token of ["more", null, ""])+ expect(() => parse({ findings: [], [key]: token })).toThrow(+ "continuation",+ );+});++test("retains supported rows and excludes malformed records and both copies of duplicate ARNs", () => {+ const supported = inspectorPackageFinding();+ const duplicate = codeFinding();+ const result = normalize([+ supported,+ null,+ duplicate,+ { ...duplicate, status: "SUPPRESSED" },+ ]);+ expect(result.read).toBe(4);+ expect(result.findings.map((row) => row.source_finding_id)).toEqual([+ supported.findingArn,+ ]);+ expect(+ result.excluded.map((row) => [row.position, row.source_finding_id]),+ ).toEqual([+ [2, null],+ [3, duplicate.findingArn],+ [4, duplicate.findingArn],+ ]);+});++test("excludes workload resources, network findings and workload-only details", () => {+ const pkg = inspectorPackageFinding();+ const code = codeFinding();+ const resource = pkg.resources[0]!;+ const workload = { type: "AWS_EC2_INSTANCE", id: "instance" };+ const detail = pkg.packageVulnerabilityDetails;+ const rows = [+ { ...pkg, resources: [workload] },+ { ...pkg, resources: [resource, workload] },+ { ...pkg, type: "NETWORK_REACHABILITY" },+ { ...pkg, networkReachabilityDetails: {} },+ { ...code, packageVulnerabilityDetails: detail },+ {+ ...pkg,+ resources: [+ {+ ...resource,+ details: { ...resource.details, awsLambdaFunction: {} },+ },+ ],+ },+ {+ ...code,+ codeVulnerabilityDetails: {+ ...code.codeVulnerabilityDetails,+ sourceLambdaLayerArn: "layer",+ },+ },+ ...["sourceLayerHash", "sourceLambdaLayerArn"].map((field) => ({+ ...pkg,+ packageVulnerabilityDetails: {+ ...detail,+ vulnerablePackages: [+ { ...detail.vulnerablePackages[0], [field]: "layer" },+ ],+ },+ })),+ ];+ for (const row of rows) {+ const result = normalize([row]);+ expect(result.findings).toEqual([]);+ expect(result.excluded[0]?.source_finding_id).toBe(row.findingArn);+ }+});++test("requires a complete HTTP(S) repository URL", () => {+ for (const source of [+ "",+ "example/project",+ "https://host.invalid/project",+ "https://user:[email protected]/org/project",+ inspectorRepositoryUrl + "?",+ inspectorRepositoryUrl + "#ref",+ "https://host.invalid/other/../org/project",+ "https://host.invalid/org%2fgroup/project",+ ])+ expect(() => normalize([], source)).toThrow();+});++test.each(["local", "cloud"] as const)(+ "compares native URLs and trusted project maps during %s import and replay",+ (target) => {+ const other = "https://other.example.test/example/project";+ const slug = projectFinding({ projectName: "example/project" });+ const map = new Map([[projectArn, enterprise]]);+ const rows = normalize([slug], enterprise, target, map).findings;+ const replay = (map?: ReadonlyMap<string, string>) =>+ inspectorReportRepository("inspector", rows, target, map);+ expect(replay(map)).toMatchObject({+ findingId: slug.findingArn,+ url: enterprise,+ });+ expect(() => normalize([slug], other, target, map)).toThrow();+ expect(() =>+ normalize([projectFinding({ projectName: other })], other, target, map),+ ).toThrow();+ expect(() => replay(new Map([[projectArn, other]]))).toThrow();++ const retained = rows[0]!.evidence.source_data!;+ retained["sourceRepositoryUrl"] = other;+ retained["projectMap"] = { [projectArn]: other };+ expect(() => replay()).toThrow();+ expect(() => replay(map)).toThrow();++ for (const key of [+ inspectorIntegrationArn,+ inspectorProjectId,+ "example/project",+ ]) {+ const partial = new Map([[key, enterprise]]);+ expect(() => normalize([slug], enterprise, target, partial)).toThrow();+ expect(() =>+ normalize(+ [projectFinding({ projectName: "example/project" }, { id: key })],+ enterprise,+ target,+ partial,+ ),+ ).toThrow();+ }+ },+);++test.each(["local", "cloud"] as const)(+ "binds native URLs to their scheme, host, and namespace for %s",+ (target) => {+ const source = "https://tenant-a.ghe.com/Example/Project";+ const read = (name?: string, id = projectArn, url = source) =>+ normalize([projectFinding({ projectName: name }, { id })], url, target);+ expect(read(source.toLowerCase() + ".git").findings).toHaveLength(1);+ expect(read("project", source).findings).toHaveLength(1);+ expect(read(undefined, source).findings).toHaveLength(1);+ expect(() => read("wrong", source)).toThrow();+ for (const claim of [+ undefined,+ "Example/Project",+ "example/project",+ inspectorProjectId,+ "https://tenant-b.ghe.com/Example/Project",+ source.replace("https:", "http:"),+ ])+ expect(() => read(claim)).toThrow();+ expect(() =>+ read("Example/Project", "ssh://[email protected]/Example/Project"),+ ).toThrow();+ expect(() => read(undefined, "Example/Project")).toThrow();+ },+);++test("only a trusted map can bind a namespaced project under a GitLab installation subpath", () => {+ const read = (+ source: string,+ mapped: boolean,+ projectName = "group/project",+ ) =>+ normalize(+ [projectFinding({ providerType: "GITLAB_SELF_MANAGED", projectName })],+ source,+ "local",+ mapped ? new Map([[projectArn, source]]) : undefined,+ );+ const source = "https://scm.example.test/gitlab/group/project";+ expect(read(source, true).findings).toHaveLength(1);+ expect(() => read(source, false)).toThrow();+ expect(() => read(source, true, "Group/project")).toThrow();+ expect(() =>+ read("https://scm.example.test/gitlab/workgroup/project", true),+ ).toThrow();+ expect(() => read(source, true, "../group/project")).toThrow();+});++test("self-managed GitLab is local only and a custom Cloud host needs a GitHub provider", () => {+ const gitlab = projectFinding({+ projectName: enterprise,+ providerType: "GITLAB_SELF_MANAGED",+ });+ const local = normalize([gitlab], enterprise, "local");+ expect(+ inspectorReportRepository("inspector", local.findings, "local")?.url,+ ).toBe(enterprise);+ expect(() =>+ inspectorReportRepository("inspector", local.findings, "cloud"),+ ).toThrow();+ expect(() => normalize([gitlab], enterprise, "cloud")).toThrow();+ expect(() =>+ normalize([projectFinding({ providerType: "GITLAB_SELF_MANAGED" })]),+ ).toThrow();+ const name = "https://gitlab.com/example/project";+ for (const providerType of ["GITHUB", "GITLAB_SELF_MANAGED"])+ expect(() =>+ normalize(+ [projectFinding({ providerType, projectName: name })],+ name,+ "local",+ ),+ ).toThrow();++ const unknown = projectFinding({+ projectName: enterprise,+ providerType: undefined,+ });+ expect(() => normalize([unknown], enterprise, "cloud")).toThrow();+ const { findings } = normalize([unknown], enterprise, "local");+ findings[0]!.evidence.source_data!["providerType"] = "GITHUB";+ expect(+ inspectorReportRepository("inspector", findings, "local")?.platform,+ ).toBeUndefined();+});++test("checks every native source before filtering duplicate or unsupported findings", () => {+ const first = inspectorPackageFinding();+ const other = projectFinding(+ {},+ { id: projectArn.replace("22222222-", "33333333-") },+ );+ expect(() =>+ normalize([first, { ...other, type: "NETWORK_REACHABILITY" }]),+ ).toThrow();+ expect(() =>+ normalize([+ { ...first, resources: [...first.resources, ...other.resources] },+ ]),+ ).toThrow();+ expect(() =>+ normalize([first, projectFinding({ projectName: "other/project" })]),+ ).toThrow();+ expect(() =>+ normalize([{ ...first, awsAccountId: "999999999999" }]),+ ).toThrow();+ for (const resource of [+ { id: projectArn.replace("us-east-1", "us-west-2") },+ { id: "arn:aws:ecr:us-east-1:123456789012:repository/example/project" },+ { providerAccountId: "999999999999" },+ { region: "us-west-2" },+ { partition: "aws-cn" },+ ])+ expect(() => normalize([projectFinding({}, resource)])).toThrow();+ expect(() =>+ normalize([+ projectFinding({+ integrationArn: inspectorIntegrationArn.replace("11111111", "44444444"),+ }),+ ]),+ ).toThrow();++ for (const [one, two] of [+ ["example/project", "Example/Project"],+ [inspectorRepositoryUrl, inspectorRepositoryUrl.toUpperCase()],+ ["integrations/1/projects/2", "integrations/2/projects/2"],+ ]) {+ expect(() =>+ normalize([+ projectFinding({}, { id: one }),+ projectFinding({}, { id: two }),+ ]),+ ).toThrow();+ }+});++function projectRow(id: string, projectName?: string, providerType?: string) {+ const row = projectFinding({ projectName, providerType });+ row.findingArn = row.findingArn.replace(/a{32}$/u, id.repeat(32));+ return row;+}++test.each([+ ["project slug without a host", "example/project", "GITHUB"],+ ["native URL without a provider", enterprise, undefined],+] as const)(+ "sharing proof for a %s requires the same integration",+ (_, name, provider) => {+ const peer = projectRow("a", enterprise, "GITHUB");+ const dependent = projectRow("b", name, provider);+ const rows = [peer, dependent];+ const { findings } = normalize(rows, enterprise);+ const raw = () => normalize(rows, enterprise);+ const replay = () =>+ inspectorReportRepository("inspector", findings, "cloud");+ for (const [index, finding] of rows.entries()) {+ finding.resources[0]!.id = "example/project";+ findings[index]!.evidence.source_data!["finding"] = finding;+ }+ for (const [peerArn, dependentArn] of [+ [inspectorIntegrationArn, inspectorIntegrationArn],+ [inspectorIntegrationArn, undefined],+ [undefined, inspectorIntegrationArn],+ [undefined, undefined],+ ]) {+ Object.assign(peer.resources[0]!.details.codeRepository, {+ integrationArn: peerArn,+ });+ Object.assign(dependent.resources[0]!.details.codeRepository, {+ integrationArn: dependentArn,+ });+ if (peerArn && dependentArn) {+ expect(raw().findings).toHaveLength(2);+ expect(replay()?.url).toBe(enterprise);+ } else {+ expect(raw).toThrow();+ expect(replay).toThrow();+ }+ }+ },+);++test("only surviving rows share project proof, independently of input order", () => {+ const known = projectRow("a", enterprise, "GITHUB");+ const dependent = projectRow("b");+ for (const rows of [+ [known, dependent],+ [dependent, known],+ ]) {+ const { findings } = normalize(rows, enterprise, "cloud");+ expect(findings).toHaveLength(2);+ expect(+ inspectorReportRepository("inspector", findings, "cloud"),+ ).toMatchObject({ url: enterprise, platform: "github" });++ known.title = "a".repeat(513);+ const result = normalize(rows, enterprise, "cloud");+ expect(result.findings).toEqual([]);+ expect(result.excluded.map((row) => row.source_finding_id).sort()).toEqual(+ [known.findingArn, dependent.findingArn].sort(),+ );+ expect(normalize(rows, enterprise, "local").findings).toHaveLength(2);+ known.title = "Restored title";+ }+});++test("after the only provider hint is excluded, valid local rows still share their native URL", () => {+ const source = "https://scm.example.test/Owner/Repo";+ const duplicate = projectRow("a", "Owner/Repo", "GITHUB");+ const exact = projectRow("b", source);+ const slug = projectRow("c", "Owner/Repo");+ const mismatch = projectRow("d", "owner/repo");+ for (const valid of [+ [exact, slug],+ [slug, exact],+ ]) {+ const rows = [duplicate, mismatch, ...valid, duplicate];+ const result = normalize(rows, source, "local");+ expect(result.findings.map((row) => row.source_finding_id)).toEqual(+ valid.map((row) => row.findingArn),+ );+ expect(result.excluded.map((row) => row.position)).toEqual([1, 2, 5]);+ expect(+ inspectorReportRepository("inspector", result.findings, "local")?.url,+ ).toBe(source);+ expect(normalize(rows, source, "cloud").findings).toHaveLength(0);+ }+});++test.each(["cloud", "local"] as const)(+ "rechecks finding identity, resource kind and host during %s replay",+ (target) => {+ const native = inspectorPackageFinding();+ const rows = normalize([native], inspectorRepositoryUrl, target).findings;+ const row = rows[0]!;+ const data = row.evidence.source_data!;+ const replay = () => inspectorReportRepository("inspector", rows, target);+ for (const patch of [+ { format: "some-new-unsupported-format" },+ { finding: codeFinding() },+ { sourceRepositoryUrl: undefined },+ { sourceRepositoryUrl: enterprise },+ { sourceRepositoryUrl: "https://github.com/other/project" },+ { finding: projectFinding({ projectName: "other/project" }) },+ { finding: { ...native, resources: [] } },+ {+ finding: {+ ...native,+ resources: [...native.resources, { type: "AWS_EC2_INSTANCE" }],+ },+ },+ ]) {+ row.evidence.source_data = { ...data, ...patch };+ expect(replay).toThrow();+ }+ row.evidence.source_data = undefined;+ expect(replay).toThrow();+ row.source_finding_id = "opaque";+ expect(replay()).toBeUndefined();+ expect(() =>+ inspectorReportRepository("inspector", rows, target, new Map()),+ ).toThrow();+ },+);++test("distinguishes a Wiz occurrence containing Inspector evidence from the Inspector occurrence itself", () => {+ const native = inspectorPackageFinding();+ const row = normalize([native]).findings[0]!;+ const wiz = (id: string, data: Record<string, unknown>) =>+ inspectorReportRepository(+ "wiz",+ [+ {+ source_finding_id: id,+ evidence: { ...row.evidence, source_data: data },+ },+ ],+ "cloud",+ );++ expect(wiz("wiz-issue", { finding: native })).toBeUndefined();+ expect(wiz(codeFinding().findingArn, { finding: native })).toBeUndefined();+ expect(wiz(native.findingArn, {})).toBeUndefined();+ expect(() => wiz("wiz-issue", row.evidence.source_data!)).toThrow();+ for (const data of [native, { finding: native }])+ expect(() => wiz(native.findingArn, data)).toThrow();+});++test("reads plain and gzip JSON with a snapshot of the supplied map", async () => {+ const directory = await mkdtemp(join(tmpdir(), "synthetic-inspector-"));+ try {+ const path = join(directory, "input.json");+ const report = inspectorReport();+ report.findings[0]!.resources[0]!.details.codeRepository.projectName =+ "example/project";+ const mapping = () => new Map([[projectArn, inspectorRepositoryUrl]]);+ const expected = normalize(+ report.findings,+ inspectorRepositoryUrl,+ "cloud",+ mapping(),+ );+ const json = JSON.stringify(report);+ for (const bytes of [Buffer.from(json), gzipSync(json)]) {+ await writeFile(path, bytes);+ const map = mapping();+ const reading = readInspectorFindings(+ path,+ inspectorRepositoryUrl,+ "cloud",+ map,+ );+ map.clear();+ expect(await reading).toEqual(expected);+ }+ for (const invalid of [+ Buffer.from('{"findings":[]}\n{"findings":[]}'),+ Buffer.from([0xff]),+ ]) {+ await writeFile(path, invalid);+ await expect(+ readInspectorFindings(path, inspectorRepositoryUrl),+ ).rejects.toThrow();+ }+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});diff --git a/sdk/typescript/tests-ts/inspector-repository-import.test.ts b/sdk/typescript/tests-ts/inspector-repository-import.test.tsnew file mode 100644index 000000000..d866f1906--- /dev/null+++ b/sdk/typescript/tests-ts/inspector-repository-import.test.ts@@ -0,0 +1,350 @@+import { expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdtemp, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { gzipSync } from "node:zlib";+import { prepareLocalExternalImport } from "../src/external-findings-import.js";+import {+ listLocalExternalFindings,+ prepareNormalizedLocalImport,+} from "../src/external-findings-local.js";+import type { ExternalFinding } from "../src/external-findings.js";+import { normalizeInspectorFindings } from "../src/inspector-findings.js";+import { localFindingsFixture } from "./external-findings-local-helpers.js";+import {+ inspectorPackageFinding,+ inspectorRepositoryUrl,+} from "./support/inspector-import-fixtures.js";++async function checkout(+ remote = inspectorRepositoryUrl,+ source = inspectorRepositoryUrl,+) {+ const { root, repository, environment, dispose } = await localFindingsFixture(+ { remote },+ );+ return {+ path: join(root, "inspector.json.gz"),+ options: {+ provider: "inspector" as const,+ sourceKey: "inspector/project",+ repository,+ sourceRepositoryUrl: source,+ },+ deps: { environment },+ [Symbol.asyncDispose]: dispose,+ };+}++function normalized(findings: ExternalFinding[]) {+ return { read: findings.length, excluded: [], findings };+}++test("Enterprise GitHub scope applies to raw and replayed rows with and without a provider", async () => {+ const url = "https://git.example.test/Example/Project";+ await using f = await checkout(+ "[email protected]:EXAMPLE/Project.git",+ url,+ );+ const known = inspectorPackageFinding();+ known.resources[0]!.details.codeRepository.projectName = url;+ const unknown = structuredClone(known);+ unknown.findingArn = unknown.findingArn.replace(/a$/u, "b");+ Reflect.deleteProperty(+ unknown.resources[0]!.details.codeRepository,+ "providerType",+ );+ await writeFile(+ f.path,+ gzipSync(JSON.stringify({ findings: [unknown, known] })),+ );+ const raw = await prepareLocalExternalImport(f.path, f.options, f.deps);+ const rows = raw.preview.findings;+ expect(rows).toHaveLength(2);+ rows[1]!.evidence.source_data!["sourceRepositoryUrl"] = url.toLowerCase();+ rows.push(typedRow("ssh://[email protected]/Example/Project.git"));+ const replay = () =>+ prepareNormalizedLocalImport(normalized(rows), f.options, f.deps);+ expect((await replay()).preview.findings).toHaveLength(3);++ unknown.resources[0]!.details.codeRepository.providerType =+ "GITLAB_SELF_MANAGED";+ rows[0] = normalizeInspectorFindings(+ { findings: [unknown] },+ url,+ "local",+ ).findings[0]!;+ await expect(replay()).rejects.toThrow(/project|provider|integration/i);+});++function typedRow(url: string): ExternalFinding {+ return {+ source_finding_id: "sdk-id",+ evidence: {+ title: "Alert",+ severity: "unknown",+ details: { kind: "sast", repository: { url } },+ },+ };+}++const home = "host.test/~/project";+const ssh = "ssh://[email protected]/example/project";+const bindings: [string, string, string?][] = [+ [+ "https://trusted.test\\@other.test/../team/repo",+ "https://trusted.test/team/repo",+ ],+ ["https://host.test/x/%2e%2e/team/repo", "https://host.test/team/repo"],+ [+ "https://host.test/previous/../team/./repo",+ "https://host.test/team/other",+ "https://host.test/team/repo",+ ],+ [" ssh://host.test/team/repo", "https://host.test/team/repo"],+ ["ssh://[email protected]:invalid/team/repo", "https://host.test/team/repo"],+ ["ssh://other.test%[email protected]/team/repo", "https://github.com/team/repo"],+ [+ "[email protected]:/srv/team/repo.git",+ "ssh://[email protected]/team/repo",+ "ssh://[email protected]/srv/team/repo.git",+ ],+ [+ "[email protected]:~/team/repo%20data",+ "ssh://[email protected]/~/team/repo%20data",+ "ssh://[email protected]/~/team/repo%2520data",+ ],+ [inspectorRepositoryUrl + "?repo=other", inspectorRepositoryUrl],+ [inspectorRepositoryUrl + "?", inspectorRepositoryUrl],+ [inspectorRepositoryUrl + "#", inspectorRepositoryUrl],+ [ssh + "?other", ssh + "?Other"],+ [ssh + "#blue", ssh + ".git#blue", ssh + "#blue.git"],+ ["git://github.com/example/project?other", inspectorRepositoryUrl],+ ["ssh://[email protected]/~/../example/project", inspectorRepositoryUrl],+ ["[email protected]:team/project#other", "[email protected]:team/project#other"],+ [+ "[email protected]:team/project#demo",+ "ssh://[email protected]/team/project#demo",+ ],+ [+ "[email protected]:example/project.git",+ "ssh://[email protected]/example/other",+ "ssh://[email protected]:443/example/project.git",+ ],+ [+ "[email protected]:team/project",+ "ssh://[email protected]/team/project",+ "ssh://[email protected]/team/project",+ ],+ ["[email protected]:team/project", "ssh://[email protected]/team/project"],+ [+ "ssh://[email protected]/team/project",+ "ssh://[email protected]/team/other",+ "ssh://[email protected]/team/project",+ ],+ ["[email protected]:D:/shared/project", "[email protected]:D:/shared/project"],+ ["[email protected]:/~/repo", "[email protected]:/~/repo"],+ [`ssh://alice@${home}`, `ssh://bob@${home}`, `ssh://${home}`],+ ["ssh://[email protected]/%7E%2F../repo", "ssh://[email protected]/%7E%2F../repo"],+ [+ "café@host.test:~/repo",+ "caf%C3%[email protected]:~/repo",+ "ssh://caf%C3%[email protected]/~/repo",+ ],+ [+ "ssh://team:[email protected]/~/repo",+ "ssh://team:[email protected]/~/repo",+ "ssh://team%[email protected]/~/repo",+ ],+ [+ "ssh://u%00%[email protected]/~/repo#x",+ "ssh://[email protected]/~/repo#v%00%23x",+ "ssh://u%2500%[email protected]/~/repo#x",+ ],+];+test.each(+ bindings.map(+ ([remote, other, equivalent = remote]) =>+ [remote, other, equivalent] as const,+ ),+)(+ "normalized Inspector repository binding for %s",+ async (remote, other, equivalent) => {+ await using f = await checkout(remote);+ const prepare = (url: string) =>+ prepareNormalizedLocalImport(+ normalized([typedRow(url)]),+ f.options,+ f.deps,+ );+ await expect(prepare(other)).rejects.toThrow(+ "does not match a configured remote",+ );+ expect((await prepare(equivalent)).preview.findings).toHaveLength(1);+ },+);++test("mapped local imports preserve their SQLite history and verify replay provenance", async () => {+ await using f = await checkout();+ const input = inspectorPackageFinding();+ const project = input.resources[0]!;+ project.details.codeRepository.projectName = "example/project";+ const options = {+ ...f.options,+ inspectorProjectMap: new Map([[project.id, inspectorRepositoryUrl]]),+ };+ const store = async (findings: unknown[]) => {+ await writeFile(f.path, gzipSync(JSON.stringify({ findings })));+ return (await prepareLocalExternalImport(f.path, options, f.deps)).import();+ };+ expect((await store([input])).counts.created).toBe(1);+ expect(+ (await store([{ ...input, status: "SUPPRESSED" }])).counts.updated,+ ).toBe(1);+ expect((await store([])).counts).toEqual({+ created: 0,+ updated: 0,+ unchanged: 0,+ });+ const records = await listLocalExternalFindings(options, f.deps);+ expect(records).toHaveLength(1);+ const saved = records[0]!;+ expect(saved).toMatchObject({+ provider: "inspector",+ sourceFindingId: input.findingArn,+ version: 2,+ assessment: { state: "not_assessed" },+ });+ const row = {+ source_finding_id: saved.sourceFindingId,+ evidence: saved.evidence,+ };+ const replay = await prepareNormalizedLocalImport(+ normalized([row]),+ options,+ f.deps,+ );+ expect((await replay.import()).counts.unchanged).toBe(1);++ await expect(+ prepareNormalizedLocalImport(+ normalized([{ ...row, source_finding_id: "wrong" }]),+ options,+ f.deps,+ ),+ ).rejects.toThrow(/ARN|identity|source finding/i);+ const other = "https://other.example.test/example/project";+ row.evidence.details = { kind: "sast", repository: { url: other } };+ await expect(+ prepareNormalizedLocalImport(normalized([row]), options, f.deps),+ ).rejects.toThrow(/retained scanner repository/i);+ // Both copies of the retained URL now match the other checkout. The trusted map still disagrees.+ row.evidence.source_data!["sourceRepositoryUrl"] = other;+ await using fork = await checkout(other);+ await expect(+ prepareNormalizedLocalImport(+ normalized([row]),+ { ...options, repository: fork.options.repository },+ fork.deps,+ ),+ ).rejects.toThrow(/project|repository/i);+});++test("a mapped custom host keeps its path casing across reader hints and caller mutations", async () => {+ const trusted = "https://scm.example.test/Team/Project";+ await using f = await checkout(trusted.toLowerCase(), trusted);+ const input = inspectorPackageFinding();+ const project = input.resources[0]!;+ project.details.codeRepository.projectName = trusted;+ const report = { findings: [input] };+ const map = new Map([[project.id, trusted]]);+ const data = normalizeInspectorFindings(report, trusted, "local", map);+ await writeFile(f.path, gzipSync(JSON.stringify(report)));+ for (const raw of [false, true]) {+ const options = { ...f.options, inspectorProjectMap: new Map(map) };+ const pending = raw+ ? prepareLocalExternalImport(f.path, options, f.deps)+ : prepareNormalizedLocalImport(data, options, {+ ...f.deps,+ sourceRepositories: [{ url: trusted, platform: "github" }],+ });+ options.inspectorProjectMap.clear();+ await expect(pending).rejects.toThrow("does not match a configured remote");+ }+});++test("normalized imports bind mixed projects, native evidence and maps to their provider", async () => {+ await using f = await checkout();+ const native = inspectorPackageFinding();+ const row = normalizeInspectorFindings(+ { findings: [native] },+ inspectorRepositoryUrl,+ "local",+ ).findings[0]!;+ const fork = structuredClone(native);+ fork.findingArn = fork.findingArn.replace(/a$/u, "b");+ const project = fork.resources[0]!;+ project.id = project.id.replace("22222222", "33333333");+ project.details.codeRepository.projectName =+ "https://github.com/fork/project";+ const others = normalizeInspectorFindings(+ { findings: [fork] },+ project.details.codeRepository.projectName,+ "local",+ ).findings;+ await expect(+ prepareNormalizedLocalImport(+ normalized([row, ...others]),+ f.options,+ f.deps,+ ),+ ).rejects.toThrow("more than one repository project");++ const forkUrl = project.details.codeRepository.projectName;+ execFileSync("git", [+ "-C",+ f.options.repository,+ "remote",+ "add",+ "fork",+ forkUrl,+ ]);+ const plain = await mkdtemp(join(dirname(f.path), "plain-"));+ for (const repository of [plain, f.options.repository]) {+ await expect(+ prepareNormalizedLocalImport(+ normalized([row, typedRow(forkUrl)]),+ { ...f.options, repository },+ f.deps,+ ),+ ).rejects.toThrow("does not match the retained Inspector repository");+ }+ row.evidence.source_data = {+ ...native,+ resources: [{ type: "AWS_EC2_INSTANCE", id: "i-example" }],+ };+ await expect(+ prepareNormalizedLocalImport(+ normalized([{ ...row, source_finding_id: "CVE-2099-1234" }]),+ f.options,+ f.deps,+ ),+ ).rejects.toThrow("retained Inspector");+ row.evidence.source_data = {};+ const wiz = { ...f.options, provider: "wiz" as const };+ await expect(+ prepareNormalizedLocalImport(+ normalized([row]),+ { ...wiz, inspectorProjectMap: new Map() },+ f.deps,+ ),+ ).rejects.toThrow("map requires the inspector provider");+ const otherProvider = await prepareNormalizedLocalImport(+ normalized([row]),+ wiz,+ f.deps,+ );+ expect(otherProvider.preview.findings[0]!.source_finding_id).toBe(+ native.findingArn,+ );+});diff --git a/sdk/typescript/tests-ts/support/inspector-import-fixtures.ts b/sdk/typescript/tests-ts/support/inspector-import-fixtures.tsnew file mode 100644index 000000000..5f44c8ec5--- /dev/null+++ b/sdk/typescript/tests-ts/support/inspector-import-fixtures.ts@@ -0,0 +1,56 @@+export const inspectorRepositoryUrl = "https://github.com/example/project";+export const inspectorIntegrationArn =+ "arn:aws:inspector2:us-east-1:123456789012:codesecurity-integration/11111111-1111-4111-8111-111111111111";+export const inspectorProjectId =+ "project-22222222-2222-4222-8222-222222222222";++export function inspectorPackageFinding() {+ return {+ findingArn: `arn:aws:inspector2:us-east-1:123456789012:finding/${"a".repeat(32)}`,+ awsAccountId: "123456789012",+ type: "PACKAGE_VULNERABILITY",+ title: "Synthetic dependency finding",+ description: "A repository dependency was reported by Inspector.",+ severity: "HIGH",+ status: "ACTIVE",+ firstObservedAt: "2026-01-02T03:04:05Z",+ lastObservedAt: "2026-01-03T04:05:06Z",+ updatedAt: "2026-01-04T05:06:07Z",+ remediation: { recommendation: { text: "Review the dependency update." } },+ resources: [+ {+ id: `${inspectorIntegrationArn}/${inspectorProjectId}`,+ type: "CODE_REPOSITORY",+ partition: "aws",+ region: "us-east-1",+ details: {+ codeRepository: {+ projectName: inspectorRepositoryUrl,+ integrationArn: inspectorIntegrationArn,+ providerType: "GITHUB",+ },+ },+ },+ ],+ fixAvailable: "YES",+ packageVulnerabilityDetails: {+ vulnerabilityId: "CVE-2099-1234",+ source: "NVD",+ sourceUrl: "https://example.invalid/advisories/CVE-2099-1234",+ relatedVulnerabilities: ["GHSA-2345-6789-cfgh"],+ vulnerablePackages: [+ {+ name: "example-package",+ version: "1.0.0",+ fixedInVersion: "1.0.1",+ packageManager: "NPM",+ filePath: "apps/web/package.json",+ },+ ],+ },+ };+}++export function inspectorReport() {+ return { findings: [inspectorPackageFinding()] };+}