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(imports): import saved Semgrep selections through the CLI (#2166)
Michael D'Angelo3f501a2e15df
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.mdindex a8bfaa55b..625373a9f 100644--- a/docs/scanner-imports/schema-guide.md+++ b/docs/scanner-imports/schema-guide.md@@ -23,17 +23,17 @@ The reader derives the source finding ID from the export. The differences matterwhen a finding moves, an advisory affects several packages, or the export formatchanges.-| Report | What identifies one record |-| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| [Amazon Inspector](inspector.md), [Endor Labs](endor.md), [SonarQube Cloud](sonar.md) | Inspector finding ARN, Endor Finding UUID or Sonar issue key. Endor native JSON and SARIF use the same UUID. |-| [AWS Continuum](continuum.md) | Continuum finding ARN. A list summary and a detailed response for that ARN update the same record. |-| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |-| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |-| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |-| [Snyk Open Source](snyk.md) | Native CLI JSON distinguishes manifest, package manager, advisory, package name and version, and dependency path. Plugin and SARIF reports use different identities. |-| [Black Duck SCA](blackduck.md), [Veracode Static Analysis](veracode.md) | Black Duck combines project version, component version, origin and advisory identity. Veracode scopes a native issue ID to its API origin, application and context. |-| [Semgrep CLI or CI reports](semgrep.md), [OpenGrep](opengrep.md) | Semgrep prefers a fingerprint and falls back to rule, path and range. OpenGrep groups traces by rule, path and range. Both store provider `semgrep`. Use a separate OpenGrep source key. |-| [Semgrep Platform SAST](semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk) | Deployment, project ID, SAST product, full Git ref and native finding ID. The same occurrence keeps its identity when its file moves. |+| Report | What identifies one record |+| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| [Amazon Inspector](inspector.md), [Endor Labs](endor.md), [SonarQube Cloud](sonar.md) | Inspector finding ARN, Endor Finding UUID or Sonar issue key. Endor native JSON and SARIF use the same UUID. |+| [AWS Continuum](continuum.md) | Continuum finding ARN. A list summary and a detailed response for that ARN update the same record. |+| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |+| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |+| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |+| [Snyk Open Source](snyk.md) | Native CLI JSON distinguishes manifest, package manager, advisory, package name and version, and dependency path. Plugin and SARIF reports use different identities. |+| [Black Duck SCA](blackduck.md), [Veracode Static Analysis](veracode.md) | Black Duck combines project version, component version, origin and advisory identity. Veracode scopes a native issue ID to its API origin, application and context. |+| [Semgrep CLI or CI reports](semgrep.md), [OpenGrep](opengrep.md) | Semgrep prefers a fingerprint and falls back to rule, path and range. OpenGrep groups traces by rule, path and range. Both store provider `semgrep`. Use a separate OpenGrep source key. |+| [Semgrep Platform SAST](semgrep.md#existing-platform-findings) | Deployment, project ID, SAST product, full Git ref and native finding ID. The same occurrence keeps its identity when its file moves. |Repeat local imports replace changed evidence for the same identity. Identicalevidence is unchanged, and records omitted from a later report remain stored.diff --git a/docs/scanner-imports/semgrep.md b/docs/scanner-imports/semgrep.mdindex 3a51a4114..6d1c87fb8 100644--- a/docs/scanner-imports/semgrep.md+++ b/docs/scanner-imports/semgrep.md@@ -7,6 +7,8 @@ For selected findings from the Semgrep Platform API, use the## Quick start+For local import of selected existing Code findings, see [Existing Platform findings](#existing-platform-findings).+[Enable external imports](README.md#preview-a-report). From the scanned checkout root,preview a saved SAST report using the repository's credential-free HTTP(S) URLand a stable key for the organization, project and branch. If you need a report,@@ -33,6 +35,91 @@ or wholly excluded report, the preview alone does not establish a repository mat[Save or publish and verify](README.md#save-or-publish-and-verify) using thesame source URL and key. Cloud uses the `semgrep` provider.+## Existing Platform findings++Use the SDK to select exact IDs from **Semgrep Code (SAST)**. The official+[Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex)+can help identify them. For import, save the native+[project response](https://docs.semgrep.dev/api-reference/v1/projectsservice/get-project-details)+and the [Findings API pages](https://docs.semgrep.dev/api-reference/v1/findingsservice/list-code-supply-chain-or-ai-powered-detection-findings)+for that deployment, project ID and fully qualified Git ref (for example,+`refs/heads/release` or `refs/tags/release`), using `issue_type=sast` and+`dedup=false`. Use a Web API token with read access. Read through the pages+until you have the requested IDs. Use a project with an HTTP(S) repository URL.+For Git fetch URLs on an IP address, use its canonical spelling in the checkout+(for example, `127.0.0.1` or `[::1]`) so the HTTP host identifies the same source.+Each selected finding must match the requested ref. When the finding includes+a repository URL or project ID, each must match the selected project. If the URL+is absent, the native project ID and full repository name must match the decoded+path of the project URL.++Pass the response text directly to the selector to preserve numeric IDs and+other numeric evidence exactly. Keep the responses and selection together in a+private directory outside the checkout. Run this example in that directory+with the SDK installed. Local preview compares the project URL with Git’s+named fetch URLs offline. If a checkout only has legacy or unreadable Git remote+metadata, configure a normal named fetch URL first, for example+`git remote add scanner-origin <verified-url>`. Checkouts with empty or absent+legacy remote directories can also use Git's default fetch source. With legacy+metadata present, use a named remote with a nonempty final URL entry. The local+Git and SSH clients control SSH command overrides and DNS routing.++```js+import { readFile, writeFile } from "node:fs/promises";+import { selectSemgrepPlatformFindings } from "@openai/codex-security";++const selected = selectSemgrepPlatformFindings({+ deployment: "example",+ ref: "refs/heads/release",+ projectResponse: await readFile("project.json", "utf8"),+ findingsResponses: [await readFile("page-0.json", "utf8")],+ findingIds: ["101", "103"],+});+await writeFile("selected.json", JSON.stringify(selected), {+ flag: "wx",+ mode: 0o600,+});+```++Preview and import the saved selection into the local workbench:++```sh+codex-security publish findings /path/to/private/selected.json --to local --provider semgrep \+ --repository /path/to/project --source-key example/project/release/platform --dry-run+```++After review, repeat without `--dry-run` and confirm the import. Reusing the+same source key updates the same records, keyed by deployment, project ID,+product, ref and finding ID. Semgrep's native signed 64-bit IDs match across the SDK+and file workflows. For synthetic IDs above that range, the two workflows can+produce different keys, even from a new capture. To replay those IDs, use the+same workflow and preserve the original ID spelling and JSON type (number or+string).++Replay preserves the exact ref of an existing selection, including an older+short ref. The archive reader compares the stored ref as literal identity text+and never evaluates it as a Git revision. For URL-less rows with a matching+native repository ID and ref, the saved-file reader also accepts the complete+percent-encoded repository path. New captures require the decoded path.+Importing the same findings reports unchanged+records even if the API reordered JSON object keys. Use a separate source key+for CLI scans. The selected native finding is retained as JSON text in+`source_data.semgrepPlatformFindingJson`, including locations that cannot be mapped to the repository.+Projected code locations retain the original spelling of a valid relative+`location.file_path`, including literal backslashes. The API row does not+identify the path convention. For a custom GitHub Enterprise host, supply the trusted+repository URL and `platform: "github"` in the SDK `sourceRepositories` option+when selecting and preparing the records. For an independently known self-managed+GitLab instance, `platform: "gitlab"` allows its HTTPS web and clone URLs to+differ by the usual `.git` suffix. For an internationalized hostname, use its+ASCII (Punycode) spelling in the Git SSH remote. OpenSSH can send the literal+UTF-8 hostname to DNS while the HTTPS project URL uses its ASCII spelling.++When passing normalized findings to the SDK, keep each generated Semgrep+`source_finding_id` with the native row it identifies. To migrate a row to a+caller-managed identity, use an opaque ID of your own. The generated Semgrep ID+requires the original scoped evidence on every import.+## Reference### CI artifactsdiff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex e8d956cff..bc0462051 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -90,7 +90,7 @@ Prefer native Code/SAST CLI or CI JSON for this reader; use self-contained SARIFFor a user-requested new scan, use the installed Semgrep CLI from the source repository root with the selected SAST rules: `semgrep scan --config /path/to/sast-rules.yaml --json-output /path/to/semgrep.json .`. Existing CI jobs can produce the same artifact using `--json-output`; authenticated `semgrep ci --code` follows the job's policy and baseline scope. Explain that this generates fresh scan findings, and do not substitute it for a request to retrieve existing Platform findings.-For selected Semgrep Platform SAST findings, follow the [local SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk). It takes the original Web API project response, SAST findings pages and selected IDs. The [Semgrep Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex) can help select and inspect findings. Guardian and the `semgrep_findings` MCP tool return different records from the SDK inputs.+For selected Semgrep Platform SAST findings, follow the [local SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk). It takes the original Web API project response, SAST findings pages and selected IDs. The [Semgrep Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex) can help select and inspect findings. Guardian and the `semgrep_findings` MCP tool return different records from the SDK inputs. For CLI import, [save and preview the selected findings locally](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#existing-platform-findings) with the same source key on replay.Import the native report with `--provider semgrep`, a stable organization/project/branch `--source-key`, and `--source-repository-url` identifying the actual source repository. Use `--to local --repository /path/to/project` for local storage or `--to cloud --repository URL_OR_ID` for Cloud. The source URL is checked against configured local Git remotes or the Cloud destination. Preview with `--dry-run --format json` before confirming the import.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex c61dda1a6..7936c61af 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -705,6 +705,7 @@ with parsed JSON. Verify the repository for the selected findings before passingUse `normalizeSelectedSemgrepPlatformFindings` for selected SAST findings from savedSemgrep Web API responses. See the [Semgrep SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk).+Use `selectSemgrepPlatformFindings` to [save a selection for the local CLI](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#existing-platform-findings).This does not affect scan publishing or the existing GitHub alert collector.The SDK also exposes `prepareExternalPublication(file, options)` for supporteddiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex fe906aff5..8c36bd3df 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1359,6 +1359,8 @@ source key and finding ID reports created, updated, or unchanged records.Records omitted from the new selection stay stored. An import with exclusionsexits with status 1. Local imports can retain evidence that exceeds Cloud's per-finding limits.+Use `--provider semgrep` for a [saved Semgrep Platform selection](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#existing-platform-findings).+For completed scans exported in the Codex Security JSON or CSV format, use[scan import](#import-findings-as-a-saved-scan).diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex b1282ffbd..49ff0fdf1 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -36,6 +36,8 @@ const distModules = ["scanner-repository-url","semgrep-findings","semgrep-platform-findings",+ "hosted-git-remotes",+ "hosted-git-repository","sonar-findings","sonar-collector","sonar-import",diff --git a/sdk/typescript/src/external-findings-import.ts b/sdk/typescript/src/external-findings-import.tsindex 599c92133..dea493c7a 100644--- a/sdk/typescript/src/external-findings-import.ts+++ b/sdk/typescript/src/external-findings-import.ts@@ -31,7 +31,7 @@ export async function prepareLocalExternalImport(dependencies.sourceRepositories,);const parsed = await abortable(- () => readExternalFindings(path, settings, "local"),+ () => readExternalFindings(path, settings, "local", readerSources),dependencies.signal,);const normalizedOptions = {@@ -39,10 +39,13 @@ export async function prepareLocalExternalImport(provider: EXTERNAL_FINDINGS_PROVIDERS[settings.provider],};let sourceRepositories = parsed.sourceRepositories ?? [];- if (normalizedOptions.provider === "semgrep") {+ if (+ normalizedOptions.provider === "semgrep" &&+ settings.sourceRepositoryUrl+ ) {// 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 = settings.sourceRepositoryUrl!;+ const source = settings.sourceRepositoryUrl;const knownGitHub = readerSources.some(({ url, platform }) =>platform === "github" &&diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex d99f79291..90135590b 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -1,3 +1,14 @@+import {+ isSemgrepSelectionEvidence,+ semgrepReferenceMatches,+ semgrepSelectionRepository,+} from "./semgrep-platform-findings.js";+import {+ gitPathToHttpPath,+ gitTransportBytes,+ hostedRepositoryMatches,+} from "./hosted-git-repository.js";+import { readHostedGitRemotes } from "./hosted-git-remotes.js";import { CodexSecurityError } from "./errors.js";import {forwardExternalImportSetting,@@ -20,7 +31,10 @@ import type {ExternalFindingEvidence,Provider,} from "./external-import-models.js";-import { localFindingRepositories } from "./external-findings-read.js";+import {+ localFindingRepositories,+ semgrepSarifRepositories,+} from "./external-findings-read.js";import {hasGitMetadata,localGitProtectionRoots,@@ -239,16 +253,8 @@ function remoteRepository(}// 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 gitPath = gitTransportBytes(transport?.[2] ?? path, scpStyle);const login = scpStyle? /^([^@/:\s?#]+)@/u.exec(value)?.[1]: /^(.*)@/u.exec(authority ?? "")?.[1];@@ -256,14 +262,7 @@ function remoteRepository(/^\/?~(?:\/|$)/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 name = gitPathToHttpPath(gitPath.slice(0, suffix?.index));// Azure's generated SCP clone URL spells spaces as %20, even though Git sends SCP paths literally.const azure =provider === "sonar" && !(scpStyle && path.startsWith("/"))@@ -279,7 +278,7 @@ function remoteRepository(: key(azure ?? origin + name);return {key: repository,- account: ssh && login ? literal(login) : undefined,+ account: ssh && login ? gitTransportBytes(login, scpStyle) : undefined,// GitHub serves the same repository path through its SCP and SSH URLs.homeRelative:ssh && platform !== "github" && !isGitHubCloudHost(hostname.toLowerCase())@@ -304,6 +303,41 @@ function matchingRemote();}+// Within one fetch key and home-relative mode, matchingRemote can use any+// account, the requested login, or an unspecified login.+function fetchAliasMatcher(+ rows: readonly { fetch: RemoteRepositoryIdentity }[],+) {+ const homes = Map.groupBy(rows, ({ fetch }) => fetch.homeRelative);+ const accounts = Array.from(+ homes.values(),+ (group) => new Map(group.map(({ fetch }) => [fetch.account, fetch])),+ );+ return (fetch: RemoteRepositoryIdentity) =>+ accounts.some((group) =>+ [+ group.values().next().value,+ group.get(fetch.account),+ group.get(undefined),+ ].some(+ (candidate) =>+ candidate !== undefined && matchingRemote(fetch, candidate),+ ),+ );+}++function fetchAliasMatchers<+ Row extends { fetch: RemoteRepositoryIdentity },+ Key,+>(rows: readonly Row[], key: (row: Row) => Key) {+ return new Map(+ Array.from(+ Map.groupBy(rows, key),+ ([name, group]) => [name, fetchAliasMatcher(group)] as const,+ ),+ );+}+/** A credential-free Sonar repository binding from a supported Git fetch transport. */export function sonarRepositoryForRemote(origin: string): string | undefined {try {@@ -508,14 +542,37 @@ async function requireMatchingRepository(provider: Provider,sources: readonly ExternalSourceRepository[],strictSources: ReadonlyMap<string, Provider>,- strictPlatformFor: (source: ExternalSourceRepository) => Provider,- protectedRoots: WorkbenchCommandOptions["protectedRoot"],+ hostedSources: readonly ExternalSourceRepository[],+ platformFor: (source: ExternalSourceRepository, bound: boolean) => Provider,+ protectedRoots: string[],environment: WorkbenchCommandOptions["environment"],signal?: AbortSignal,possibleSshHost?: string,fetchRemotes?: readonly ConfiguredFetchRemote[],): Promise<boolean> {- if (sources.length === 0) return false;+ if (sources.length === 0 && hostedSources.length === 0) return false;+ let allSourcesMatched = true;+ if (hostedSources.length) {+ if (!(await hasGitMetadata(repository, signal))) return false;+ const remotes = await readHostedGitRemotes(+ repository,+ [+ ...protectedRoots,+ await abortable(() => canonicalConfigPath(process.cwd()), signal),+ ],+ environment,+ signal,+ );+ allSourcesMatched = remotes !== undefined;+ if (remotes) {+ for (const source of hostedSources)+ if (!remotes.some((remote) => hostedRepositoryMatches(source, remote)))+ throw new CodexSecurityError(+ `Imported repository ${JSON.stringify(source.url)} does not match a configured remote of ${repository}. Select the matching local repository.`,+ );+ }+ if (!sources.length) return allSourcesMatched;+ }const remotes =fetchRemotes ??(await configuredFetchRemotes(@@ -531,7 +588,6 @@ async function requireMatchingRepository(provider === "inspector" ||provider === "blackduck" ||provider === "veracode";- const loosePlatformFor = localRepositoryPlatform(provider, sources, false);const comparable: string[] = [];const unverified: string[] = [];for (const { url: remote } of remotes) {@@ -540,12 +596,10 @@ async function requireMatchingRepository(if (verified) comparable.push(verified);else if (!/[\s\\\p{Cc}?#]/u.test(remote)) unverified.push(remote);}- let allSourcesMatched = true;for (const source of sources) {const bound = boundProvider || strictSources.has(source.url);- const platform = bound- ? (strictSources.get(source.url) ?? strictPlatformFor(source))- : loosePlatformFor(source);+ const platform =+ strictSources.get(source.url) ?? platformFor(source, bound);const identity = (url: string) =>remoteRepository(url, provider, bound, platform);const targets = comparable.flatMap((remote) => identity(remote) ?? []);@@ -582,6 +636,7 @@ export function sonarCheckoutMatchesSource("sonar",[{ url }],new Map(),+ [],() => "sonar",[...protectedRoots],environment,@@ -768,13 +823,43 @@ export async function prepareLocalImport(}}const strictSources = new Map<string, Provider>();+ const hostedSources = new Map<string, ExternalSourceRepository>();const known = new Set<string>(parsedSources.map(({ url }) => url));+ const hasPlatformEvidence =+ options.provider === "semgrep" &&+ current.findings.some(isSemgrepSelectionEvidence);+ let hasOrdinaryRows = false;+ let ordinaryRowNeedsReferences = false;for (const finding of current.findings) {+ const semgrep = semgrepSelectionRepository(finding, readerSources);+ if (semgrep && options.provider !== "semgrep")+ throw new CodexSecurityError(+ "Use the semgrep provider for Semgrep Platform selections.",+ );+ if (semgrep) hostedSources.set(semgrep.url, semgrep);+ else hasOrdinaryRows = true;const { evidence, source_finding_id: id } = finding;const url = evidence.details?.repository?.url;- if (url) sources.set(url, { url });const retained = bound.get(id);const native = nativeSources.get(finding) ?? [];+ // A selected row's projected URL was already verified against its hosted source.+ if (!semgrep && url) sources.set(url, { url });+ if (hasPlatformEvidence && !semgrep && !retained && !native.length) {+ const sarif = semgrepSarifRepositories(finding);+ for (const source of sarif) sources.set(source.url, source);+ if (!url && !sarif.length) ordinaryRowNeedsReferences = true;+ if (!url && references.length) {+ for (const source of sarif) {+ const claim = identify(source.url);+ if (+ !references.some((ref) => matchingRemote(claim, identify(ref.url)))+ )+ throw new CodexSecurityError(+ `The reader must supply the projected Semgrep SARIF repository ${JSON.stringify(source.url)} for the configured remote.`,+ );+ }+ }+ }if (retained) {const claims = [retained.url,@@ -815,12 +900,76 @@ export async function prepareLocalImport(}for (const source of native) known.add(source.url);}+ // Match references for native Platform rows using their hosted Git identity.+ const hosted = Array.from(hostedSources.values());+ const hostedReferences = new Set(+ references.filter((ref) =>+ hosted.some((source) => semgrepReferenceMatches(source, ref.url)),+ ),+ );+ const sharedReferences = new Set<ExternalSourceRepository>();+ const ordinaryReferences = new Set<ExternalSourceRepository>();+ if (hostedReferences.size) {+ const readerPlatform = localRepositoryPlatform(+ options.provider,+ [...sources.values(), ...references],+ false,+ );+ const ordinaryIdentity = (url: string) =>+ remoteRepository(+ url,+ options.provider,+ false,+ readerPlatform({ url }),+ ) ?? { key: url };+ const aliases = references.map((ref) => ({+ ref,+ fetch: identify(ref.url),+ ordinary: ordinaryIdentity(ref.url).key,+ }));+ const claims = Map.groupBy(+ Array.from(sources.keys(), (url) => ({+ fetch: identify(url),+ ordinary: strictSources.has(url)+ ? undefined+ : ordinaryIdentity(url).key,+ })),+ (claim) => claim.fetch.key,+ );+ for (const [key, refs] of Map.groupBy(+ aliases,+ (alias) => alias.fetch.key,+ )) {+ const hosted = refs.filter(({ ref }) => hostedReferences.has(ref));+ const group = claims.get(key);+ if (!hosted.length || !group) continue;+ const shared = fetchAliasMatcher(group);+ const readers = fetchAliasMatchers(refs, (alias) => alias.ordinary);+ // Keep a sole fetch alias subject to checkout validation. A redundant+ // Platform spelling can be dropped when another reference serves the reader.+ const required = fetchAliasMatchers(group, ({ fetch, ordinary }) =>+ ordinary !== undefined && readers.get(ordinary)?.(fetch)+ ? ordinary+ : undefined,+ );+ for (const alias of hosted) {+ if (!shared(alias.fetch)) continue;+ sharedReferences.add(alias.ref);+ if (+ required.get(undefined)?.(alias.fetch) ||+ required.get(alias.ordinary)?.(alias.fetch)+ )+ ordinaryReferences.add(alias.ref);+ }+ }+ }if (mixed) {- // A caller reference with no matching row spelling can still be a Git alias.+ // Other caller references must identify an ordinary row or one of its Git aliases.const rows = [...sources.keys(), ...known].map(identify);const byKey = Map.groupBy(rows, (remote) => remote.key);const represented = new Set(rows.map((remote) => JSON.stringify(remote)));const aliases = readerSources+ .filter((ref) => !hostedReferences.has(ref) || sharedReferences.has(ref)).map(({ url }) => identify(url)).filter((remote) => !represented.has(JSON.stringify(remote)));for (const [key, group] of Map.groupBy(aliases, (remote) => remote.key)) {@@ -836,11 +985,17 @@ export async function prepareLocalImport(Array.from(strictSources.keys(), (url) => identify(url).key),);for (const source of references)- if (!strictSources.has(source.url) && keys.has(identify(source.url).key))+ if (+ !strictSources.has(source.url) &&+ keys.has(identify(source.url).key)+ ) {strictSources.set(source.url, platformFor(source));+ if (sharedReferences.has(source)) ordinaryReferences.add(source);+ }}if (inspector) {- const platform = inspector.platform ?? options.provider;+ const platform =+ inspector.platform === "github" ? "github" : options.provider;const native = remoteRepository(inspector.url,options.provider,@@ -858,7 +1013,28 @@ export async function prepareLocalImport();}}+ if (+ readerSources.length &&+ hosted.length &&+ ((!hasOrdinaryRows &&+ !readerSources.every((ref) => hostedReferences.has(ref))) ||+ hosted.some(+ (source) =>+ !readerSources.some((ref) =>+ semgrepReferenceMatches(source, ref.url),+ ),+ ))+ )+ throw new CodexSecurityError(+ "The reader's source repository does not match the selected Semgrep project.",+ );for (const source of [...(inspector ? [inspector] : []), ...references]) {+ if (+ !ordinaryRowNeedsReferences &&+ hostedReferences.has(source) &&+ !ordinaryReferences.has(source)+ )+ continue;// A reader's platform must not loosen an operator-supplied Inspector map.if (sources.get(source.url)?.platform !== "github")sources.set(@@ -903,13 +1079,21 @@ export async function prepareLocalImport(url: dependabotSource,platform: "github",});+ const ordinarySources = [...sources.values()];+ // A reader can identify the VCS for both a hosted project and an ordinary row.+ const loosePlatformFor = localRepositoryPlatform(+ options.provider,+ [...ordinarySources, ...hostedReferences],+ false,+ );const selected = manualSource ? new URL(manualSource) : undefined;const matchesRepositoryRemote = await requireMatchingRepository(repository,options.provider,- [...sources.values()],+ ordinarySources,strictSources,- platformFor,+ hosted,+ (source, bound) => (bound ? platformFor(source) : loosePlatformFor(source)),workbenchOptions.protectedRoot,workbenchOptions.environment,dependencies.signal,diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 849f14ab2..0b084c69e 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -12,7 +12,12 @@ import {import { createRequire } from "node:module";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";-import { isBoxedPrimitive, isNativeError, isProxy } from "node:util/types";+import {+ isBoxedPrimitive,+ isNativeError,+ isProxy,+ isStringObject,+} from "node:util/types";import {privateImportClient,selectPrivateReport,@@ -27,6 +32,7 @@ import {cloudFindingsUrl,DEFAULT_CLOUD_BASE_URL,} from "./cloud-endpoint.js";+import { isSemgrepSelectionEvidence } from "./semgrep-platform-findings.js";import { CodexSecurityError, errorMessage } from "./errors.js";import { requireExternalImports } from "./external-imports-feature.js";import {@@ -64,6 +70,7 @@ import {cloneImportPreview,nativeErrorStackGetter,snapshotNormalizedFindings,+ type ExternalFinding,type ExternalFindings,type ExternalPublicationInput,} from "./external-findings.js";@@ -475,6 +482,48 @@ async function withImportLocks<T>(}}+// A caller's serializer may deliberately omit an ID accessor. Inspect stored+// IDs here and check the actual exported rows after normalization.+function storedFindingId(finding: ExternalFinding): string {+ const seen = new Set<object>();+ for (+ let owner: object | null = finding;+ owner && !seen.has(owner);+ owner = Object.getPrototypeOf(owner) as object | null+ ) {+ const property = Object.getOwnPropertyDescriptor(+ owner,+ "source_finding_id",+ );+ if (property) {+ const id: unknown = property.value;+ return typeof id === "string" || isStringObject(id)+ ? String.prototype.valueOf.call(id)+ : "";+ }+ seen.add(owner);+ }+ return "";+}++function rejectLocalSelections(input: ExternalFindings): void {+ const rows = input?.findings;+ if (!Array.isArray(rows)) return;+ if (+ rows.some(+ (row) =>+ row &&+ isSemgrepSelectionEvidence({+ source_finding_id: storedFindingId(row),+ evidence: row.evidence,+ }),+ )+ )+ throw new CodexSecurityError(+ "Semgrep Platform selections require a local import.",+ );+}+export async function prepareExternalPublication(path: string,options: ExternalPublicationOptions,@@ -483,6 +532,7 @@ export async function prepareExternalPublication(requireExternalImports(dependencies.environment);const settings = snapshotImportOptions(options);const parsed = await readExternalFindings(path, settings);+ rejectLocalSelections(parsed.findings);return preparePublicationInput(parsed.publication ?? normalizedPublicationInput(parsed.findings),{ ...settings, provider: EXTERNAL_FINDINGS_PROVIDERS[settings.provider] },@@ -498,6 +548,7 @@ export async function prepareNormalizedExternalPublication(dependencies: ExternalPublicationDependencies = {},): Promise<PreparedExternalPublication> {requireExternalImports(dependencies.environment);+ rejectLocalSelections(input);const settings = snapshotImportOptions(options);return preparePublicationInput(normalizedPublicationInput(input),@@ -759,6 +810,7 @@ function normalizedPublicationInput(: undefined;if (reader) native = reader.snapshot;const original = historicalPublication(native);+ if (original) rejectLocalSelections(original.parsed);try {validatePublicationFindings(current, validateExternalEvidence);} catch (error) {@@ -771,6 +823,7 @@ function normalizedPublicationInput(// Only the old selection can be reviewed when fresh validation failed.current = { read: original.parsed.read, findings: [], excluded: [] };}+ rejectLocalSelections(current);const identity = publicationIdentity(current);return {current,@@ -1117,6 +1170,7 @@ async function preparePublicationInput(!verifiableLegacyMetadata(originalParsed, true))throw unmatchedPreviousNumbers();+ rejectLocalSelections({ ...parsed, findings: saved });return content;}@@ -1128,7 +1182,8 @@ async function preparePublicationInput(): SavedSubmission | "different-wire" | undefined {const content = readSaved(record);const projection = content.inputProjection;- const savedWire = wireJson(submissionFindings(content.requests));+ const saved = submissionFindings(content.requests);+ const savedWire = wireJson(saved);const wireDigest = hash("sha256", savedWire);if (projection?.inputDigest !== jsonDigest(originalIdentity, canonicalJson))throw unmatchedPreviousNumbers();@@ -1150,6 +1205,7 @@ async function preparePublicationInput(!verifiableLegacyMetadata(originalParsed, false))throw unmatchedPreviousNumbers();+ rejectLocalSelections({ ...parsed, findings: saved });content.legacyApproval = true;content.inputProjection = {identityFormat: 2,diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex 46e0ce102..25f8c2a89 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -7,7 +7,10 @@ import type {import type { Provider } from "./external-import-models.js";import type { ExternalImportTarget } from "./external-import-contract.js";import { readSnykFindings, snykRepositoryUrls } from "./snyk-findings.js";-import { readSemgrepFindings } from "./semgrep-findings.js";+import {+ isSemgrepSarifDriver,+ readSemgrepFindings,+} from "./semgrep-findings.js";import { readOpenGrepFindings } from "./opengrep-findings.js";import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";import { dependabotRepository } from "./github-dependabot-findings.js";@@ -84,11 +87,43 @@ export function localFindingRepositories(return [];}+/** Repository claims retained by the Semgrep SARIF reader. */+export function semgrepSarifRepositories({+ evidence,+}: ExternalFinding): ExternalSourceRepository[] {+ const data = evidence.source_data;+ const document = data?.["documentContext"];+ const driver = data?.["driverContext"];+ if (+ !isRecord(document) ||+ document["version"] !== "2.1.0" ||+ !isRecord(driver) ||+ typeof driver["name"] !== "string" ||+ !isSemgrepSarifDriver(driver["name"]) ||+ !isRecord(data?.["result"])+ )+ return [];+ const context = data["runContext"];+ const references = isRecord(context)+ ? context["versionControlProvenance"]+ : undefined;+ return Array.isArray(references)+ ? references.flatMap((reference) =>+ isRecord(reference) &&+ typeof reference["repositoryUri"] === "string" &&+ reference["repositoryUri"].trim()+ ? [{ url: reference["repositoryUri"] }]+ : [],+ )+ : [];+}+/** @internal Read vendor evidence for the local and Cloud import entrypoints. */export async function readExternalFindings(path: string,options: ExternalFindingsReaderOptions,target: ExternalImportTarget = "cloud",+ references: readonly ExternalSourceRepository[] = [],): Promise<ReadExternalFindings> {if (options.provider === "sonar") {const url = options.sourceRepositoryUrl;@@ -128,24 +163,13 @@ export async function readExternalFindings(path,{sourceRepositoryUrl: options.sourceRepositoryUrl ?? "",+ sourceRepositories: references,},target,);- const sourceRepositories = findings.findings.flatMap(({ evidence }) => {- const context = evidence.source_data?.["runContext"];- const references = isRecord(context)- ? context["versionControlProvenance"]- : undefined;- return Array.isArray(references)- ? references.flatMap((reference) =>- isRecord(reference) &&- typeof reference["repositoryUri"] === "string" &&- reference["repositoryUri"].trim()- ? [{ url: reference["repositoryUri"] }]- : [],- )- : [];- });+ const sourceRepositories = findings.findings.flatMap(+ semgrepSarifRepositories,+ );return { findings, sourceRepositories };}if (options.provider === "github")diff --git a/sdk/typescript/src/external-findings.ts b/sdk/typescript/src/external-findings.tsindex 3738a72f4..44cd66702 100644--- a/sdk/typescript/src/external-findings.ts+++ b/sdk/typescript/src/external-findings.ts@@ -19,7 +19,7 @@ export interface ExternalFinding {/** Repository provenance retained by a reader outside the published evidence. */export interface ExternalSourceRepository {url: string;- platform?: "github";+ platform?: "github" | "gitlab";}export function snapshotSourceRepositories(diff --git a/sdk/typescript/src/external-import-contract.ts b/sdk/typescript/src/external-import-contract.tsindex df39c7818..fdc64fdb7 100644--- a/sdk/typescript/src/external-import-contract.ts+++ b/sdk/typescript/src/external-import-contract.ts@@ -228,7 +228,7 @@ export const validateSourceReports =export const validateSourceReport = validator<SourceReport>("SourceReport");// Normalize equivalent JSON numbers exactly. Keep very large exponents compact.-export function canonicalNumber(token: string): string {+export function canonicalNumber(token: string, fixedDigits = 21): string {const [, sign = "", integer, fraction = "", exponent = "0"] =/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/iu.exec(token)!;const significant = (integer + fraction).replace(/^0+/u, "");@@ -238,7 +238,7 @@ export function canonicalNumber(token: string): string {const digits = significant.slice(0, end);const point = BigInt(exponent) + BigInt(significant.length - fraction.length);// Ordinary evidence follows JSON.stringify’s fixed/scientific notation thresholds.- if (point > -6n && point <= 21n) {+ if (point > -6n && point <= BigInt(fixedDigits)) {const split = Number(point);if (split <= 0) return sign + "0." + "0".repeat(-split) + digits;if (split >= digits.length) return sign + digits.padEnd(split, "0");diff --git a/sdk/typescript/src/hosted-git-remotes.ts b/sdk/typescript/src/hosted-git-remotes.tsnew file mode 100644index 000000000..1dace6433--- /dev/null+++ b/sdk/typescript/src/hosted-git-remotes.ts@@ -0,0 +1,319 @@+import { constants } from "node:fs";+import { access, lstat, readdir, stat } from "node:fs/promises";+import { delimiter, isAbsolute, join, resolve, sep } from "node:path";++import { isUtf8 } from "node:buffer";+import { environmentEntry } from "./auth.js";+import {+ isLocalGitRemote,+ isWindowsGitDrive,+} from "./hosted-git-repository.js";+import { abortable, gitOutput, trustedGitCommand } from "./targets.js";++async function recognizedCurlHelper(+ name: string,+ repository: string,+ trustedEnvironment: () => Promise<NodeJS.ProcessEnv>,+ readGit: (args: readonly string[]) => Promise<string | undefined>,+): Promise<boolean> {+ const lower = name.toLowerCase();+ if (!/^(?:https?|ftps?)$/u.test(lower)) return false;+ if (name === lower) return true;++ const environment = await trustedEnvironment();+ const execPath = await readGit(["--exec-path"]);+ if (!execPath) return false;+ // Git prepends its exec path at the invocation directory and again when dispatching from the worktree.+ const cwd = resolve(+ repository,+ (await readGit(["rev-parse", "--show-cdup"])) ?? "",+ );+ const locations = (base: string) =>+ (isAbsolute(execPath) ? execPath : base + sep + execPath).split(delimiter);+ const directories = [+ ...locations(cwd),+ ...(cwd === repository ? [] : locations(repository)),+ ...(environmentEntry(environment, "PATH") ?? "").split(delimiter),+ ];+ const find = async (helper: string) => {+ for (const dir of directories) {+ // Git for Windows tries .exe before the extensionless helper, within each directory.+ for (const suffix of process.platform === "win32" ? [".exe", ""] : [""]) {+ const filename = "git-remote-" + helper + suffix;+ // POSIX resolves symlinks before a following '..', as Git does during PATH lookup.+ const path =+ process.platform === "win32"+ ? resolve(cwd, dir, filename)+ : (dir.startsWith("/") ? dir : cwd + "/" + dir) + "/" + filename;+ try {+ await access(+ path,+ process.platform === "win32" ? constants.F_OK : constants.X_OK,+ );+ const file = await stat(path, { bigint: true });+ if (file.isFile()) return file;+ if (suffix) return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== "ENOENT" && code !== "ENOTDIR" && code !== "EACCES")+ return;+ }+ }+ }+ };+ // Different spellings can resolve to one file on a case-insensitive volume.+ const [selected, standard] = await Promise.all([find(name), find(lower)]);+ return (+ !!selected &&+ !!standard &&+ selected.ino !== 0n &&+ selected.dev === standard.dev &&+ selected.ino === standard.ino+ );+}++async function emptyLegacyRemotes(+ common: string | undefined,+): Promise<boolean> {+ if (!common) return false;+ for (const folder of ["remotes", "branches"]) {+ const dir = join(common, folder);+ try {+ if (!(await lstat(dir)).isDirectory() || (await readdir(dir)).length)+ return false;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false;+ }+ }+ return true;+}++/** Read effective external Git URLs without invoking a transport. An empty result means none could be verified. */+export async function readHostedGitRemotes(+ repository: string,+ protectedRoots: string[],+ environment?: NodeJS.ProcessEnv,+ signal?: AbortSignal,+): Promise<string[] | undefined> {+ const readGit = (args: readonly string[]) => {+ const overrides: NodeJS.ProcessEnv = { LC_ALL: "C" };+ // GIT_CONFIG redirects only git config; read the same configuration as git remote.+ if (args[0] === "config")+ for (const name of Object.keys(environment ?? process.env))+ if (+ (process.platform === "win32" ? name.toUpperCase() : name) ===+ "GIT_CONFIG"+ )+ overrides[name] = undefined;+ return abortable(async () => {+ try {+ const output = await gitOutput(+ repository,+ args,+ signal,+ overrides,+ undefined,+ "buffer",+ protectedRoots,+ environment,+ );+ // Keep a byte per character until Git's record boundaries and config keys have been matched.+ return output.toString("latin1").replace(/\n$/u, "");+ } catch (error) {+ // The SDK exposes Git's original UTF-8 diagnostics on command errors.+ if (error instanceof Error) {+ if ("stderr" in error && Buffer.isBuffer(error.stderr))+ error.stderr = error.stderr.toString("utf8");+ if ("stdout" in error && Buffer.isBuffer(error.stdout))+ error.stdout = error.stdout.toString("utf8");+ }+ throw error;+ }+ }, signal);+ };+ const utf8 = (raw: string) => {+ const bytes = Buffer.from(raw, "latin1");+ return isUtf8(bytes) ? bytes.toString("utf8") : undefined;+ };+ let remoteNames: string;+ try {+ remoteNames = await readGit(["remote"]);+ } catch (error) {+ signal?.throwIfAborted();+ // A local source directory need not be a Git checkout.+ if (+ error instanceof Error &&+ "code" in error &&+ error.code === 128 &&+ "stderr" in error &&+ typeof error.stderr === "string" &&+ (error.stderr.trimEnd() ===+ "fatal: not a git repository (or any of the parent directories): .git" ||+ /^fatal: not a git repository \(or any parent up to mount point [^\r\n]+\)\r?\nStopping at filesystem boundary \(GIT_DISCOVERY_ACROSS_FILESYSTEM not set\)\.$/u.test(+ error.stderr.trimEnd(),+ ))+ )+ return;+ throw error;+ }+ const config = await readGit([+ "config",+ "--null",+ "--get-regexp",+ "^(remote\\..*\\.(url|vcs)|branch\\..*\\.remote)$",+ ]).catch((error: unknown) => {+ if (error instanceof Error && "code" in error && error.code === 1)+ return "";+ throw error;+ });+ const settings = new Map<string, string>();+ for (const entry of config.split("\0")) {+ const end = entry.indexOf("\n");+ if (end < 0) continue;+ const key = entry.slice(0, end);+ settings.set(key, entry.slice(end + 1));+ }+ const listed = new Set(remoteNames.split("\n").filter(Boolean));+ const unlistedDefaults = new Set<string>();+ for (const [key, remote] of settings) {+ if (key.startsWith("branch.") && remote && !listed.has(remote))+ unlistedDefaults.add(+ "refs/heads/" + key.slice("branch.".length, -".remote".length),+ );+ }+ const remotes: string[] = [];+ let hasUnverifiedRemote = false;+ async function* candidates() {+ const fallbackNames: string[] = [];+ for (const name of listed) {+ // A nonempty last URL makes named resolution safe even on Git versions where an empty value resets earlier URLs.+ if (settings.get(`remote.${name}.url`)) yield name;+ else fallbackNames.push(name);+ }+ const branch = unlistedDefaults.size+ ? await readGit(["symbolic-ref", "--quiet", "HEAD"]).catch(+ (error: unknown) => {+ if (error instanceof Error && "code" in error && error.code === 1)+ return "";+ throw error;+ },+ )+ : "";+ const additionalDefault = unlistedDefaults.has(branch);+ if (remotes.length && !fallbackNames.length && !additionalDefault) return;++ // An implicit fetch can open legacy descriptors. Inspect directory metadata only.+ const common = utf8(+ await readGit([+ "rev-parse",+ "--path-format=absolute",+ "--git-common-dir",+ ]),+ );+ if (!(await abortable(() => emptyLegacyRemotes(common), signal))) {+ if (!remotes.length)+ throw new Error(+ "Configure a named Git fetch URL (for example, git remote add scanner-origin <verified-url>) to import into this checkout with legacy or unreadable Git remote metadata.",+ );+ return;+ }+ yield* fallbackNames;+ if (additionalDefault || (!remotes.length && !hasUnverifiedRemote))+ yield "";+ }+ for await (const rawName of candidates()) {+ const name = utf8(rawName);+ if (name === undefined) {+ hasUnverifiedRemote = true;+ continue;+ }+ const configuredHelper = settings.get(`remote.${rawName}.vcs`);+ const missingUrl = name+ ? `fatal: remote ${name} has no configured URL`+ : "fatal: No remote configured to list refs from.";+ // Resolve the same first URL as a fetch, including rewrites on an implicit local remote name.+ // --get-url exits before Git connects to a transport.+ const rawUrl = await readGit([+ "ls-remote",+ "--get-url",+ ...(name ? ["--", name] : []),+ ]).catch((error: unknown) => {+ if (+ error instanceof Error &&+ "code" in error &&+ error.code === 128 &&+ "stderr" in error &&+ typeof error.stderr === "string" &&+ error.stderr.split(/\r?\n/u).includes(missingUrl)+ )+ return undefined;+ throw error;+ });+ if (rawUrl === undefined) {+ if (name) hasUnverifiedRemote = true;+ continue;+ }+ // Explicit helper:: takes precedence over remote.<name>.vcs.+ const explicit = /^([a-z0-9][a-z0-9+.-]*)::/iu.exec(rawUrl);+ const helper = explicit?.[1] ?? configuredHelper;+ const address = explicit ? rawUrl.slice(explicit[0].length) : rawUrl;+ if (helper === undefined && isLocalGitRemote(address)) continue;+ const url = utf8(address);+ if (url === undefined) {+ hasUnverifiedRemote = true;+ continue;+ }+ const transport = /^([a-z0-9][a-z0-9+.-]*):\/\//iu.exec(url)?.[1] ?? "";+ const curlHelper = /^(?:https?|ftps?)$/u;+ const curl = curlHelper.test(transport.toLowerCase());+ // Git uses the scheme spelling in the implicit git-remote-<scheme> executable name.+ const effectiveHelper = helper ?? transport;+ const recognized = curl+ ? await recognizedCurlHelper(+ effectiveHelper,+ repository,+ async () =>+ (+ await trustedGitCommand(+ repository,+ true,+ environment ?? process.env,+ protectedRoots,+ signal,+ )+ ).environment,+ async (args) => utf8(await readGit(args)),+ )+ : helper === undefined &&+ (!url.includes("://") ||+ /^(?:ssh|git\+ssh|ssh\+git|git)$/u.test(transport));+ // libcurl rejects raw ASCII control characters and spaces that URL() may discard.+ if (!recognized || (curl && /[\x00-\x20\x7f]/u.test(url))) {+ hasUnverifiedRemote = true;+ continue;+ }+ if (isWindowsGitDrive(url) && !url.startsWith("-")) {+ // Git's Windows path validity rules decide between a drive and an SSH host.+ // Diagnostic mode opens no repository. gitOutput disables all transports before SSH setup.+ try {+ await readGit(["fetch-pack", "--diag-url", url]);+ continue;+ } catch (error) {+ if (!(+ error instanceof Error &&+ "code" in error &&+ error.code === 128 &&+ "stderr" in error &&+ typeof error.stderr === "string" &&+ error.stderr+ .split(/\r?\n/u)+ .filter((line) => line.startsWith("fatal: "))+ .join("\n") === "fatal: transport 'ssh' not allowed"+ ))+ throw error;+ }+ }+ remotes.push(url);+ }+ return hasUnverifiedRemote || remotes.length ? remotes : undefined;+}diff --git a/sdk/typescript/src/hosted-git-repository.ts b/sdk/typescript/src/hosted-git-repository.tsnew file mode 100644index 000000000..17a6199ae--- /dev/null+++ b/sdk/typescript/src/hosted-git-repository.ts@@ -0,0 +1,294 @@+import { isIPv4 } from "node:net";+import {+ cloudRepositoryUrlKey,+ repositoryUrlKey,+} from "./external-import-contract.js";+import { isGitHubCloudHost } from "./git-remote.js";++// Git treats a colon followed by "//" as the start of a URL transport.+const scpRemote = /^(?:([^@/:\s?#]+)@)?(\[[^\]]+\]|[^@/:\s?#]+):(?!\/\/)(.+)$/u;++const sshRemote = /^(?:ssh|git\+ssh|ssh\+git):\/\/([^/]+?)(?:\/|%2[fF])/u;++/** A native file URL or an unambiguous local path. */+export function isLocalGitRemote(remote: string): boolean {+ if (remote.includes("://")) return remote.startsWith("file://");+ const colon = remote.indexOf(":");+ return colon < 0 || remote.slice(0, colon).includes("/");+}++export function isWindowsGitDrive(remote: string): boolean {+ // Git for Windows accepts one character or up to four consecutive non-ASCII bytes before a drive colon.+ return (+ process.platform === "win32" &&+ !remote.includes("://") &&+ /^(?:.|[\u0080-\u07ff]{2}):(?!:)/su.test(remote)+ );+}++function parseScpRemote(remote: string): RegExpExecArray | null {+ return !isLocalGitRemote(remote) &&+ !remote.includes("://") &&+ !/^[a-z\d][a-z\d+.-]*::/iu.test(remote)+ ? scpRemote.exec(remote)+ : null;+}++function sshAuthority(host: string): URL | null {+ if (/[\/\\?#@\s\x00-\x1f\x7f]/u.test(host)) return null;+ // Git passes a leading plus on decimal ports through to OpenSSH.+ const parse = (authority: string) =>+ URL.parse("ssh://" + authority.replace(/:\+(\d+)$/u, ":$1"));+ const parsed = parse(host);+ if (parsed) return parsed;+ // Git accepts brackets around DNS names, with an SSH port inside or after the brackets.+ const bracketed = /^\[([^\]]+)\](?::(\+?\d*))?$/u.exec(host);+ // An empty port outside the brackets is ignored, but an inner trailing colon is a hostname byte.+ if (!bracketed || bracketed[1]!.endsWith(":")) return null;+ const [, name, port] = bracketed;+ return parse(name + (port ? `:${port}` : ""));+}++/** Git decodes URI escapes once except for NUL, and sends SCP bytes literally. */+export function gitTransportBytes(raw: string, scpStyle: boolean): 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)),+ );+}++/** Decode only URI escapes whose ASCII bytes cannot introduce a delimiter. */+export function decodeUnreserved(value: string): string {+ return value.replace(/%([0-9a-f]{2})/giu, (escape, hex: string) => {+ const byte = String.fromCharCode(parseInt(hex, 16));+ return /^[a-z0-9._~-]$/iu.test(byte) ? byte : escape.toUpperCase();+ });+}++/** Represent upload-pack path bytes relative to an HTTP repository origin. */+export function gitPathToHttpPath(bytes: string): string {+ return bytes+ .replace(/^\//u, "")+ .replace(+ /[%\x00-\x20\x7f-\xff]/gu,+ (byte) =>+ "%" + byte.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"),+ );+}++/** Ignore the optional DNS root dot for provider classification only. */+export function gitServiceHostname(hostname: string): string {+ return hostname.replace(/\.$/u, "");+}++export function isPublicGitHost(host: string): boolean {+ return (+ isGitHubCloudHost(host) || host === "gitlab.com" || host === "bitbucket.org"+ );+}++/** Public SSH-over-443 hosts share the HTTPS hostname after the first DNS label. */+function publicGitSsh443Host(hostname: string): string | undefined {+ switch (gitServiceHostname(hostname)) {+ case "ssh.github.com":+ case "altssh.gitlab.com":+ case "altssh.bitbucket.org":+ return hostname.slice(hostname.indexOf(".") + 1);+ }+}++function matchesHttpsHost(url: string | undefined, hostname: string): boolean {+ const source = url && URL.parse(url);+ return (+ !!source &&+ source.protocol === "https:" &&+ source.hostname.toLowerCase() === hostname+ );+}++/** Standard public SSH aliases, plus a hosted SCM established by the caller. */+export function normalizeHostedGitRepositoryUrl(+ remote: string,+ source: string | undefined,+ trustedScm: boolean,+): string {+ // A projected single-project report may retain only its SSH spelling.+ return normalizeGitSshAlias(+ remote,+ (host) =>+ (trustedScm || isPublicGitHost(gitServiceHostname(host))) &&+ matchesHttpsHost(source ?? `https://${host}`, host),+ );+}++function normalizeGitSshAlias(+ repository: string,+ isAliasHost: (host: string) => boolean,+): string {+ const isGitSshUser = (username: string, hostname: string) =>+ (username === "git" && hostname === "github.com") ||+ (isAliasHost(hostname) &&+ (username === "git" ||+ username ===+ /^([^.]+)\.ghe\.com$/u.exec(gitServiceHostname(hostname))?.[1]));+ const hostedAlias = (+ url: URL,+ user: string,+ path: string,+ scpStyle: boolean,+ ) => {+ const hostname = url.hostname.toLowerCase();+ const standard =+ isGitSshUser(user, hostname) && (url.port === "" || url.port === "22");+ const alternate =+ user === "git" && url.port === "443" && publicGitSsh443Host(hostname);+ if (!standard && !alternate) return repository;+ const bytes = gitTransportBytes(path, scpStyle);+ if (/[?#\\]/u.test(bytes) || /(?:^|\/)\.{1,2}(?:\/|$)/u.test(bytes))+ return repository;+ return `https://${alternate || hostname}/${gitPathToHttpPath(bytes)}`;+ };+ const scp = parseScpRemote(repository);+ if (scp) {+ if (!scp[1]) return repository;+ const authority = sshAuthority(scp[2]!);+ return authority+ ? hostedAlias(authority, scp[1], scp[3]!, true)+ : repository;+ }+ // Git separates the decoded authority from the path at the first slash.+ const ssh = sshRemote.exec(repository);+ if (ssh && !/[\t\r\n]/u.test(repository)) {+ const authority = gitTransportBytes(ssh[1]!, false);+ const login = /^([^@:]+)@([^@]+)$/u.exec(authority);+ if (!login || /[/\\%?#\s]/u.test(authority)) return repository;+ const url = sshAuthority(login[2]!);+ if (url)+ return hostedAlias(+ url,+ login[1]!,+ "/" + repository.slice(ssh[0].length),+ false,+ );+ }+ return repository;+}++function hostedHttpAuthority(authority: string): string {+ if (/[%@\\\s]/u.test(authority)) return authority;+ const hostname = URL.parse(`https://${authority}/`)?.hostname;+ // Hostname serialization handles IP literals and IDNA. The connector distinguishes explicit ports.+ const port = /:\d*$/u.exec(authority)?.[0] ?? "";+ return hostname ? hostname + port : authority;+}++function hostedHttpPath(path: string): string {+ const segments: string[] = [];+ for (const segment of path.split("/")) {+ // Git's HTTP transport resolves literal dot segments before sending the path.+ if (segment === "..") {+ segments.pop();+ } else if (segment !== ".") {+ const spelling = segment.replace(/\P{ASCII}+/gu, (text) =>+ encodeURIComponent(text.toWellFormed()),+ );+ const decoded = decodeUnreserved(spelling);+ segments.push(+ decoded === "." || decoded === ".." ? segment.toUpperCase() : decoded,+ );+ }+ }+ if (/(?:^|\/)\.{1,2}$/u.test(path)) segments.push("");+ return segments.join("/");+}++/** Compare the HTTP request path a browser and Git would send for the same link. */+export function ambiguousHostedHttpPath(value: string): boolean {+ const path = /^https?:\/\/[^/?#]+\/([^?#]*)/iu.exec(value)?.[1];+ if (path === undefined) return false;+ const web = URL.parse(value)?.pathname.slice(1);+ return (+ web !== undefined &&+ path !== web &&+ hostedHttpPath(path) !== hostedHttpPath(web)+ );+}++/** Compare hosted HTTP repository spellings without changing the retained evidence. */+export function hostedRepositoryUrlKey(+ value: string,+ github = false,+ knownGitSuffix = false,+): string {+ const url = value.replace(+ /^(https?:\/\/)([^/?#]+)\/([^?#]*)/iu,+ (_, scheme: string, authority: string, path: string) =>+ scheme + hostedHttpAuthority(authority) + "/" + hostedHttpPath(path),+ );+ if (github) return cloudRepositoryUrlKey(url);+ const host = URL.parse(url)?.hostname ?? "";+ const service = /^https?:\/\//iu.test(url) ? gitServiceHostname(host) : host;+ if (service !== host && isGitHubCloudHost(service))+ return cloudRepositoryUrlKey(url);+ // An arbitrary Git server can serve different repositories at /repo and /repo.git.+ const key = repositoryUrlKey(url);+ return !knownGitSuffix && !isPublicGitHost(service) && /\.git\/?$/u.test(url)+ ? key + ".git"+ : key;+}++/** The Git HTTP Host and TLS server name can differ from the web URL's parsed IP literal. */+function ambiguousGitIpHost(url: string): boolean {+ const host = URL.parse(url)?.hostname;+ if (!host || (!isIPv4(host) && !host.startsWith("["))) return false;+ const authority = /^https?:\/\/([^/?#]*)/iu.exec(url)?.[1] ?? "";+ const rawHost = authority+ .slice(authority.lastIndexOf("@") + 1)+ .replace(/:\d*$/u, "");+ return rawHost.toLowerCase() !== host;+}++/** Match a Git checkout to an independently selected hosted repository. */+export function hostedRepositoryMatches(+ source: { url: string; platform?: string; gitlab?: boolean },+ remote: string,+): boolean {+ if (!/^https?:\/\//iu.test(source.url)) return remote === source.url;+ const github = source.platform === "github";+ const url = normalizeHostedGitRepositoryUrl(+ remote,+ source.url,+ github || source.platform === "gitlab",+ );+ const userinfo = /^https?:\/\/([^/?#]*)@/iu.exec(url)?.[1] ?? "";+ // Git passes raw URL paths to its HTTP transport. Do not turn backslashes,+ // controls or an encoded traversal into a match via web URL serialization.+ if (+ !/^https?:\/\//iu.test(url) ||+ /[\\\x00-\x20\x7f?#]/u.test(url) ||+ // libcurl accepts encoded userinfo but rejects multiple literal authority delimiters.+ userinfo.includes("@") ||+ // Git rejects a decoded line feed in credentials and libcurl rejects a NUL in usernames.+ /%0a/iu.test(userinfo) ||+ /^[^:]*%00/u.test(userinfo) ||+ ambiguousGitIpHost(url) ||+ ambiguousHostedHttpPath(url)+ )+ return false;+ // The local checkout's credentials and default HTTP port don't change the server path.+ const key = (value: string) =>+ hostedRepositoryUrlKey(+ value.replace(+ /^(https?:\/\/)([^/?#\\]+)\//iu,+ (match, scheme: string, authority: string) => {+ const parsed = URL.parse(scheme + authority);+ return parsed ? scheme + parsed.host + "/" : match;+ },+ ),+ github,+ source.gitlab || source.platform === "gitlab",+ );+ return key(url) === key(source.url);+}diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 453d62d43..3befeaad2 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -360,13 +360,17 @@ export {normalizeSnykSarif,readSnykFindings,} from "./snyk-findings.js";-export { normalizeSelectedSemgrepPlatformFindings } from "./semgrep-platform-findings.js";export {normalizeSemgrepFindings,normalizeSemgrepSarif,readSemgrepFindings,type SemgrepImportOptions,} from "./semgrep-findings.js";+export {+ normalizeSelectedSemgrepPlatformFindings,+ selectSemgrepPlatformFindings,+ type SemgrepPlatformSelection,+} from "./semgrep-platform-findings.js";export {normalizeEndorFindings,normalizeEndorSarif,diff --git a/sdk/typescript/src/semgrep-findings.ts b/sdk/typescript/src/semgrep-findings.tsindex 073b4d5fa..0bf795366 100644--- a/sdk/typescript/src/semgrep-findings.ts+++ b/sdk/typescript/src/semgrep-findings.ts@@ -1,9 +1,16 @@+import {+ normalizeSemgrepPlatformSelection,+ semgrepSelectionFormat,+} from "./semgrep-platform-findings.js";import type { ExternalImportTarget } from "./external-import-contract.js";import {cloudRepositoryUrlKey,validateExternalEvidence,} from "./external-import-contract.js";-import type { ExternalFindings } from "./external-findings.js";+import type {+ ExternalFindings,+ ExternalSourceRepository,+} from "./external-findings.js";import {messageText,parseNativeJsonResult,@@ -28,6 +35,8 @@ import {} from "./scanner-import.js";export interface SemgrepImportOptions {+ /** Independent source references from the SDK reader. */+ sourceRepositories?: readonly ExternalSourceRepository[];/** Source repository declared by the caller; never inferred from the destination. */sourceRepositoryUrl: string;}@@ -151,6 +160,16 @@ export function normalizeSemgrepFindings(target: ExternalImportTarget = "cloud",): ExternalFindings {const document = record(input, "Semgrep report");+ if (document["format"] === semgrepSelectionFormat) {+ if (target !== "local")+ throw new Error("Semgrep Platform selections require a local import.");+ return normalizeSemgrepPlatformSelection(+ document,+ options?.sourceRepositoryUrl,+ target,+ options?.sourceRepositories,+ );+ }if (document["version"] === "2.1.0" && document["runs"] !== undefined)return normalizeSemgrepSarif(document, options, target);const repositoryUrl = sourceRepository(options);@@ -175,6 +194,10 @@ export function normalizeSemgrepFindings();}+export function isSemgrepSarifDriver(name: string): boolean {+ return ["semgrep", "semgrep oss", "semgrep pro"].includes(name.toLowerCase());+}+export function normalizeSemgrepSarif(input: unknown,options: SemgrepImportOptions,@@ -203,11 +226,7 @@ export function normalizeSemgrepSarif(}const tool = record(run["tool"], "SARIF tool");const driver = record(tool["driver"], "SARIF driver");- if (- !["semgrep", "semgrep oss", "semgrep pro"].includes(- requiredText(driver["name"], "SARIF producer").toLowerCase(),- )- )+ if (!isSemgrepSarifDriver(requiredText(driver["name"], "SARIF producer")))throw new Error("Expected a Semgrep SARIF producer.");if (hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])diff --git a/sdk/typescript/src/semgrep-platform-findings.ts b/sdk/typescript/src/semgrep-platform-findings.tsindex 49fa8d7ac..8e1583052 100644--- a/sdk/typescript/src/semgrep-platform-findings.ts+++ b/sdk/typescript/src/semgrep-platform-findings.ts@@ -1,8 +1,19 @@import {canonicalNumber,validateExternalEvidence,+ type ExternalImportTarget,} from "./external-import-contract.js";-import type { ExternalFindings } from "./external-findings.js";+import type {+ ExternalFinding,+ ExternalFindings,+ ExternalSourceRepository,+} from "./external-findings.js";+import {+ gitServiceHostname,+ hostedRepositoryMatches,+ hostedRepositoryUrlKey,+} from "./hosted-git-repository.js";+import { isGitHubCloudHost } from "./git-remote.js";import { isRecord } from "./record.js";import { position, weaknessIds } from "./native-json-findings.js";import {@@ -17,6 +28,21 @@ import {} from "./scanner-import.js";import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";+export const semgrepSelectionFormat = "semgrep-platform-selection/v1";++export interface SemgrepPlatformScope {+ deployment: string;+ project: { id: string; name: string; url: string };+ ref: string;+ product: "sast";+}++export interface SemgrepPlatformSelection extends SemgrepPlatformScope {+ format: typeof semgrepSelectionFormat;+ /** Each native finding is JSON text so numbers retain their exact wire values through replay. */+ findings: string[];+}+// These v1 Findings API response fields belong only to AI detections or Supply Chain.const nonSastFields = ["ai_impact",@@ -64,7 +90,7 @@ function sourceLine(value: unknown): number | null {}/** Keep original number tokens, including adjacent int64 IDs above Number.MAX_SAFE_INTEGER. */-function parseSemgrepResponse(json: string): Record<string, unknown> {+export function parseSemgrepResponse(json: string): Record<string, unknown> {return responseRecord(JSON.parse(json.replace(/^\uFEFF/u, ""),@@ -90,40 +116,192 @@ function platformId(value: unknown): string | undefined {: undefined;}-function requiredPlatformId(value: unknown): string {+export function semgrepPlatformId(value: unknown): string {const id = platformId(value);if (!id) throw new Error("Expected an exact, positive Semgrep Platform ID.");return id;}-/** Select SAST findings from operator-supplied Web API responses for local SDK import. */-export function normalizeSelectedSemgrepPlatformFindings(options: {- deployment: string;- ref: string;- /** Independently supplied by the operator for the selected local checkout. */- sourceRepositoryUrl: string;- projectResponse: string;- findingsResponses: Iterable<string>;- findingIds: readonly string[];-}): ExternalFindings {- const native = responseRecord(- parseSemgrepResponse(options.projectResponse)["project"],- "Semgrep project",- );- const scope = {- deployment: requiredText(options.deployment, "Semgrep deployment"),+// Older selections retained full decimal ID tokens beyond Semgrep's native int64 range.+function archivedPlatformId(value: unknown): string {+ const token = wireJson.isRawJSON(value)+ ? canonicalNumber(value.rawJSON, Math.max(21, value.rawJSON.length))+ : value;+ return typeof token === "string" && /^[1-9][0-9]*$/u.test(token)+ ? token+ : semgrepPlatformId(value);+}++function scopeOf(+ deployment: unknown,+ project: unknown,+ ref: unknown,+): SemgrepPlatformScope {+ const row = responseRecord(project, "Semgrep project");+ const id = semgrepPlatformId(row["id"]);+ return {+ deployment: requiredText(deployment, "Semgrep deployment"),project: {- id: requiredPlatformId(native["id"]),- name: requiredText(native["name"], "Semgrep project name"),+ id: text(row["id"]) ?? id,+ name: requiredText(row["name"], "Semgrep project name"),url: declaredScannerRepositoryUrl(- options.sourceRepositoryUrl,- "Semgrep",+ row["url"],+ "Semgrep Platform","local",),},- ref: requiredText(options.ref, "Semgrep ref"),+ ref: requiredText(ref, "Semgrep ref"),product: "sast",};+}++/** Readers may pass the SCM web link from the project response or its equivalent Git transport. */+export function semgrepReferenceMatches(+ source: ExternalSourceRepository,+ url: string,+): boolean {+ // A standard explicit Git HTTP(S) helper carries the same fetch URL.+ const helper = /^(?:https?|ftps?)::(?=([a-zA-Z]+):\/\/)/u.exec(url);+ if (helper)+ return (+ /^https?$/iu.test(helper[1]!) &&+ hostedRepositoryMatches(source, url.slice(helper[0].length))+ );+ if (hostedRepositoryMatches(source, url)) return true;+ try {+ // Serialize only a valid repository link. Git checkout URLs retain their original bytes.+ const link = declaredScannerRepositoryUrl(url, "Semgrep", "local");+ return hostedRepositoryMatches(source, new URL(link).href);+ } catch {+ return false;+ }+}++function repositoryContext(+ scope: SemgrepPlatformScope,+ references: readonly ExternalSourceRepository[] = [],+) {+ // Apply HTTP serialization to native HTTP URLs only. Git's SSH port has its own meaning.+ const http = (value: string) => URL.parse(value)?.href ?? value;+ const projectUrl = http(scope.project.url);+ const source: ExternalSourceRepository = { url: projectUrl };+ const nativeHost = gitServiceHostname(new URL(projectUrl).hostname);+ const ownPlatformMatches = ({ url, platform }: ExternalSourceRepository) =>+ platform !== undefined &&+ semgrepReferenceMatches({ url: projectUrl, platform }, url);+ const platform = isGitHubCloudHost(nativeHost)+ ? "github"+ : references.find(ownPlatformMatches)?.platform;+ if (platform) {+ source.platform = platform;+ if (+ references.some(+ (ref) =>+ ref.platform &&+ ref.platform !== platform &&+ (ownPlatformMatches(ref) || semgrepReferenceMatches(source, ref.url)),+ )+ )+ throw new Error(+ "Conflicting SCM platforms for the selected Semgrep repository.",+ );+ }+ const github = source.platform === "github";+ return {+ source,+ key: (url: string) =>+ hostedRepositoryUrlKey(http(url), github, source.platform === "gitlab"),+ name: (value: string) => (github ? value.toLowerCase() : value),+ };+}++function selectionRepository(+ scope: SemgrepPlatformScope,+ references: readonly ExternalSourceRepository[] = [],+) {+ const repository = repositoryContext(scope, references);+ if (+ !references.every(({ url }) =>+ semgrepReferenceMatches(repository.source, url),+ )+ )+ throw new Error(+ "The reader's source repository does not match the selected Semgrep project.",+ );+ return repository;+}++function checkRow(+ finding: Record<string, unknown>,+ scope: SemgrepPlatformScope,+ repository: Pick<ReturnType<typeof repositoryContext>, "name" | "key">,+ capture = false,+) {+ semgrepPlatformId(finding["id"]);+ const repo = responseRecord(+ finding["repository"],+ "Semgrep finding repository",+ );+ const repositoryId =+ repo["id"] == null ? undefined : semgrepPlatformId(repo["id"]);+ const url =+ repo["url"] == null+ ? null+ : declaredScannerRepositoryUrl(repo["url"], "Semgrep finding", "local");+ const name = repo["name"];+ const rowName = typeof name === "string" ? repository.name(name) : null;+ const encodedPath = new URL(scope.project.url).pathname.replace(+ /^\/|\/$/gu,+ "",+ );+ // Archived captures may retain the encoded path spelling as their repository name.+ const qualifiedName =+ rowName?.includes("/") &&+ (rowName === repository.name(decodeURIComponent(encodedPath)) ||+ (!capture && rowName === repository.name(encodedPath)));+ if (+ finding["ref"] !== scope.ref ||+ (repositoryId !== undefined &&+ repositoryId !== semgrepPlatformId(wireJson.rawJSON(scope.project.id))) ||+ (url !== null+ ? repository.key(url) !== repository.key(scope.project.url)+ : repositoryId === undefined || !qualifiedName)+ )+ throw new Error(+ "Semgrep finding does not belong to the selected project and ref.",+ );+ for (const product of [finding["issue_type"], finding["product"]]) {+ if (+ product != null &&+ (typeof product !== "string" ||+ !["sast", "code"].includes(product.toLowerCase()))+ )+ throw new Error("Select Semgrep Code (SAST) findings.");+ }+ // Saved rows and normalized evidence have no original page to check.+ if (!capture && identifiesNonSastProduct(finding))+ throw new Error("Select Semgrep Code (SAST) findings.");+}++interface SemgrepSelectionInput {+ deployment: string;+ ref: string;+ projectResponse: string;+ findingsResponses: Iterable<string>;+ findingIds: readonly string[];+}++function selectedRows(+ options: SemgrepSelectionInput,+ repositoryFor: (+ scope: SemgrepPlatformScope,+ ) => Pick<ReturnType<typeof repositoryContext>, "name" | "key">,+) {+ const scope = scopeOf(+ options.deployment,+ parseSemgrepResponse(options.projectResponse)["project"],+ options.ref,+ );// git-check-ref-format distinguishes literal branch/tag names from revision expressions.const refParts = scope.ref.split("/");if (@@ -140,13 +318,10 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {throw new Error("Use a fully qualified Semgrep ref such as refs/heads/topic.",);- if (native["url"] !== scope.project.url)- throw new Error(- "Selected Semgrep project does not match the operator's source repository URL.",- );+ const repository = repositoryFor(scope);const wanted = new Set(options.findingIds.map((id) =>- requiredPlatformId(requiredText(id, "Selected Semgrep finding ID")),+ semgrepPlatformId(requiredText(id, "Selected Semgrep finding ID")),),);if (!wanted.size) throw new Error("Select at least one Semgrep finding ID.");@@ -155,12 +330,9 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {typeof options.findingsResponses === "string"? [options.findingsResponses]: options.findingsResponses;- const projectPath = decodeURIComponent(- new URL(scope.project.url).pathname,- ).replace(/^\/|\/$/gu, "");- for (const response of pages) {+ for (const page of pages) {const findings = array(- parseSemgrepResponse(response)["findings"],+ parseSemgrepResponse(page)["findings"],"Semgrep findings",);const previousCount = selected.size;@@ -170,35 +342,7 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {if (!id || !wanted.has(id)) continue;if (selected.has(id))throw new Error(`Duplicate selected Semgrep finding ${id}.`);- const repo = responseRecord(- finding["repository"],- "Semgrep finding repository",- );- const repositoryId =- repo["id"] == null ? undefined : requiredPlatformId(repo["id"]);- const url = repo["url"];- const name = repo["name"];- const matchesQualifiedPath =- name === projectPath && projectPath.includes("/");- if (- finding["ref"] !== scope.ref ||- (repositoryId !== undefined && repositoryId !== scope.project.id) ||- (url != null- ? url !== scope.project.url- : repositoryId === undefined || !matchesQualifiedPath)- )- throw new Error(- "Selected Semgrep finding does not belong to the selected project and ref.",- );- if (- [finding["issue_type"], finding["product"]].some(- (product) =>- product != null &&- (typeof product !== "string" ||- !["sast", "code"].includes(product.toLowerCase())),- )- )- throw new Error("Select Semgrep Code (SAST) findings.");+ checkRow(finding, scope, repository, true);selected.set(id, finding);}// The v1 findings endpoint returns a single product per response page.@@ -209,19 +353,207 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {throw new Error("Select Semgrep Code (SAST) findings.");}const rows = Array.from(wanted, (id) => {- const found = selected.get(id);- if (!found) throw new Error(`Selected Semgrep finding ${id} is missing.`);- return found;+ const value = selected.get(id);+ if (!value)+ throw new Error(+ `Selected Semgrep finding ${id} is missing from the supplied pages.`,+ );+ return value;+ });+ return { scope, rows };+}++/** Select existing SAST findings from native Web API responses for one project and ref. */+export function selectSemgrepPlatformFindings(+ options: SemgrepSelectionInput & {+ sourceRepositories?: readonly ExternalSourceRepository[];+ },+): SemgrepPlatformSelection {+ const { scope, rows } = selectedRows(options, (scope) =>+ selectionRepository(scope, options.sourceRepositories),+ );+ return {+ format: semgrepSelectionFormat,+ ...scope,+ findings: rows.map((row) => stringifySemgrepFinding(row)),+ };+}++/** Select SAST findings using the operator's exact, independently supplied HTTP(S) spelling. */+export function normalizeSelectedSemgrepPlatformFindings(+ options: SemgrepSelectionInput & {+ sourceRepositoryUrl: string;+ },+): ExternalFindings {+ const url = declaredScannerRepositoryUrl(+ options.sourceRepositoryUrl,+ "Semgrep",+ "local",+ );+ const { scope, rows } = selectedRows(options, (scope) => {+ if (scope.project.url !== url)+ throw new Error(+ "Selected Semgrep project does not match the operator's source repository URL.",+ );+ const exact = (value: string) => value;+ return { key: exact, name: exact };});- // Older Platform imports hash safe integers as numbers, and larger IDs as strings.+ return normalizeSelectionRows(rows, scope, "local");+}++function sourceId(+ scope: SemgrepPlatformScope,+ finding: Record<string, unknown>,+ idOf = semgrepPlatformId,+) {+ // Keep the same tuple for a selected import and a subsequent scoped Platform collection.const exact = (id: string) =>Number.isSafeInteger(Number(id)) ? Number(id) : id;+ return stableId("semgrep-platform", [+ scope.deployment,+ exact(idOf(wireJson.rawJSON(scope.project.id))),+ scope.product,+ scope.ref,+ exact(idOf(finding["id"])),+ ]);+}++function readScope(input: Record<string, unknown>) {+ if (input["product"] !== "sast")+ throw new Error("Select Semgrep Code (SAST) findings.");+ const project = record(input["project"], "Semgrep project");+ // The selector emits decimal strings; ordinary file JSON parsing would round numeric IDs.+ const id = requiredText(project["id"], "Semgrep selected project ID");+ const scope = scopeOf(+ input["deployment"],+ { ...project, id: wireJson.rawJSON(id) },+ input["ref"],+ );+ if (scope.project.id !== id && !/^[1-9][0-9]*$/u.test(id))+ throw new Error("Invalid saved Semgrep project ID.");+ scope.project.id = id;+ return scope;+}++const generatedId = /^semgrep-platform:[0-9a-f]{64}$/u;++/** Recognize retained Platform evidence after an SDK caller projects away wrapper fields. */+export function isSemgrepSelectionEvidence(finding: ExternalFinding): boolean {+ const data = finding.evidence?.source_data;+ return (+ generatedId.test(finding.source_finding_id) ||+ data?.["format"] === semgrepSelectionFormat ||+ (data != null && Object.hasOwn(data, "semgrepPlatformFindingJson"))+ );+}++/** Recheck the source repository when an SDK caller supplies normalized evidence directly. */+export function semgrepSelectionRepository(+ finding: ExternalFinding,+ references: readonly ExternalSourceRepository[] = [],+): ExternalSourceRepository | undefined {+ if (!isSemgrepSelectionEvidence(finding)) return;+ const data = record(+ finding.evidence.source_data,+ "Semgrep Platform source data",+ );+ const scope = readScope(data);+ const row = parseSemgrepResponse(+ requiredText(data["semgrepPlatformFindingJson"], "Semgrep finding JSON"),+ );+ const repository = repositoryContext(scope, references);+ checkRow(row, scope, repository);+ if (+ generatedId.test(finding.source_finding_id) &&+ finding.source_finding_id !== sourceId(scope, row) &&+ finding.source_finding_id !== sourceId(scope, row, archivedPlatformId)+ )+ throw new Error(+ "The generated Semgrep finding ID does not match its native occurrence.",+ );+ const claimed = finding.evidence.details?.repository?.url;+ if (+ finding.evidence.branch !== scope.ref ||+ !claimed ||+ repository.key(+ declaredScannerRepositoryUrl(claimed, "Semgrep", "local"),+ ) !== repository.key(scope.project.url)+ )+ throw new Error(+ "The normalized finding does not match its original Semgrep repository and ref.",+ );+ return repository.source;+}++export function normalizeSemgrepPlatformSelection(+ input: Record<string, unknown>,+ declaredUrl?: string,+ target: ExternalImportTarget = "local",+ references: readonly ExternalSourceRepository[] = [],+) {+ const scope = readScope(input);+ const repository = selectionRepository(scope, references);+ if (+ declaredUrl &&+ repository.key(+ declaredScannerRepositoryUrl(declaredUrl, "Semgrep", "local"),+ ) !== repository.key(scope.project.url)+ )+ throw new Error(+ "Semgrep project does not match the declared source repository URL.",+ );+ const selected = array(input["findings"], "Semgrep selected findings");+ if (!selected.length)+ throw new Error(+ "A saved Semgrep selection must contain at least one finding.",+ );+ const rows = selected.map((value) => {+ const raw = requiredText(value, "Semgrep finding JSON");+ const finding = parseSemgrepResponse(raw);+ checkRow(finding, scope, repository);+ return finding;+ });+ return normalizeSelectionRows(rows, scope, target, archivedPlatformId);+}++function stringifySemgrepFinding(+ finding: Record<string, unknown>,+ idOf = semgrepPlatformId,+): string {+ const repository = responseRecord(+ finding["repository"],+ "Semgrep finding repository",+ );+ const nativeIds = [finding["id"], repository["id"]];+ return JSON.stringify(finding, (_key, value: unknown) => {+ if (wireJson.isRawJSON(value))+ return wireJson.rawJSON(+ nativeIds.includes(value)+ ? idOf(value)+ : canonicalNumber(value.rawJSON),+ );+ // Stable evidence only needs the retained row's object keys to be ordered.+ if (isRecord(value))+ return Object.fromEntries(+ Object.keys(value)+ .sort()+ .map((key) => [key, value[key]]),+ );+ return value;+ });+}++function normalizeSelectionRows(+ rows: Record<string, unknown>[],+ scope: SemgrepPlatformScope,+ target: ExternalImportTarget,+ idOf = semgrepPlatformId,+) {return normalizeRecords(rows,(finding) => {const rule = responseRecord(finding["rule"] ?? {}, "Semgrep rule");const name = text(rule["name"]) ?? text(finding["rule_name"]);- const severity = text(finding["severity"])?.toLowerCase() ?? "";const description =text(rule["message"]) ?? text(finding["rule_message"]);const location = responseRecord(@@ -234,6 +566,7 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {relative && !relative.endsWith("/.") && repositoryFilePath(relative)? rawPath: null;+ const severity = text(finding["severity"])?.toLowerCase() ?? "";const startLine = path ? sourceLine(location["line"]) : null;return validateExternalEvidence({@@ -257,40 +590,16 @@ export function normalizeSelectedSemgrepPlatformFindings(options: {},},source_data: {- format: "semgrep-platform-selection/v1",+ format: semgrepSelectionFormat,...scope,- project: {- ...scope.project,- id: text(native["id"]) ?? scope.project.id,- },- semgrepPlatformFindingJson: JSON.stringify(- finding,- (_key, value: unknown) => {- if (wireJson.isRawJSON(value))- return wireJson.rawJSON(canonicalNumber(value.rawJSON));- // Native object key order can vary across otherwise identical reads.- if (isRecord(value))- return Object.fromEntries(- Object.keys(value)- .sort()- .map((key) => [key, value[key]]),- );- return value;- },- ),+ project: { ...scope.project },+ semgrepPlatformFindingJson: stringifySemgrepFinding(finding, idOf),},},- "local",+ target,);},- (finding) =>- stableId("semgrep-platform", [- scope.deployment,- exact(scope.project.id),- scope.product,- scope.ref,- exact(requiredPlatformId(finding["id"])),- ]),- "local",+ (finding) => sourceId(scope, finding, idOf),+ target,);}diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.tsindex 6fa5ab513..d1cfe415e 100644--- a/sdk/typescript/src/targets.ts+++ b/sdk/typescript/src/targets.ts@@ -757,6 +757,28 @@ export async function gitHistoryIdentity(return { commonDirectory, origin };}+/** Resolve Git and its sanitized executable search path for a single selected checkout. */+export async function trustedGitCommand(+ repository: string,+ preserveConfiguration: boolean,+ sourceEnvironment: NodeJS.ProcessEnv,+ protectedRoots: string | readonly string[],+ signal?: AbortSignal,+) {+ const command = await resolveTrustedExecutable(+ "git",+ isolatedGitEnvironment(preserveConfiguration, sourceEnvironment),+ [+ (await gitMarkerRoot(repository, signal, "outermost")) ?? repository,+ ...(typeof protectedRoots === "string"+ ? [protectedRoots]+ : protectedRoots),+ ],+ );+ if (!command) throw new Error("Git is not available on a trusted PATH.");+ return command;+}+export function gitOutput(repository: string,args: readonly string[],@@ -788,27 +810,30 @@ export async function gitOutput(sourceEnvironment: NodeJS.ProcessEnv = process.env,): Promise<string | Buffer> {throwIfAborted(signal);- const command = await resolveTrustedExecutable(- "git",- isolatedGitEnvironment(- args[0] === "rev-parse" ||- args[0] === "config" ||- args[0] === "ls-files" ||- (args[0] === "remote" &&- (args.length === 1 ||- (args[1] === "get-url" &&- (args[2] === "--all" || args[2] === "--")))),- sourceEnvironment,- ),- [- (await gitMarkerRoot(repository, signal, "outermost")) ?? repository,- ...(typeof protectedRoots === "string"- ? [protectedRoots]- : protectedRoots),- ],+ const command = await trustedGitCommand(+ repository,+ args[0] === "rev-parse" ||+ (args[0] === "symbolic-ref" &&+ args[1] === "--quiet" &&+ args[2] === "HEAD" &&+ args.length === 3) ||+ (args[0] === "--exec-path" && args.length === 1) ||+ args[0] === "config" ||+ (args[0] === "fetch-pack" &&+ args[1] === "--diag-url" &&+ args.length === 3) ||+ (args[0] === "ls-remote" &&+ args[1] === "--get-url" &&+ (args.length === 2 || (args[2] === "--" && args.length === 4))) ||+ args[0] === "ls-files" ||+ (args[0] === "remote" &&+ (args.length === 1 ||+ (args[1] === "get-url" &&+ (args[2] === "--all" || args[2] === "--")))),+ sourceEnvironment,+ protectedRoots,+ signal,);- if (command === null)- throw new Error("Git is not available on a trusted PATH.");throwIfAborted(signal);const { stdout } = await execFile(command.executable,diff --git a/sdk/typescript/tests-ts/external-findings-local-helpers.ts b/sdk/typescript/tests-ts/external-findings-local-helpers.tsindex b12667d15..bfb91e6eb 100644--- a/sdk/typescript/tests-ts/external-findings-local-helpers.ts+++ b/sdk/typescript/tests-ts/external-findings-local-helpers.ts@@ -12,12 +12,22 @@ import { join } from "node:path";import { sonarGitTestEnvironment } from "./support/sonar-import-fixtures.js";/** Real Git checkout and separate state, shared by normalized and vendor import tests. */-export async function localFindingsFixture(options: { remote?: string } = {}) {+type Checkout = {+ remote?: string;+ environment?: NodeJS.ProcessEnv;+ isolatedGit?: boolean;+};++export async function localFindingsFixture(options: Checkout = {}) {const root = await mkdtemp(join(await realpath(tmpdir()), "codex-security-external-local-"),);const repository = join(root, "repository");- const env = sonarGitTestEnvironment();+ const env = sonarGitTestEnvironment(options.environment);+ if (options.isolatedGit) {+ env.GIT_CONFIG_GLOBAL = join(root, "global.gitconfig");+ await writeFile(env.GIT_CONFIG_GLOBAL, "");+ }const dispose = () => rm(root, { recursive: true, force: true });const git = (...args: string[]) =>execFileSync("git", ["-C", repository, ...args], { env, encoding: "utf8" });@@ -54,7 +64,7 @@ export async function localFindingsFixture(options: { remote?: string } = {}) {export async function localReportFixture(filename: string,source: Omit<ExternalPublicationOptions, "repository">,- checkout: { remote?: string } = {},+ checkout: Checkout = {},) {const fixture = await localFindingsFixture(checkout);const file = join(fixture.root, filename);diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 71904ee1c..ad4c8c297 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -4563,6 +4563,45 @@ async function stageReleasedCheckpoint(}// These filenames, request IDs and projections were recorded by the old SDK.+test("a verified retry checks the scanner evidence in its saved request", async () => {+ const f = await fixture();+ const marker = "semgrep-platform-selection/v1";+ class Format extends String {+ toJSON() {+ return "ordinary";+ }+ }+ const input = {+ read: 1,+ excluded: [],+ findings: [+ {+ source_finding_id: "example",+ evidence: {+ title: "Example",+ severity: "low" as const,+ source_data: { format: new Format(marker) as unknown as string },+ },+ },+ ],+ };+ const preview = await prepareReleased(f, input);+ const request = structuredClone(preview.preview.requests[0]!);+ expect(request.items[0]!.evidence.source_data?.["format"]).toBe("ordinary");+ request.items[0]!.evidence.source_data!["format"] = marker;+ // The released publisher saved this string after detaching the evidence.+ const { path, saved } = await stageReleasedCheckpoint(f, {+ filename:+ "52123d2374947cb5393a2305c5dd90bf77749966cb9e4c7bfd9871293eab7b70.pending.json",+ requests: [request],+ inputDigest:+ "90deee40efc1c9475a8850da689b5b6da4ba22b1c9ded04592eb29b35cfb4c08",+ });+ await expect(prepareReleased(f, input)).rejects.toThrow("local import");+ expect(f.posts).toHaveLength(0);+ expect(await readFile(path, "utf8")).toBe(saved);+});+async function oldScoreApproval(field: string, stageApproval = true) {const f = await fixture();const { filename, requestId, inputProjection } =diff --git a/sdk/typescript/tests-ts/semgrep-platform-selection-file.test.ts b/sdk/typescript/tests-ts/semgrep-platform-selection-file.test.tsnew file mode 100644index 000000000..bd88ff6d3--- /dev/null+++ b/sdk/typescript/tests-ts/semgrep-platform-selection-file.test.ts@@ -0,0 +1,1631 @@+import { expect, mock, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { join } from "node:path";+import {+ link,+ mkdir,+ stat,+ symlink,+ unlink,+ writeFile,+} from "node:fs/promises";+import type { ExternalSourceRepository } from "../src/external-findings.js";+import { prepareLocalExternalImport } from "../src/external-findings-import.js";+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";+import { prepareNormalizedExternalPublication } from "../src/external-findings-publish.js";+import { normalizeSemgrepFindings } from "../src/semgrep-findings.js";+import { selectSemgrepPlatformFindings } from "../src/semgrep-platform-findings.js";+import { semgrepSarif } from "./support/semgrep-import-fixtures.js";+import { localReportFixture as reportFixture } from "./external-findings-local-helpers.js";++async function localReportFixture(remote?: string) {+ const fixture = await reportFixture("selected.json", platformSource, {+ remote,+ isolatedGit: true,+ });+ return {+ ...fixture,+ git: (...args: string[]) =>+ execFileSync("git", ["-C", fixture.repository, ...args], {+ env: fixture.environment,+ }),+ };+}++const url = "https://github.com/example/project";+const ref = "refs/heads/release";+const rawFindingKey = "semgrepPlatformFindingJson";+const ids = ["9007199254740992", "9007199254740993"];+const project = { id: 77, name: "example/project", url };+const platformSource = {+ provider: "semgrep" as const,+ sourceKey: "example/project/release/platform",+};+const page = (+ id: string,+ options: { ref?: string; url?: string; name?: string } = {},+) =>+ `{"findings":[{"id":${id},"repository":${JSON.stringify({ name: options.name ?? project.name, url: options.url ?? url })},+ "ref":${JSON.stringify(options.ref ?? ref)},"rule":{"name":"sample.rule","message":"Example","cwe_names":["CWE-79: example"]},+ "location":{"file_path":"src/example.ts","line":2.0,"end_line":4},"severity":"medium","status":"reviewing","score":1.0000000000000000003}]}`;+const selection = (pages: string[], findingIds: readonly string[] = ids) =>+ selectSemgrepPlatformFindings({+ deployment: "example",+ ref,+ projectResponse: JSON.stringify({ project }),+ findingsResponses: pages,+ findingIds,+ });+const selectRow = (fields: Record<string, unknown>) =>+ selection(+ [+ JSON.stringify({+ findings: [+ {+ id: 8,+ ref,+ rule: { name: "example.rule" },+ repository: project,+ ...fields,+ },+ ],+ }),+ ],+ ["8"],+ );+const selectedRepository = (+ projectUrl: string,+ findingUrl: string,+ sourceRepositories: readonly ExternalSourceRepository[] = [],+ findingName = project.name,+) =>+ selectSemgrepPlatformFindings({+ deployment: "example",+ ref,+ projectResponse: JSON.stringify({+ project: { ...project, url: projectUrl },+ }),+ findingsResponses: [page("8", { url: findingUrl, name: findingName })],+ findingIds: ["8"],+ sourceRepositories,+ });++function normalizedProject(url: string) {+ return normalizeSemgrepFindings(+ selectedRepository(url, url),+ { sourceRepositoryUrl: url },+ "local",+ );+}++test("rechecks decimal native IDs when other evidence uses scientific notation", async () => {+ const findingId = "1000000000000000000001";+ const projectId = "1000000000000000000002";+ const report = selectSemgrepPlatformFindings({+ deployment: "example",+ ref,+ projectResponse: `{"project":{"url":"${url}","name":"example/project","id":${projectId}}}`,+ findingsResponses: `{"findings":[{"id":${findingId},"ref":"${ref}","repository":{"id":${projectId},"url":"${url}"},"rule":{"name":"example.rule"},"size":1e40}]}`,+ findingIds: [findingId],+ });+ await using fixture = await localReportFixture(url);+ await fixture.writeJson(report);+ const first = await fixture.prepare();+ expect(first.preview.excluded).toEqual([]);+ expect((await first.import()).counts.created).toBe(1);+ expect((await (await fixture.prepare()).import()).counts.unchanged).toBe(1);+});++test.each(["", ".0", "e0"])(+ "an archived selection keeps its original occurrence ID for an integer token with suffix %s",+ (suffix) => {+ const finding =+ '{"id":1000000000000000000001,"ref":"refs/heads/release","rule":{"name":"example.rule"},"repository":{"id":1000000000000000000002,"url":"https://github.com/example/project"}}'.replace(+ "1000000000000000000001,",+ "1000000000000000000001" + suffix + ",",+ );+ const archived = {+ ...selectedRepository(url, url),+ project: { ...project, id: "1000000000000000000002" },+ findings: [finding],+ };+ const row = normalizeSemgrepFindings(+ archived,+ { sourceRepositoryUrl: url },+ "local",+ ).findings[0]!;+ expect(row.source_finding_id).toBe(+ "semgrep-platform:702c8f5d11896dc0316d2cc74426c02af20b6292374c3e08b0cf7e717c6fce4a",+ );+ expect(row.evidence.title).toBe("example.rule");+ expect(row.evidence.source_data![rawFindingKey]).toContain(+ '"id":1000000000000000000001',+ );+ },+);++test("two selected Platform SAST IDs from separate pages replay unchanged in SQLite", async () => {+ const report = selection([+ page("8"),+ ...ids.map((id) => "\uFEFF" + page(id)),+ ]);+ const [left, right] = normalizeSemgrepFindings(+ report,+ { sourceRepositoryUrl: url },+ "local",+ ).findings;+ expect(left!.evidence.source_data!["project"]).not.toBe(+ right!.evidence.source_data!["project"],+ );+ await using fixture = await localReportFixture(url);+ await fixture.writeJson(report);+ const first = await fixture.prepare();+ expect(first.preview.excluded).toEqual([]);+ expect(first.preview.findings).toHaveLength(2);+ expect(first.preview.findings[0]?.evidence).toMatchObject({+ branch: ref,+ severity: "medium",+ locations: [{ path: "src/example.ts", line: 2 }],+ details: {+ rule: { id: "sample.rule" },+ source_status: "reviewing",+ weakness_ids: ["CWE-79"],+ },+ });+ expect(await fixture.read()).toEqual([]);+ expect((await first.import()).counts).toEqual({+ created: 2,+ updated: 0,+ unchanged: 0,+ });+ const saved = await fixture.read();+ expect(new Set(saved.map((row) => row.sourceFindingId)).size).toBe(2);+ const originals = saved.map(+ (row) => row.evidence.source_data?.[rawFindingKey],+ );+ for (const id of ids)+ expect(+ originals.some(+ (raw) =>+ typeof raw === "string" &&+ raw.includes('"id":' + id) &&+ raw.includes('"score":1.0000000000000000003'),+ ),+ ).toBe(true);+ const reorderedPages = ids.map((id) =>+ page(id).replace(+ `"id":${id},"repository":${JSON.stringify({ name: project.name, url })}`,+ `"repository":${JSON.stringify({ url, name: project.name })},"id":${id}`,+ ),+ );+ expect(reorderedPages[0]).not.toBe(page(ids[0]!));+ await fixture.writeJson(selection(reorderedPages));+ expect((await (await fixture.prepare()).import()).counts).toEqual({+ created: 0,+ updated: 0,+ unchanged: 2,+ });+ expect(await fixture.read()).toEqual(saved);+ expect(() =>+ normalizeSemgrepFindings(report, { sourceRepositoryUrl: url }, "cloud"),+ ).toThrow("local import");+});++test("native IDs and source URLs can identify a row with an empty display name", () => {+ const report = selectRow({ repository: { id: project.id, url, name: "" } });+ expect(report.findings).toHaveLength(1);+ expect(selectRow({ repository: { url, name: "" } }).findings).toHaveLength(1);+});++test("a short project name accepts a qualified display name on the same encoded clone URL", () => {+ const projectUrl = url.replace("project", "%70roject.git");+ const report = selectSemgrepPlatformFindings({+ deployment: "example",+ ref,+ projectResponse: JSON.stringify({+ project: { ...project, name: "project", url: projectUrl },+ }),+ findingsResponses: page("8", { url, name: "example/project" }),+ findingIds: ["8"],+ });+ expect(report.findings).toHaveLength(1);+});++test("a URL-less name must identify the exact project path on a private server", () => {+ const label = (path: string, name: string) =>+ selectSemgrepPlatformFindings({+ deployment: "example",+ ref,+ findingIds: ["8"],+ projectResponse: JSON.stringify({+ project: {+ ...project,+ name: "renamed",+ url: "https://scm.example.test/" + path,+ },+ }),+ findingsResponses: JSON.stringify({+ findings: [{ id: 8, ref, repository: { id: project.id, name } }],+ }),+ });+ expect(() => label("team/project.git", "team/project")).toThrow(+ "project and ref",+ );+ expect(label("team/proj%20one", "team/proj one").findings).toHaveLength(1);+ expect(() => label("team/proj%20one", "team/proj%20one")).toThrow(+ "project and ref",+ );+});++test("an archived display name does not bind a URL-less row to a different checkout", () => {+ const archived = selectRow({+ repository: { id: project.id, name: project.name },+ });+ const other = "https://github.com/another/project";+ const changed = { ...archived, project: { ...archived.project, url: other } };+ expect(() =>+ normalizeSemgrepFindings(changed, { sourceRepositoryUrl: other }, "local"),+ ).toThrow("project and ref");+});++test("contradictory private SCM mappings fail regardless of their order", () => {+ const web = "https://scm.example.test/team/project";+ const refs: ExternalSourceRepository[] = [+ { url: web, platform: "gitlab" },+ { url: web, platform: "github" },+ ];+ for (const alias of [web, web.replace("/team/project", "/Team/Project")]) {+ refs[0] = { url: alias, platform: "gitlab" };+ for (const sources of [refs, [...refs].reverse()])+ expect(() => selectedRepository(web, web, sources)).toThrow(+ "Conflicting SCM",+ );+ }+});++test("a saved identity without a rule name or message cannot replace stored evidence", async () => {+ await using fixture = await localReportFixture(url);+ await fixture.writeJson(selectRow({}));+ expect((await (await fixture.prepare()).import()).counts.created).toBe(1);+ const original = await fixture.read();+ await fixture.writeJson(selectRow({ rule: {} }));+ const incomplete = await fixture.prepare();+ expect(incomplete.preview.findings).toHaveLength(0);+ expect(incomplete.preview.excluded[0]?.reason).toContain("title");+ expect((await incomplete.import()).counts).toEqual({+ created: 0,+ updated: 0,+ unchanged: 0,+ });+ expect(await fixture.read()).toEqual(original);+});++test("an empty saved selection reports the missing native findings", () => {+ const empty = { ...selectedRepository(url, url), findings: [] };+ expect(() =>+ normalizeSemgrepFindings(empty, { sourceRepositoryUrl: url }, "local"),+ ).toThrow("at least one");+});++test("replaying a saved selection requires the original string project ID", async () => {+ const report = selectedRepository(url, url);+ await using fixture = await localReportFixture(url);+ await writeFile(+ fixture.file,+ JSON.stringify(report).replace('"id":"77"', '"id":77.00000000000000000001'),+ );+ await expect(fixture.prepare()).rejects.toThrow("selected project ID");+});++test.each(["release", "refs/heads/topic~1"])(+ "new captures reject %s while the archive replays its literal ref",+ async (branch) => {+ const pageWithRef = page("8", { ref: branch });+ const input = {+ deployment: "example",+ ref: branch,+ projectResponse: JSON.stringify({ project }),+ findingsResponses: pageWithRef,+ findingIds: ["8"],+ };+ expect(() => selectSemgrepPlatformFindings(input)).toThrow(+ "fully qualified",+ );+ const prior = {+ ...selectedRepository(url, url),+ ref: branch,+ findings: [JSON.stringify(JSON.parse(pageWithRef).findings[0])],+ };+ await using fixture = await localReportFixture(url);+ await fixture.writeJson(prior);+ const first = await fixture.prepare();+ expect(first.preview.findings[0]?.evidence.branch).toBe(branch);+ expect((await first.import()).counts.created).toBe(1);+ expect((await (await fixture.prepare()).import()).counts.unchanged).toBe(1);+ },+);++test("selection requires exact IDs from the selected source and ref", () => {+ const [first, second] = ids as [string, string];+ expect(() => selection([page(first)])).toThrow(second);+ expect(() => selection([page(first), page(first)])).toThrow("Duplicate");+ for (const options of [+ { ref: "refs/heads/main" },+ { url: "https://github.com/example/other" },+ ])+ expect(() => selection([page(first), page(second, options)])).toThrow(+ "project and ref",+ );+ const report = selection(ids.map((id) => page(id)));+ expect(() =>+ normalizeSemgrepFindings(+ report,+ { sourceRepositoryUrl: "https://github.com/example/other" },+ "local",+ ),+ ).toThrow("declared source");+});++test.each([+ ["github.com", undefined],+ ["github.com.", undefined],+ ["git.example.test", "https://git.example.test/example/PROJECT"],+ ["git.example.test", "[email protected]:example/project.git"],+ ["git.example.test", "ssh://[email protected]/example/project.git"],+] as const)(+ "GitHub input on %s agrees with reader source %s in file and SDK imports",+ async (host, hint) => {+ const projectUrl = `https://${host}:443/Example/Project`;+ const findingUrl = `https://${host}/example/PROJECT`;+ const declared = `https://${host}/EXAMPLE/project.git`;+ const sources = hint ? [{ url: hint, platform: "github" as const }] : [];+ const report = selectedRepository(+ projectUrl,+ findingUrl,+ sources,+ "EXAMPLE/Project",+ );+ await using fixture = await localReportFixture(declared);+ await fixture.writeJson(report);+ const options = {+ ...platformSource,+ repository: fixture.repository,+ sourceRepositoryUrl: declared,+ };+ const dependencies = {+ environment: fixture.environment,+ sourceRepositories: sources,+ };+ const file = await prepareLocalExternalImport(+ fixture.file,+ options,+ dependencies,+ );+ expect(+ (await prepareNormalizedLocalImport(file.preview, options, dependencies))+ .preview.findings,+ ).toHaveLength(1);+ },+);++test.each([+ ["github.com", "https::HTTPS://github.com/example/project", true],+ ["github.com", "https://a@[email protected]/example/project", false],+ ["github.com", "https://a%[email protected]/example/project", true],+ ["github.com", "https://reader%[email protected]/example/project", false],+ ["github.com", "https://a:b%[email protected]/example/project", false],+ ["github.com", "https://a%[email protected]/example/project", false],+ ["github.com", "https://a:b%[email protected]/example/project", true],+ ["git.example.test", "https://git.example.test/example/project.git", false],+ ["git.example.test", "ssh://[email protected]/example/project", false],+ ["git.example.test", "ssh://[email protected]:443/example/project", false],+ ["git.example.test", "[email protected]:example/project", false],+ ["github.com", "ssh://[email protected]:443/example/project.git", false],+ ["github.com", "ssh://[email protected]:443/example/project.git", true],+ ["gitlab.com", "ssh://[email protected]:443/example/project.git", true],+ [+ "bitbucket.org",+ "ssh://[email protected]:443/example/project.git",+ true,+ ],+] as const)(+ "binds %s to its Git fetch remote %s",+ async (host, remote, matches) => {+ const projectUrl = `https://${host}/example/project`;+ await using fixture = await localReportFixture(remote);+ await fixture.writeJson(selectedRepository(projectUrl, projectUrl));+ if (matches)+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ else {+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ expect(await fixture.read()).toEqual([]);+ }+ },+);++test.each([+ "HTTPS://github.com/example/project",+ "HTTPS::https://github.com/example/project",+ url,+])(+ "mixed-case Git helper identity for %s follows the checkout's actual executable lookup",+ async (remote) => {+ await using fixture = await localReportFixture(remote);+ await fixture.writeJson(selectedRepository(url, url));+ if (remote === url)+ Object.assign(fixture.environment, {+ GIT_CONFIG_COUNT: "1",+ GIT_CONFIG_KEY_0: "remote.origin.vcs",+ GIT_CONFIG_VALUE_0: "HTTPS",+ });+ const gitCore = join(fixture.root, "git-core");+ await mkdir(gitCore);+ Object.assign(fixture.environment, {+ [process.platform === "win32" ? "Git_Exec_Path" : "GIT_EXEC_PATH"]:+ gitCore,+ });+ const suffix = process.platform === "win32" ? ".exe" : "";+ const lower = join(gitCore, "git-remote-https" + suffix);+ const upper = join(gitCore, "git-remote-HTTPS" + suffix);+ await writeFile(lower, "#!/bin/sh\nexit 1\n", { mode: 0o700 });+ if (!(await stat(upper).catch(() => undefined))) {+ await writeFile(upper, "#!/bin/sh\nexit 1\n", { mode: 0o700 });+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ await unlink(upper);+ await link(lower, upper);+ }+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ },+);++test.skipIf(process.platform === "win32")(+ "mixed-case Git helper lookup follows POSIX symlinks and exec-path entries",+ async () => {+ await using fixture = await localReportFixture(+ "HTTPS://github.com/example/project",+ );+ await fixture.writeJson(selectedRepository(url, url));+ const core = join(fixture.root, "git-core");+ await mkdir(core);+ await writeFile(join(core, "git-remote-https"), "#!/bin/sh\nexit 1\n", {+ mode: 0o700,+ });+ if (!(await stat(join(core, "git-remote-HTTPS")).catch(() => undefined)))+ await link(+ join(core, "git-remote-https"),+ join(core, "git-remote-HTTPS"),+ );+ Object.assign(fixture.environment, {+ GIT_EXEC_PATH: join(fixture.root, "missing") + ":" + core,+ });+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ const deep = join(fixture.root, "actual", "deep");+ await mkdir(deep, { recursive: true });+ const alias = join(fixture.root, "lexical");+ await symlink(deep, alias);+ Object.assign(fixture.environment, {+ GIT_EXEC_PATH: alias + "/../git-core",+ });+ // The helpers under the lexically shortened path are not on this Git search path.+ const bin = join(fixture.root, "bin");+ await mkdir(bin);+ const git = execFileSync("sh", ["-c", "command -v git"], {+ env: fixture.environment,+ encoding: "utf8",+ }).trim();+ await symlink(git, join(bin, "git"));+ Object.assign(fixture.environment, { PATH: bin });+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ const subdir = join(fixture.repository, "nested");+ await mkdir(subdir);+ Object.assign(fixture.environment, { GIT_EXEC_PATH: "../git-core" });+ const prepareNested = () =>+ prepareLocalExternalImport(+ fixture.file,+ { ...platformSource, repository: subdir },+ { environment: fixture.environment },+ );+ expect((await prepareNested()).preview.findings).toHaveLength(1);+ // If the root-relative location is missing, Git still searches the exec path inherited from -C.+ await symlink(core, join(subdir, "relative-helpers"));+ Object.assign(fixture.environment, { GIT_EXEC_PATH: "relative-helpers" });+ expect((await prepareNested()).preview.findings).toHaveLength(1);+ },+);++test("a literal branch default and a named backup have independent transports", async () => {+ await using fixture = await localReportFixture(url + "-backup");+ await fixture.writeJson(selectedRepository(url, url));+ fixture.git("symbolic-ref", "HEAD", "refs/heads/active");+ fixture.git("config", "branch.inactive.remote", url);+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ fixture.git("config", "branch.active.remote", url);+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ fixture.git("config", "remote.origin.vcs", "custom");+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ fixture.git("config", "branch.active.remote", "origin");+ fixture.git("remote", "set-url", "origin", url);+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+});++test("Git resolves an effective named fetch URL after an empty config value", async () => {+ await using fixture = await localReportFixture();+ await fixture.writeJson(selectedRepository(url, url));+ fixture.git("config", "--add", "remote.origin.url", "");+ fixture.git("config", "--add", "remote.origin.url", url);+ const effective = fixture+ .git("ls-remote", "--get-url", "--", "origin")+ .toString()+ .trim();+ const dir = join(fixture.repository, ".git", "remotes");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "origin"), "URL: " + url + "-legacy\n");+ if (effective === url)+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ else+ await expect(fixture.prepare()).rejects.toThrow(+ "Configure a named Git fetch URL",+ );+});++test.each(["remotes", "branches"])(+ "legacy .git/%s entries require a named fetch URL",+ async (kind) => {+ await using fixture = await localReportFixture();+ await fixture.writeJson(selectedRepository(url, url));+ const dir = join(fixture.repository, ".git", kind);+ await mkdir(dir, { recursive: true });+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ const branch = fixture+ .git("symbolic-ref", "--short", "HEAD")+ .toString()+ .trim();+ fixture.git("config", `branch.${branch}.remote`, url + "-other");+ await expect(fixture.prepare()).rejects.toThrow(+ "does not match a configured remote",+ );+ fixture.git("config", `branch.${branch}.remote`, url);+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ await writeFile(+ join(dir, "origin"),+ kind === "remotes" ? `URL: ${url}\n` : url,+ );+ await expect(fixture.prepare()).rejects.toThrow(+ "Configure a named Git fetch URL",+ );+ fixture.git("remote", "add", "scanner-origin", url);+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ fixture.git("remote", "set-url", "scanner-origin", url + "-other");+ await expect(fixture.prepare()).rejects.toThrow(+ "does not match a configured remote",+ );+ },+);++test.skipIf(process.platform === "win32")(+ "legacy remote links and FIFOs require a named fetch URL",+ async () => {+ await using fixture = await localReportFixture();+ await fixture.writeJson(selectedRepository(url, url));+ const dir = join(fixture.repository, ".git", "remotes");+ const empty = join(fixture.root, "empty");+ const fifo = join(fixture.root, "fifo");+ const origin = join(dir, "origin");+ const expectNamedUrl = () =>+ expect(fixture.prepare()).rejects.toThrow(+ "Configure a named Git fetch URL",+ );+ await mkdir(empty);+ await symlink(empty, dir);+ await expectNamedUrl();+ await unlink(dir);+ await mkdir(dir);+ execFileSync("mkfifo", [fifo, origin]);+ await expectNamedUrl();+ fixture.git("config", "--add", "remote.origin.url", url);+ fixture.git("config", "--add", "remote.origin.url", "");+ await expectNamedUrl();+ for (const target of [fixture.file, fifo]) {+ await unlink(origin);+ await symlink(target, origin);+ await expectNamedUrl();+ }+ fixture.git("remote", "add", "scanner-origin", url);+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ },+);++test.each([+ ["127.0.0.1", "127.0.0.1", true],+ ["127.0.0.1", "0177.1.", false],+ ["127.0.0.1", "127%2e1", false],+ ["[::1]", "[::1]", true],+ ["[::ffff:7f00:1]", "[::ffff:127.0.0.1]", false],+] as const)(+ "compares Git request authority %s with %s",+ async (host, fetchHost, matches) => {+ const source = `https://${host}/org/project`;+ await using fixture = await localReportFixture(+ `https://${fetchHost}/org/project`,+ );+ await fixture.writeJson(selectedRepository(source, source));+ if (matches)+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ else await expect(fixture.prepare()).rejects.toThrow("configured remote");+ },+);++test.each([url, undefined])(+ "a helper-only remote does not override other fetch evidence: %s",+ async (origin) => {+ await using fixture = await localReportFixture(origin);+ await fixture.writeJson(selectedRepository(url, url));+ Object.assign(fixture.environment, {+ GIT_CONFIG_COUNT: "1",+ GIT_CONFIG_KEY_0: "remote.backup.vcs",+ GIT_TRACE: "1",+ GIT_TRACE_PERFORMANCE: "1",+ GIT_CONFIG_VALUE_0: "example",+ });+ if (origin)+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ else await expect(fixture.prepare()).rejects.toThrow("configured remote");+ },+);++test("a selection checks every caller-supplied source before saving API findings", () => {+ const foreign = { url: "https://github.com/example/other" };+ for (const refs of [[foreign], [{ url }, foreign]]) {+ expect(() => selectedRepository(url, url, refs)).toThrow(+ "reader's source repository",+ );+ expect(() =>+ normalizeSemgrepFindings(+ selectedRepository(url, url),+ { sourceRepositoryUrl: url, sourceRepositories: refs },+ "local",+ ),+ ).toThrow("reader's source repository");+ }+});++test("each named Git remote contributes only its active fetch URL", async () => {+ await using fixture = await localReportFixture(+ "https://github.com/example/other",+ );+ await fixture.writeJson(selectedRepository(url, url));+ fixture.git(+ "config",+ "--file",+ join(fixture.repository, ".git", "config"),+ "--add",+ "remote.origin.url",+ url,+ );+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ fixture.git("remote", "add", "second", url);+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+});++test.each([+ { origin: undefined, fallback: undefined, matches: true },+ { origin: "./mirror", fallback: undefined, matches: true },+ { origin: url, fallback: undefined, matches: true },+ { origin: undefined, fallback: url, matches: true },+ {+ origin: undefined,+ fallback: "https://github.com/example/other",+ matches: false,+ },+ {+ origin: "https://github.com/example/other",+ fallback: undefined,+ matches: false,+ },+])(+ "resolves the effective fetch source for a push-only remote with origin $origin and rewrite $fallback",+ async ({ origin, fallback, matches }) => {+ await using fixture = await localReportFixture(origin);+ await fixture.writeJson(selectedRepository(url, url));+ Object.assign(fixture.environment, {+ GIT_CONFIG_COUNT: fallback ? "2" : "1",+ GIT_CONFIG_KEY_0: "remote.backup.pushurl",+ GIT_CONFIG_VALUE_0: "https://github.com/example/backup",+ ...(fallback && {+ GIT_CONFIG_KEY_1: `url.${fallback}.insteadOf`,+ GIT_CONFIG_VALUE_1: "backup",+ }),+ });+ if (matches) {+ expect((await fixture.prepare()).preview.findings).toHaveLength(1);+ } else {+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ }+ },+);++test("the Platform HTTP URL is serialized while Git fetch paths keep their literal bytes", async () => {+ const raw = "https://git.example.test/org/repo{one}";+ const encoded = new URL(raw).href;+ for (const remote of [raw, encoded]) {+ await using fixture = await localReportFixture(remote);+ const references = [{ url: raw }];+ const selection = selectedRepository(raw, encoded, references);+ await fixture.writeJson(selection);+ if (remote === encoded) {+ const options = { ...platformSource, repository: fixture.repository };+ const dependencies = {+ environment: fixture.environment,+ sourceRepositories: references,+ };+ const prepared = await prepareLocalExternalImport(+ fixture.file,+ options,+ dependencies,+ );+ expect(+ (+ await prepareNormalizedLocalImport(+ prepared.preview,+ options,+ dependencies,+ )+ ).preview.findings,+ ).toHaveLength(1);+ expect(+ prepared.preview.findings[0]!.evidence.details!.repository!.url,+ ).toBe(raw);+ } else {+ await expect(fixture.prepare()).rejects.toThrow("configured remote");+ }+ }+});++test("a file and its projected SDK rows use the same declared GitHub repository alias", async () => {+ const native = "https://git.example.test/org/project";+ const declared = native + ".git";+ const encoded = "https://git.example.test/org/%70roject.git";+ const references = [{ url: declared, platform: "github" as const }];+ await using fixture = await localReportFixture(encoded);+ const report = selectedRepository(native, native, references);+ await fixture.writeJson(report);+ const options = {+ ...platformSource,+ repository: fixture.repository,+ sourceRepositoryUrl: declared,+ };+ const deps = {+ environment: fixture.environment,+ sourceRepositories: references,+ };+ const file = await prepareLocalExternalImport(fixture.file, options, deps);+ for (const normalized of [+ file.preview,+ normalizeSemgrepFindings(+ report,+ { sourceRepositoryUrl: declared, sourceRepositories: references },+ "local",+ ),+ ]) {+ expect(+ (await prepareNormalizedLocalImport(normalized, options, deps)).preview+ .findings,+ ).toHaveLength(1);+ }+});++test("a trusted private GitLab SSH remote uses the DNS host actually passed to OpenSSH", async () => {+ const web = "https://bücher.example/group/project";+ const hint = { url: web, platform: "gitlab" as const };+ const report = selectedRepository(web, web, [hint]);+ for (const host of ["xn--bcher-kva.example", "bücher.example"]) {+ await using fixture = await localReportFixture(+ `git@${host}:group/project.git`,+ );+ await fixture.writeJson(report);+ const prepare = () =>+ prepareLocalExternalImport(+ fixture.file,+ { ...platformSource, repository: fixture.repository },+ { environment: fixture.environment, sourceRepositories: [hint] },+ );+ if (host.startsWith("xn--"))+ expect((await prepare()).preview.findings).toHaveLength(1);+ else await expect(prepare()).rejects.toThrow("configured remote");+ }+});++test("an explicit Git helper uses the checkout's literal request path", () => {+ const web = "https://git.example.test/group/repo%7Bone%7D";+ const typed = (path: string) => [+ {+ url: "https::https://git.example.test/group/" + path,+ platform: "gitlab" as const,+ },+ ];+ expect(+ selectedRepository(web, web, typed("repo%7Bone%7D.git")).findings,+ ).toHaveLength(1);+ expect(() => selectedRepository(web, web, typed("repo{one}.git"))).toThrow(+ "source repository",+ );+});++test.each([+ "https://git.example.test/group/project.git",+ "[email protected]:group/project.git",+ "https::https://git.example.test/group/project.git",+ "https::HTTPS://git.example.test/group/project.git",+ "http::https://git.example.test/group/project.git",+])("a trusted private GitLab mapping accepts clone %s", async (checkout) => {+ const web = "https://git.example.test/group/project";+ const clone = web + ".git";+ const source = { url: checkout, platform: "gitlab" as const };+ await using fixture = await localReportFixture(checkout);+ await fixture.writeJson(selectedRepository(web, clone, [source]));+ const options = { ...platformSource, repository: fixture.repository };+ const deps = {+ environment: fixture.environment,+ sourceRepositories: [source],+ };+ const prepared = await prepareLocalExternalImport(+ fixture.file,+ options,+ deps,+ );+ expect(+ (await prepareNormalizedLocalImport(prepared.preview, options, deps))+ .preview.findings,+ ).toHaveLength(1);+ for (const refs of [+ [],+ [{ url: web + "-other", platform: "gitlab" as const }],+ ]) {+ await expect(+ prepareLocalExternalImport(fixture.file, options, {+ ...deps,+ sourceRepositories: refs,+ }),+ ).rejects.toThrow(/repository|project/);+ }+});++test("an extra custom Git reader source must match the selected checkout", async () => {+ const nativeUrl = "https://git.example.test/example/project";+ await using fixture = await localReportFixture(nativeUrl);+ await fixture.writeJson(selectedRepository(nativeUrl, nativeUrl));+ const options = { ...platformSource, repository: fixture.repository };+ const dependencies = {+ environment: fixture.environment,+ sourceRepositories: [{ url: nativeUrl + ".git" }],+ };+ await expect(+ prepareLocalExternalImport(fixture.file, options, dependencies),+ ).rejects.toThrow(/repository|remote/i);+});++test("raw UTF-8 and percent-encoded HTTP paths identify the same project", () => {+ const report = selectedRepository(+ "https://git.example.test/example/café",+ "https://git.example.test/example/caf%c3%a9",+ );+ expect(report.findings).toHaveLength(1);+});++test("a row without a repository URL needs the same project ID and name", () => {+ // The Findings API example has a short SCM name alongside an exact repository URL.+ expect(+ selectRow({ repository: { name: "project", url } }).findings,+ ).toHaveLength(1);+ expect(+ selectRow({ repository: { name: "another-project", url } }).findings,+ ).toHaveLength(1);+ const repository = { name: project.name, url: null };+ expect(() => selectRow({ repository })).toThrow("project and ref");+ expect(+ selectRow({ repository: { ...repository, id: project.id } }).findings,+ ).toHaveLength(1);+ expect(() =>+ selectRow({+ repository: { ...repository, id: project.id, name: "other/project" },+ }),+ ).toThrow("project and ref");+ expect(() =>+ selectRow({ repository: { ...project, id: project.id + 1 } }),+ ).toThrow("project and ref");+});++test("SAST selection, saved files and retained evidence reject other Semgrep products", async () => {+ await using fixture = await localReportFixture(url);+ const valid = selectRow({});+ const report = normalizeSemgrepFindings(+ valid,+ { sourceRepositoryUrl: url },+ "local",+ );+ for (const fields of [+ { ai_impact: "Synthetic impact" },+ { epss_score: { score: 0 } },+ { fix_recommendations: [] },+ { found_dependency: {} },+ { is_malicious: false },+ { reachability: "reachable" },+ { reachable_condition: "imported" },+ { usage: {} },+ { vulnerability_identifier: "CVE-2099-0001" },+ { issue_type: "ai_sast" },+ { product: "sca" },+ ]) {+ expect(() => selectRow(fields)).toThrow("SAST");+ const row = JSON.stringify({+ ...JSON.parse(valid.findings[0]!),+ ...fields,+ });+ await fixture.writeJson({ ...valid, findings: [row] });+ await expect(fixture.prepare()).rejects.toThrow("SAST");+ const forged = structuredClone(report);+ forged.findings[0]!.evidence.source_data![rawFindingKey] = row;+ await expect(+ prepareNormalizedLocalImport(+ forged,+ { ...platformSource, repository: fixture.repository },+ { environment: fixture.environment },+ ),+ ).rejects.toThrow("SAST");+ }+});++test("projects the original relative path including literal backslashes", () => {+ const file_path = "src\\example.ts";+ const selection = selectRow({+ location: { file_path, line: 2, end_line: 4 },+ });+ const { findings } = normalizeSemgrepFindings(+ selection,+ { sourceRepositoryUrl: url },+ "local",+ );+ expect(findings[0]!.evidence.locations).toEqual([+ { path: file_path, line: 2 },+ ]);+ expect(+ JSON.parse(String(findings[0]!.evidence.source_data?.[rawFindingKey]))+ .location.file_path,+ ).toBe(file_path);+});++test.each(["../outside.ts", "https://example.test/source.ts"])(+ "unprojectable path %s stays in the stored native evidence",+ async (file_path) => {+ const location = { file_path, line: 2, end_line: 4 };+ await using fixture = await localReportFixture(url);+ await fixture.writeJson(selectRow({ location }));+ expect((await (await fixture.prepare()).import()).counts.created).toBe(1);+ const [stored] = await fixture.read();+ expect(stored!.evidence.locations).toEqual([]);+ expect(stored!.evidence.details?.code?.end_line ?? null).toBeNull();+ expect(+ JSON.parse(String(stored!.evidence.source_data?.[rawFindingKey]))+ .location,+ ).toEqual(location);+ },+);++test("direct SDK imports respect the native source even with a caller-selected ID", async () => {+ await using fixture = await localReportFixture(url);+ const normalized = normalizeSemgrepFindings(+ selectRow({}),+ { sourceRepositoryUrl: url },+ "local",+ );+ const options = {+ repository: fixture.repository,+ provider: "semgrep" as const,+ sourceKey: fixture.sourceKey,+ };+ const deps = { environment: fixture.environment };+ const fetch = mock(async () => {+ throw new Error("Unexpected Cloud request");+ });+ await expect(+ prepareNormalizedExternalPublication(normalized, options, {+ ...deps,+ fetch,+ }),+ ).rejects.toThrow("local import");+ const oversized = structuredClone(normalized);+ oversized.findings[0]!.evidence.title = "a".repeat(256 * 1024);+ await expect(+ prepareNormalizedExternalPublication(oversized, options, {+ ...deps,+ fetch,+ }),+ ).rejects.toThrow("local import");+ const exported = {+ source_finding_id: "example",+ evidence: { title: "Example", severity: "low" as const },+ toJSON: () => normalized.findings[0],+ };+ await expect(+ prepareNormalizedExternalPublication(+ { ...normalized, findings: [exported] },+ options,+ { ...deps, fetch },+ ),+ ).rejects.toThrow("local import");+ expect(fetch).not.toHaveBeenCalled();++ const row = normalized.findings[0]!;+ const nativeId = row.source_finding_id;+ row.source_finding_id = normalizeSemgrepFindings(+ selection([page("9")], ["9"]),+ { sourceRepositoryUrl: url },+ "local",+ ).findings[0]!.source_finding_id;+ await expect(+ prepareNormalizedLocalImport(normalized, options, deps),+ ).rejects.toThrow("does not match its native occurrence");+ row.source_finding_id = "chosen-id";+ const prepared = await prepareNormalizedLocalImport(+ normalized,+ options,+ deps,+ );+ expect(prepared.preview.findings[0]!.source_finding_id).toBe("chosen-id");++ const genericOptions = { ...options, provider: "wiz" as const };+ delete row.evidence.source_data!["format"];+ await expect(+ prepareNormalizedLocalImport(normalized, genericOptions, deps),+ ).rejects.toThrow("semgrep provider");+ await expect(+ prepareNormalizedExternalPublication(normalized, genericOptions, {+ ...deps,+ fetch,+ }),+ ).rejects.toThrow("local import");+ const data = row.evidence.source_data!;+ const original = data[rawFindingKey] as string;+ data[rawFindingKey] = JSON.stringify({+ ...JSON.parse(original),+ id: "invalid",+ });+ await expect(+ prepareNormalizedLocalImport(normalized, options, deps),+ ).rejects.toThrow("Semgrep Platform ID");+ data[rawFindingKey] = original;+ row.evidence.details!.repository!.url = "https://github.com/example/other";+ await expect(+ prepareNormalizedLocalImport(normalized, options, deps),+ ).rejects.toThrow("original Semgrep repository and ref");++ row.evidence.details!.repository!.url = url;+ const rejectIncomplete = async () => {+ await expect(+ prepareNormalizedLocalImport(normalized, options, deps),+ ).rejects.toThrow(/Semgrep/i);+ await expect(+ prepareNormalizedExternalPublication(normalized, options, {+ ...deps,+ fetch,+ }),+ ).rejects.toThrow("local import");+ };+ delete data["deployment"];+ await rejectIncomplete();+ row.source_finding_id = nativeId;+ for (const raw of [+ { [rawFindingKey]: original },+ JSON.parse(original),+ undefined,+ ]) {+ if (raw) row.evidence.source_data = raw;+ else delete row.evidence.source_data;+ await rejectIncomplete();+ }+ expect(fetch).not.toHaveBeenCalled();++ const source_data = {+ findingJson: "{}",+ project: "example",+ ref,+ product: "sast",+ deployment: "example",+ };+ const evidence = { title: "Example", severity: "low" as const, source_data };+ const generic = {+ read: 1,+ excluded: [],+ findings: [{ source_finding_id: "vendor-1", evidence }],+ };+ expect(+ (await prepareNormalizedLocalImport(generic, genericOptions, deps)).preview+ .findings,+ ).toHaveLength(1);+ const credentials = async () => {+ throw new Error("Reached Cloud credentials");+ };+ await expect(+ prepareNormalizedExternalPublication(generic, genericOptions, {+ ...deps,+ fetch,+ credentials,+ }),+ ).rejects.toThrow("Reached Cloud credentials");+});++test("every selected native project must have an independent reference when supplied", async () => {+ const secondUrl = "https://github.com/example/other";+ const second = selectedRepository(secondUrl, secondUrl);+ second.project.id = "78";+ const combine = (selection: typeof second) =>+ normalizeSemgrepFindings(+ selection,+ { sourceRepositoryUrl: selection.project.url },+ "local",+ ).findings;+ const input = {+ read: 2,+ findings: [...combine(selectRow({})), ...combine(second)],+ excluded: [],+ };+ await using fixture = await localReportFixture();+ const options = {+ ...platformSource,+ repository: fixture.repository,+ provider: "semgrep" as const,+ };+ const prepare = (urls: string[]) =>+ prepareNormalizedLocalImport(input, options, {+ environment: fixture.environment,+ sourceRepositories: urls.map((url) => ({ url })),+ });+ await expect(prepare([url])).rejects.toThrow("reader's source repository");+ expect((await prepare([url, secondUrl])).preview.findings).toHaveLength(2);+});++test("a hosted projected alias uses the same fetch match while a separate generic source still must match", async () => {+ const web = "https://gitlab.com/example/project";+ const native = web + ".git";+ const report = normalizedProject(native);+ const row = report.findings[0]!;+ row.evidence.details!.repository!.url = web;+ await using fixture = await localReportFixture(+ "ssh://[email protected]:443/example/project.git",+ );+ const options = {+ ...platformSource,+ repository: fixture.repository,+ provider: "semgrep" as const,+ };+ const deps = { environment: fixture.environment };+ expect(+ (await prepareNormalizedLocalImport(report, options, deps)).preview+ .findings,+ ).toHaveLength(1);+ const generic = structuredClone(row);+ generic.source_finding_id = "unrelated";+ delete generic.evidence.source_data;+ generic.evidence.details!.repository!.url =+ "https://gitlab.com/example/other";+ report.findings.push(generic);+ report.read++;+ const both = {+ ...deps,+ sourceRepositories: [+ { url: native },+ { url: generic.evidence.details!.repository!.url! },+ ],+ };+ for (const reader of [deps, both]) {+ await expect(+ prepareNormalizedLocalImport(report, options, reader),+ ).rejects.toThrow("configured remote");+ }+ fixture.git(+ "remote",+ "add",+ "second",+ generic.evidence.details!.repository!.url!,+ );+ expect(+ (await prepareNormalizedLocalImport(report, options, both)).preview+ .findings,+ ).toHaveLength(2);+});++test("ordinary and Platform findings retain a shared GitHub Enterprise reader hint", async () => {+ const native = "https://git.example.test/Example/Project";+ const ordinary = native.toLowerCase();+ const sourceRepositories = [{ url: native, platform: "github" as const }];+ const report = normalizeSemgrepFindings(+ selectedRepository(native, native, sourceRepositories),+ { sourceRepositoryUrl: native },+ "local",+ );+ const other = {+ source_finding_id: "ordinary",+ evidence: {+ title: "Ordinary finding",+ severity: "low" as const,+ details: { kind: "sast" as const, repository: { url: ordinary } },+ },+ };+ await using fixture = await localReportFixture(native);+ const options = { ...platformSource, repository: fixture.repository };+ const prepare = (findings: typeof report.findings) =>+ prepareNormalizedLocalImport(+ { read: findings.length, findings, excluded: [] },+ options,+ { environment: fixture.environment, sourceRepositories },+ );+ expect((await prepare([other])).preview.findings).toHaveLength(1);+ for (const findings of [+ [...report.findings, other],+ [other, ...report.findings],+ ])+ expect((await prepare(findings)).preview.findings).toHaveLength(2);+ other.evidence.details.repository.url = ordinary + "-other";+ await expect(prepare([...report.findings, other])).rejects.toThrow(+ "configured remote",+ );+});++test("ordinary findings still validate the checkout when their URL equals the selected project's", async () => {+ const native = "https://gitlab.com/example/project";+ const report = normalizedProject(native);+ await using fixture = await localReportFixture(+ "ssh://[email protected]:443/example/project.git",+ );+ const options = { ...platformSource, repository: fixture.repository };+ const deps = { environment: fixture.environment };+ const ordinary = structuredClone(report.findings[0]!);+ ordinary.source_finding_id = "ordinary";+ delete ordinary.evidence.source_data;+ await expect(+ prepareNormalizedLocalImport(+ { ...report, findings: [ordinary] },+ options,+ deps,+ ),+ ).rejects.toThrow("configured remote");+ report.findings.push(ordinary);+ report.read++;+ await expect(+ prepareNormalizedLocalImport(report, options, deps),+ ).rejects.toThrow("configured remote");+});++test("an ordinary finding without a repository still checks the shared reader source", async () => {+ const native = "https://gitlab.com/example/project";+ const ssh = "ssh://[email protected]:443/example/project.git";+ const { findings } = normalizedProject(native);+ const ordinary = {+ source_finding_id: "ordinary",+ evidence: { title: "Example", severity: "low" as const },+ };+ await using fixture = await localReportFixture(ssh);+ const options = { ...platformSource, repository: fixture.repository };+ const prepare = (rows: typeof findings) =>+ prepareNormalizedLocalImport(+ { read: rows.length, findings: rows, excluded: [] },+ options,+ {+ environment: fixture.environment,+ sourceRepositories: [{ url: native }],+ },+ );+ expect((await prepare(findings)).preview.findings).toHaveLength(1);+ await expect(prepare([ordinary])).rejects.toThrow("configured remote");+ await expect(prepare([...findings, ordinary])).rejects.toThrow(+ "configured remote",+ );+ fixture.git("remote", "add", "web", native);+ expect(+ (await prepare([...findings, ordinary])).preview.findings,+ ).toHaveLength(2);+});++function projectedSarif(origin: string, sourceRepositoryUrl: string) {+ const sarif = semgrepSarif();+ Object.assign(sarif.runs[0]!, {+ versionControlProvenance: [{ repositoryUri: origin }],+ });+ return normalizeSemgrepFindings(sarif, { sourceRepositoryUrl }, "local")+ .findings;+}++function prepareMixed(+ fixture: Awaited<ReturnType<typeof localReportFixture>>,+ findings: ReturnType<typeof normalizedProject>["findings"],+ ...urls: string[]+) {+ return prepareNormalizedLocalImport(+ { read: findings.length, findings, excluded: [] },+ { ...platformSource, repository: fixture.repository },+ {+ environment: fixture.environment,+ sourceRepositories: urls.map((url) => ({ url })),+ },+ );+}++const projectedBlackDuck = (url: string) => ({+ source_finding_id: "blackduck-bom:" + "a".repeat(64),+ evidence: {+ title: "Projected finding",+ severity: "low" as const,+ source_data: { sourceRepositoryUrl: url },+ },+});++test("a projected Black Duck row and a hosted Platform row validate their own reader references", async () => {+ const native = "https://gitlab.com/example/project";+ const ssh = "ssh://[email protected]:443/example/project.git";+ const projected = "https://git.example.test/example/analysis";+ const { findings } = normalizedProject(native);+ findings.push(projectedBlackDuck(projected));+ await using fixture = await localReportFixture(ssh);+ const prepare = (reference: string) =>+ prepareNormalizedLocalImport(+ { read: findings.length, findings, excluded: [] },+ { ...platformSource, repository: fixture.repository },+ {+ environment: fixture.environment,+ sourceRepositories: [{ url: ssh }, { url: reference }],+ },+ );+ await expect(prepare(projected)).rejects.toThrow("configured remote");+ fixture.git("remote", "add", "projected", projected);+ expect((await prepare(projected)).preview.findings).toHaveLength(2);+ for (const wrong of [+ projected + "-other",+ "[email protected]:example/project.git",+ ])+ await expect(prepare(wrong)).rejects.toThrow("Reader repository");+ fixture.git("remote", "remove", "origin");+ await expect(prepare(projected)).rejects.toThrow("configured remote");+});++test("a selected project preserves an ordinary row's shared SARIF provenance", async () => {+ const native = "https://git.example.test/team/Project";+ const projected = native.toLowerCase();+ const hosted = normalizedProject(native).findings;+ const ordinary = projectedSarif(native, projected);+ await using fixture = await localReportFixture(projected);+ fixture.git("remote", "add", "platform", "https::" + native);+ const prepare = (findings: typeof hosted, url: string) =>+ prepareNormalizedLocalImport(+ { read: findings.length, findings, excluded: [] },+ { ...platformSource, repository: fixture.repository },+ { environment: fixture.environment, sourceRepositories: [{ url }] },+ );+ for (const url of [+ native,+ native.replace("git.example.test", "GIT.EXAMPLE.TEST"),+ ]) {+ expect((await prepare(hosted, url)).preview.findings).toHaveLength(1);+ await expect(prepare(ordinary, url)).rejects.toThrow("configured remote");+ await expect(prepare([...hosted, ...ordinary], url)).rejects.toThrow(+ "configured remote",+ );+ }+ fixture.git("remote", "set-url", "platform", native);+ expect(+ (await prepare([...hosted, ...ordinary], native)).preview.findings,+ ).toHaveLength(2);+});++test("mixed Semgrep imports preserve each reader's SSH alias semantics", async () => {+ const { findings } = normalizedProject(url);+ const ordinary = projectedSarif(url, url);+ const alias = "ssh://[email protected]/ex%61mple/project";+ await using fixture = await localReportFixture(url);+ const combined = [...findings, ...ordinary];+ expect(+ (await prepareMixed(fixture, combined, url)).preview.findings,+ ).toHaveLength(2);+ expect(+ (await prepareMixed(fixture, combined, url, alias)).preview.findings,+ ).toHaveLength(2);+ await expect(prepareMixed(fixture, ordinary, url, alias)).rejects.toThrow(+ "configured remote",+ );+ delete ordinary[0]!.evidence.details!.repository;+ await expect(prepareMixed(fixture, combined, alias)).rejects.toThrow(+ "configured remote",+ );+ expect(+ (await prepareMixed(fixture, combined, url, alias)).preview.findings,+ ).toHaveLength(2);+ fixture.git("remote", "add", "encoded", alias);+ expect(+ (await prepareMixed(fixture, combined, alias)).preview.findings,+ ).toHaveLength(2);+});++test("projected SARIF provenance keeps literal SSH fetch paths", async () => {+ const source = "https://git.example.test/team/repo";+ const other = "ssh://[email protected]/team/repo?other";+ const ordinary = projectedSarif(source, source);+ delete ordinary[0]!.evidence.details!.repository;+ await using fixture = await localReportFixture(url);+ fixture.git("remote", "add", "other", other);+ const rows = [...normalizedProject(url).findings, ...ordinary];+ await expect(prepareMixed(fixture, rows, url, other)).rejects.toThrow(+ "supply the projected Semgrep SARIF repository",+ );+});++test("a hosted alias stays separate from a different SARIF fetch path in a mixed projection", async () => {+ const encoded = "https://github.com/ex%61mple/project";+ const ssh = "ssh://[email protected]/ex%61mple/project";+ const projected = "https://git.example.test/team/other";+ await using fixture = await localReportFixture(ssh);+ fixture.git("remote", "add", "projected", projected);+ const rows = [+ ...normalizedProject(url).findings,+ ...projectedSarif(encoded, encoded),+ projectedBlackDuck(projected),+ ];+ expect(+ (await prepareMixed(fixture, rows, ssh, encoded, projected)).preview+ .findings,+ ).toHaveLength(3);+});++test("a shared reader reference still checks the projected SSH account", async () => {+ const rows = [+ ...normalizedProject(url).findings,+ ...projectedSarif(url, url),+ {+ ...projectedBlackDuck(url),+ evidence: {+ title: "Projected finding",+ severity: "low" as const,+ details: {+ kind: "sast" as const,+ repository: { url: "[email protected]:example/project" },+ },+ },+ },+ {+ source_finding_id: "ordinary",+ evidence: { title: "Example", severity: "low" as const },+ },+ ];+ await using fixture = await localReportFixture();+ await expect(+ prepareMixed(fixture, rows, "ssh://[email protected]/ex%61mple/project"),+ ).rejects.toThrow("Reader repository");+});++test("a redundant Platform alias retains a projected row's checkout account", async () => {+ const git = "ssh://[email protected]/example/project";+ const deploy = "[email protected]:example/project";+ const row = (id: string, url: string) => ({+ source_finding_id: id,+ evidence: {+ title: "Projected finding",+ severity: "low" as const,+ details: { kind: "sast" as const, repository: { url } },+ },+ });+ const rows = [+ ...normalizedProject(url).findings,+ row("ordinary", url),+ row("ssh", git),+ row("blackduck-bom:" + "a".repeat(64), deploy),+ ];+ await using fixture = await localReportFixture(deploy);+ fixture.git(+ "remote",+ "add",+ "encoded",+ "https://github.com/ex%61mple/project",+ );+ await expect(+ prepareMixed(fixture, rows, url, "ssh://[email protected]/ex%61mple/project"),+ ).rejects.toThrow("configured remote");+});++test("shared Platform aliases preserve the ordinary Black Duck SSH account check", async () => {+ const native = "https://github.com/example/project";+ const { findings } = normalizedProject(native);+ const projected = projectedBlackDuck(native);+ await using fixture = await localReportFixture(native);+ const git = "[email protected]:example/project.git";+ const deploy = "[email protected]:example/project.git";+ const prepare = (rows: typeof findings, urls: string[]) =>+ prepareMixed(fixture, rows, ...urls);+ await expect(prepare([projected], [git, deploy])).rejects.toThrow(+ "Reader repository",+ );+ expect(+ (await prepare([...findings, projected], [git])).preview.findings,+ ).toHaveLength(2);+ await expect(+ prepare([...findings, projected], [git, deploy]),+ ).rejects.toThrow("Reader repository");+ Object.assign(projected.evidence.source_data, {+ runContext: {+ versionControlProvenance: [git, deploy].map((repositoryUri) => ({+ repositoryUri,+ })),+ },+ });+ await expect(+ prepare([...findings, projected], [git, deploy]),+ ).rejects.toThrow("Reader repository");+});++test("a projected SARIF finding uses its own supplied provenance alongside a separate Platform reference", async () => {+ const native = "https://gitlab.com/example/project";+ const original = "https://git.example.test/team/repo";+ const { findings } = normalizedProject(native);+ const ordinary = projectedSarif(original, original);+ delete ordinary[0]!.evidence.details!.repository;+ await using fixture = await localReportFixture(+ "ssh://[email protected]:443/example/project.git",+ );+ fixture.git("remote", "add", "ordinary", original);+ const prepare = (rows: typeof findings, urls: string[]) =>+ prepareMixed(fixture, rows, ...urls);+ expect((await prepare(findings, [native])).preview.findings).toHaveLength(1);+ expect((await prepare(ordinary, [original])).preview.findings).toHaveLength(+ 1,+ );+ await expect(prepare([...findings, ...ordinary], [native])).rejects.toThrow(+ "configured remote",+ );+ expect(+ (await prepare([...findings, ...ordinary], [native, original])).preview+ .findings,+ ).toHaveLength(2);+ fixture.git("remote", "remove", "ordinary");+ await expect(+ prepare([...findings, ...ordinary], [native, original]),+ ).rejects.toThrow("configured remote");+});++test("only the hosted reader needs to recognize GitLab's alternate SSH address", async () => {+ const web = "https://gitlab.com/example/project";+ const ssh = "ssh://[email protected]:443/example/project.git";+ const hosted = normalizedProject(web).findings;+ await using fixture = await localReportFixture(web);+ for (const row of [projectedBlackDuck(web), ...projectedSarif(web, web)]) {+ expect(+ (await prepareMixed(fixture, [row], web)).preview.findings,+ ).toHaveLength(1);+ expect(+ (await prepareMixed(fixture, [...hosted, row], ssh, web)).preview+ .findings,+ ).toHaveLength(2);+ }+});++test("a projected SARIF repository cannot be replaced by another row's matching HTTPS reference", async () => {+ const a = "https://git.example.test/team/a";+ const b = "https://git.example.test/team/b";+ const ordinary = projectedSarif(b, b);+ delete ordinary[0]!.evidence.details!.repository;+ const rows = [...normalizedProject(a).findings, ...ordinary];+ await using fixture = await localReportFixture(a);+ await expect(prepareMixed(fixture, rows, a)).rejects.toThrow(+ /repository|remote/i,+ );+ await expect(prepareMixed(fixture, rows, a, b)).rejects.toThrow(+ /repository|remote/i,+ );+ await expect(prepareMixed(fixture, rows)).rejects.toThrow(+ "configured remote",+ );+ fixture.git("remote", "add", "sarif", b);+ expect((await prepareMixed(fixture, rows)).preview.findings).toHaveLength(2);+ await expect(prepareMixed(fixture, rows, a)).rejects.toThrow(+ /repository|remote/i,+ );+ expect(+ (await prepareMixed(fixture, rows, a, b)).preview.findings,+ ).toHaveLength(2);+});