OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat: import SonarQube Cloud security findings (#2162)
Michael D'Angelo6f0a4caeada7
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.mdindex b51aa6b13..9d219ba6e 100644--- a/docs/scanner-imports/schema-guide.md+++ b/docs/scanner-imports/schema-guide.md@@ -26,6 +26,7 @@ to investigate records together, not instructions to merge them.| [Amazon Inspector Code Security ListFindings JSON](inspector.md) | Full Inspector finding ARN | AWS account, Region and repository project || [Snyk Open Source CLI JSON, plugin v1 or SARIF](snyk.md) | CLI: manager, manifest, advisory, package/version and dependency path; plugin: supplied composite; SARIF: advisory, manifest set and project when known | Repository, branch, scan target and format || [Semgrep Code CLI/CI JSON or SARIF](semgrep.md) | Fingerprint; otherwise rule, literal path and start/end lines and columns | Organization, project and branch |+| [SonarQube Cloud capture or native issue-search pages](sonar.md) | Sonar issue key | Cloud instance, org, project and ref || [GitHub Dependabot repository REST alerts](github-dependabot.md) | Host, repository and alert number | Host, repository and Dependabot family || [GitHub saved `import github` output](../../sdk/typescript/docs/cli.md#import-github-findings-locally-or-to-cloud) | Host, repository, alert number and hash of selected ref | Host, repository and code-scanning family || [GitHub saved `import github-advisories` output](../../sdk/typescript/docs/cli.md#import-ghsa-advisories-separately) | Host, repository **or** global scope, and GHSA ID | Separate advisory stream from alerts |@@ -90,6 +91,11 @@ before preparing a fresh submission.envelopes and general Supply Chain/Secrets feeds are not Code CLI or SARIF exports.- **OpenGrep.** Use native JSON and supply `--source-repository-url`. The[OpenGrep guide](opengrep.md) covers export and occurrence identity.+- **SonarQube Cloud.** Use [the Sonar import workflow](sonar.md) to capture+ security issues for one project and branch or PR through the authenticated+ Sonar CLI. Keep the capture to import and publish the same native evidence.+ The issue key identifies the occurrence. The rule identifies the check that+ raised it.- **GitHub:** For code scanning, the selected instance supplies path/range, refand commit. The rule's `security_severity_level` supplies severity; diagnostic`error` alone means `unknown`. An alert-wide dismissal takes precedence overdiff --git a/docs/scanner-imports/sonar.md b/docs/scanner-imports/sonar.mdnew file mode 100644index 000000000..ca0982eef--- /dev/null+++ b/docs/scanner-imports/sonar.md@@ -0,0 +1,117 @@+# Import SonarQube Cloud security issues++Import the open security issues for a SonarQube Cloud project or the issues+you selected in the SonarQube plugin for Codex. The live import uses the+authenticated `sonar` CLI to read findings from the project's Issues view.+Keep the same Sonar server and organization selected until the fetch finishes.+A live fetch saves a capture so you can review and publish the same records later.++## Start in Codex++In the checkout, ask the SonarQube plugin to show security issues on a branch+or pull request. Then ask Codex Security to “import those two findings locally”+or “import those two findings locally and publish them to Codex Security Cloud.”+The [publish-findings skill](../../plugins/codex-security/skills/publish-findings/SKILL.md#sonarqube-cloud-issues)+uses the project's key, the selected ref, and the original Sonar issue keys to+retrieve the full records and preview the destination. You can also start in+the terminal with those same identifiers. If you installed only the Codex+Security plugin, install a version of `@openai/codex-security` that includes+the Sonar importer from a trusted directory, then run that CLI in the checkout.++## Preview a local import++Run the command from the matching checkout. Enable external imports for the+session. If you already use the Sonar plugin's issue list, the collector uses+the same `sonar` login. For first-time setup, sign in with `sonar auth login`+using an account that can browse the selected project.++```sh+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1+codex-security import sonar --sonar-project example_project --sonar-branch main \+ --sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json+```++For a pull request, replace `--sonar-branch main` with, for example,+`--sonar-pull-request 42`. With neither ref option, the collector reads the+project's main branch. Omit the issue options to collect open security+issues for the selected project and ref. If the search exceeds Sonar's+10,000-result window, pass the keys of the issues you want to import.+You can omit `--sonar-project` when+Sonar binds the checkout's Git origin to exactly one project in the signed-in+organization. For a monorepo with several Sonar projects, pass the project key+you want to import. If Sonar cannot supply the project's+repository binding, verify its Git URL in Sonar and retry the preview with+`import sonar CAPTURE --source-repository-url GIT_URL --dry-run --format json`+using the reported capture path. Check the target and selection before importing.++If the checkout uses an SSH host alias, supply the project's verified HTTPS URL+with `--source-repository-url` so the importer can compare the repository path.+The saved preview remembers that mapping for this checkout and its configured+fetch URLs, including when you preview the capture for Cloud. If the fetch URLs+change, verify the new mapping and preview again. SDK callers can pass the same+URL as `sourceRepositoryUrl` when preparing a local import.++The preview saves a private copy even when the input is a file. Use the path+it returns in `capture` to import the reviewed evidence into the local+workbench. Use the preview's `repository` path to read the findings back:++```sh+codex-security import sonar "/path/from/capture.json" --yes+codex-security findings imported "/checkout/from/preview" --format json+```++For a portable capture, or if you change the checkout or Codex Security state+directory, run `--dry-run` there first and pass the returned path to `--yes`.++Codex Security keeps each Sonar issue key and its native evidence, including+reported file ranges and available data-flow traces. For monorepos, Codex+Security maps paths relative to the Sonar project when it can verify the+project's base directory in the checkout. When the base is unknown, the+native components, ranges and flows remain available in the evidence.+Reimporting the same issue in the same source and repository updates its+record. Imported records start as unassessed findings.++## Publish the same capture to Cloud++From the same checkout, preview the capture with your Codex Security Cloud+login. Your Cloud account must be enabled for external imports, and the+deployment must accept the `sonar` source provider. Review the Cloud account,+repository, environments, counts, and exclusions before confirming. Use+the `capture` path from this Cloud preview to confirm. If the destination+changes, preview again and confirm using the new path. Replaying the capture+works without a Sonar login. For a checkout without a usable Git remote,+verify the Sonar project's repository and pass `--source-repository-url` to+the Cloud preview. If the configured remotes point to another repository,+use the matching checkout or add its verified upstream remote before previewing.++```sh+codex-security import sonar "/path/from/local-preview.json" --to cloud --dry-run --format json+codex-security import sonar "/path/from/cloud-preview.json" --to cloud --yes+```++For a single local-and-Cloud workflow, add `--to cloud` to the first live+preview and confirm using its saved capture. If Cloud authentication or+repository selection fails, you can finish the local import, then rerun the+Cloud preview with the saved capture. If an approved upload is interrupted,+retry with the same file and destination.++## Use a native JSON export++If you already have the complete response from `GET /api/issues/search` for+one project and ref, save the page object or an array containing every page.+The file reader uses the repository URL you verified for that Sonar project:++```sh+codex-security publish findings "/path/to/sonar-pages.json" --provider sonar \+ --to local --repository . --source-repository-url https://github.com/example/project \+ --source-key sonarcloud.io/example/example_project/branch/main --dry-run --format json+```++Keep the source key stable for the same Sonar instance, organization, project,+and ref. For updates to a previous import, use its exact source key. The+native page can omit the branch, project repository URL, and Sonar instance.+Only a Codex Security capture carries the collector's context for offline replay.++See [Sonar's Codex plugin](https://www.sonarsource.com/blog/now-available-sonarqube-plugin-for-codex/),+[Sonar CLI authentication](https://docs.sonarsource.com/sonarqube-cli/quickstart-guide#step-2-authenticate),+and the [Codex Security Cloud publication guide](../../sdk/typescript/docs/cli.md#publish-findings-to-cloud).diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex da894d130..88762ac1d 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -1,13 +1,13 @@---name: publish-findings-description: Requires explicit opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Preview and import scanner findings into the local workbench or Codex Security Cloud. Use the selected provider's documented export format.+description: Requires explicit opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Preview and import scanner findings, including issues selected in the SonarQube plugin, into the local workbench or Codex Security Cloud.---# Publish external findingsBefore acquiring or importing findings, check for `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` in the command environment. If it is unset or has another value, stop and ask the user to enable imports.-Use the installed `codex-security publish findings` command for preview and import. Select `--to local` for the local workbench or `--to cloud` for Cloud. The command owns source mapping, persistence, and Cloud authentication and retries. Do not implement another store or uploader or put credentials in command arguments.+Use `codex-security import sonar` for [live SonarQube Cloud issues](#sonarqube-cloud-issues) or a capture saved by that command. Use `codex-security publish findings` for native scanner exports, including Sonar `/api/issues/search` pages with `--provider sonar`. Select the requested destination. The CLI owns source mapping, persistence, and Cloud authentication and retries. Do not implement another store or uploader or put credentials in command arguments.## Select the evidence@@ -96,6 +96,21 @@ Keep supplied fingerprints. Reimporting the same fingerprint after code moves upImport native OpenGrep JSON with `--provider opengrep`, `--source-repository-url`, and a stable OpenGrep-specific `--source-key`. Preview the destination and scan diagnostics before importing. Local and Cloud imports use the Semgrep provider and retain OpenGrep as the scanner origin.+## SonarQube Cloud issues++For “import these Sonar findings,” carry over the Sonar project, branch or PR, and the exact issue keys selected in the [SonarQube plugin for Codex](https://www.sonarsource.com/blog/now-available-sonarqube-plugin-for-codex/). Use the keys from the underlying Sonar result. If only a formatted table remains, resolve the selected rows against the same project and ref and ask about ambiguous matches. A rule can occur more than once. Never turn a selection into a project-wide import.++From the intended checkout, preview the selection using the developer's authenticated `sonar` CLI. Use `--sonar-pull-request` in place of `--sonar-branch` for a PR. Omit `--sonar-issue` only when the user wants the project's open security issues. If the project has no verified SCM binding, confirm the repository URL that belongs to the project and pass it with `--source-repository-url`.++```sh+codex-security import sonar --sonar-project example_project --sonar-branch main \+ --sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json+```++Pass `--to cloud` at preview time if the user also requested Cloud publication. Show the selected issues and exclusions, the local repository, and any Cloud destination as described under [Publish to Cloud](#publish-to-cloud). The preview returns a private evidence file in `capture`. After confirmation, run `codex-security import sonar CAPTURE --yes` for local import. For Cloud, use the exact `capture` from the successful Cloud preview and add `--to cloud`. If the account, repository, or environment changes, show a fresh preview and ask for confirmation. If Cloud is unavailable, finish the requested local import and report the Cloud error. For a request to publish an existing import, start with its capture. Report the saved path so the developer can resume.++Sonar authentication is required only for a live fetch. If the local CLI lacks a login, direct the user to `sonar auth login` and keep the selection. A hosted MCP connection can help identify issues, but its issue summaries omit flow evidence. Use the signed-in CLI or a saved Codex Security Sonar capture to complete the import. If `codex-security` is absent, ask the user to install it from a trusted directory and invoke that installed executable in the checkout.+## GitHub alerts and advisoriesAcquire code-scanning findings with `codex-security import github OWNER/REPO --format json` and save its complete JSON output for local import or Cloud publication. This existing collector completes pagination, fetches alert details, and retains the selected ref's instance. In Codex, use the official [GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github) for discovery and selecting alerts, then pass that selection to the collector. Its GitHub MCP server paginates each list call separately. Do not ask the user to download JSON from a website or reconstruct a code-scanning import envelope from MCP summaries. Use the saved collector output for code-scanning alerts.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 699ad36b3..c1457c17a 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -663,11 +663,16 @@ for setup and review steps, or [Linear publication](docs/cli.md#publish-completefor issue creation.External vendor imports are opt-in. Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`-to enable `publish findings`, `findings imported`, `import github-advisories`, and-the SDK's external publication, local import/readback, and advisory acquisition+to enable `publish findings`, `findings imported`, `import sonar`, `import github-advisories`, and+the SDK's external publication, local import/readback, Sonar issue collection, and advisory acquisitionAPIs. They are disabled otherwise; CLI commands are hidden from help and schemas.SDK callers can supply the flag through the existing per-call-`dependencies.environment`. Pure normalizers and file readers remain available.+`dependencies.environment`, or in `options.environment` for `collectSonarIssues(options)`.+For an SDK import of selected Sonar issues, pass their keys in `options.issueKeys`.+Omit `issueKeys` to collect the project's open security issues. An empty list is rejected.+If you know the source repository, pass its Git URL in `options.sourceRepositoryUrl`+to check the Sonar binding before fetching issues.+Pure normalizers and file readers remain available.This does not affect scan publishing or the existing GitHub alert collector.The SDK also exposes `prepareExternalPublication(file, options)` for supported@@ -685,6 +690,11 @@ options where supported, and changing formats can change record identities orreplace richer evidence with less detail. See the[import guide](docs/cli.md#import-vendor-findings-locally) for format selection.+For SonarQube Cloud, `codex-security import sonar` reads open security issues+through the signed-in Sonar CLI. You can pass exact issue keys from the+SonarQube plugin for Codex and save a local capture for later Cloud publication.+See the [Sonar import commands](docs/cli.md#import-sonarqube-cloud-issues).+For Amazon Inspector Code Security, use `--provider inspector` with a completeListFindings JSON export and `--source-repository-url`. When the export identifiesthe repository by an ARN and name, pass `--inspector-project-arn ARN` with the ARNdiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex f6e7793b7..4976ceb10 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -32,6 +32,7 @@ without running security analysis.- [Review one system across repositories](#review-one-system-across-repositories)or [run independent bulk scans](#bulk-scans).- [Import vendor findings locally](#import-vendor-findings-locally),+ [import Sonar issues selected in Codex](#import-sonarqube-cloud-issues),[save findings as a scan](#import-findings-as-a-saved-scan), or[retrieve GitHub alerts](#import-alerts-from-the-cli).- [Inspect saved scans and rerun them](#scan-history-and-reruns),@@ -1292,7 +1293,7 @@ export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1In PowerShell, use `$env:CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS = '1'`.Only `1` enables the feature. Without it, `publish findings`, `findings imported`,-and `import github-advisories` are absent from command help and schemas and cannot+`import sonar`, and `import github-advisories` are absent from command help and schemas and cannotrun. The SDK's external publication, local import/readback, and advisoryacquisition APIs require the same flag in their effective environment. An explicit`dependencies.environment` is used instead of the process environment. Pure@@ -1322,6 +1323,7 @@ Wiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-finding[Black Duck SCA project-version vulnerabilities](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/blackduck.md),[Veracode Static Analysis policy findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/veracode.md),[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),+[SonarQube Cloud issue-search pages](#import-sonarqube-cloud-issues),[OpenGrep native JSON](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md),[GitHub Dependabot repository alerts](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md),and [saved GitHub code-scanning alerts and GHSA advisories](#import-github-findings-locally-or-to-cloud):@@ -2443,6 +2445,33 @@ record absolute Node/CLI paths. If those change, back up and remove the verifiedgenerated hook, then reinstall with the same threshold. Restore the backup ifinstallation fails. The installer respects `core.hooksPath`.+## Import SonarQube Cloud issues++Enable [external imports](#import-vendor-findings-locally) and run+`codex-security import sonar` from the project's checkout to import open+security issues from the active Sonar CLI connection. For issues selected in+the SonarQube plugin, pass each issue key with `--sonar-issue`, its project+with `--sonar-project`, and its branch or PR with `--sonar-branch` or+`--sonar-pull-request`. The plugin and terminal use the same Sonar login.+When you omit `--sonar-project`, Sonar must bind the checkout's Git origin to+one project in that login's organization.++```sh+codex-security import sonar --sonar-project example_project --sonar-branch main \+ --sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json+codex-security import sonar "/path/from/capture.json" --yes+```++`--dry-run` saves the reviewed selection and returns its path in `capture`.+The default destination is the local workbench. For both local import and+Cloud publication, preview with `--to cloud` and confirm with the exact+`capture` path from the successful Cloud preview and `--to cloud --yes`.+If the checkout or Cloud destination changes, preview again. For a structured+success or error envelope, use `--full-output` with `--format json` or+`--format jsonl`. You can publish a local import later+without reconnecting to Sonar. See [Sonar import and replay](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/sonar.md)+for authentication, repository mapping, and native JSON input.+## Import GitHub findings locally or to CloudLocal and Cloud ingestion require the [external-import opt-in](#import-vendor-findings-locally).diff --git a/sdk/typescript/schemas/external-findings.schema.json b/sdk/typescript/schemas/external-findings.schema.jsonindex bec300246..0b49fc3dd 100644--- a/sdk/typescript/schemas/external-findings.schema.json+++ b/sdk/typescript/schemas/external-findings.schema.json@@ -386,7 +386,8 @@"semgrep","inspector","blackduck",- "veracode"+ "veracode",+ "sonar"],"title": "Provider","type": "string"diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex 23708ced6..ad94df7e8 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -32,6 +32,9 @@ const distModules = ["snyk-findings","scanner-repository-url","semgrep-findings",+ "sonar-findings",+ "sonar-collector",+ "sonar-import","native-json-findings","opengrep-findings","external-findings-publish",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5e13b2f98..61a011b52 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -120,6 +120,8 @@ import {externalImportsEnabled,} from "./external-imports-feature.js";import { listLocalExternalFindings } from "./external-findings-local.js";+import type { collectSonarIssues } from "./sonar-collector.js";+import { prepareSonarImport } from "./sonar-import.js";import { EXTERNAL_FINDINGS_READERS } from "./external-findings-read.js";import type { ExternalFindings } from "./external-findings.js";import {@@ -1248,6 +1250,7 @@ interface CliDependencies {publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select"> &Partial<Pick<BulkScanPrompt, "checkbox">>;externalPublicationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "confirm">;+ collectSonarIssues?: typeof collectSonarIssues;prepareLocalExternalImport?: typeof prepareLocalExternalImport;listLocalExternalFindings?: typeof listLocalExternalFindings;checkScanPublication?: typeof checkScanPublication;@@ -3890,7 +3893,7 @@ export async function main(});const imports = Cli.create("import", {description: importsEnabled- ? "Read GitHub code scanning alerts and security advisories."+ ? "Import Sonar security issues or read GitHub security findings.": "Read GitHub code scanning alerts.",}).command("github", {description: "Read GitHub code scanning alerts without changing GitHub.",@@ -4071,7 +4074,251 @@ export async function main(},});}- if (importsEnabled) registerGitHubAdvisories();+ function registerSonarImport() {+ imports.command("sonar", {+ description:+ "Collect Sonar security findings or replay a saved capture into the local workbench.",+ hint: "Uses the active sonar CLI login. --to cloud also publishes the locally imported selection to the connected Cloud repository. --dry-run saves a live capture for review without importing findings.",+ destructive: true,+ mcp: false,+ args: z.object({+ capture: z+ .string()+ .min(1)+ .optional()+ .describe(+ "Replay a saved sonar-issues/v1 capture without connecting to Sonar.",+ ),+ }),+ options: z.object({+ sonarProject: optionValue("--sonar-project")+ .optional()+ .describe(+ "Sonar project key (defaults to the checkout’s project binding).",+ ),+ sonarBranch: optionValue("--sonar-branch")+ .optional()+ .describe(+ "Analyzed Sonar branch (default: the project's main branch).",+ ),+ sonarPullRequest: optionValue("--sonar-pull-request")+ .optional()+ .describe("Sonar pull request key, instead of a branch."),+ sonarIssue: z+ .array(optionValue("--sonar-issue"))+ .default([])+ .describe(+ "Exact Sonar security issue key. Repeat to import a selection. Defaults to open and confirmed security issues.",+ ),+ sourceRepositoryUrl: optionValue("--source-repository-url")+ .optional()+ .describe("Verified repository URL when Sonar has no SCM binding."),+ to: z+ .enum(["local", "cloud"])+ .default("local")+ .describe("Store locally, or also publish to Codex Security Cloud."),+ dryRun: z+ .boolean()+ .default(false)+ .describe(+ "Preview destinations and evidence without storing or publishing findings.",+ ),+ yes: z+ .boolean()+ .default(false)+ .describe("Confirm import of the reviewed selection."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, options, format, formatExplicit, error: incurError }) {+ return await withTerminalErrorsHandled(errorOutput, async () => {+ const humanSummary =+ format === "toon" &&+ !formatExplicit &&+ !argv.some((arg) => OUTPUT_OPTION.test(arg));+ const controller = new AbortController();+ const removeSignals = listenForAbort(dependencies, controller);+ const note = (line: string) =>+ notify(() => errorOutput.write(line + "\n"));+ const cloudFailure = (message: string) => {+ const reason = controller.signal.reason;+ exitCode =+ reason === "SIGINT" ? 130 : reason === "SIGTERM" ? 143 : 2;+ if (+ argv.includes("--full-output") &&+ (format === "json" || format === "jsonl")+ )+ failedResultOutput = {+ format,+ code: "SONAR_IMPORT_FAILED",+ message,+ };+ };+ try {+ if (+ importsEnabled &&+ argv.includes("--full-output") &&+ format !== "json" &&+ format !== "jsonl"+ ) {+ structuredError = true;+ exitCode = 2;+ return incurError({+ code: "INVALID_ARGUMENTS",+ message:+ "Sonar imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",+ exitCode,+ });+ }+ const prepared = await prepareSonarImport(+ {+ cwd: dependencies.currentDirectory(),+ capture: args.capture,+ project: options.sonarProject,+ branch: options.sonarBranch,+ pullRequest: options.sonarPullRequest,+ issueKeys: options.sonarIssue,+ sourceRepositoryUrl: options.sourceRepositoryUrl,+ to: options.to,+ dryRun: options.dryRun,+ yes: options.yes,+ },+ {+ environment: dependencies.environment,+ signal: controller.signal,+ fetch: dependencies.cloudFetch,+ collect: dependencies.collectSonarIssues,+ onCapture: (path) =>+ note("Evidence file: " + diagnosticValue(path)),+ },+ );+ const { info, local, cloud, cloudError } = prepared;+ const ref = info.pullRequest+ ? `pull request ${info.pullRequest}`+ : (info.branch ?? "unspecified ref");+ note(+ `Sonar project: ${diagnosticValue(info.organization)}/${diagnosticValue(info.project)} (${diagnosticValue(ref)}) on ${diagnosticValue(info.server)}`,+ );+ note(`Local repository: ${diagnosticValue(info.repository)}`);+ note(+ `Local: ${local.findings.length} ready, ${local.excluded.length} excluded.`,+ );+ if (cloud) {+ const environments = new Set(+ cloud.requests.map(+ (request) => request.repository.environment_id,+ ),+ );+ note(+ `Cloud account: ${diagnosticValue(cloud.accountId)} on ${diagnosticValue(cloud.cloudApiUrl)}`,+ );+ note(+ `Cloud repository: ${diagnosticValue(cloud.destination.url)} · Environments: ${[...environments].map(diagnosticValue).join(", ")}`,+ );+ note(+ `Cloud: ${cloud.findings.length} ready, ${cloud.excluded.length} excluded.`,+ );+ }+ if (options.to === "cloud" && local.read === 0)+ note("No Sonar findings to publish to Cloud.");+ if (cloudError)+ note(`Cloud unavailable: ${diagnosticValue(cloudError)}`);+ for (const { source_finding_id, evidence } of local.findings.slice(+ 0,+ 5,+ ))+ note(+ ` ${diagnosticValue(source_finding_id)} [${evidence.severity}] ${diagnosticValue(evidence.title)}`,+ );+ if (local.findings.length > 5)+ note(+ ` Showing the first 5 of ${local.findings.length} ready findings. Use --dry-run --format json for the full selection.`,+ );+ const exclusions = new Set(+ [...local.excluded, ...(cloud?.excluded ?? [])].map(+ (item) =>+ `Excluded ${diagnosticValue(item.source_finding_id ?? `item ${item.position}`)}: ${diagnosticValue(item.reason)}`,+ ),+ );+ for (const line of exclusions) note(line);+ if (options.dryRun) {+ if (cloudError) cloudFailure(cloudError);+ if (humanSummary)+ renderedOutput = cloudError+ ? "Evidence saved. Retry with the saved file and --to cloud --dry-run to review the Cloud destination.\n"+ : "Preview complete. Use the saved evidence file to import this selection.\n";+ return { ...info, local, cloud, cloudError, dryRun: true };+ }+ if (!options.yes) {+ const prompt =+ dependencies.externalPublicationPrompt ??+ createTerminalPrompt(errorOutput);+ if (!prompt.isInteractive())+ throw new Error(+ "Review the saved capture with --dry-run, then pass its path and --yes to confirm.",+ );+ const action = cloud+ ? " and publish " ++ cloud.findings.length ++ " to the displayed Cloud destination"+ : " locally";+ if (+ !(await prompt.confirm(+ "Import " ++ local.findings.length ++ " Sonar findings" ++ action ++ "?",+ false,+ controller.signal,+ ))+ ) {+ if (humanSummary) renderedOutput = "Import canceled.\n";+ return { ...info, imported: false };+ }+ }+ const result = await prepared.import();+ if (result.cloudError) {+ cloudFailure(result.cloudError);+ note(+ "Stored locally. Cloud: " + diagnosticValue(result.cloudError),+ );+ } else if (+ result.local.excluded.length ||+ result.cloud?.status === "partial"+ )+ exitCode = 1;+ if (result.cloud?.cloudUrl)+ note(+ "Cloud repository: " + diagnosticValue(result.cloud.cloudUrl),+ );+ if (humanSummary) {+ const { created, updated, unchanged } = result.local.counts;+ renderedOutput = `Local import: ${created} created, ${updated} updated, ${unchanged} unchanged.\n`;+ if (result.cloud)+ renderedOutput += renderExternalPublicationSummary(+ result.cloud,+ );+ }+ return { ...result };+ } catch (error) {+ reportPublicationError(error, controller.signal.reason);+ if (argv.includes("--full-output")) structuredError = true;+ return incurError({+ code: "SONAR_IMPORT_FAILED",+ message: diagnosticValue(error),+ exitCode,+ });+ } finally {+ removeSignals();+ }+ });+ },+ });+ }+ if (importsEnabled) {+ registerGitHubAdvisories();+ registerSonarImport();+ }const infoOutput = z.object({sdkVersion: z.string(),bundledPluginVersion: z.string(),@@ -6838,7 +7085,8 @@ export async function main(!importsEnabled &&((command === "publish" && subcommand === "findings") ||(command === "findings" && subcommand === "imported") ||- (command === "import" && subcommand === "github-advisories"))+ (command === "import" &&+ (subcommand === "github-advisories" || subcommand === "sonar")))) {if (process.env["COMPLETE"] ||@@ -6858,6 +7106,7 @@ export async function main(// This route only formats a disabled command; it is not an installed skill.cliOptions.sync = false;if (command === "publish") registerFindingPublication();+ else if (subcommand === "sonar") registerSonarImport();else registerGitHubAdvisories();valueOptions = cliValueOptions(commands);}diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex aa3d14376..8be8c7bd5 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -27,9 +27,17 @@ import {blackDuckReportRepositories,projectedBlackDuckRepositoryUrl,} from "./blackduck-findings.js";-import { isGitHubCloudHost, parseGitRemote } from "./git-remote.js";+import {+ azureReposHttpsUrl,+ isGitHubCloudHost,+ isGitHubSshOverHttps,+ isGitSsh,+ parseGitRemote,+} from "./git-remote.js";import { veracodeReportRepositories } from "./veracode-findings.js";import { inspectorReportRepository } from "./inspector-findings.js";+import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";+import { sonarRepositoryUrls } from "./sonar-findings.js";import { isRecord } from "./record.js";import { dependabotRepository } from "./github-dependabot-findings.js";import {@@ -44,6 +52,7 @@ import {} from "./runtime.js";import {abortable,+ enclosingGitWorktreeRoot,gitMarkerRoot,gitOutput,gitProtectionRoots,@@ -71,6 +80,8 @@ export interface NormalizedLocalImportOptions {provider: Provider;/** Stable scanner organization/project/branch namespace across imports. */sourceKey: string;+ /** Explicitly verified Sonar repository when a checkout uses an SSH host alias. */+ sourceRepositoryUrl?: string;/** Full Inspector project ARNs mapped to independently verified repository URLs. */inspectorProjectMap?: ReadonlyMap<string, string>;}@@ -99,6 +110,8 @@ export interface LocalExternalImportResult {}export interface PreparedLocalExternalImport {+ /** Every declared source matched a configured Git remote of the checkout. */+ matchesRepositoryRemote: boolean;preview: LocalExternalImportPreview;import(): Promise<LocalExternalImportResult>;}@@ -131,10 +144,28 @@ interface RemoteRepositoryIdentity {homeRelative?: boolean;}+function sonarHostedGit(hostname: string) {+ return (+ isGitHubCloudHost(hostname) ||+ hostname === "gitlab.com" ||+ hostname === "bitbucket.org"+ );+}++function sonarHostedHostname(hostname: string) {+ const name = hostname.toLowerCase().replace(/\.$/u, "");+ return sonarHostedGit(name) ||+ ["ssh.github.com", "ssh.dev.azure.com", "dev.azure.com"].includes(name)+ ? name+ : undefined;+}+function remoteRepository(value: string,provider: Provider,bound: boolean,+ platform: Provider = provider,+ possibleSshHost?: string,): RemoteRepositoryIdentity | undefined {if (/^[A-Za-z]:[\\/]/u.test(value)) return undefined;const transport = bound@@ -159,20 +190,23 @@ function remoteRepository(if (!remote || !Object.hasOwn(gitTransportPorts, remote.url.protocol))return undefined;const { url, path, scpStyle } = remote;- const ssh = url.protocol.includes("ssh");+ const ssh = isGitSsh(url.protocol);const protocol = url.protocol === "http:" ? "http:" : "https:";- const githubSshOverHttps =- ssh &&- url.hostname.toLowerCase() === "ssh.github.com" &&- url.port === "443";- const hostname = githubSshOverHttps ? "github.com" : url.hostname;+ const hosted = sonarHostedHostname(url.hostname);+ if (provider === "sonar" && hosted) url.hostname = hosted;+ const githubSshOverHttps = isGitHubSshOverHttps(url);+ let hostname = githubSshOverHttps ? "github.com" : url.hostname;+ // An unresolved SSH name can be a local Host alias. Only substitute the+ // supplied hostname when checking the path of an unverified manual mapping.+ if (possibleSshHost && ssh && (!hosted || hosted === "dev.azure.com"))+ hostname = sonarHostedHostname(possibleSshHost) ?? possibleSshHost;const port =githubSshOverHttps || url.port === gitTransportPorts[url.protocol]? "": url.port;// A GitHub source identifies a case-insensitive repository on custom Enterprise// hosts too; other providers can refer to VCS hosts with case-sensitive paths.- const key = provider === "github" ? cloudRepositoryUrlKey : repositoryUrlKey;+ const key = platform === "github" ? cloudRepositoryUrlKey : repositoryUrlKey;const origin = `${protocol}//${hostname}${port ? `:${port}` : ""}/`;if (!bound) return { key: key(origin + path) };@@ -221,17 +255,25 @@ function remoteRepository((byte) =>"%" + byte.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"),);+ // Azure's generated SCP clone URL spells spaces as %20, even though Git sends SCP paths literally.+ const azure =+ provider === "sonar" && !(scpStyle && path.startsWith("/"))+ ? azureReposHttpsUrl(+ url,+ scpStyle ? name.replace(/%2520/gu, "%20") : name,+ )+ : undefined;const repository = suffix? key(origin + name + "?") +"\0" +suffix[0].replace(/\/$/u, "").replace(/\.git$/u, "")- : key(origin + name);+ : key(azure ?? origin + name);return {key: repository,account: ssh && login ? literal(login) : undefined,// GitHub serves the same repository path through its SCP and SSH URLs.homeRelative:- ssh && provider !== "github" && !isGitHubCloudHost(hostname.toLowerCase())+ ssh && platform !== "github" && !isGitHubCloudHost(hostname.toLowerCase())? homeRelative: undefined,};@@ -253,13 +295,83 @@ function matchingRemote();}+/** A credential-free Sonar repository binding from a supported Git fetch transport. */+export function sonarRepositoryForRemote(origin: string): string | undefined {+ try {+ if (/[\s\\\p{Cc}?#]/u.test(origin)) return;+ const remote = parseGitRemote(origin);+ if (!remote) return;+ const { url } = remote;+ // Git dispatches remote helpers by the literal scheme, while URL lowercases it.+ if (!remote.scpStyle && !origin.startsWith(url.protocol + "//")) return;+ // Git passes literal SSH paths to upload-pack. URL.pathname collapses dot segments.+ const path = remote.scpStyle+ ? remote.path+ : /^[^:/]+:\/\/[^/]+\/(.+)$/u.exec(origin)?.[1];+ if (!path) return;+ const hostname = url.hostname.toLowerCase();+ let candidate: string | undefined;+ if (url.protocol === "http:" || url.protocol === "https:") {+ candidate = `${url.origin}/${path}`;+ } else if (url.username === "git" && isGitHubSshOverHttps(url)) {+ candidate = `https://github.com/${path}`;+ } else if (+ isGitSsh(url.protocol) &&+ url.username === "git" &&+ (!url.port || url.port === "22") &&+ sonarHostedGit(hostname)+ ) {+ candidate = `https://${hostname}/${path}`;+ } else {+ candidate = azureReposHttpsUrl(url, path);+ }+ if (!candidate) return;+ const source = declaredScannerRepositoryUrl(+ candidate.replace(/\.git$/iu, ""),+ "Sonar",+ "local",+ );+ const candidateRemote = remoteRepository(origin, "sonar", true);+ const target = remoteRepository(source, "sonar", true);+ if (isGitSsh(url.protocol) && candidateRemote?.account !== "git") return;+ return candidateRemote && target && matchingRemote(candidateRemote, target)+ ? source+ : undefined;+ } catch {+ return undefined;+ }+}++/** Use the same executable and configuration boundaries for every Git query proving a binding. */+export function boundSonarWorktree(+ repository: string,+ protectedRoots: string | readonly string[],+ environment: NodeJS.ProcessEnv | undefined,+ signal?: AbortSignal,+) {+ return enclosingGitWorktreeRoot(repository, signal, {+ requireIfPresent: true,+ readGit: (directory, args) =>+ gitOutput(+ directory,+ args,+ signal,+ undefined,+ undefined,+ "utf8",+ protectedRoots,+ environment,+ ),+ });+}+function localRepositoryPlatform(provider: Provider,sources: readonly ExternalSourceRepository[],bound: boolean,) {const githubKey = (url: string) =>- remoteRepository(url, "github", bound)?.key;+ remoteRepository(url, provider, bound, "github")?.key;const githubRepositories = new Set(sources.flatMap((source) => {if (source.platform !== "github") return [];@@ -413,7 +525,7 @@ async function associatedMetadataRoots(return roots;}-async function localGitProtectionRoots(+export async function localGitProtectionRoots(repository: string,environment: NodeJS.ProcessEnv,signal?: AbortSignal,@@ -481,24 +593,41 @@ async function hasGitMetadata();}-async function requireMatchingRepository(+/** @internal */+export interface ConfiguredFetchRemote {+ name: string;+ url: string;+}++/** @internal Effective fetch URLs from the selected, protected checkout. */+export async function configuredFetchRemotes(repository: string,provider: Provider,- sources: readonly ExternalSourceRepository[],- strictSources: ReadonlyMap<string, Provider>,- strictPlatformFor: (source: ExternalSourceRepository) => Provider,protectedRoots: WorkbenchCommandOptions["protectedRoot"],environment: WorkbenchCommandOptions["environment"],signal?: AbortSignal,-): Promise<void> {- if (sources.length === 0) return;- if (!(await hasGitMetadata(repository, signal))) return;+): Promise<ConfiguredFetchRemote[]> {+ if (!(await hasGitMetadata(repository, signal))) return [];const gitProtectedRoots = [...(typeof protectedRoots === "string"? [protectedRoots]: (protectedRoots ?? [])),- await abortable(() => canonicalConfigPath(process.cwd()), signal),];+ // The Sonar caller includes the discovered Git roots for both checkouts.+ if (provider !== "sonar")+ gitProtectedRoots.push(+ await abortable(() => canonicalConfigPath(process.cwd()), signal),+ );+ if (+ provider === "sonar" &&+ !(await boundSonarWorktree(+ repository,+ gitProtectedRoots,+ environment,+ signal,+ ))+ )+ return [];const readGit = (args: readonly string[]) =>abortable(() =>@@ -532,33 +661,110 @@ async function requireMatchingRepository(error.stderr.trimEnd(),)))- return;+ return [];throw error;}- const remotes: string[] = [];+ const remotes: ConfiguredFetchRemote[] = [];for (const name of remoteNames.split(/\r?\n/u).filter(Boolean)) {- const urls = await readGit(["remote", "get-url", "--all", "--", name]);- remotes.push(...urls.split(/\r?\n/u));+ if (provider === "sonar") {+ // Git fetches from only the first URL, after insteadOf rewrites.+ const url = await readGit(["remote", "get-url", "--", name]);+ if (/[\r\n]/u.test(url))+ throw new CodexSecurityError(+ "A configured Git remote URL contains a line break. Configure each fetch URL as a separate Git value.",+ );+ remotes.push({ name, url });+ } else {+ const urls = await readGit(["remote", "get-url", "--all", "--", name]);+ for (const url of urls.split(/\r?\n/u)) remotes.push({ name, url });+ }}+ return remotes;+}++async function requireMatchingRepository(+ repository: string,+ provider: Provider,+ sources: readonly ExternalSourceRepository[],+ strictSources: ReadonlyMap<string, Provider>,+ strictPlatformFor: (source: ExternalSourceRepository) => Provider,+ protectedRoots: WorkbenchCommandOptions["protectedRoot"],+ environment: WorkbenchCommandOptions["environment"],+ signal?: AbortSignal,+ possibleSshHost?: string,+ fetchRemotes?: readonly ConfiguredFetchRemote[],+): Promise<boolean> {+ if (sources.length === 0) return false;+ const remotes =+ fetchRemotes ??+ (await configuredFetchRemotes(+ repository,+ provider,+ protectedRoots,+ environment,+ signal,+ ));const boundProvider =+ provider === "sonar" ||provider === "inspector" ||provider === "blackduck" ||provider === "veracode";const loosePlatformFor = localRepositoryPlatform(provider, sources, false);+ const comparable: string[] = [];+ const unverified: string[] = [];+ for (const { url: remote } of remotes) {+ const verified =+ provider === "sonar" ? sonarRepositoryForRemote(remote) : remote;+ 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 identity = (url: string) => remoteRepository(url, platform, bound);- const targets = remotes.flatMap((remote) => identity(remote) ?? []);- if (!targets.length) continue;+ const identity = (url: string) =>+ remoteRepository(url, provider, bound, platform);+ const targets = comparable.flatMap((remote) => identity(remote) ?? []);const target = identity(source.url);- if (!target || !targets.some((remote) => matchingRemote(remote, target)))+ if (target && targets.some((remote) => matchingRemote(remote, target)))+ continue;+ allSourcesMatched = false;+ // A custom SSH upstream can agree with a manual mapping even when a+ // recognized HTTPS remote points at a fork. It cannot prove a Cloud binding.+ const configured = unverified.flatMap(+ (remote) =>+ remoteRepository(remote, provider, bound, platform, possibleSshHost) ??+ [],+ );+ if (target && configured.some((remote) => matchingRemote(remote, target)))+ continue;+ if (targets.length || configured.length)throw new CodexSecurityError(`Imported repository ${JSON.stringify(source.url)} does not match a configured remote of ${repository}. Select the matching local repository.`,);}+ return allSourcesMatched;+}++export function sonarCheckoutMatchesSource(+ repository: string,+ url: string,+ protectedRoots: readonly string[],+ environment: NodeJS.ProcessEnv,+ signal?: AbortSignal,+) {+ return requireMatchingRepository(+ repository,+ "sonar",+ [{ url }],+ new Map(),+ () => "sonar",+ [...protectedRoots],+ environment,+ signal,+ );}async function localContext(@@ -639,6 +845,7 @@ export async function prepareLocalImport(dependencies: LocalExternalImportDependencies,readerSources = snapshotSourceRepositories(dependencies.sourceRepositories),parsedSources: readonly ExternalSourceRepository[] = [],+ fetchRemotes?: readonly ConfiguredFetchRemote[],): Promise<PreparedLocalExternalImport> {requireIdentity(options.sourceKey, "Source key");const current = structuredClone(input);@@ -717,7 +924,9 @@ export async function prepareLocalImport(true,);const identify = (url: string) =>- remoteRepository(url, platformFor({ url }), true) ?? { key: url };+ remoteRepository(url, options.provider, true, platformFor({ url })) ?? {+ key: url,+ };// A hint from an independent reader applies across projected rows. A native// GitHub asset in one row only identifies the platform of that row's claims.const operatorPlatform = localRepositoryPlatform(@@ -765,7 +974,12 @@ export async function prepareLocalImport(!sameScannerRepositories(claims.map((claim) =>- remoteRepository(claim, rowPlatform(claim), true) ?? {+ remoteRepository(+ claim,+ options.provider,+ true,+ rowPlatform(claim),+ ) ?? {key: claim,},),@@ -810,9 +1024,18 @@ export async function prepareLocalImport(}if (inspector) {const platform = inspector.platform ?? options.provider;- const native = remoteRepository(inspector.url, platform, true);+ const native = remoteRepository(+ inspector.url,+ options.provider,+ true,+ platform,+ );for (const url of sources.keys()) {- if (!native || remoteRepository(url, platform, true)?.key !== native.key)+ if (+ !native ||+ remoteRepository(url, options.provider, true, platform)?.key !==+ native.key+ )throw new CodexSecurityError(`Imported repository ${JSON.stringify(url)} does not match the retained Inspector repository ${JSON.stringify(inspector.url)}.`,);@@ -826,6 +1049,29 @@ export async function prepareLocalImport(options.inspectorProjectMap ? { url: source.url } : source,);}+ const sonarSources = sonarRepositoryUrls(+ options.provider,+ current.findings,+ current.report,+ "local",+ );+ const manualSource =+ options.provider === "sonar" && options.sourceRepositoryUrl+ ? declaredScannerRepositoryUrl(+ options.sourceRepositoryUrl,+ "Sonar",+ "local",+ )+ : undefined;+ if (manualSource) sonarSources.add(manualSource);+ for (const url of sonarSources)+ if (!sources.has(url)) sources.set(url, { url });+ if (sonarSources.size && !sameRepositories(sources.keys()))+ throw new CodexSecurityError(+ manualSource+ ? "The Sonar evidence does not match the declared source repository."+ : "The retained Sonar repository does not match the other source repository claims.",+ );if (options.provider === "blackduck" &¤t.findings.length &&@@ -840,7 +1086,8 @@ export async function prepareLocalImport(url: dependabotSource,platform: "github",});- await requireMatchingRepository(+ const selected = manualSource ? new URL(manualSource) : undefined;+ const matchesRepositoryRemote = await requireMatchingRepository(repository,options.provider,[...sources.values()],@@ -849,6 +1096,8 @@ export async function prepareLocalImport(workbenchOptions.protectedRoot,workbenchOptions.environment,dependencies.signal,+ selected?.protocol === "https:" ? selected.hostname : undefined,+ fetchRemotes,);dependencies.signal?.throwIfAborted();const preview = {@@ -873,6 +1122,7 @@ export async function prepareLocalImport(},);return {+ matchesRepositoryRemote,preview,async import() {dependencies.signal?.throwIfAborted();diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 3ac2032ae..bf428e081 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -42,6 +42,7 @@ import {} from "./blackduck-findings.js";import { veracodeReportRepositories } from "./veracode-findings.js";import { inspectorReportRepository } from "./inspector-findings.js";+import { sonarRepositoryUrls } from "./sonar-findings.js";import {snapshotImportOptions,type ExternalFindings,@@ -227,7 +228,19 @@ function reportForJson(report: ExternalFindings["report"]) {return { ...report, errors: JSON.parse(json) as unknown[] };}-async function writeAtomicJson(path: string, value: unknown): Promise<void> {+export function externalPublicationStateDirectory(+ environment: NodeJS.ProcessEnv,+): string {+ return join(+ codexSecurityStateDirectory(environment),+ "external-finding-publications",+ );+}++export async function writeAtomicJson(+ path: string,+ value: unknown,+): Promise<void> {const temporary = `${path}.${randomUUID()}.tmp`;try {const file = await open(temporary, "wx", 0o600);@@ -543,10 +556,9 @@ async function preparePublicationInput();const destination = destinations[0]!;const source = { provider: options.provider, source_key: options.sourceKey };- const state = join(- codexSecurityStateDirectory(environment),- "external-finding-publications",- );+ const importPrefix = source.provider === "sonar" ? "/v2" : "";+ const sourceReportsPath = importPrefix + sourcePath(destination);+ const state = externalPublicationStateDirectory(environment);const checkpointIdentity = [// Keep existing production checkpoints readable; other deployments must// never share a saved request or receipt with the production default.@@ -743,7 +755,10 @@ async function preparePublicationInput("Supply the verified Inspector project binding again to resume.",);- function checkRepositories(findings: ExternalFindings["findings"]) {+ function checkRepositories(+ findings: ExternalFindings["findings"],+ report?: ExternalFindings["report"],+ ) {function requireDestination(id: string, url: string | null | undefined) {if (url &&@@ -756,6 +771,15 @@ async function preparePublicationInput(// Historical checkpoints already fixed the provider and request bytes.// Recheck any projected source against the destination discovered for this retry.const replay = saved && options.provider !== "blackduck";+ if (!saved || options.provider === "sonar") {+ for (const url of sonarRepositoryUrls(+ options.provider,+ findings,+ report,+ "cloud",+ ))+ requireDestination("Sonar source", url);+ }const repositories = replay? undefined: blackDuckReportRepositories(options.provider, findings, "cloud");@@ -789,7 +813,8 @@ async function preparePublicationInput(replay &&!projected &&options.provider !== "inspector" &&- options.provider !== "veracode"+ options.provider !== "veracode" &&+ options.provider !== "sonar")continue;const urls = [@@ -815,9 +840,17 @@ async function preparePublicationInput(for (const url of urls) requireDestination(id, url);}}- checkRepositories(parsed.findings);+ checkRepositories(parsed.findings, parsed.report);// A retry sends its saved projection, which may differ from today's reader.- if (saved) checkRepositories(submissionFindings(saved.requests));+ if (saved) {+ // A common Sonar ref can supply missing row refs. Only use the report+ // associated with the input digest in the saved checkpoint.+ const report =+ saved.inputProjection?.inputDigest === inputDigest+ ? parsed.report+ : undefined;+ checkRepositories(submissionFindings(saved.requests), report);+ }let requests = saved?.requests;if (!requests) {@@ -837,7 +870,7 @@ async function preparePublicationInput(limit: "2",});const summaries = validateSourceReports(- await request(`${sourcePath(destination)}?${query}`),+ await request(`${sourceReportsPath}?${query}`),);if (summaries.has_more || summaries.data.length > 1)throw new CodexSecurityError(@@ -1022,7 +1055,7 @@ async function preparePublicationInput(for (const [batchIndex, batch] of requests.entries()) {const receipt = validatePublicationReceipt(receipts[batchIndex] ??- (await request("/finding_imports", batch)),+ (await request(`${importPrefix}/finding_imports`, batch)),batch,);acknowledged.push(receipt);@@ -1065,7 +1098,7 @@ async function preparePublicationInput(await readInBatches(readbacks, async ({ item, expected, batch }) => {const report = validateSourceReport(await request(- `${sourcePath(destination)}/${encodeURIComponent(item.source_report_id!)}`,+ `${sourceReportsPath}/${encodeURIComponent(item.source_report_id!)}`,),);if (diff --git a/sdk/typescript/src/external-findings-read.ts b/sdk/typescript/src/external-findings-read.tsindex 1fbe29145..f62d18dfd 100644--- a/sdk/typescript/src/external-findings-read.ts+++ b/sdk/typescript/src/external-findings-read.ts@@ -12,6 +12,7 @@ import { readOpenGrepFindings } from "./opengrep-findings.js";import { readEndorFindings, endorRepositoryUrls } from "./endor-findings.js";import { dependabotRepository } from "./github-dependabot-findings.js";import { readGitHubFindings } from "./github-findings.js";+import { readSonarFindings } from "./sonar-findings.js";import { readVeracodeFindings } from "./veracode-findings.js";import { readBlackDuckFindings } from "./blackduck-findings.js";import { readInspectorFindings } from "./inspector-findings.js";@@ -33,6 +34,7 @@ export const EXTERNAL_FINDINGS_PROVIDERS = {inspector: "inspector",blackduck: "blackduck",veracode: "veracode",+ sonar: "sonar",} as const satisfies Record<string, Provider>;export type ExternalFindingsReader = keyof typeof EXTERNAL_FINDINGS_PROVIDERS;@@ -85,6 +87,15 @@ export async function readExternalFindings(options: ExternalFindingsReaderOptions,target: ExternalImportTarget = "cloud",): Promise<ReadExternalFindings> {+ if (options.provider === "sonar") {+ const url = options.sourceRepositoryUrl;+ const findings = await readSonarFindings(path, url ?? "", target);+ const binding = findings.report?.["repositoryUrl"];+ return {+ findings,+ sourceRepositories: typeof binding === "string" ? [{ url: binding }] : [],+ };+ }if (options.provider === "opengrep") {const sourceRepositoryUrl = options.sourceRepositoryUrl ?? "";return {diff --git a/sdk/typescript/src/external-import-models.ts b/sdk/typescript/src/external-import-models.tsindex 50188cbb5..857da64d8 100644--- a/sdk/typescript/src/external-import-models.ts+++ b/sdk/typescript/src/external-import-models.ts@@ -13,7 +13,8 @@ export type Provider =| "semgrep"| "inspector"| "blackduck"- | "veracode";+ | "veracode"+ | "sonar";export type SourceKey = string;export type ClientId = string;export type SourceFindingId = string;diff --git a/sdk/typescript/src/git-remote.ts b/sdk/typescript/src/git-remote.tsindex 9190c8f12..7c6cc94ea 100644--- a/sdk/typescript/src/git-remote.ts+++ b/sdk/typescript/src/git-remote.ts@@ -30,3 +30,30 @@ export function parseGitRemote(remote: string): GitRemote | undefined {export function isGitHubCloudHost(host: string): boolean {return host === "github.com" || host.endsWith(".ghe.com");}++export function isGitSsh(protocol: string): boolean {+ return ["ssh:", "git+ssh:", "ssh+git:"].includes(protocol);+}++export function isGitHubSshOverHttps(url: URL): boolean {+ return (+ isGitSsh(url.protocol) &&+ url.hostname.toLowerCase() === "ssh.github.com" &&+ url.port === "443"+ );+}++/** Azure Repos uses different hosts and paths for the same SSH and HTTPS repository. */+export function azureReposHttpsUrl(url: URL, path: string): string | undefined {+ if (+ !isGitSsh(url.protocol) ||+ url.hostname.toLowerCase() !== "ssh.dev.azure.com" ||+ url.username !== "git" ||+ url.password ||+ (url.port && url.port !== "22")+ )+ return;+ const match = /^v3\/([^/]+)\/([^/]+)\/([^/]+)$/u.exec(path);+ if (match)+ return `https://dev.azure.com/${match[1]}/${match[2]}/_git/${match[3]}`;+}diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 3c9dc1981..cc810740a 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -331,6 +331,11 @@ export {readOpenGrepFindings,type OpenGrepImportOptions,} from "./opengrep-findings.js";+export { readSonarFindings, type SonarCapture } from "./sonar-findings.js";+export {+ collectSonarIssues,+ type SonarCollectionOptions,+} from "./sonar-collector.js";export {normalizeVeracodeFindings,readVeracodeFindings,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex d5e7e15a2..b77ac396d 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -404,14 +404,14 @@ export async function preparePolicyOutputDirectory();}-async function requirePrivateDirectory(+export async function requirePrivateDirectory(metadata: Pick<Stats, "mode" | "uid">,path: string,description: string,options: {platform?: NodeJS.Platform;secureWindowsHome?: (path: string) => Promise<void>;- },+ } = {},): Promise<void> {if ((options.platform ?? process.platform) !== "win32") {requirePrivateOutputDirectory(metadata, path);diff --git a/sdk/typescript/src/scanner-import.ts b/sdk/typescript/src/scanner-import.tsindex cc21b00c8..7b1da57d3 100644--- a/sdk/typescript/src/scanner-import.ts+++ b/sdk/typescript/src/scanner-import.ts@@ -1,5 +1,5 @@import { hash } from "node:crypto";-import { readFile } from "node:fs/promises";+import { readFile, type FileHandle } from "node:fs/promises";import { promisify } from "node:util";import { gunzip } from "node:zlib";import { CodexSecurityError, errorMessage } from "./errors.js";@@ -52,7 +52,7 @@ export function stableId(prefix: string, fields: unknown[]): string {const strictUtf8 = new TextDecoder("utf-8", { fatal: true });const gunzipAsync = promisify(gunzip);-async function readScannerBytes(path: string): Promise<Buffer> {+async function readScannerBytes(path: string | FileHandle): Promise<Buffer> {const bytes = await readFile(path);return bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipAsync(bytes) : bytes;}@@ -72,7 +72,9 @@ export function parseJsonOrJsonl(contents: string): unknown {}}-export async function readScannerJson(path: string): Promise<unknown> {+export async function readScannerJson(+ path: string | FileHandle,+): Promise<unknown> {const bytes = await readScannerBytes(path);let decoded: string;try {diff --git a/sdk/typescript/src/sonar-collector.ts b/sdk/typescript/src/sonar-collector.tsnew file mode 100644index 000000000..ac66a98c5--- /dev/null+++ b/sdk/typescript/src/sonar-collector.ts@@ -0,0 +1,563 @@+import { execFile as execFileCallback } from "node:child_process";+import { dirname, resolve } from "node:path";+import { promisify } from "node:util";+import { CodexSecurityError, errorMessage } from "./errors.js";+import {+ boundSonarWorktree,+ sonarRepositoryForRemote,+ sonarCheckoutMatchesSource,+ localGitProtectionRoots,+} from "./external-findings-local.js";+import { repositoryUrlKey } from "./external-import-contract.js";+import {+ forwardExternalImportSetting,+ requireExternalImports,+} from "./external-imports-feature.js";+import { isRecord } from "./record.js";+import { array, record, relativePath, requiredText } from "./scanner-import.js";+import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";+import {+ completeSonarPages,+ mergeSonarIssueScope,+ type SonarCapture,+} from "./sonar-findings.js";+import { gitOutput } from "./targets.js";+import {+ inspectTrustedExecutable,+ resolveTrustedExecutable,+} from "./trusted-executable.js";+import { isSafeNonNegativeInteger } from "./value.js";++const execFile = promisify(execFileCallback);++export interface SonarCollectionOptions {+ cwd: string;+ project?: string;+ sourceRepositoryUrl?: string | undefined;+ branch?: string;+ pullRequest?: string;+ issueKeys?: readonly string[];+ environment?: NodeJS.ProcessEnv;+ signal?: AbortSignal;+}++type SonarCommand = (args: string[]) => Promise<Record<string, unknown>>;++async function sonarCommand(+ options: SonarCollectionOptions,+ protectedRoots: string[],+): Promise<SonarCommand> {+ const { environment = process.env, signal } = options;+ const trusted = await resolveTrustedExecutable(+ "sonar",+ environment,+ protectedRoots,+ );+ if (!trusted) {+ throw new CodexSecurityError(+ "Install the SonarQube CLI (sonar) and run 'sonar auth login', or import a saved Sonar export.",+ );+ }+ const git = await inspectTrustedExecutable(+ "git",+ trusted.environment,+ protectedRoots,+ );+ return async (args) => {+ signal?.throwIfAborted();+ let stdout: string;+ try {+ ({ stdout } = await execFile(trusted.executable, args, {+ // Authentication and raw API calls use the signed-in connection independently of checkout configuration.+ cwd: dirname(trusted.executable),+ env: git.environment,+ signal,+ maxBuffer: Infinity,+ }));+ } catch (error) {+ signal?.throwIfAborted();+ // Sonar reports authentication failures on stdout in JSON mode.+ if (+ args[0] === "auth" &&+ isRecord(error) &&+ typeof error["stdout"] === "string" &&+ error["stdout"].trim()+ ) {+ throw new CodexSecurityError(+ `Sonar authentication check failed. ${error["stdout"].trim()}\n${errorMessage(error)}\nCheck 'sonar auth status' or run 'sonar auth login'.`,+ { cause: error },+ );+ }+ throw error;+ }+ return record(JSON.parse(stdout), `sonar ${args[0]} response`);+ };+}++async function checkoutOrigin(+ options: SonarCollectionOptions,+ protectedRoots: string[],+): Promise<string | undefined> {+ try {+ if (+ !(await boundSonarWorktree(+ options.cwd,+ protectedRoots,+ options.environment,+ options.signal,+ ))+ )+ return;+ const origin = await gitOutput(+ options.cwd,+ ["remote", "get-url", "--", "origin"],+ options.signal,+ undefined,+ undefined,+ "utf8",+ protectedRoots,+ options.environment,+ );+ return sonarRepositoryForRemote(origin);+ } catch {+ options.signal?.throwIfAborted();+ return undefined;+ }+}++const selectProjectHint =+ "Select the Sonar project with --sonar-project KEY. The checkout's Git origin must identify one project in the signed-in Sonar organization for automatic discovery.";++async function projectFromOrigin(+ sonar: SonarCommand,+ origin: string,+ organization: string,+ selected?: string,+ selectedId?: string,+): Promise<string | undefined> {+ const response = await sonar([+ "api",+ "get",+ `/dop-translation/project-bindings?${new URLSearchParams({ url: origin })}`,+ ]);+ const bindings = array(response["bindings"], "Sonar repository bindings");+ if (selectedId !== undefined) {+ return bindings.some(+ (item) => isRecord(item) && item["projectId"] === selectedId,+ )+ ? selected+ : undefined;+ }+ if (selected === undefined && bindings.length !== 1) return;+ for (const binding of bindings) {+ const id = requiredText(+ record(binding, "Sonar repository binding")["projectId"],+ "Sonar bound project ID",+ );+ if (id.includes(",")) continue;+ const result = await sonar([+ "api",+ "get",+ `/api/components/search_projects?${new URLSearchParams({ projectIds: id, organization })}`,+ ]);+ const components = array(result["components"], "Sonar bound projects");+ const component = components.length === 1 ? components[0] : undefined;+ if (+ !isRecord(component) ||+ (component["id"] !== undefined && component["id"] !== id) ||+ (component["organization"] !== undefined &&+ component["organization"] !== organization)+ )+ continue;+ const project = requiredText(component["key"], "Sonar bound project key");+ if (selected === undefined || selected === project) return project;+ }+ return undefined;+}++async function verifySelectedProject(+ sonar: SonarCommand,+ selected: string,+ organization: string,+) {+ const result = await sonar([+ "api",+ "get",+ `/api/components/show?${new URLSearchParams({ component: selected })}`,+ ]);+ const component = result["component"];+ if (+ !isRecord(component) ||+ component["key"] !== selected ||+ component["organization"] !== organization ||+ component["qualifier"] !== "TRK"+ )+ throw new CodexSecurityError(+ "Sonar could not verify the selected project in the signed-in organization. Check --sonar-project and 'sonar auth status'.",+ );+}++async function resolveProject(+ sonar: SonarCommand,+ organization: string,+ origin: string | undefined,+ selected: string | undefined,+ signal?: AbortSignal,+): Promise<{ project: string; repositoryUrl?: string }> {+ let selectedId: string | undefined;+ if (selected !== undefined) {+ // The handoff or user has already selected this project.+ const component = await sonar([+ "api",+ "get",+ `/api/navigation/component?${new URLSearchParams({ component: selected, organization })}`,+ ]).catch(() => {+ // Some token sessions cannot read browser navigation metadata.+ signal?.throwIfAborted();+ return undefined;+ });+ if (+ component &&+ ((component["key"] !== undefined && component["key"] !== selected) ||+ (component["organization"] !== undefined &&+ component["organization"] !== organization))+ ) {+ throw new CodexSecurityError(+ "Sonar returned a different project or organization. Check --sonar-project and the organization in 'sonar auth status'.",+ );+ }+ if (component?.["key"] === selected) {+ const alm = component["alm"];+ if (isRecord(alm) && alm["url"]) {+ await verifySelectedProject(sonar, selected, organization);+ return {+ project: selected,+ repositoryUrl: declaredScannerRepositoryUrl(+ alm["url"],+ "Sonar",+ "local",+ ),+ };+ }+ if (+ component["organization"] === organization &&+ typeof component["id"] === "string"+ )+ selectedId = component["id"];+ }+ }+ if (origin !== undefined) {+ try {+ const project = await projectFromOrigin(+ sonar,+ origin,+ organization,+ selected,+ selectedId,+ );+ if (project !== undefined) return { project, repositoryUrl: origin };+ } catch (error) {+ signal?.throwIfAborted();+ if (selected === undefined)+ throw new CodexSecurityError(+ `${selectProjectHint}\n${errorMessage(error)}`,+ { cause: error },+ );+ }+ }+ if (selected !== undefined) {+ await verifySelectedProject(sonar, selected, organization);+ return { project: selected };+ }+ throw new CodexSecurityError(selectProjectHint);+}++async function activeSonarConnection(sonar: SonarCommand) {+ const auth = await sonar(["auth", "status", "--format", "json"]);+ if (auth["status"] !== "connected")+ throw new CodexSecurityError(+ `Sonar CLI is not connected (${String(auth["status"])}). Run 'sonar auth login'.`,+ );+ const url = URL.parse(requiredText(auth["server"], "Sonar server"));+ const server = url?.origin;+ if (+ !server ||+ url?.href !== server + "/" ||+ !["https://sonarcloud.io", "https://sonarqube.us"].includes(server) ||+ !auth["org"]+ )+ throw new CodexSecurityError(+ "Connect the Sonar CLI to a SonarQube Cloud organization with 'sonar auth login'.",+ );+ const organization = requiredText(auth["org"], "Sonar organization");+ return { server, organization };+}++async function latestAnalysisBase(+ sonar: SonarCommand,+ project: string,+ branch: string,+ signal?: AbortSignal,+) {+ try {+ const metadata = await sonar([+ "api",+ "get",+ `/api/project_analyses/search?${new URLSearchParams({ project, branch, ps: "1" })}`,+ ]);+ const analysis = array(metadata["analyses"], "Sonar analyses")[0];+ if (+ !isRecord(analysis) ||+ typeof analysis["key"] !== "string" ||+ !analysis["key"].trim()+ )+ return;+ const base = analysis["relativePathFromScmRoot"];+ const path = base === "" || base === "." ? "" : relativePath(base);+ if (path !== null) return { key: analysis["key"], path };+ } catch {+ signal?.throwIfAborted();+ }+ return undefined;+}++function exactIssueBatches(+ server: string,+ query: URLSearchParams,+ keys: Set<string>,+): Set<string>[] {+ if (!keys.size) return [keys];+ // RFC 9110 §4.1 recommends support for URIs up to 8,000 octets. URLSearchParams+ // emits ASCII, including three bytes for each encoded comma between issue keys.+ const prefix = `${server}/api/issues/search?${query}&p=10000&issues=`.length;+ const batches: Set<string>[] = [];+ let batch = new Set<string>();+ let size = prefix;+ for (const key of keys) {+ const encoded =+ new URLSearchParams({ issues: key }).toString().length - "issues=".length;+ if (batch.size && size + 3 + encoded > 8_000) {+ batches.push(batch);+ batch = new Set();+ size = prefix;+ }+ size += encoded + (batch.size ? 3 : 0);+ batch.add(key);+ }+ batches.push(batch);+ return batches;+}++/** Fetch native SonarQube Cloud evidence through the developer's existing CLI session. */+export async function collectSonarIssues(+ options: SonarCollectionOptions,+ runSonar?: SonarCommand,+): Promise<SonarCapture> {+ const suppliedEnvironment = options.environment ?? process.env;+ requireExternalImports(suppliedEnvironment);+ const environment: NodeJS.ProcessEnv = Object.create(null);+ for (const name in suppliedEnvironment)+ environment[name] = suppliedEnvironment[name];+ forwardExternalImportSetting(suppliedEnvironment, environment);+ options = { ...options, cwd: resolve(options.cwd), environment };+ options.signal?.throwIfAborted();+ const { pullRequest } = options;+ let { branch } = options;+ if (branch !== undefined && pullRequest !== undefined)+ throw new CodexSecurityError(+ "Select either a Sonar branch or a pull request.",+ );+ for (const [label, value] of [+ ["branch", branch],+ ["pull request", pullRequest],+ ["project", options.project],+ ] as const) {+ if (value !== undefined) requiredText(value, `Sonar ${label}`);+ }+ const keys = new Set(options.issueKeys);+ if (options.issueKeys !== undefined && keys.size === 0)+ throw new CodexSecurityError("The Sonar issue selection is empty.");+ for (const key of keys) {+ if (!key.trim() || key.includes(","))+ throw new CodexSecurityError(+ "Provide individual, nonempty Sonar issue keys.",+ );+ }+ if (options.project?.includes(","))+ throw new CodexSecurityError("Select one Sonar project key.");+ const protectedRoots = [options.cwd];+ for (const root of new Set([options.cwd, process.cwd()])) {+ protectedRoots.push(+ ...(await localGitProtectionRoots(root, environment, options.signal)),+ );+ }+ const expected =+ options.sourceRepositoryUrl === undefined+ ? undefined+ : declaredScannerRepositoryUrl(+ options.sourceRepositoryUrl,+ "Sonar",+ "local",+ );+ const origin = await checkoutOrigin(options, protectedRoots);+ const checkExpectedRepository = (boundUrl: string | undefined) => {+ if (+ expected &&+ boundUrl &&+ repositoryUrlKey(expected) !== repositoryUrlKey(boundUrl)+ )+ throw new CodexSecurityError(+ "The selected Sonar repository does not match --source-repository-url.",+ );+ };+ if (options.project === undefined) checkExpectedRepository(origin);+ if (options.project === undefined && origin === undefined)+ throw new CodexSecurityError(selectProjectHint);+ const sonar = runSonar ?? (await sonarCommand(options, protectedRoots));+ const { server, organization } = await activeSonarConnection(sonar);+ const { project, repositoryUrl } = await resolveProject(+ sonar,+ organization,+ origin,+ options.project,+ options.signal,+ );+ checkExpectedRepository(repositoryUrl);+ if (project.includes(","))+ throw new CodexSecurityError("Select one Sonar project key.");+ if (branch === undefined && pullRequest === undefined) {+ const response = await sonar([+ "api",+ "get",+ `/api/project_branches/list?${new URLSearchParams({ project })}`,+ ]);+ const main = array(response["branches"], "Sonar branches").find(+ (item) => isRecord(item) && item["isMain"] === true,+ );+ if (+ !isRecord(main) ||+ typeof main["name"] !== "string" ||+ !main["name"].trim()+ )+ throw new CodexSecurityError(+ "Sonar did not return its main branch. Select the source branch with --sonar-branch.",+ );+ branch = main["name"];+ }+ let analysis;+ if (branch !== undefined && repositoryUrl !== undefined) {+ const matched =+ (origin &&+ repositoryUrlKey(origin) === repositoryUrlKey(repositoryUrl)) ||+ (await sonarCheckoutMatchesSource(+ options.cwd,+ repositoryUrl,+ protectedRoots,+ environment,+ options.signal,+ ).catch(() => {+ options.signal?.throwIfAborted();+ return false;+ }));+ if (matched)+ analysis = await latestAnalysisBase(+ sonar,+ project,+ branch,+ options.signal,+ );+ }+ const query = new URLSearchParams({+ organization,+ componentKeys: project,+ impactSoftwareQualities: "SECURITY",+ additionalFields: "rules",+ ps: "100",+ });+ if (branch !== undefined) query.set("branch", branch);+ if (pullRequest !== undefined) query.set("pullRequest", pullRequest);+ const pages: Record<string, unknown>[] = [];+ const queryPageCounts: number[] = [];+ const missing = new Set(keys);+ const scope = {+ organization,+ project,+ ...(branch === undefined ? {} : { branch }),+ ...(pullRequest === undefined ? {} : { pullRequest }),+ };+ for (const batch of exactIssueBatches(server, query, keys)) {+ if (batch.size) query.set("issues", [...batch].join(","));+ else query.set("issueStatuses", "OPEN,CONFIRMED");+ const queryPages: Record<string, unknown>[] = [];+ for (let index = 1; ; index++) {+ options.signal?.throwIfAborted();+ query.set("p", String(index));+ const page = await sonar(["api", "get", `/api/issues/search?${query}`]);+ const issues = array(page["issues"], "Sonar issues");+ const paging = record(page["paging"], "Sonar paging");+ const size = paging["pageSize"],+ total = paging["total"];+ if (+ paging["pageIndex"] !== index ||+ !isSafeNonNegativeInteger(size) ||+ size === 0 ||+ !isSafeNonNegativeInteger(total) ||+ (!issues.length && index * size < total)+ ) {+ throw new CodexSecurityError(+ `Incomplete pagination in Sonar issues page ${index}.`,+ );+ }+ queryPages.push(page);+ if (total > 10_000)+ throw new CodexSecurityError(+ "Sonar issue search returns at most 10,000 results. Narrow the selection with --sonar-issue KEY or select a different branch or pull request.",+ );+ if (index * size >= total) break;+ }++ for (const { issues } of completeSonarPages(queryPages)) {+ for (const issue of issues) {+ const key = requiredText(issue["key"], "Sonar issue key");+ if (issue["project"] !== project || (batch.size && !batch.has(key)))+ throw new CodexSecurityError(+ `Sonar returned issue ${key} outside the selected project or issue keys.`,+ );+ mergeSonarIssueScope(scope, issue);+ missing.delete(key);+ }+ }+ pages.push(...queryPages);+ queryPageCounts.push(queryPages.length);+ }+ if (missing.size)+ throw new CodexSecurityError(+ `Selected Sonar security issues were not returned for this project and ref: ${[...missing].join(", ")}.`,+ );+ // Keep native paths when a newer analysis may have changed their repository base during collection.+ const latest =+ analysis && branch !== undefined+ ? await latestAnalysisBase(sonar, project, branch, options.signal)+ : undefined;+ const projectBase =+ analysis && latest?.key === analysis.key && latest.path === analysis.path+ ? analysis.path+ : undefined;+ const active = await activeSonarConnection(sonar);+ if (active.server !== server || active.organization !== organization)+ throw new CodexSecurityError(+ "The active Sonar connection changed during collection. Select the intended connection and collect again.",+ );+ return {+ format: "sonar-issues/v1",+ server,+ organization,+ project,+ branch,+ pullRequest,+ repositoryUrl,+ projectBase,+ pages,+ ...(queryPageCounts.length > 1 ? { queryPageCounts } : {}),+ };+}diff --git a/sdk/typescript/src/sonar-findings.ts b/sdk/typescript/src/sonar-findings.tsnew file mode 100644index 000000000..4fd78679f--- /dev/null+++ b/sdk/typescript/src/sonar-findings.ts@@ -0,0 +1,432 @@+import { z } from "zod";+import {+ cloudRepositoryUrlKey,+ type ExternalImportTarget,+ repositoryUrlKey,+ validateExternalEvidence,+} from "./external-import-contract.js";+import type { ExternalFindings } from "./external-findings.js";+import type { Provider, Severity } from "./external-import-models.js";+import { isRecord } from "./record.js";+import {+ array,+ normalizeRecords,+ readScannerJson,+ record,+ relativePath,+ requiredText,+ text,+} from "./scanner-import.js";+import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";++const sonarFormat = "sonar-issues/v1";+const captureText = z.string().refine((value) => Boolean(value.trim()));+const captureSchema = z.object({+ format: z.literal(sonarFormat),+ server: captureText,+ organization: captureText,+ project: captureText,+ branch: captureText.optional(),+ pullRequest: captureText.optional(),+ repositoryUrl: captureText.optional(),+ projectBase: z+ .string()+ .refine((path) => path === "" || relativePath(path) === path)+ .optional(),+ pages: z.array(z.unknown()).min(1),+ queryPageCounts: z.array(z.int().positive()).min(1).optional(),+});+export type SonarCapture = z.infer<typeof captureSchema>;++export function parseSonarCapture(value: unknown): SonarCapture {+ const capture = captureSchema.parse(value);+ if (capture.branch && capture.pullRequest)+ throw new Error(+ "A Sonar capture must select a branch or a pull request, not both.",+ );+ const url = URL.parse(capture.server);+ if (+ !url ||+ !["https:", "http:"].includes(url.protocol) ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ )+ throw new Error(+ "Expected an HTTP(S) Sonar server URL without credentials, query or fragment.",+ );+ capture.server = url.href.replace(/\/$/u, "");+ if (capture.repositoryUrl)+ declaredScannerRepositoryUrl(capture.repositoryUrl, "Sonar", "local");+ return capture;+}++type NativeRecord = Record<string, unknown>;++const issueScopeFields = [+ "organization",+ "project",+ "branch",+ "pullRequest",+] as const;+const scopeFields = ["server", ...issueScopeFields] as const;+type SonarScope = Partial<Record<(typeof scopeFields)[number], string>>;++function mergeSonarScope(+ scope: SonarScope,+ data: NativeRecord,+ fields: readonly (keyof SonarScope)[] = scopeFields,+) {+ for (const field of fields) {+ const value = text(data[field]);+ if (value === null) continue;+ if (scope[field] !== undefined && scope[field] !== value)+ throw new Error(`The Sonar export contains conflicting ${field} values.`);+ scope[field] = value;+ }+ if (scope.branch && scope.pullRequest)+ throw new Error("The Sonar export mixes branch and pull request results.");+}++function requireConsistentSonarRef(+ scope: SonarScope,+ hasUnscopedIssue: boolean,+) {+ if (hasUnscopedIssue && (scope.branch || scope.pullRequest))+ throw new Error(+ "The Sonar export mixes issues with a named ref and issues without a ref.",+ );+}++/** Normalized Sonar reports and their individual issues retain the source repository. */+export function sonarRepositoryUrls(+ provider: Provider,+ findings: ExternalFindings["findings"],+ report: ExternalFindings["report"],+ target: ExternalImportTarget,+): Set<string> {+ const urls = new Set<string>();+ function add(data: NativeRecord | undefined, scope: SonarScope) {+ if (data?.["format"] !== sonarFormat) return;+ if (provider !== "sonar")+ throw new Error("Retained Sonar evidence requires the sonar provider.");+ mergeSonarScope(scope, data);+ urls.add(+ declaredScannerRepositoryUrl(data["repositoryUrl"], "Sonar", target),+ );+ }+ const reportScope: SonarScope = {};+ add(report, reportScope);+ const scope = { ...reportScope };+ let hasUnscopedIssue = false;+ for (const { evidence, source_finding_id } of findings) {+ const data = evidence.source_data;+ const rowScope = { ...reportScope };+ add(data ?? undefined, rowScope);+ if (data?.["format"] === sonarFormat && data["issue"] !== undefined) {+ const issue = record(data["issue"], "Retained Sonar issue");+ mergeSonarScope(rowScope, issue, issueScopeFields);+ if (+ requiredText(issue["key"], "Retained Sonar issue key") !==+ source_finding_id+ )+ throw new Error(+ "The normalized finding ID does not match the retained Sonar issue key.",+ );+ }+ mergeSonarScope(scope, rowScope);+ if (!rowScope.branch && !rowScope.pullRequest) hasUnscopedIssue = true;+ }+ requireConsistentSonarRef(scope, hasUnscopedIssue);+ if (+ scope.branch &&+ findings.some(+ ({ evidence }) =>+ (report?.["format"] === sonarFormat ||+ evidence.source_data?.["format"] === sonarFormat) &&+ evidence.branch != null &&+ evidence.branch !== scope.branch,+ )+ )+ throw new Error(+ "The finding branch does not match the retained Sonar branch.",+ );+ return urls;+}++const pagingSchema = z.object({+ pageIndex: z.int().positive(),+ pageSize: z.int().positive(),+ total: z.int().nonnegative(),+});++function indexByKey(value: unknown, label: string) {+ const index = new Map<string, NativeRecord>();+ for (const item of array(value ?? [], label)) {+ const row = record(item, label);+ const key = requiredText(row["key"], `${label} key`);+ index.set(key, row);+ }+ return index;+}++export function mergeSonarIssueScope(scope: SonarScope, issue: NativeRecord) {+ mergeSonarScope(scope, issue, issueScopeFields);+}++function readPage(value: unknown) {+ const page = record(value, "Sonar issue search page");+ return {+ paging: pagingSchema.parse(page["paging"]),+ issues: array(page["issues"], "Sonar issues").map((issue) =>+ record(issue, "Sonar issue"),+ ),+ components: indexByKey(page["components"], "Sonar component"),+ rules: indexByKey(page["rules"], "Sonar rule"),+ };+}++function completeQueryPages(values: unknown[]) {+ const pages = values+ .map(readPage)+ .sort((a, b) => a.paging.pageIndex - b.paging.pageIndex);+ const first = pages[0]?.paging;+ if (+ !first ||+ pages.length !== Math.max(1, Math.ceil(first.total / first.pageSize)) ||+ pages.some(+ ({ paging, issues }, i) =>+ paging.pageIndex !== i + 1 ||+ paging.total !== first.total ||+ paging.pageSize !== first.pageSize ||+ issues.length !==+ Math.min(first.pageSize, first.total - i * first.pageSize),+ )+ )+ throw new Error(+ "Supply every Sonar issue search page exactly once, with consistent paging and issue counts.",+ );+ return pages;+}++export function completeSonarPages(+ values: unknown[],+ queryPageCounts?: number[],+) {+ const counts = queryPageCounts ?? [values.length];+ if (counts.reduce((sum, count) => sum + count, 0) !== values.length)+ throw new Error("Sonar query page counts do not match the captured pages.");+ let offset = 0;+ const pages = counts.flatMap((count) => {+ const query = values.slice(offset, offset + count);+ offset += count;+ return completeQueryPages(query);+ });+ const ids = new Set<string>();+ for (const { issues } of pages) {+ for (const issue of issues) {+ const id = text(issue["key"]);+ if (id && ids.has(id))+ throw new Error(+ "Sonar issue search pages overlap. Collect the selection again.",+ );+ if (id) ids.add(id);+ }+ }+ return pages;+}++const severityLevels: Readonly<Record<string, Severity>> = {+ BLOCKER: "critical",+ HIGH: "high",+ MEDIUM: "medium",+ LOW: "low",+ INFO: "informational",+ CRITICAL: "high",+ MAJOR: "medium",+ MINOR: "low",+};++function securitySeverity(issue: NativeRecord): Severity {+ const impacts = array(issue["impacts"] ?? [], "Sonar issue impacts");+ const security = impacts.find(+ (impact) => isRecord(impact) && impact["softwareQuality"] === "SECURITY",+ );+ if (+ !isRecord(security) &&+ (impacts.length || issue["type"] !== "VULNERABILITY")+ )+ throw new Error(+ "Sonar issue has no security impact or legacy vulnerability type.",+ );+ const value = isRecord(security) ? security["severity"] : issue["severity"];+ return typeof value === "string" && Object.hasOwn(severityLevels, value)+ ? severityLevels[value]!+ : "unknown";+}++function relatedComponents(+ issue: NativeRecord,+ primary: string,+ components: Map<string, NativeRecord>,+) {+ const keys = new Set([primary]);+ for (const value of array(issue["flows"] ?? [], "Sonar issue flows")) {+ const flow = record(value, "Sonar flow");+ for (const entry of array(flow["locations"], "Sonar flow locations")) {+ const location = record(entry, "Sonar flow location");+ const key = text(location["component"]);+ if (key) keys.add(key);+ }+ }+ return Array.from(keys).flatMap((key) => components.get(key) ?? []);+}++function issueLink(+ server: string,+ project: string,+ id: string,+ branch?: string,+ pullRequest?: string,+) {+ const link = new URL("project/issues", server + "/");+ link.searchParams.set("id", project);+ if (branch) link.searchParams.set("branch", branch);+ if (pullRequest) link.searchParams.set("pullRequest", pullRequest);+ link.searchParams.set("open", id);+ link.searchParams.set("issues", id);+ return link.href;+}++export function normalizeSonarFindings(+ input: unknown,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+) {+ const capture =+ isRecord(input) && "format" in input ? parseSonarCapture(input) : undefined;+ const repository = declaredScannerRepositoryUrl(+ capture?.repositoryUrl ?? sourceRepositoryUrl,+ "Sonar",+ target,+ );+ if (capture?.repositoryUrl && sourceRepositoryUrl) {+ const key = target === "cloud" ? cloudRepositoryUrlKey : repositoryUrlKey;+ if (+ key(repository) !==+ key(declaredScannerRepositoryUrl(sourceRepositoryUrl, "Sonar", target))+ )+ throw new Error(+ "The Sonar capture repository does not match the declared source repository.",+ );+ }+ const pages = completeSonarPages(+ capture?.pages ?? (Array.isArray(input) ? input : [input]),+ capture?.queryPageCounts,+ );+ const rows = pages.flatMap((page) =>+ page.issues.map((issue) => ({ issue, page })),+ );+ const scope: SonarScope = {};+ if (capture) mergeSonarScope(scope, capture);+ const hasUnscopedIssue = rows.some(+ ({ issue }) => !text(issue["branch"]) && !text(issue["pullRequest"]),+ );+ for (const { issue } of rows) {+ requiredText(issue["project"], "Sonar issue project");+ mergeSonarIssueScope(scope, issue);+ }+ requireConsistentSonarRef(+ scope,+ !capture?.branch && !capture?.pullRequest && hasUnscopedIssue,+ );+ const context = {+ format: sonarFormat,+ ...(capture?.projectBase !== undefined && {+ projectBase: capture.projectBase,+ }),+ ...scope,+ repositoryUrl: repository,+ };+ const result = normalizeRecords(+ rows,+ ({ issue, page }, id) => {+ const component = requiredText(+ issue["component"],+ "Sonar issue component",+ );+ const componentPath = relativePath(+ page.components.get(component)?.["path"],+ );+ const base = capture?.projectBase;+ const path =+ componentPath && base !== undefined+ ? base+ ? `${base}/${componentPath}`+ : componentPath+ : null;+ const range =+ issue["textRange"] == null+ ? null+ : record(issue["textRange"], "Sonar issue textRange");+ const line = range?.["startLine"] ?? issue["line"] ?? null;+ const rule = requiredText(issue["rule"], "Sonar issue rule");+ const descriptor = page.rules.get(rule);+ const name = text(descriptor?.["name"]);+ const updated = text(issue["updateDate"]);+ const severity = securitySeverity(issue);+ return validateExternalEvidence(+ {+ title: name ?? rule,+ severity,+ description: text(issue["message"]),+ url: capture+ ? issueLink(+ capture.server,+ capture.project,+ id,+ scope.branch,+ scope.pullRequest,+ )+ : null,+ locations: path ? [{ path, line }] : [],+ branch: scope.branch ?? null,+ source_updated_at: updated+ ? Math.floor(Date.parse(updated) / 1000)+ : null,+ details: {+ kind: "sast",+ scanner_origin: "SonarQube",+ repository: { url: repository },+ source_status: text(issue["issueStatus"]) ?? text(issue["status"]),+ rule: { id: rule, name },+ code: { end_line: path ? (range?.["endLine"] ?? null) : null },+ },+ source_data: structuredClone({+ ...context,+ issue,+ components: relatedComponents(issue, component, page.components),+ ...(descriptor && { rule: descriptor }),+ }),+ },+ target,+ );+ },+ ({ issue }) => requiredText(issue["key"], "Sonar issue key"),+ target,+ );+ return { ...result, report: context };+}++export async function readSonarFindings(+ path: string,+ sourceRepositoryUrl: string,+ target: ExternalImportTarget = "cloud",+): Promise<ExternalFindings> {+ return normalizeSonarFindings(+ await readScannerJson(path),+ sourceRepositoryUrl,+ target,+ );+}diff --git a/sdk/typescript/src/sonar-import.ts b/sdk/typescript/src/sonar-import.tsnew file mode 100644index 000000000..7daa8f728--- /dev/null+++ b/sdk/typescript/src/sonar-import.ts@@ -0,0 +1,409 @@+import { hash } from "node:crypto";+import { lstat, open, readlink, realpath, stat } from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import { resolveConfigPath } from "./config-path.js";+import { collectSonarIssues } from "./sonar-collector.js";+import { normalizeSonarFindings, parseSonarCapture } from "./sonar-findings.js";+import { requireExternalImports } from "./external-imports-feature.js";+import {+ configuredFetchRemotes,+ type ConfiguredFetchRemote,+ localGitProtectionRoots,+ prepareLocalImport,+} from "./external-findings-local.js";+import {+ ExternalPublicationError,+ externalPublicationStateDirectory,+ prepareNormalizedExternalPublication,+ writeAtomicJson,+ type ExternalPublicationDependencies,+ type ExternalPublicationPreview,+ type PreparedExternalPublication,+} from "./external-findings-publish.js";+import { readScannerJson, stableId } from "./scanner-import.js";+import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";+import {+ canonicalConfigPath,+ codexSecurityStateDirectory,+ preparePersistentOutputRoot,+ requirePrivateDirectory,+ requireSecureOutputAncestry,+ requireOutputOutsideRepositories,+ workbenchEnvironment,+} from "./runtime.js";+import { gitMarkerRoot, normalizeRepository } from "./targets.js";+import { errorMessage } from "./errors.js";+import { canonicalJson } from "./record.js";+import {+ repositoryUrlKey,+ validateExternalReport,+} from "./external-import-contract.js";+import { notify } from "./value.js";++interface SonarImportOptions {+ cwd: string;+ capture?: string | undefined;+ project?: string | undefined;+ branch?: string | undefined;+ pullRequest?: string | undefined;+ issueKeys: string[];+ sourceRepositoryUrl?: string | undefined;+ to: "local" | "cloud";+ dryRun: boolean;+ yes: boolean;+}++function cloudReviewDigest(+ preview: ExternalPublicationPreview,+ checkout: string,+) {+ return hash(+ "sha256",+ canonicalJson({+ checkout,+ api: preview.cloudApiUrl,+ account: preview.accountId,+ repository: preview.destination.id,+ connector: preview.destination.repo_connector_id,+ url: preview.destination.url,+ reset: preview.destination.reset_marker,+ source: preview.source,+ items: preview.requests.flatMap((request) =>+ request.items.map((item) => [+ item.source_finding_id,+ item.expected_version,+ request.repository.environment_id,+ item.evidence,+ ]),+ ),+ }),+ );+}++async function readCapture(input: string) {+ if (!(await stat(input)).isFile())+ return { path: input, raw: await readScannerJson(input) };+ if (process.platform === "linux") {+ const file = await open(input, "r");+ try {+ // Use the same open file for its bytes and its retained evidence name.+ // An unlinked descriptor is still readable, even if its name is reused.+ const name = await readlink(`/proc/self/fd/${file.fd}`).catch(+ async (error: unknown) => {+ const opened = await file.stat({ bigint: true });+ if (opened.nlink === 0n)+ throw new Error(+ `Could not verify the unlinked Sonar capture's name: ${errorMessage(error)}. Select a named JSON file and retry.`,+ { cause: error },+ );+ const path = await realpath(input);+ const named = await stat(path, { bigint: true });+ if (named.ino !== opened.ino || named.dev !== opened.dev)+ throw new Error(+ "The selected Sonar capture changed while being opened. Preview it again.",+ { cause: error },+ );+ return path;+ },+ );+ let path = name;+ const deletedSuffix = " (deleted)";+ if (name.endsWith(deletedSuffix)) {+ // The suffix can also be literal. Only ascribe the former name to+ // this descriptor when the displayed name does not identify it.+ const opened = await file.stat({ bigint: true });+ const named =+ opened.nlink > 0n+ ? await stat(name, { bigint: true }).catch(() => undefined)+ : undefined;+ if (named?.ino !== opened.ino || named.dev !== opened.dev)+ path = name.slice(0, -deletedSuffix.length);+ }+ return { path, raw: await readScannerJson(file) };+ } finally {+ await file.close();+ }+ }+ const path = await realpath(input);+ return { path, raw: await readScannerJson(path) };+}++export async function prepareSonarImport(+ options: SonarImportOptions,+ dependencies: ExternalPublicationDependencies & {+ collect?: typeof collectSonarIssues;+ onCapture?: (path: string) => void;+ },+) {+ const { signal, environment = process.env } = dependencies;+ requireExternalImports(environment);+ signal?.throwIfAborted();+ if (+ options.capture &&+ (options.project ||+ options.branch ||+ options.pullRequest ||+ options.issueKeys.length)+ )+ throw new Error(+ "A saved capture already identifies the selected Sonar project, ref and issues. Omit the live selection options.",+ );+ const repository =+ (await gitMarkerRoot(options.cwd, signal, "nearest")) ??+ (await normalizeRepository(options.cwd, signal));+ const selectedPath =+ options.capture && resolveConfigPath(options.cwd, options.capture);+ // Resolve directory aliases while keeping the evidence and approval digests+ // in the filename selected by the caller.+ const input =+ selectedPath &&+ join(await realpath(dirname(selectedPath)), basename(selectedPath));+ const captureData = input ? await readCapture(input) : undefined;+ const raw = captureData+ ? captureData.raw+ : await (dependencies.collect ?? collectSonarIssues)({+ cwd: options.cwd,+ project: options.project,+ sourceRepositoryUrl: options.sourceRepositoryUrl,+ branch: options.branch,+ pullRequest: options.pullRequest,+ issueKeys: options.issueKeys.length ? options.issueKeys : undefined,+ environment,+ signal,+ });+ let report = parseSonarCapture(raw);+ validateExternalReport(report);+ const configuredState = codexSecurityStateDirectory(environment);+ const protectedRoots = [+ repository,+ ...(await localGitProtectionRoots(options.cwd, environment, signal)),+ ...(await localGitProtectionRoots(process.cwd(), environment, signal)),+ ];+ requireOutputOutsideRepositories(protectedRoots, configuredState, "runtime");+ const state = await canonicalConfigPath(configuredState);+ const destination = await canonicalConfigPath(+ join(state, "imports", "sonar"),+ );+ requireOutputOutsideRepositories(protectedRoots, state, "runtime");+ requireOutputOutsideRepositories(protectedRoots, destination, "runtime");+ await requireSecureOutputAncestry(destination);+ const root = await preparePersistentOutputRoot(state, "imports", "sonar");+ await requirePrivateDirectory(+ await lstat(root),+ root,+ "Sonar capture directory",+ );+ const retainedName = (path: string | undefined) =>+ path && dirname(path) === root+ ? /^([a-f0-9]{64})(?:\.([a-f0-9]{64})(?:\.([a-f0-9]{64}))?)?\.json$/u.exec(+ basename(path),+ )+ : undefined;+ const retained = retainedName(input);+ const target = retainedName(captureData?.path);+ if (retained || target) {+ const digest = hash("sha256", JSON.stringify(raw));+ if (+ (retained && retained[1] !== digest) ||+ (target && target[1] !== digest)+ )+ throw new Error(+ "The saved Sonar capture has changed. Preview a fresh copy of the Sonar evidence.",+ );+ }+ if (!report.repositoryUrl && options.sourceRepositoryUrl) {+ report = parseSonarCapture({+ ...report,+ repositoryUrl: declaredScannerRepositoryUrl(+ options.sourceRepositoryUrl,+ "Sonar",+ "local",+ ),+ });+ }+ const evidenceDigest = hash("sha256", JSON.stringify(report));+ async function recoverLiveSelection(error: unknown): Promise<never> {+ if (!input) {+ // Keep the collected bytes replayable without marking them reviewed.+ const recovery = join(root, `${evidenceDigest}.json`);+ try {+ await writeAtomicJson(recovery, report);+ } catch (recoveryError) {+ throw new Error(+ `${errorMessage(error)}. Could not save the Sonar capture: ${errorMessage(recoveryError)}`,+ { cause: error },+ );+ }+ notify(() => dependencies.onCapture?.(recovery));+ }+ throw error;+ }+ let checkout = hash("sha256", repository);+ let sourceRepositoryUrl = options.sourceRepositoryUrl;+ let fetchRemotes: ConfiguredFetchRemote[] | undefined;+ // A portable report can name a repository. Only a reviewed capture can+ // restore the operator's mapping to this checkout's effective fetch URLs.+ const mappedUrl =+ sourceRepositoryUrl ??+ (retained?.[1] === evidenceDigest && retained[2] && retained[2] !== checkout+ ? report.repositoryUrl+ : undefined);+ if (mappedUrl) {+ fetchRemotes = await configuredFetchRemotes(+ repository,+ "sonar",+ protectedRoots,+ workbenchEnvironment(environment),+ signal,+ ).catch(recoverLiveSelection);+ const mapped = hash(+ "sha256",+ canonicalJson([repository, repositoryUrlKey(mappedUrl), fetchRemotes]),+ );+ if (sourceRepositoryUrl || mapped === retained?.[2]) {+ sourceRepositoryUrl = mappedUrl;+ checkout = mapped;+ }+ }+ const localCapture = join(root, `${evidenceDigest}.${checkout}.json`);+ if (+ options.to === "local" &&+ options.yes &&+ !options.dryRun &&+ input &&+ (retained?.[1] !== evidenceDigest || retained[2] !== checkout)+ ) {+ throw new Error(+ "This Sonar capture has not been reviewed for this checkout. Run import sonar with this capture and --dry-run here, then confirm the returned capture.",+ );+ }+ let capture =+ options.to === "cloud" &&+ input &&+ retained?.[1] === evidenceDigest &&+ retained?.[2] === checkout+ ? input+ : localCapture;+ if (capture !== input)+ await writeAtomicJson(capture, report).catch(recoverLiveSelection);+ try {+ const repositoryUrl = report.repositoryUrl ?? options.sourceRepositoryUrl;+ if (!repositoryUrl) {+ throw new Error(+ "Sonar did not supply a repository binding. Verify the project's repository and rerun with the saved capture and --source-repository-url.",+ );+ }+ const findings = normalizeSonarFindings(+ report,+ options.sourceRepositoryUrl ?? "",+ "local",+ );+ const { branch, pullRequest } = findings.report;+ const sourceKey = stableId("sonar", [+ report.server,+ report.organization,+ report.project,+ branch ?? null,+ pullRequest ?? null,+ ]);+ const source = { provider: "sonar", sourceKey } as const;+ const local = await prepareLocalImport(+ findings,+ { repository, ...source, sourceRepositoryUrl },+ { environment, signal },+ [{ url: repositoryUrl }],+ [],+ fetchRemotes,+ );+ let cloud: PreparedExternalPublication | undefined;+ let cloudError: string | undefined;+ if (options.to === "cloud" && local.preview.read > 0) {+ const reviewedCheckout =+ retained?.[2] === checkout && Boolean(retained?.[3]);+ const reviewError =+ "Cloud publication requires the reviewed capture for this checkout, account, repository and environment. Run import sonar with this capture and --to cloud --dry-run, then pass the returned capture path with --to cloud --yes.";+ if (options.yes && !options.dryRun && !reviewedCheckout)+ throw new Error(reviewError);+ try {+ requireOutputOutsideRepositories(+ protectedRoots,+ await canonicalConfigPath(+ externalPublicationStateDirectory(environment),+ ),+ "runtime",+ );+ const confirmedRepository =+ local.matchesRepositoryRemote || sourceRepositoryUrl;+ const bindingError =+ "This checkout has no matching Git remote. Verify the Sonar project's repository and pass --source-repository-url to preview Cloud publication.";+ if (!confirmedRepository && !reviewedCheckout)+ throw new Error(bindingError);+ const prepared = await prepareNormalizedExternalPublication(+ normalizeSonarFindings(+ report,+ options.sourceRepositoryUrl ?? "",+ "cloud",+ ),+ { repository: repositoryUrl, ...source },+ dependencies,+ );+ const review = cloudReviewDigest(prepared.preview, repository);+ const reviewedCapture = join(+ root,+ `${evidenceDigest}.${checkout}.${review}.json`,+ );+ if (input !== reviewedCapture) {+ if (!confirmedRepository) throw new Error(bindingError);+ if (options.yes && !options.dryRun) throw new Error(reviewError);+ await writeAtomicJson(reviewedCapture, report);+ }+ capture = reviewedCapture;+ cloud = prepared;+ } catch (error) {+ signal?.throwIfAborted();+ cloudError = errorMessage(error);+ }+ }+ const info = {+ capture,+ repository,+ repositoryUrl,+ sourceKey,+ server: report.server,+ organization: report.organization,+ project: report.project,+ branch,+ pullRequest,+ };+ return {+ info,+ local: local.preview,+ cloud: cloud?.preview,+ cloudError,+ async import() {+ signal?.throwIfAborted();+ const { counts, ready, excluded } = await local.import();+ const saved = { ...info, local: { counts, ready, excluded } };+ if (!cloud) return { ...saved, cloudError, cloud: undefined };+ try {+ return {+ ...saved,+ cloud: await cloud.publish(),+ cloudError: undefined,+ };+ } catch (error) {+ return {+ ...saved,+ cloudError: errorMessage(error),+ cloud:+ error instanceof ExternalPublicationError+ ? error.result+ : undefined,+ };+ }+ },+ };+ } finally {+ notify(() => dependencies.onCapture?.(capture));+ }+}diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.tsindex 57999f7a1..6fa5ab513 100644--- a/sdk/typescript/src/targets.ts+++ b/sdk/typescript/src/targets.ts@@ -161,12 +161,19 @@ function requirePortableWindowsRepositoryPath(path: string): void {}}+type ReadWorktreeGit = (+ repository: string,+ args: readonly string[],+ signal?: AbortSignal,+) => Promise<string>;+export async function enclosingGitWorktreeRoot(repository: string,signal?: AbortSignal,- options: { requireIfPresent?: boolean } = {},+ options: { requireIfPresent?: boolean; readGit?: ReadWorktreeGit } = {},): Promise<string | null> {const strict = options.requireIfPresent === true;+ const readGit = options.readGit ?? gitOutput;const markerRoot = strict? await gitMarkerRoot(repository, signal, "nearest"): null;@@ -174,7 +181,7 @@ export async function enclosingGitWorktreeRoot(try {if (strict) {if (- (await gitOutput(+ (await readGit(repository,["rev-parse", "--is-inside-git-dir"],signal,@@ -186,7 +193,7 @@ export async function enclosingGitWorktreeRoot(}if (markerRoot === null) return null;}- const root = await gitOutput(+ const root = await readGit(repository,["rev-parse", "--show-toplevel"],signal,@@ -215,7 +222,7 @@ export async function enclosingGitWorktreeRoot();}if (markerRoot !== null)- await requireGitWorktreeBinding(canonicalRoot, signal);+ await requireGitWorktreeBinding(canonicalRoot, signal, readGit);return canonicalRoot;}@@ -321,11 +328,12 @@ export async function isGitMetadataDirectory(export async function gitMetadataDirectories(repository: string,signal?: AbortSignal,- options: { includeLocalObjects?: boolean } = {},+ options: { includeLocalObjects?: boolean; readGit?: ReadWorktreeGit } = {},): Promise<[string, string, ...string[]]> {+ const readGit = options.readGit ?? gitOutput;const [directory, commonDirectory] = await Promise.all([- gitOutput(repository, ["rev-parse", "--absolute-git-dir"], signal),- gitOutput(repository, ["rev-parse", "--git-common-dir"], signal),+ readGit(repository, ["rev-parse", "--absolute-git-dir"], signal),+ readGit(repository, ["rev-parse", "--git-common-dir"], signal),]);const roots = await Promise.all([abortable(() => realpath(resolve(repository, directory)), signal),@@ -434,13 +442,15 @@ export async function gitObjectDirectories(async function requireGitWorktreeBinding(repository: string,- signal?: AbortSignal,+ signal: AbortSignal | undefined,+ readGit: ReadWorktreeGit,): Promise<void> {let cause: unknown;try {const [directory, commonDirectory] = await gitMetadataDirectories(repository,signal,+ { readGit },);if ([directory, commonDirectory].every(@@ -451,11 +461,7 @@ async function requireGitWorktreeBinding(if (relative(directory, commonDirectory) === "") {// The toplevel check already verified the configured worktree path.if (- await gitOutput(- repository,- ["config", "--get", "core.worktree"],- signal,- )+ await readGit(repository, ["config", "--get", "core.worktree"], signal))return;} else {@@ -790,7 +796,8 @@ export async function gitOutput(args[0] === "ls-files" ||(args[0] === "remote" &&(args.length === 1 ||- (args[1] === "get-url" && args[2] === "--all"))),+ (args[1] === "get-url" &&+ (args[2] === "--all" || args[2] === "--")))),sourceEnvironment,),[@@ -813,9 +820,14 @@ export async function gitOutput(maxBuffer: Infinity,},);- return typeof stdout === "string"- ? stdout.replace(process.platform === "win32" ? /\r?\n$/u : /\n$/u, "")- : stdout;+ if (typeof stdout !== "string") return stdout;+ // Git writes remote URLs to binary stdout even on Windows. Only the final LF+ // is a delimiter; a preceding CR belongs to the configured URL.+ const remoteUrl = args[0] === "remote" && args[1] === "get-url";+ return stdout.replace(+ process.platform === "win32" && !remoteUrl ? /\r?\n$/u : /\n$/u,+ "",+ );}export async function gitMarkerRoot(diff --git a/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts b/sdk/typescript/tests-ts/cli-external-imports-feature.test.tsindex d89de04ef..12d2f0651 100644--- a/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts+++ b/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts@@ -1,4 +1,5 @@import { spawnSync } from "node:child_process";+import { Writable } from "node:stream";import { fileURLToPath } from "node:url";import { expect, mock, test } from "bun:test";import { main } from "../src/cli.js";@@ -7,7 +8,7 @@ import {removeTemporaryDirectory,temporaryDirectory,} from "./support/temporary-directories.js";-import { dependencies } from "./cli-fixtures.js";+import { capture, dependencies } from "./cli-fixtures.js";import { createCliTest } from "./support/cli-run.js";import { importedAlert } from "./support/github-import-fixtures.js";import { runTestInSubprocess } from "./support/test-subprocess.js";@@ -16,6 +17,7 @@ const commands = [["publish", "findings"],["findings", "imported"],["import", "github-advisories"],+ ["import", "sonar"],];const publishLocal = [@@ -101,6 +103,7 @@ test("disabled commands cannot invoke import, storage, or publication handlers",],["findings", "imported", "."],["import", "github-advisories", "example/project"],+ ["import", "sonar"],]) {const cli = createCliTest(main);expect(await cli.runCli(command, deps)).not.toBe(0);@@ -161,7 +164,9 @@ test("disabled commands cannot invoke import, storage, or publication handlers",),).toBe(2);expect(unsupported.stdout.text()).toContain("INVALID_ARGUMENTS");- } else if (command[1] === "github-advisories") {+ } else if (command[0] === "import") {+ const errorCode =+ command[1] === "sonar" ? "SONAR_IMPORT_FAILED" : "GITHUB_IMPORT_FAILED";for (const format of [undefined, "json", "jsonl", "yaml", "md", "toon"]) {const formatted = createCliTest(main);expect(@@ -177,10 +182,10 @@ test("disabled commands cannot invoke import, storage, or publication handlers",if (format === "json" || format === "jsonl") {expect(JSON.parse(formatted.stdout.text())).toMatchObject({ok: false,- error: { code: "GITHUB_IMPORT_FAILED" },+ error: { code: errorCode },});} else {- expect(formatted.stdout.text()).toContain("GITHUB_IMPORT_FAILED");+ expect(formatted.stdout.text()).toContain(errorCode);}expect(formatted.stdout.text()).toContain("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",@@ -191,6 +196,48 @@ test("disabled commands cannot invoke import, storage, or publication handlers",expect(unexpected).not.toHaveBeenCalled();});+test("a closed diagnostic pipe preserves the Sonar error envelope", async () => {+ const stdout = capture();+ const stderr = new Writable({+ write(_chunk, _encoding, done) {+ setImmediate(() =>+ done(Object.assign(new Error("closed"), { code: "EPIPE" })),+ );+ },+ });+ const closed = new Promise<void>((resolve) => stderr.once("close", resolve));+ const code = await main(+ ["import", "sonar", "--full-output", "--format=json"],+ stdout.stream,+ stderr,+ dependencies({ environment: {} }),+ );+ await closed;+ expect(code).toBe(2);+ expect(JSON.parse(stdout.text()).error.code).toBe("SONAR_IMPORT_FAILED");+});++test("rejects unsupported Sonar full-output formats before collecting findings", async () => {+ const collectSonarIssues = mock(async (): Promise<never> => {+ throw new Error("Unexpected collection");+ });+ const cli = createCliTest(main);+ const deps = {+ ...dependencies({+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },+ }),+ collectSonarIssues,+ };+ expect(+ await cli.runCli(+ ["import", "sonar", "--yes", "--full-output", "--format", "yaml"],+ deps,+ ),+ ).toBe(2);+ expect(cli.stdout.text()).toContain("INVALID_ARGUMENTS");+ expect(collectSonarIssues).not.toHaveBeenCalled();+});+const installedSkills ="installed skills preserve import errors and collector output";test(installedSkills, async () => {diff --git a/sdk/typescript/tests-ts/external-findings-local-helpers.ts b/sdk/typescript/tests-ts/external-findings-local-helpers.tsindex d81b20741..34aaf2c94 100644--- a/sdk/typescript/tests-ts/external-findings-local-helpers.ts+++ b/sdk/typescript/tests-ts/external-findings-local-helpers.ts@@ -9,6 +9,7 @@ import { execFileSync } from "node:child_process";import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";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 } = {}) {@@ -16,17 +17,15 @@ export async function localFindingsFixture(options: { remote?: string } = {}) {join(await realpath(tmpdir()), "codex-security-external-local-"),);const repository = join(root, "repository");+ const env = sonarGitTestEnvironment();await mkdir(repository);- execFileSync("git", ["init", "--quiet", repository]);+ execFileSync("git", ["init", "--quiet", repository], { env });if (options.remote !== undefined)- execFileSync("git", [- "-C",- repository,- "remote",- "add",- "origin",- options.remote,- ]);+ execFileSync(+ "git",+ ["-C", repository, "remote", "add", "origin", options.remote],+ { env },+ );const stateDirectory = join(root, "state");const dispose = () => rm(root, { recursive: true, force: true });return {@@ -35,7 +34,7 @@ export async function localFindingsFixture(options: { remote?: string } = {}) {stateDirectory,environment: {...Object.fromEntries(- Object.entries(process.env).filter(+ Object.entries(env).filter(([name]) =>name.toUpperCase() !== "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS",),diff --git a/sdk/typescript/tests-ts/external-findings-local.test.ts b/sdk/typescript/tests-ts/external-findings-local.test.tsindex 6cf86f9c7..c3515b9b6 100644--- a/sdk/typescript/tests-ts/external-findings-local.test.ts+++ b/sdk/typescript/tests-ts/external-findings-local.test.ts@@ -1597,6 +1597,289 @@ describe("local normalized scanner findings", () => {},);+ test.each(["\nhttps://github.com/other/repo", "\r"])(+ "a line break in the primary Git URL cannot establish a repository match: %j",+ async (suffix) => {+ const url = "https://github.com/example/project";+ const { repository, environment } = await fixture({+ remote: url + suffix,+ });+ await expect(+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar" },+ {+ environment,+ sourceRepositories: [{ url }],+ },+ ),+ ).rejects.toThrow("remote URL contains a line break");+ },+ );++ test.each([+ ["git@github-work:team/project.git", "https://github.com/team/project"],+ [+ "[email protected]:team/project.git",+ "https://github.com/team/project",+ ],+ [+ "ssh://git@github-work/team/project.git",+ "https://github.com/team/project",+ ],+ ])(+ "allows a manual Sonar mapping for %s alongside an HTTPS fork",+ async (upstream, url) => {+ const { repository, environment } = await fixture({+ remote: "https://fork.example.invalid/team/project.git",+ });+ execFileSync(+ "git",+ ["-C", repository, "remote", "add", "upstream", upstream],+ { env: environment },+ );+ const prepare = (sourceUrl: string, sourceRepositoryUrl?: string) =>+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar", sourceRepositoryUrl },+ { environment, sourceRepositories: [{ url: sourceUrl }] },+ );+ await expect(prepare(url)).rejects.toThrow(+ "does not match a configured remote",+ );+ await expect(prepare(url, url + "-other")).rejects.toThrow(+ "does not match the declared source repository",+ );+ expect((await prepare(url, url)).matchesRepositoryRemote).toBe(false);+ await expect(prepare(url + "-other", url + "-other")).rejects.toThrow(+ "does not match a configured remote",+ );+ },+ );++ test.each([+ ["[email protected].:team/project.git", "https://gitlab.com/team/project"],+ ["[email protected].:team/project.git", "https://gitlab.com./team/project"],+ ["git@work:team/project.git", "https://gitlab.com./team/project"],+ [+ "ssh://[email protected].:443/team/project.git",+ "https://github.com/team/project",+ ],+ [+ "[email protected].:v3/team/project/repo",+ "https://dev.azure.com/team/project/_git/repo",+ ],+ ])(+ "an explicit Sonar mapping accepts the dotted provider host in %s",+ async (remote, url) => {+ const { repository, environment } = await fixture({ remote });+ const prepared = await prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar", sourceRepositoryUrl: url },+ { environment, sourceRepositories: [{ url }] },+ );+ expect(prepared.matchesRepositoryRemote).toBe(false);+ },+ );++ test.each([+ "[email protected]:team/project.git",+ "ssh://gitlab.com/team/project.git",+ "[email protected].:team/project.git",+ "[email protected].:team/project.git",+ ])(+ "a recognized Sonar SSH host cannot be remapped to another provider: %s",+ async (remote) => {+ const { repository, environment } = await fixture({+ remote,+ });+ await expect(+ prepareNormalizedLocalImport(+ input(),+ {+ repository,+ ...source,+ provider: "sonar",+ sourceRepositoryUrl: "https://github.com/team/project",+ },+ {+ environment,+ sourceRepositories: [{ url: "https://github.com/team/project" }],+ },+ ),+ ).rejects.toThrow("does not match a configured remote");+ },+ );++ test.each([+ [+ "[email protected].:team/project.git",+ "https://github.com/team/project",+ false,+ ],+ [+ "[email protected]:team/project.git",+ "https://github.com./team/project",+ true,+ ],+ [+ "ssh://[email protected].:443/team/project.git",+ "https://github.com./team/project",+ false,+ ],+ ] as const)(+ "a GitHub reader hint preserves a dotted Sonar mapping for %s and %s",+ async (remote, url, verified) => {+ const { repository, environment } = await fixture({ remote });+ const prepared = await prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar", sourceRepositoryUrl: url },+ { environment, sourceRepositories: [{ url, platform: "github" }] },+ );+ expect(prepared.matchesRepositoryRemote).toBe(verified);+ },+ );++ test.each([+ "ssh://gitlab.com/team/project.git",+ "[email protected].:team/project.git",+ ])(+ "a GitHub reader hint cannot remap a recognized GitLab SSH host: %s",+ async (remote) => {+ const { repository, environment } = await fixture({ remote });+ const url = "https://github.com/team/project";+ await expect(+ prepareNormalizedLocalImport(+ input(),+ {+ repository,+ ...source,+ provider: "sonar",+ sourceRepositoryUrl: url,+ },+ { environment, sourceRepositories: [{ url, platform: "github" }] },+ ),+ ).rejects.toThrow("does not match a configured remote");+ },+ );++ test("the normalized Sonar repository selection must agree with retained and reader sources, even outside Git", async () => {+ const url = "https://github.com/example/project";+ const { repository, root, environment } = await fixture({ remote: url });+ const directory = join(root, "plain");+ await mkdir(directory);+ const retained = {+ ...input(),+ report: { format: "sonar-issues/v1", repositoryUrl: url },+ };+ for (const checkout of [repository, directory]) {+ const options = {+ repository: checkout,+ ...source,+ provider: "sonar" as const,+ sourceRepositoryUrl: url + "-other",+ };+ await expect(+ prepareNormalizedLocalImport(retained, options, { environment }),+ ).rejects.toThrow("does not match the declared source repository");+ await expect(+ prepareNormalizedLocalImport(input(), options, {+ environment,+ sourceRepositories: [{ url }],+ }),+ ).rejects.toThrow("does not match the declared source repository");+ }+ });++ test("an explicit HTTPS mapping accepts an equivalent SCP reader claim for a checkout SSH alias", async () => {+ const { repository, environment } = await fixture({+ remote: "git@work:team/project.git",+ });+ const prepared = await prepareNormalizedLocalImport(+ input(),+ {+ repository,+ ...source,+ provider: "sonar",+ sourceRepositoryUrl: "https://github.com/team/project",+ },+ {+ environment,+ sourceRepositories: [{ url: "[email protected]:team/project.git" }],+ },+ );+ expect(prepared.matchesRepositoryRemote).toBe(false);+ });++ test.each([+ "https://git.example.invalid/team/project",+ "[email protected]:team/project.git",+ ])("a custom SSH remote must match the claimed project: %s", async (url) => {+ const { repository, environment } = await fixture({+ remote: "[email protected]:team/other.git",+ });+ await expect(+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar" },+ {+ environment,+ sourceRepositories: [{ url }],+ },+ ),+ ).rejects.toThrow("does not match a configured remote");+ execFileSync(+ "git",+ [+ "-C",+ repository,+ "remote",+ "set-url",+ "origin",+ "[email protected]:team/project.git",+ ],+ { env: environment },+ );+ expect(+ (+ await prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar" },+ { environment, sourceRepositories: [{ url }] },+ )+ ).matchesRepositoryRemote,+ ).toBe(false);+ });++ test.each([+ [+ "ftp://example.invalid/team/project",+ "https://example.invalid/team/project",+ false,+ ],+ [+ "https://example.invalid/team/pro\tject",+ "https://example.invalid/team/project",+ false,+ ],+ [+ "[email protected]:v3/example/My%20Project/repo",+ "https://dev.azure.com/example/My%20Project/_git/repo",+ true,+ ],+ ] as const)(+ "checks the same Sonar binding for replay of %s as for discovery",+ async (remote, url, matches) => {+ const { repository, environment } = await fixture({ remote });+ const prepared = await prepareNormalizedLocalImport(+ input(),+ { repository, ...source, provider: "sonar" },+ { environment, sourceRepositories: [{ url }] },+ );+ expect(prepared.matchesRepositoryRemote).toBe(matches);+ },+ );+test.each(["local", "global"])("matches all effective fetch URLs with %s Git URL rewrites",async (scope) => {diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 7202d140f..210dedb16 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -17,6 +17,7 @@ import {semgrepSarif,} from "./support/semgrep-import-fixtures.js";import { endorFinding, endorSarif } from "./support/endor-import-fixtures.js";+import { sonarGitTestEnvironment } from "./support/sonar-import-fixtures.js";import { normalizeEndorFindings } from "../src/endor-findings.js";import { createServer, type ServerResponse } from "node:http";import { execFile } from "node:child_process";@@ -673,6 +674,247 @@ async function fixture(};}+test("Sonar replays the selected evidence locally and to Cloud without signing in to Sonar again", async () => {+ const repo = "https://github.com/example/project";+ const source = {+ format: "sonar-issues/v1" as const,+ server: "https://sonarcloud.io",+ organization: "example",+ project: "example_project",+ branch: "main",+ projectBase: "",+ repositoryUrl: repo,+ pages: [+ {+ paging: { pageIndex: 1, pageSize: 100, total: 1 },+ issues: [+ {+ key: "issue-1",+ project: "example_project",+ component: "file",+ rule: "example:R1",+ message: "Review input handling",+ type: "VULNERABILITY",+ severity: "CRITICAL",+ flows: [+ {+ locations: [+ {+ component: "file",+ textRange: { startLine: 2, endLine: 3 },+ },+ ],+ },+ ],+ },+ ],+ components: [{ key: "file", path: "src/example.ts" }],+ },+ ],+ };+ const f = await fixture(source, repo);+ const checkout = join(f.root, "checkout");+ const git = promisify(execFile);+ const environment = sonarGitTestEnvironment({+ ...f.cliDeps.environment,+ CODEX_SECURITY_CLOUD_BASE_URL: "https://cloud.example.test",+ });+ await git("git", ["init", "--quiet", checkout], { env: environment });+ await git("git", ["-C", checkout, "remote", "add", "origin", repo], {+ env: environment,+ });+ const paths = new Set<string>();+ const deps = {+ ...f.cliDeps,+ environment,+ currentDirectory: () => checkout,+ cloudFetch: (url: string, init: RequestInit) => {+ paths.add(new URL(url).pathname);+ return f.cliDeps.cloudFetch(url, init);+ },+ };+ const first = createCliTest(main);+ const previewExit = await first.runCli(+ [+ "import",+ "sonar",+ "--sonar-project",+ source.project,+ "--sonar-branch",+ source.branch,+ "--sonar-issue",+ "issue-1",+ "--dry-run",+ "--format",+ "json",+ ],+ {+ ...deps,+ collectSonarIssues: async (selection) => {+ expect(selection.issueKeys).toEqual(["issue-1"]);+ return source;+ },+ },+ );+ expect(previewExit, first.stderr.text()).toBe(0);+ expect(f.posts).toHaveLength(0);+ const capture: string = JSON.parse(first.stdout.text()).capture;+ expect(JSON.parse(await readFile(capture, "utf8"))).toEqual(source);+ const previewArgs = [+ "import",+ "sonar",+ capture,+ "--to",+ "cloud",+ "--format",+ "json",+ ];++ const outside = join(f.root, "without-remotes");+ await mkdir(outside);+ const noRemotes = createCliTest(main);+ expect(+ await noRemotes.runCli([...previewArgs, "--dry-run"], {+ ...deps,+ currentDirectory: () => outside,+ }),+ ).toBe(2);+ expect(noRemotes.stderr.text()).toContain("--source-repository-url");+ expect(f.posts).toHaveLength(0);++ const cloudPreview = createCliTest(main);+ expect(await cloudPreview.runCli([...previewArgs, "--dry-run"], deps)).toBe(+ 0,+ );+ const reviewed = JSON.parse(cloudPreview.stdout.text());+ expect(reviewed.cloud.destination.url).toBe(repo);+ expect(reviewed.capture).not.toBe(capture);+ expect(f.posts).toHaveLength(0);+ const args = [+ "import",+ "sonar",+ reviewed.capture,+ "--to",+ "cloud",+ "--format",+ "json",+ ];++ const unavailable = createCliTest(main);+ expect(+ await unavailable.runCli([...args, "--yes"], {+ ...deps,+ cloudFetch: async () => new Response("Unknown account", { status: 403 }),+ }),+ ).toBe(2);+ expect(JSON.parse(unavailable.stdout.text()).local.counts.created).toBe(1);++ const replay = createCliTest(main);+ expect(await replay.runCli([...args, "--yes"], deps)).toBe(0);+ const result = JSON.parse(replay.stdout.text());+ expect(result.local.counts.unchanged).toBe(1);+ expect(result.cloud.verified).toBe(1);+ const posted = JSON.parse(f.posts[0]!);+ expect(posted.source).toEqual({+ provider: "sonar",+ source_key: result.sourceKey,+ });+ expect(posted.items[0].source_finding_id).toBe("issue-1");+ const repository = f.destination();+ const reportsPath = `/external/v2/repository_connectors/${repository.repo_connector_id}/repositories/${repository.id}/source_reports`;+ expect(paths).toEqual(+ new Set([+ "/external/repositories",+ reportsPath,+ "/external/v2/finding_imports",+ `${reportsPath}/${f.reports.get("issue-1")!.id}`,+ ]),+ );+ expect(posted.items[0].evidence.source_data.issue.flows).toEqual(+ source.pages[0]!.issues[0]!.flows,+ );+});++test("normalized Sonar publication checks retained bindings on preview and retry", async () => {+ const f = await fixture();+ const repository = f.state.repositoryUrl;+ const foreign = repository + "-other";+ const selected = { ...options, provider: "sonar" as const };+ const context = { format: "sonar-issues/v1", repositoryUrl: repository };+ const finding = {+ source_finding_id: "issue-1",+ evidence: {+ title: "Review input handling",+ severity: "high" as const,+ source_data: { ...context, issue: { key: "issue-1" } },+ },+ };+ const rows = { read: 1, findings: [finding], excluded: [] };+ const named = {+ source_finding_id: "issue-2",+ evidence: {+ ...finding.evidence,+ branch: "main",+ source_data: { ...context, branch: "main", issue: { key: "issue-2" } },+ },+ };+ const selection = { read: 2, findings: [finding, named], excluded: [] };+ const prepare = () =>+ prepareNormalizedExternalPublication(+ { ...selection, report: { ...context, branch: "main" } },+ selected,+ f.deps,+ );+ await expect(+ prepareNormalizedExternalPublication(selection, selected, f.deps),+ ).rejects.toThrow("without a ref");+ await expect(+ prepareNormalizedExternalPublication(+ {+ ...rows,+ report: { ...context, branch: "main" },+ findings: [+ {+ ...finding,+ evidence: { ...finding.evidence, branch: "unrelated" },+ },+ ],+ },+ selected,+ f.deps,+ ),+ ).rejects.toThrow("retained Sonar branch");+ await expect(+ prepareNormalizedExternalPublication(+ { ...rows, report: { ...context, repositoryUrl: foreign } },+ selected,+ f.deps,+ ),+ ).rejects.toThrow("does not match the selected Cloud repository");+ f.state.loseResponse = true;+ await expect((await prepare()).publish()).rejects.toThrow(+ "resume the saved request",+ );+ await expect(+ prepareNormalizedExternalPublication(+ { ...selection, report: { ...context, branch: "other" } },+ selected,+ f.deps,+ ),+ ).rejects.toThrow("conflicting branch");+ f.state.repositoryUrl = foreign;+ await expect(prepare()).rejects.toThrow(+ "does not match the selected Cloud repository",+ );+ expect(f.posts).toHaveLength(1);+ f.state.repositoryUrl = repository;+ const retry = await prepare();+ expect(retry.preview.resumed).toBe(true);+ await retry.publish();+ expect(f.posts).toHaveLength(2);+ expect(f.posts[1]).toBe(f.posts[0]);+});+test("Wiz occurrence mapping preserves original evidence without inventing repository provenance", async () => {const record = {id: "wiz-occurrence",@@ -1192,35 +1434,38 @@ test("publishing an Inspector retry adopts its project map without changing theexpect(f.posts).toEqual([body, body, body]);});-test("a normalized Inspector retry checks its typed repository without native evidence", async () => {- const f = await fixture();- const finding = {- source_finding_id: "vendor-1",- evidence: {- title: "Synthetic code finding",- severity: "high" as const,- details: {- kind: "sast" as const,- repository: { url: inspectorRepositoryUrl },+test.each(["inspector", "sonar"] as const)(+ "a normalized %s retry checks its typed repository without native evidence",+ async (provider) => {+ const f = await fixture();+ const finding = {+ source_finding_id: "vendor-1",+ evidence: {+ title: "Synthetic code finding",+ severity: "high" as const,+ details: {+ kind: "sast" as const,+ repository: { url: inspectorRepositoryUrl },+ },},- },- };- const prepare = () =>- prepareNormalizedExternalPublication(- { read: 1, findings: [finding], excluded: [] },- inspectorOptions,- f.deps,+ };+ const prepare = () =>+ prepareNormalizedExternalPublication(+ { read: 1, findings: [finding], excluded: [] },+ { ...options, provider },+ f.deps,+ );+ f.state.loseResponse = true;+ await expect((await prepare()).publish()).rejects.toThrow(+ "resume the saved request",);- f.state.loseResponse = true;- await expect((await prepare()).publish()).rejects.toThrow(- "resume the saved request",- );- f.state.repositoryUrl = "https://github.com/different/project";- await expect(prepare()).rejects.toThrow(- "does not match the selected Cloud repository",- );- expect(f.posts).toHaveLength(1);-});+ f.state.repositoryUrl = "https://github.com/different/project";+ await expect(prepare()).rejects.toThrow(+ "does not match the selected Cloud repository",+ );+ expect(f.posts).toHaveLength(1);+ },+);const savedBlackDuckEvidence = {data: { format: "blackduck-bom-6" },@@ -3315,6 +3560,7 @@ test("Cloud deployment routing covers every request and isolates saved retries",expect(requested.some((url) => url.includes("/source_reports?"))).toBe(true);expect(requested.some((url) => url.endsWith("/finding_imports"))).toBe(true);expect(requested.some((url) => url.includes("/source_reports/"))).toBe(true);+ expect(requested.some((url) => url.includes("/external/v2/"))).toBe(false);});test.each(["localhost", "127.0.0.1", "127.0.0.2", "[::1]"])(diff --git a/sdk/typescript/tests-ts/sonar-collector.test.ts b/sdk/typescript/tests-ts/sonar-collector.test.tsnew file mode 100644index 000000000..a69a8bcd0--- /dev/null+++ b/sdk/typescript/tests-ts/sonar-collector.test.ts@@ -0,0 +1,954 @@+import { afterEach, expect, spyOn, test } from "bun:test";+import { execFileSync } from "node:child_process";+import {+ copyFile,+ mkdir,+ mkdtemp,+ realpath,+ rm,+ symlink,+ stat,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { delimiter, join } from "node:path";+import { collectSonarIssues } from "../src/sonar-collector.js";+import {+ normalizeSonarFindings,+ readSonarFindings,+} from "../src/sonar-findings.js";+import { sonarGitTestEnvironment } from "./support/sonar-import-fixtures.js";++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++const server = "https://sonarqube.us";+const organization = "example";+const project = "example:service";+const repositoryUrl = "https://example.invalid/team/service";+const auth = { status: "connected", org: organization, server };+const environment = {+ ...sonarGitTestEnvironment(),+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+};++function git(...args: string[]) {+ return execFileSync("git", args, { env: environment });+}++async function checkout() {+ const cwd = await realpath(await mkdtemp(join(tmpdir(), "sonar import ")));+ roots.push(cwd);+ git("init", "--quiet", cwd);+ git(+ "-C",+ cwd,+ "remote",+ "add",+ "origin",+ "https://synthetic-user:example@" ++ new URL(repositoryUrl).host ++ "/team/service.git",+ );+ return cwd;+}++function page(key: string, index = 1, total = 1) {+ return {+ issues: [+ {+ project,+ key,+ component: project + ":source.ts",+ type: "VULNERABILITY",+ rule: "test:S1",+ flows: [+ {+ locations: [+ {+ component: project + ":source.ts",+ textRange: { startLine: 1, endLine: 3 },+ },+ ],+ },+ ],+ },+ ],+ components: [{ key: project + ":source.ts", path: "source.ts" }],+ paging: { pageIndex: index, pageSize: 1, total },+ };+}++function sonarSession(options: {+ pages:+ | Record<string, unknown>[]+ | ((query: URLSearchParams) => Record<string, unknown>);+ bindings?: Record<string, unknown>[];+ navigationDenied?: boolean;+ connection?: () => typeof auth;+ navigation?: Record<string, unknown>;+ shownComponent?: Record<string, unknown> | Error;+ components?: Record<string, unknown>[];+ componentsById?: Record<string, Record<string, unknown>[]>;+ repositoryUrl?: string;+ analyses?:+ Record<string, unknown>[] | Error | (() => Record<string, unknown>[]);+}) {+ const commands: string[][] = [];+ const queries: URLSearchParams[] = [];+ return {+ commands,+ queries,+ run: async (args: string[]): Promise<Record<string, unknown>> => {+ commands.push(args);+ if (args[0] === "auth") return options.connection?.() ?? auth;+ expect(args.slice(0, 2)).toEqual(["api", "get"]);+ const url = new URL(args[2]!, server);+ if (url.pathname === "/api/project_branches/list")+ return {+ branches: [+ { name: "other", isMain: false },+ { name: "trunk", isMain: true },+ ],+ };+ if (url.pathname === "/api/navigation/component") {+ if (options.navigationDenied)+ throw new Error("Navigation requires a browser session");+ return {+ key: project,+ id: "p-1",+ organization,+ badgeToken: "synthetic badge metadata",+ ...options.navigation,+ };+ }+ if (url.pathname === "/api/components/show") {+ expect(url.searchParams.get("component")).toBe(project);+ if (options.shownComponent instanceof Error)+ throw options.shownComponent;+ return {+ component: options.shownComponent ?? {+ key: project,+ organization,+ qualifier: "TRK",+ },+ };+ }+ if (url.pathname === "/dop-translation/project-bindings") {+ expect(url.searchParams.get("url")).toBe(+ options.repositoryUrl ?? repositoryUrl,+ );+ return { bindings: options.bindings ?? [{ projectId: "p-1" }] };+ }+ if (url.pathname === "/api/components/search_projects") {+ const id = url.searchParams.get("projectIds")!;+ if (!options.componentsById) expect(id).toBe("p-1");+ expect(url.searchParams.get("organization")).toBe(organization);+ return {+ components: options.componentsById?.[id] ??+ options.components ?? [{ key: project, id: "p-1", organization }],+ };+ }+ if (url.pathname === "/api/project_analyses/search") {+ if (options.analyses instanceof Error) throw options.analyses;+ if (typeof options.analyses === "function")+ return { analyses: options.analyses() };+ return { analyses: options.analyses ?? [] };+ }+ expect(url.pathname).toBe("/api/issues/search");+ queries.push(url.searchParams);+ if (typeof options.pages === "function")+ return options.pages(url.searchParams);+ return options.pages[Number(url.searchParams.get("p")) - 1]!;+ },+ };+}++test("uses the signed-in CLI and a verified checkout binding, retaining all security issue pages", async () => {+ const pages = [page("A", 1, 2), page("B", 2, 2)];+ const cwd = await checkout();+ const session = sonarSession({+ pages,+ analyses: [{ key: "analysis", relativePathFromScmRoot: "" }],+ });+ const branch = "release/space & plus+";+ const capture = await collectSonarIssues(+ { cwd, branch, environment },+ session.run,+ );+ expect(session.commands[0]).toEqual(["auth", "status", "--format", "json"]);+ expect(session.commands[1]).toEqual([+ "api",+ "get",+ `/dop-translation/project-bindings?${new URLSearchParams({ url: repositoryUrl })}`,+ ]);+ expect(session.commands.flat().join(" ")).not.toContain("synthetic-user");+ expect(capture).toMatchObject({+ format: "sonar-issues/v1",+ server,+ organization,+ project,+ branch,+ repositoryUrl,+ projectBase: "",+ pages,+ });+ expect(JSON.stringify(capture)).not.toContain("synthetic");+ expect(session.queries.length).toBe(2);+ for (const query of session.queries) {+ expect(query.get("organization")).toBe(organization);+ expect(query.get("componentKeys")).toBe(project);+ expect(query.get("branch")).toBe(branch);+ expect(query.get("impactSoftwareQualities")).toBe("SECURITY");+ expect(query.get("additionalFields")).toBe("rules");+ expect(query.get("issueStatuses")).toBe("OPEN,CONFIRMED");+ }+});++test("collects the exact issue keys and PR selected in the plugin handoff", async () => {+ const cwd = await checkout();+ const issueKeys = ["A", "B"];+ const session = sonarSession({+ pages: [page("A", 1, 2), page("B", 2, 2)],+ analyses: [+ { key: "analysis", relativePathFromScmRoot: "packages/main-branch" },+ ],+ });+ const capture = await collectSonarIssues(+ { cwd, project, pullRequest: "35", issueKeys, environment },+ session.run,+ );+ expect(capture.pullRequest).toBe("35");+ expect(capture.projectBase).toBeUndefined();+ expect(session.commands.flat().join(" ")).not.toContain(+ "/api/project_analyses/search",+ );+ const query = session.queries[0]!;+ expect(query.get("issues")).toBe("A,B");+ expect(query.get("pullRequest")).toBe("35");+ expect(query.has("branch")).toBe(false);+ expect(query.has("issueStatuses")).toBe(false);+ for (const [key, error] of [+ ["A", "were not returned"],+ ["unselected", "outside the selected"],+ ] as const) {+ const incomplete = sonarSession({ pages: [page(key)] });+ await expect(+ collectSonarIssues(+ { cwd, project, issueKeys, environment },+ incomplete.run,+ ),+ ).rejects.toThrow(error);+ }+});++const largeSelection = Array.from(+ { length: 2_000 },+ (_, index) => "example-issue-" + index,+);++function exactIssuePage(+ query: URLSearchParams,+ keys = query.get("issues")!.split(","),+) {+ const index = Number(query.get("p")),+ size = Number(query.get("ps"));+ return {+ paging: { pageIndex: index, pageSize: size, total: keys.length },+ issues: keys.slice((index - 1) * size, index * size).map((key) => ({+ key,+ project,+ component: project + ":source.ts",+ rule: "test:S1",+ type: "VULNERABILITY",+ })),+ };+}++test("a large exact selection retains each query's native pages for offline replay", async () => {+ const cwd = await checkout();+ const nativePages: Record<string, unknown>[] = [];+ const session = sonarSession({+ pages: (query) => {+ const result = exactIssuePage(query);+ nativePages.push(result);+ return result;+ },+ });+ const capture = await collectSonarIssues(+ { cwd, project, branch: "main", issueKeys: largeSelection, environment },+ session.run,+ );+ const firstPages = session.queries.filter((query) => query.get("p") === "1");+ expect(firstPages.length).toBeGreaterThan(1);+ expect(+ firstPages.flatMap((query) => query.get("issues")!.split(",")),+ ).toEqual(largeSelection);+ expect(capture.pages).toEqual(nativePages);+ expect(nativePages.length).toBeGreaterThan(firstPages.length);+ const path = join(cwd, "selection.json");+ await writeFile(path, JSON.stringify(capture));+ const replay = await readSonarFindings(path, repositoryUrl, "local");+ expect(replay.findings.map((finding) => finding.source_finding_id)).toEqual(+ largeSelection,+ );+});++test("multiple exact-key queries reject missing, foreign, and duplicate keys in later responses", async () => {+ const cwd = await checkout();+ for (const [defect, error] of [+ ["missing", /were not returned/],+ ["foreign", /outside the selected/],+ ["duplicate", /overlap/],+ ] as const) {+ const session = sonarSession({+ pages: (query) => {+ const keys = query.get("issues")!.split(",");+ if (keys[0] !== largeSelection[0]) {+ if (defect === "missing") keys.shift();+ if (defect === "foreign") keys[0] = largeSelection[0]!;+ if (defect === "duplicate") keys[0] = keys[1]!;+ }+ return exactIssuePage(query, keys);+ },+ });+ await expect(+ collectSonarIssues(+ {+ cwd,+ project,+ branch: "main",+ issueKeys: largeSelection,+ environment,+ },+ session.run,+ ),+ ).rejects.toThrow(error);+ expect(+ session.queries.filter((query) => query.get("p") === "1").length,+ ).toBeGreaterThan(1);+ }+});++test("an omitted ref and the explicit Sonar main branch produce identical captures", async () => {+ const cwd = await checkout();+ const session = sonarSession({ pages: [page("A")] });+ const implicit = await collectSonarIssues(+ { cwd, project, environment },+ session.run,+ );+ const explicit = await collectSonarIssues(+ { cwd, project, branch: "trunk", environment },+ session.run,+ );+ expect(implicit).toEqual(explicit);+ expect(session.queries.map((query) => query.get("branch"))).toEqual([+ "trunk",+ "trunk",+ ]);+});++test("SDK collection keeps the checkout and issue selection supplied when the call started", async () => {+ const cwd = await checkout();+ const session = sonarSession({ pages: [page("A")] });+ const options = {+ cwd,+ project,+ branch: "trunk",+ issueKeys: ["A"],+ sourceRepositoryUrl: repositoryUrl,+ environment: { ...environment, PATH: process.env["PATH"] },+ };+ const collection = collectSonarIssues(options, session.run);+ options.cwd = join(cwd, "absent");+ options.project = "another-project";+ options.branch = "another-branch";+ options.issueKeys[0] = "B";+ options.sourceRepositoryUrl += "-other";+ options.environment.PATH = "";+ const capture = await collection;+ expect(capture).toMatchObject({ project, branch: "trunk", repositoryUrl });+ expect(session.queries.map((query) => query.get("issues"))).toEqual(["A"]);+});++test("a supplied source repository must agree with checkout discovery and selected project metadata before issue search", async () => {+ const cwd = await checkout();+ const sourceRepositoryUrl = repositoryUrl + "-other";+ const implicit = sonarSession({ pages: [] });+ await expect(+ collectSonarIssues({ cwd, sourceRepositoryUrl, environment }, implicit.run),+ ).rejects.toThrow("--source-repository-url");+ expect(implicit.commands).toEqual([]);+ const explicit = sonarSession({+ pages: [],+ navigation: { alm: { url: sourceRepositoryUrl } },+ });+ await expect(+ collectSonarIssues(+ { cwd, project, sourceRepositoryUrl: repositoryUrl, environment },+ explicit.run,+ ),+ ).rejects.toThrow("--source-repository-url");+ expect(explicit.queries).toEqual([]);+});++test("conflicting organization, branch, and pull request on returned issues fail collection", async () => {+ const cwd = await checkout();+ for (const [selection, scope, error] of [+ [{ branch: "main" }, { organization: "other" }, /organization/],+ [{ branch: "main" }, { branch: "other" }, /branch/],+ [{ pullRequest: "12" }, { pullRequest: "13" }, /pullRequest/],+ [{ pullRequest: "12" }, { branch: "main" }, /branch and pull request/],+ ] as const) {+ const result = page("A");+ Object.assign(result.issues[0]!, scope);+ const session = sonarSession({ pages: [result] });+ await expect(+ collectSonarIssues(+ { cwd, project, ...selection, environment },+ session.run,+ ),+ ).rejects.toThrow(error);+ expect(session.queries).toHaveLength(1);+ }+});++test("automatic discovery rejects a forged Git pointer but accepts a registered linked worktree", async () => {+ const cwd = await checkout();+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "sonar worktrees ")),+ );+ roots.push(root);+ const forged = join(root, "forged");+ await mkdir(forged);+ await writeFile(join(forged, ".git"), `gitdir: ${join(cwd, ".git")}\n`);+ const session = sonarSession({ pages: [page("A")] });+ await expect(+ collectSonarIssues({ cwd: forged, environment }, session.run),+ ).rejects.toThrow("--sonar-project");+ expect(session.commands).toEqual([]);++ git(+ "-C",+ cwd,+ "-c",+ "user.name=Fixture",+ "-c",+ "[email protected]",+ "commit",+ "--quiet",+ "--allow-empty",+ "-m",+ "fixture",+ );+ const linked = join(root, "linked");+ git("-C", cwd, "worktree", "add", "--quiet", "--detach", linked);+ git(+ "-C",+ cwd,+ "remote",+ "set-url",+ "--add",+ "origin",+ repositoryUrl + "-mirror",+ );+ const capture = await collectSonarIssues(+ { cwd: linked, environment },+ session.run,+ );+ expect(capture).toMatchObject({ project, repositoryUrl });+ expect(session.queries).toHaveLength(1);+});++test("automatic discovery uses only the rewritten primary fetch URL of origin", async () => {+ const cwd = await checkout();+ git("-C", cwd, "config", `url.${repositoryUrl}.insteadOf`, "source:service");+ git("-C", cwd, "remote", "set-url", "origin", "source:service.git");+ git(+ "-C",+ cwd,+ "remote",+ "set-url",+ "--add",+ "origin",+ repositoryUrl + "-mirror",+ );+ const session = sonarSession({ pages: [page("A")] });+ const capture = await collectSonarIssues({ cwd, environment }, session.run);+ expect(capture).toMatchObject({ project, repositoryUrl });++ git(+ "-C",+ cwd,+ "config",+ "--replace-all",+ "remote.origin.url",+ "unsupported::service",+ "^source:",+ );+ const rejected = sonarSession({ pages: [] });+ await expect(+ collectSonarIssues({ cwd, environment }, rejected.run),+ ).rejects.toThrow("--sonar-project");+ expect(rejected.commands).toEqual([]);+});++test("uses the explicit project in token-only sessions and claims only a matching binding", async () => {+ const cwd = await checkout();+ for (const resolvedProject of [project, "other"]) {+ const session = sonarSession({+ pages: [page("A")],+ navigationDenied: true,+ components: [{ key: resolvedProject }],+ });+ const capture = await collectSonarIssues(+ { cwd, project, environment },+ session.run,+ );+ expect(capture.project).toBe(project);+ expect(capture.repositoryUrl).toBe(+ resolvedProject === project ? repositoryUrl : undefined,+ );+ expect(+ session.commands.some((args) =>+ args[2]?.startsWith("/api/components/show?"),+ ),+ ).toBe(resolvedProject !== project);+ expect(session.queries.map((query) => query.get("componentKeys"))).toEqual([+ project,+ ]);+ }+});++test("an empty search cannot validate an unbound project without Browse access in the active organization", async () => {+ const cwd = await checkout();+ for (const shownComponent of [+ { key: "other", organization, qualifier: "TRK" },+ { key: project, organization: "other", qualifier: "TRK" },+ { key: project, organization, qualifier: "FIL" },+ new Error("Browse denied"),+ ]) {+ const session = sonarSession({+ pages: [+ { issues: [], paging: { pageIndex: 1, pageSize: 100, total: 0 } },+ ],+ navigationDenied:+ shownComponent instanceof Error || shownComponent.qualifier !== "FIL",+ bindings: [],+ shownComponent,+ });+ await expect(+ collectSonarIssues(+ { cwd, project, sourceRepositoryUrl: repositoryUrl, environment },+ session.run,+ ),+ ).rejects.toThrow(/selected project|Browse denied/);+ expect(session.commands.flat().join(" ")).not.toContain(+ "/api/project_branches/list",+ );+ expect(session.queries).toEqual([]);+ }+});++test("an explicit project disambiguates token-only monorepo bindings", async () => {+ const cwd = await checkout();+ const session = sonarSession({+ pages: [page("A")],+ navigationDenied: true,+ bindings: [{ projectId: "p-other" }, { projectId: "p-1" }],+ componentsById: {+ "p-other": [{ key: "other", id: "p-other", organization }],+ "p-1": [{ key: project, id: "p-1", organization }],+ },+ });+ const capture = await collectSonarIssues(+ { cwd, project, environment },+ session.run,+ );+ expect(capture.repositoryUrl).toBe(repositoryUrl);+ expect(session.queries.map((q) => q.get("componentKeys"))).toEqual([project]);+});++test("a confirmed project or organization mismatch stops before further lookups", async () => {+ const cwd = await checkout();+ for (const navigation of [{ key: "foreign" }, { organization: "foreign" }]) {+ const session = sonarSession({ pages: [], navigation });+ await expect(+ collectSonarIssues({ cwd, project, environment }, session.run),+ ).rejects.toThrow("different project or organization");+ expect(session.commands).toHaveLength(2);+ }+});++test("explicitly selecting zero issues never broadens to all open issues", async () => {+ const cwd = await checkout();+ const session = sonarSession({ pages: [] });+ await expect(+ collectSonarIssues(+ { cwd, project, issueKeys: [], environment },+ session.run,+ ),+ ).rejects.toThrow("selection is empty");+ expect(session.commands).toEqual([]);+});++test("asks for a narrower selection on the first page exceeding Sonar's search window", async () => {+ const cwd = await checkout();+ const session = sonarSession({ pages: [page("A", 1, 10_001)] });+ await expect(+ collectSonarIssues({ cwd, project, environment }, session.run),+ ).rejects.toThrow("--sonar-issue");+ expect(session.queries).toHaveLength(1);+});++test("cannot save a partial or overlapping Sonar search as a complete capture", async () => {+ const cwd = await checkout();+ for (const pages of [+ [page("A", 1, 2), page("A", 2, 2)],+ [page("A", 1, 2), page("B", 2, 1)],+ ]) {+ const session = sonarSession({ pages });+ await expect(+ collectSonarIssues(+ { cwd, project, branch: "main", environment },+ session.run,+ ),+ ).rejects.toThrow(/overlap|paging/);+ }+});++test("asks for a project before fetching findings from an ambiguous or unverified checkout", async () => {+ const cwd = await checkout();+ for (const options of [+ { bindings: [] },+ { bindings: [{ projectId: "p-1" }, { projectId: "p-2" }] },+ { components: [] },+ { components: [{ key: project }, { key: "unrelated" }] },+ { components: [{ key: project, organization: "unrelated" }] },+ { components: [{ key: project, id: "p-2" }] },+ ]) {+ const session = sonarSession({ ...options, pages: [] });+ await expect(+ collectSonarIssues({ cwd, environment }, session.run),+ ).rejects.toThrow("--sonar-project");+ expect(session.queries).toHaveLength(0);+ expect(session.commands.flat().join(" ")).not.toContain(+ "/api/navigation/component",+ );+ }+});++test("guides disconnected users to sign in and honors cancellation before opening Sonar", async () => {+ const cwd = await checkout();+ await expect(+ collectSonarIssues({ cwd, environment }, async () => ({+ status: "token_missing",+ })),+ ).rejects.toThrow("sonar auth login");+ await expect(+ collectSonarIssues({+ cwd,+ project,+ environment: { ...environment, PATH: "" },+ }),+ ).rejects.toThrow("Install the SonarQube CLI");+ const aborted = AbortSignal.abort(new Error("cancel collection"));+ await expect(+ collectSonarIssues({ cwd, signal: aborted, environment }, async () => {+ throw new Error("unexpected CLI call");+ }),+ ).rejects.toThrow("cancel collection");+});++test("honors the SDK caller's inherited opt-in and explicit non-enumerable opt-out before invoking Sonar", async () => {+ const cwd = await checkout();+ const allowed = sonarSession({ pages: [page("A")] });+ const capture = await collectSonarIssues(+ { cwd, environment: Object.create(environment) },+ allowed.run,+ );+ expect(capture.repositoryUrl).toBe(repositoryUrl);+ const session = sonarSession({ pages: [] });+ const denied = Object.defineProperty(+ { codex_security_enable_external_imports: "1" },+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS",+ { value: "0" },+ );+ await expect(+ collectSonarIssues(+ {+ cwd: ".",+ environment: denied,+ },+ session.run,+ ),+ ).rejects.toThrow("imports are disabled");+ expect(session.commands).toEqual([]);+});++test("canonical Cloud endpoints are accepted and connection changes during issue search discard the capture", async () => {+ const cwd = await checkout();+ for (const [initialServer, final] of [+ ["https://SONARCLOUD.IO:443", { ...auth, server: "https://sonarcloud.io" }],+ ["https://SONARQUBE.US:443/", auth],+ [server, { ...auth, org: "other" }],+ [server, { ...auth, server: "https://sonarcloud.io" }],+ ] as const) {+ let active: typeof auth = { ...auth, server: initialServer };+ const session = sonarSession({+ connection: () => active,+ pages: () => {+ active = final;+ return page("A");+ },+ });+ const result = collectSonarIssues(+ { cwd, branch: "trunk", environment },+ session.run,+ );+ if (initialServer === server)+ await expect(result).rejects.toThrow("connection changed");+ else expect((await result).server).toBe(final.server);+ expect(session.queries).toHaveLength(1);+ }+});++test("projects paths only from the selected branch's recorded analysis base", async () => {+ const cwd = await checkout();+ const branch = "release/service";+ for (const [analyses, expected] of [+ [+ [{ key: "analysis", relativePathFromScmRoot: "packages/service" }],+ "packages/service",+ ],+ [[{ relativePathFromScmRoot: "packages/service" }], undefined],+ [[{ key: "analysis", relativePathFromScmRoot: "../outside" }], undefined],+ [[{}], undefined],+ [new Error("Analysis metadata unavailable"), undefined],+ ] as Array<[Record<string, unknown>[] | Error, string | undefined]>) {+ const session = sonarSession({+ pages: [page("A")],+ analyses,+ });+ const capture = await collectSonarIssues(+ { cwd, branch, environment },+ session.run,+ );+ expect(session.commands).toContainEqual([+ "api",+ "get",+ `/api/project_analyses/search?${new URLSearchParams({ project, branch, ps: "1" })}`,+ ]);+ expect(capture.projectBase).toBe(expected);+ expect(capture.pages[0]).toEqual(page("A"));+ }+});++test("preserves native paths without projecting a changed analysis or base during pagination", async () => {+ const cwd = await checkout();+ const first = { key: "first", relativePathFromScmRoot: "packages/one" };+ for (const next of [+ { ...first, key: "next" },+ { ...first, relativePathFromScmRoot: "packages/two" },+ ]) {+ let active = first;+ const session = sonarSession({+ analyses: () => [active],+ pages: (query) => {+ active = next;+ const index = Number(query.get("p"));+ return page("issue-" + index, index, 2);+ },+ });+ const capture = await collectSonarIssues(+ { cwd, branch: "main", environment },+ session.run,+ );+ expect(capture.projectBase).toBeUndefined();+ expect(capture.pages).toEqual([+ page("issue-1", 1, 2),+ page("issue-2", 2, 2),+ ]);+ }+});++test("a fork with a matching upstream projects the selected project's stable analysis paths", async () => {+ const cwd = await checkout();+ git("-C", cwd, "remote", "rename", "origin", "upstream");+ git("-C", cwd, "remote", "add", "origin", repositoryUrl + "-fork");+ const session = sonarSession({+ navigation: { alm: { url: repositoryUrl } },+ analyses: [{ key: "stable", relativePathFromScmRoot: "packages/service" }],+ pages: [page("A")],+ });+ const capture = await collectSonarIssues(+ { cwd, project, branch: "main", environment },+ session.run,+ );+ const { findings } = normalizeSonarFindings(capture, repositoryUrl, "local");+ expect(findings[0]?.evidence.locations).toMatchObject([+ { path: "packages/service/source.ts" },+ ]);+});++test.each([+ [+ "ssh://[email protected]:443/team/service.git",+ "https://github.com/team/service",+ ],+ ["[email protected]:Team/Service.git", "https://github.com/Team/Service"],+ [+ "git+ssh://[email protected]/team/service.git",+ "https://github.com/team/service",+ ],+ [+ "ssh+git://[email protected]:22/team/service.git",+ "https://gitlab.com/team/service",+ ],+ [+ "git+ssh://[email protected]:22/v3/Org/Project/Repo",+ "https://dev.azure.com/Org/Project/_git/Repo",+ ],+ [+ "[email protected]:v3/Org/Project/Repo",+ "https://dev.azure.com/Org/Project/_git/Repo",+ ],+ [+ "[email protected]:v3/Org/Project%20Name/Repo%20Name",+ "https://dev.azure.com/Org/Project%20Name/_git/Repo%20Name",+ ],+ [+ "ssh://[email protected]:22/v3/Org/Project/Repo",+ "https://dev.azure.com/Org/Project/_git/Repo",+ ],+])(+ "verifies the HTTPS repository binding for SSH origin %s",+ async (origin, source) => {+ const cwd = await checkout();+ git("-C", cwd, "remote", "set-url", "origin", origin);+ const session = sonarSession({ pages: [page("A")], repositoryUrl: source });+ const capture = await collectSonarIssues({ cwd, environment }, session.run);+ expect(capture.repositoryUrl).toBe(source);+ },+);++test("rejects ambiguous Git transport and credential-bearing query strings before Sonar discovery", async () => {+ const cwd = await checkout();+ await writeFile(+ join(cwd, "sonar-project.properties"),+ "sonar.projectKey=unselected\n",+ );+ for (const origin of [+ "https://example.invalid/team/service.git?access_token=synthetic",+ "https://example.invalid/team/old/../service.git",+ "ssh://[email protected]/team/old/../service.git",+ "ssh+git://[email protected]/team/old/../service.git",+ "GIT+SSH://[email protected]/team/service.git",+ "ssh+GIT://[email protected]/team/service.git",+ "SSH://[email protected]/team/service.git",+ "HTTPS://github.com/team/service.git",+ "hTtp://github.com/team/service.git",+ "git+ssh://[email protected]:2222/team/service.git",+ "git+ssh://[email protected]/team/service.git",+ "git+ssh://git:[email protected]/team/service.git",+ "git@github-work:team/service.git",+ "ssh://[email protected]/team/old/%2e%2e/service.git",+ "ssh://[email protected]%2f/team/service.git",+ "[email protected]:team/%73ervice.git",+ "ssh://[email protected]:2222/v3/Org/Project/Repo",+ "[email protected]:v3/Org/../Repo",+ ]) {+ git("-C", cwd, "remote", "set-url", "origin", origin);+ const session = sonarSession({ pages: [] });+ await expect(+ collectSonarIssues({ cwd, environment }, session.run),+ ).rejects.toThrow("--sonar-project");+ expect(session.commands).toEqual([]);+ }+});++test.skipIf(process.platform === "win32")(+ "Sonar installed under a non-repository home runs without following a child Git symlink into the checkout",+ async () => {+ const cwd = await checkout();+ const root = await realpath(await mkdtemp(join(tmpdir(), "sonar tools ")));+ roots.push(root);+ const bin = join(root, ".local", "share", "sonarqube-cli", "bin"),+ aliases = join(root, "aliases"),+ marker = join(root, "executed");+ await Promise.all([mkdir(bin, { recursive: true }), mkdir(aliases)]);+ await writeFile(+ join(cwd, "git"),+ '#!/bin/sh\ntouch "$SONAR_CHILD_MARKER"\n',+ { mode: 0o700 },+ );+ await symlink(join(cwd, "git"), join(aliases, "git"));+ await writeFile(+ join(bin, "sonar"),+ `#!/bin/sh+test "$SONAR_TOKEN" = "synthetic" || exit 1+git --version >/dev/null || exit 1+printf '{"status":"token_missing"}'+`,+ { mode: 0o700 },+ );+ const current = spyOn(process, "cwd").mockReturnValue(root);+ try {+ await expect(+ collectSonarIssues({+ cwd,+ project,+ environment: {+ ...environment,+ HOME: root,+ PATH: [aliases, bin, process.env["PATH"]].join(delimiter),+ SONAR_CHILD_MARKER: marker,+ SONAR_TOKEN: "synthetic",+ },+ }),+ ).rejects.toThrow("sonar auth login");+ } finally {+ current.mockRestore();+ }+ await expect(stat(marker)).rejects.toMatchObject({ code: "ENOENT" });+ },+);++test.each(["checkout", "metadata"])(+ "excludes Git in a separate caller %s from the SDK lookup",+ async (kind) => {+ const cwd = await checkout();+ const root = await realpath(await mkdtemp(join(tmpdir(), "sonar caller ")));+ roots.push(root);+ const caller = join(root, "caller");+ const metadata = join(root, "caller.git");+ git("init", "--quiet", "--separate-git-dir", metadata, caller);+ const bin = join(kind === "checkout" ? caller : metadata, "bin");+ await mkdir(bin);+ if (process.platform === "win32")+ await copyFile(process.execPath, join(bin, "git.exe"));+ else+ await writeFile(join(bin, "git"), "#!/bin/sh\nexit 1\n", { mode: 0o700 });+ const current = spyOn(process, "cwd").mockReturnValue(caller);+ try {+ const session = sonarSession({ pages: [page("A")] });+ const capture = await collectSonarIssues(+ {+ cwd,+ environment: {+ ...environment,+ PATH: [bin, process.env["PATH"]].join(delimiter),+ },+ },+ session.run,+ );+ expect(capture.repositoryUrl).toBe(repositoryUrl);+ } finally {+ current.mockRestore();+ }+ },+);diff --git a/sdk/typescript/tests-ts/sonar-findings.test.ts b/sdk/typescript/tests-ts/sonar-findings.test.tsnew file mode 100644index 000000000..d4fdc7f05--- /dev/null+++ b/sdk/typescript/tests-ts/sonar-findings.test.ts@@ -0,0 +1,397 @@+import { expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";+import {+ normalizeSonarFindings,+ readSonarFindings,+ sonarRepositoryUrls,+} from "../src/sonar-findings.js";+import { scopedTemporaryDirectory } from "./support/temporary-directories.js";+import { sonarGitTestEnvironment } from "./support/sonar-import-fixtures.js";++const project = "team:application";+const repository = "https://vcs.example.test/team/application";+const primary = { key: project + ":primary", path: "src/app.ts" };+const secondary = { key: project + ":secondary", path: "src/source.ts" };+const rule = { key: "example:S1", name: "Untrusted input reaches a sink" };++function issue(key = "issue-1") {+ return {+ key,+ project,+ component: primary.key,+ rule: rule.key,+ message: "Check the source of this input.",+ issueStatus: "OPEN",+ type: "VULNERABILITY",+ impacts: [+ { softwareQuality: "RELIABILITY", severity: "BLOCKER" },+ { softwareQuality: "SECURITY", severity: "HIGH" },+ ],+ textRange: { startLine: 7, endLine: 9, startOffset: 4, endOffset: 20 },+ flows: [+ {+ locations: [+ {+ component: secondary.key,+ msg: "Input originates here.",+ textRange: { startLine: 2, endLine: 2 },+ },+ ],+ },+ ],+ updateDate: "2026-10-30T10:05:00+0000",+ };+}++function page(+ issues: Record<string, unknown>[],+ pageIndex = 1,+ pageSize = 10,+ total = issues.length,+) {+ return {+ paging: { pageIndex, pageSize, total },+ issues,+ components: [primary, secondary, { key: "unrelated", path: "other.ts" }],+ rules: [rule],+ };+}++function capture(pages: unknown[]) {+ return {+ format: "sonar-issues/v1",+ server: "https://sonar.example.test/",+ organization: "test-org",+ project,+ branch: "release/v1",+ repositoryUrl: repository,+ projectBase: "",+ pages,+ };+}++test("reads a saved Sonar capture and keeps per-issue primary and cross-file evidence", async () => {+ await using tmp = await scopedTemporaryDirectory("sonar-evidence-");+ const finding = issue("key+1");+ const input = capture([page([finding])]);+ const path = join(tmp.path, "capture.json");+ await writeFile(path, JSON.stringify(input));+ const result = await readSonarFindings(path, "", "local");+ expect(result.excluded).toEqual([]);+ expect(result.findings).toHaveLength(1);+ const imported = result.findings[0]!;+ expect(imported.source_finding_id).toBe(finding.key);+ expect(imported.evidence).toMatchObject({+ title: rule.name,+ description: finding.message,+ severity: "high",+ locations: [{ path: primary.path, line: 7 }],+ branch: "release/v1",+ source_updated_at: Date.parse(finding.updateDate) / 1000,+ details: {+ kind: "sast",+ source_status: "OPEN",+ repository: { url: repository },+ rule: { id: rule.key },+ code: { end_line: 9 },+ },+ source_data: {+ issue: finding,+ components: [primary, secondary],+ rule,+ project,+ organization: "test-org",+ },+ });+ const link = new URL(imported.evidence.url!);+ expect(link.pathname).toBe("/project/issues");+ expect(Object.fromEntries(link.searchParams)).toEqual({+ id: project,+ branch: "release/v1",+ open: finding.key,+ issues: finding.key,+ });+ expect(normalizeSonarFindings(input, repository, "cloud").findings).toEqual(+ result.findings,+ );+});++test("reads complete native pages, keeping stable IDs and distinguishing security from quality", () => {+ const current = issue();+ const classic = {+ ...issue("classic"),+ type: "VULNERABILITY",+ severity: "CRITICAL",+ impacts: undefined,+ issueStatus: undefined,+ status: "CONFIRMED",+ };+ const unrelated = {+ ...issue("other"),+ type: "CODE_SMELL",+ impacts: [{ softwareQuality: "MAINTAINABILITY", severity: "HIGH" }],+ };+ const input = [page([unrelated], 2, 2, 3), page([current, classic], 1, 2, 3)];+ const parsed = normalizeSonarFindings(input, repository);+ expect(parsed.read).toBe(3);+ expect(parsed.excluded).toMatchObject([+ { position: 3, source_finding_id: "other" },+ ]);+ expect(parsed.findings.map((item) => item.source_finding_id)).toEqual([+ "issue-1",+ "classic",+ ]);+ expect(parsed.findings[1]!.evidence).toMatchObject({+ severity: "high",+ url: null,+ details: { source_status: "CONFIRMED" },+ });+ const updated = normalizeSonarFindings(+ page([+ {+ ...current,+ textRange: { startLine: 55, endLine: 55 },+ issueStatus: "FIXED",+ },+ ]),+ repository,+ );+ expect(updated.findings[0]!.source_finding_id).toEqual(+ parsed.findings[0]!.source_finding_id,+ );+ expect(updated.findings[0]!.evidence.details?.source_status).toEqual("FIXED");+ expect(() => normalizeSonarFindings(input, "")).toThrow(+ "source-repository-url",+ );+});++test("rejects missing, overlapping, or changed pages before importing any records", () => {+ const one = page([issue("one")], 1, 1, 2);+ const two = page([issue("two")], 2, 1, 2);+ for (const pages of [+ [one],+ [one, one],+ [one, page([], 2, 1, 2)],+ [one, { ...two, paging: { ...two.paging, total: 3 } }],+ ])+ expect(() => normalizeSonarFindings(capture(pages), repository)).toThrow(+ "every Sonar",+ );+ expect(() =>+ normalizeSonarFindings(+ capture([one, { ...two, issues: one.issues }]),+ repository,+ ),+ ).toThrow("overlap");+ const empty = normalizeSonarFindings(capture([page([])]), "");+ expect(empty).toMatchObject({+ read: 0,+ findings: [],+ report: { project, repositoryUrl: repository },+ });+});++test("validates the repository binding and native project or ref before attributing evidence", () => {+ const mixed = page([+ issue("main"),+ { ...issue("feature"), branch: "feature" },+ ]);+ expect(() => normalizeSonarFindings(mixed, repository)).toThrow(+ "without a ref",+ );+ expect(() =>+ normalizeSonarFindings(capture([page([issue()])]), repository + "-other"),+ ).toThrow("does not match");+ for (const field of [+ { project: "other" },+ { organization: "other" },+ { branch: "other" },+ { pullRequest: "2" },+ ]) {+ expect(() =>+ normalizeSonarFindings(+ capture([page([{ ...issue(), ...field }])]),+ repository,+ ),+ ).toThrow(/conflicting|mixes/);+ }+ const pr = {+ ...capture([page([{ ...issue(), pullRequest: "23" }])]),+ branch: undefined,+ pullRequest: "23",+ };+ const evidence = normalizeSonarFindings(pr, "").findings[0]!.evidence;+ expect(new URL(evidence.url!).searchParams.get("pullRequest")).toBe("23");+ expect(evidence.source_data?.["pullRequest"]).toBe("23");+ expect(evidence.branch).toBeNull();+});++test("normalized local imports verify both report and issue bindings against the checkout and projections", async () => {+ await using tmp = await scopedTemporaryDirectory("sonar-binding-");+ const checkout = join(tmp.path, "checkout");+ await mkdir(checkout);+ const environment = {+ ...sonarGitTestEnvironment(),+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+ CODEX_SECURITY_STATE_DIR: join(tmp.path, "state"),+ };+ const foreign = repository + "-other";+ const git = (...args: string[]) =>+ execFileSync("git", ["-C", checkout, ...args], { env: environment });+ git("init", "--quiet");+ git("remote", "add", "origin", foreign);+ const options = {+ repository: checkout,+ provider: "sonar",+ sourceKey: project,+ } as const;+ const deps = { environment };+ const { report, ...rows } = normalizeSonarFindings(+ capture([page([issue()])]),+ repository,+ "local",+ );+ const finding = rows.findings[0]!;+ delete finding.evidence.details;+ await expect(+ prepareNormalizedLocalImport(rows, options, deps),+ ).rejects.toThrow("does not match a configured remote");+ const reportOnly = { report, read: 0, excluded: [], findings: [] };+ await expect(+ prepareNormalizedLocalImport(reportOnly, options, deps),+ ).rejects.toThrow("does not match a configured remote");+ git("remote", "add", "upstream", repository);+ expect(+ (await prepareNormalizedLocalImport(rows, options, deps))+ .matchesRepositoryRemote,+ ).toBe(true);+ await expect(+ prepareNormalizedLocalImport(rows, { ...options, provider: "wiz" }, deps),+ ).rejects.toThrow("requires the sonar provider");+ const id = finding.source_finding_id;+ finding.source_finding_id = "different-issue";+ await expect(+ prepareNormalizedLocalImport(rows, options, deps),+ ).rejects.toThrow("retained Sonar issue key");+ finding.source_finding_id = id;+ const wrongBranch = {+ ...finding,+ evidence: { ...finding.evidence, branch: "unrelated" },+ };+ await expect(+ prepareNormalizedLocalImport(+ { ...rows, findings: [wrongBranch] },+ options,+ deps,+ ),+ ).rejects.toThrow("retained Sonar branch");+ const alternate = structuredClone(finding);+ alternate.source_finding_id = "other-key";+ const native = alternate.evidence.source_data!;+ native["project"] = "another-project";+ native["issue"] = { key: "other-key", project: "another-project" };+ await expect(+ prepareNormalizedLocalImport(+ { ...rows, report, findings: [finding, alternate] },+ options,+ deps,+ ),+ ).rejects.toThrow("conflicting project");+ finding.evidence.details = { kind: "sast", repository: { url: foreign } };+ await expect(+ prepareNormalizedLocalImport(rows, options, deps),+ ).rejects.toThrow("retained Sonar repository");+});++test("normalized Sonar rows share a ref only when each row or a common report supplies it", () => {+ for (const target of ["local", "cloud"] as const) {+ const unscoped = normalizeSonarFindings(+ page([issue("unscoped")]),+ repository,+ target,+ );+ for (const ref of [{ branch: "release" }, { pullRequest: "23" }]) {+ const named = normalizeSonarFindings(+ page([{ ...issue("named"), ...ref }]),+ repository,+ target,+ );+ for (const findings of [+ [...unscoped.findings, ...named.findings],+ [...named.findings, ...unscoped.findings],+ ]) {+ expect(() =>+ sonarRepositoryUrls("sonar", findings, undefined, target),+ ).toThrow("without a ref");+ expect(() =>+ sonarRepositoryUrls("sonar", findings, unscoped.report, target),+ ).toThrow("without a ref");+ expect(+ sonarRepositoryUrls("sonar", findings, named.report, target),+ ).toEqual(new Set([repository]));+ }+ }+ expect(+ sonarRepositoryUrls("sonar", unscoped.findings, undefined, target),+ ).toEqual(new Set([repository]));+ }+});++test("maps native component paths relative to a verified monorepo project base", () => {+ const raw = page([issue()]);+ const monorepo = { ...capture([raw]), projectBase: "packages/backend" };+ const finding = normalizeSonarFindings(monorepo, repository).findings[0]!;+ expect(finding.evidence.locations).toEqual([+ { path: "packages/backend/src/app.ts", line: 7 },+ ]);+ expect(finding.evidence.source_data?.["components"]).toEqual([+ primary,+ secondary,+ ]);+ expect(finding.evidence.source_data?.["projectBase"]).toBe(+ "packages/backend",+ );+ for (const input of [raw, { ...monorepo, projectBase: undefined }]) {+ const unknown = normalizeSonarFindings(input, repository).findings[0]!;+ expect(unknown.evidence.locations).toEqual([]);+ expect(unknown.evidence.source_data?.["components"]).toEqual([+ primary,+ secondary,+ ]);+ }+ for (const projectBase of ["../outside", "/absolute", "C:/absolute"]) {+ expect(() =>+ normalizeSonarFindings({ ...monorepo, projectBase }, repository),+ ).toThrow();+ }+});++test("keeps uncertainty about a source path in the evidence", () => {+ const raw = page([issue()]);+ raw.components[0] = { ...primary, path: "../outside/app.ts" };+ const result = normalizeSonarFindings(capture([raw]), repository);+ expect(result.excluded).toEqual([]);+ expect(result.findings[0]!.evidence.locations).toEqual([]);+ expect(result.findings[0]!.evidence.source_data?.["components"]).toEqual([+ raw.components[0],+ secondary,+ ]);+});++test("unknown Sonar ratings retain their native evidence locally and in Cloud", () => {+ const finding = {+ ...issue(),+ impacts: [{ softwareQuality: "SECURITY", severity: "UNRATED" }],+ };+ const input = page([finding]);+ const local = normalizeSonarFindings(input, repository, "local");+ expect(local.findings[0]?.evidence.severity).toBe("unknown");+ expect(local.findings[0]?.evidence.source_data?.["issue"]).toEqual(finding);+ const cloud = normalizeSonarFindings(input, repository, "cloud");+ expect(cloud.excluded).toEqual([]);+ expect(cloud.findings[0]?.evidence.severity).toBe("unknown");+ expect(cloud.findings[0]?.evidence.source_data?.["issue"]).toEqual(finding);+});diff --git a/sdk/typescript/tests-ts/sonar-import.test.ts b/sdk/typescript/tests-ts/sonar-import.test.tsnew file mode 100644index 000000000..12766ed38--- /dev/null+++ b/sdk/typescript/tests-ts/sonar-import.test.ts@@ -0,0 +1,839 @@+import { expect, spyOn, test } from "bun:test";+import { execFileSync } from "node:child_process";+import {+ chmod,+ copyFile,+ link,+ mkdir,+ open,+ readdir,+ readFile,+ rm,+ stat,+ symlink,+ writeFile,+} from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import { prepareSonarImport } from "../src/sonar-import.js";+import { prepareLocalExternalImport } from "../src/external-findings-import.js";+import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";+import {+ normalizeSonarFindings,+ parseSonarCapture,+} from "../src/sonar-findings.js";+import { scopedTemporaryDirectory } from "./support/temporary-directories.js";+import { sonarGitTestEnvironment } from "./support/sonar-import-fixtures.js";++const repositoryUrl = "https://github.com/example/project";++async function fixture(root: string, name = "checkout") {+ const checkout = join(root, name);+ const environment = {+ ...sonarGitTestEnvironment(),+ CODEX_HOME: join(root, "codex"),+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ const git = (...args: string[]) =>+ execFileSync("git", ["-C", checkout, ...args], { env: environment });+ await mkdir(checkout);+ git("init", "--quiet");+ git("remote", "add", "origin", repositoryUrl);+ const capture = join(checkout, "report.json");+ const report = {+ format: "sonar-issues/v1",+ server: "https://sonarcloud.io",+ organization: "example",+ project: "example_project",+ branch: "main",+ repositoryUrl,+ pages: [+ {+ paging: { pageIndex: 1, pageSize: 100, total: 1 },+ issues: [+ {+ key: "issue-1",+ project: "example_project",+ component: "example_project:service.ts",+ rule: "example:R1",+ type: "VULNERABILITY",+ severity: "CRITICAL",+ message: "Reviewed evidence",+ },+ ],+ },+ ],+ };+ await writeFile(capture, JSON.stringify(report));+ return {+ git,+ report,+ options: {+ cwd: checkout,+ capture,+ issueKeys: [],+ dryRun: true,+ yes: false,+ },+ deps: { environment },+ };+}++test("preview snapshots caller-owned evidence and rejects changes to the retained copy", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-preview-");+ const { report, options, deps } = await fixture(directory.path);+ const selection = { ...options, to: "local" } as const;+ const { info } = await prepareSonarImport(selection, deps);+ expect(info.capture).not.toBe(options.capture);+ report.pages[0]!.issues[0]!.message = "Changed evidence";+ await writeFile(options.capture, JSON.stringify(report));+ const replay = await prepareSonarImport(+ { ...selection, capture: info.capture },+ deps,+ );+ expect(replay.local.findings[0]!.evidence.description).toBe(+ "Reviewed evidence",+ );+ const changed = await prepareSonarImport(selection, deps);+ expect(changed.info.capture).not.toBe(info.capture);+ const alias = join(directory.path, "capture-alias");+ await symlink(dirname(info.capture), alias, "junction");+ await copyFile(options.capture, info.capture);+ await expect(+ prepareSonarImport(+ { ...selection, capture: join(alias, basename(info.capture)) },+ deps,+ ),+ ).rejects.toThrow("saved Sonar capture has changed");+ if (process.platform !== "win32") {+ const outsideAlias = join(directory.path, "latest.json");+ await symlink(info.capture, outsideAlias);+ await expect(+ prepareSonarImport({ ...selection, capture: outsideAlias }, deps),+ ).rejects.toThrow("saved Sonar capture has changed");+ await rm(info.capture);+ await symlink(changed.info.capture, info.capture);+ await expect(+ prepareSonarImport(+ { ...selection, capture: info.capture, yes: true, dryRun: false },+ deps,+ ),+ ).rejects.toThrow("saved Sonar capture has changed");+ }+});++test.skipIf(process.platform !== "linux")(+ "previews a capture from an unlinked regular file descriptor",+ async () => {+ await using directory = await scopedTemporaryDirectory("sonar-fd-");+ const { options, deps } = await fixture(directory.path);+ const file = await open(options.capture, "r");+ try {+ await link(options.capture, join(directory.path, "other-link.json"));+ await rm(options.capture);+ const unrelated = join(directory.path, "unrelated.json");+ await writeFile(unrelated, "unrelated contents");+ await symlink(unrelated, `${options.capture} (deleted)`);+ const preview = await prepareSonarImport(+ { ...options, to: "local", capture: `/proc/self/fd/${file.fd}` },+ deps,+ );+ expect(preview.local.findings[0]!.source_finding_id).toBe("issue-1");+ } finally {+ await file.close();+ }+ },+);++test.skipIf(process.platform !== "linux")(+ "reads a zero-link descriptor even when its deleted display name exceeds the filesystem limit",+ async () => {+ await using directory = await scopedTemporaryDirectory("sonar-fd-");+ const { options, deps } = await fixture(directory.path);+ const name = join(directory.path, "x".repeat(255));+ await copyFile(options.capture, name);+ const file = await open(name, "r");+ try {+ await rm(name);+ const preview = await prepareSonarImport(+ { ...options, to: "local", capture: `/proc/self/fd/${file.fd}` },+ deps,+ );+ expect(preview.local.findings[0]!.source_finding_id).toBe("issue-1");+ } finally {+ await file.close();+ }+ },+);++test.skipIf(process.platform !== "linux")(+ "checks an unlinked retained capture and accepts a literal deleted suffix",+ async () => {+ await using directory = await scopedTemporaryDirectory("sonar-fd-");+ const { options, deps, report } = await fixture(directory.path);+ const selection = { ...options, to: "local" } as const;+ const { info } = await prepareSonarImport(selection, deps);+ report.pages[0]!.issues[0]!.message = "Updated evidence";+ const bytes = JSON.stringify(report);+ const literal = `${info.capture} (deleted)`;+ await writeFile(literal, bytes);+ const updated = await prepareSonarImport(+ { ...selection, capture: literal },+ deps,+ );+ expect(updated.local.findings[0]!.evidence.description).toBe(+ "Updated evidence",+ );+ await writeFile(info.capture, bytes);+ const file = await open(info.capture, "r");+ try {+ await rm(info.capture);+ await expect(+ prepareSonarImport(+ { ...selection, capture: `/proc/self/fd/${file.fd}` },+ deps,+ ),+ ).rejects.toThrow("saved Sonar capture has changed");+ } finally {+ await file.close();+ }+ },+);++test.skipIf(process.platform !== "linux")(+ "requires the selected file's identity when procfs metadata is unavailable",+ async () => {+ await using directory =+ await scopedTemporaryDirectory("sonar-fd-identity-");+ const { options, deps } = await fixture(directory.path);+ const selection = { ...options, to: "local" } as const;+ const files = await import("node:fs/promises");+ const original = files.readlink;+ const target = await files.realpath(options.capture);+ let changeFile: (() => Promise<void>) | undefined;+ const lookup = spyOn(files, "readlink").mockImplementation((async (+ ...args: Parameters<typeof original>+ ) => {+ if (!String(args[0]).startsWith("/proc/self/fd/"))+ return original(...args);+ const change = changeFile;+ changeFile = undefined;+ await change?.();+ throw Object.assign(new Error("procfs access denied"), {+ code: "EACCES",+ });+ }) as typeof original);+ try {+ expect((await prepareSonarImport(selection, deps)).local.read).toBe(1);+ changeFile = async () => {+ await files.rename(target, `${target}.original`);+ await copyFile(`${target}.original`, target);+ };+ await expect(prepareSonarImport(selection, deps)).rejects.toThrow(+ "changed while being opened",+ );+ changeFile = () => rm(target);+ await expect(prepareSonarImport(selection, deps)).rejects.toThrow(+ "Could not verify the unlinked Sonar capture",+ );+ } finally {+ lookup.mockRestore();+ }+ },+);++test("confirming a local preview in another checkout requires previewing that checkout", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-local-review-");+ const first = await fixture(directory.path);+ const second = await fixture(directory.path, "second-checkout");+ const previewOptions = {+ ...first.options,+ to: "local",+ dryRun: true,+ } as const;+ const preview = await prepareSonarImport(previewOptions, first.deps);+ const alias = join(directory.path, "capture-alias");+ await symlink(dirname(preview.info.capture), alias, "junction");+ const moved = {+ ...previewOptions,+ cwd: second.options.cwd,+ capture: join(alias, basename(preview.info.capture)),+ };+ await expect(+ prepareSonarImport({ ...moved, yes: true, dryRun: false }, first.deps),+ ).rejects.toThrow("has not been reviewed for this checkout");+ const newState = {+ environment: {+ ...second.deps.environment,+ CODEX_SECURITY_STATE_DIR: join(directory.path, "other-state"),+ },+ };+ await expect(+ prepareSonarImport(+ {+ ...previewOptions,+ capture: preview.info.capture,+ yes: true,+ dryRun: false,+ },+ newState,+ ),+ ).rejects.toThrow("has not been reviewed for this checkout");+ const renewed = await prepareSonarImport(moved, first.deps);+ expect(renewed.info.capture).not.toBe(preview.info.capture);+ const confirmed = await prepareSonarImport(+ { ...moved, capture: renewed.info.capture, yes: true, dryRun: false },+ first.deps,+ );+ expect((await confirmed.import()).local.counts.created).toBe(1);+});++test("a portable capture supports interactive review but requires the returned local preview path with --yes", async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-portable-replay-",+ );+ const { options, deps } = await fixture(directory.path);+ const selection = { ...options, to: "local", dryRun: false } as const;+ await expect(+ prepareSonarImport({ ...selection, yes: true }, deps),+ ).rejects.toThrow("has not been reviewed for this checkout");+ const interactive = await prepareSonarImport(selection, deps);+ expect(interactive.local.findings).toHaveLength(1);+ expect(interactive.info.capture).not.toBe(options.capture);+ const callerPath = join(directory.path, "reviewed");+ await symlink(dirname(interactive.info.capture), callerPath, "junction");+ const confirmed = await prepareSonarImport(+ {+ ...selection,+ yes: true,+ capture: join(callerPath, basename(interactive.info.capture)),+ },+ deps,+ );+ expect(confirmed.info.capture).toBe(interactive.info.capture);+});++test("live import passes the expected repository to the collector before saving evidence", async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-expected-source-",+ );+ const { options, deps, report } = await fixture(directory.path);+ let source: string | undefined;+ await expect(+ prepareSonarImport(+ {+ ...options,+ capture: undefined,+ to: "local",+ sourceRepositoryUrl: repositoryUrl,+ },+ {+ ...deps,+ collect: async (selection) => {+ source = selection.sourceRepositoryUrl;+ throw new Error("Conflicting Sonar binding");+ },+ },+ ),+ ).rejects.toThrow("Conflicting Sonar binding");+ expect(source).toBe(repositoryUrl);+ expect(+ await stat(deps.environment.CODEX_SECURITY_STATE_DIR).catch(() => null),+ ).toBeNull();+ const success = await prepareSonarImport(+ {+ ...options,+ capture: undefined,+ to: "local",+ sourceRepositoryUrl: repositoryUrl,+ },+ { ...deps, collect: async () => parseSonarCapture(report) },+ );+ expect(await readdir(dirname(success.info.capture))).toEqual([+ basename(success.info.capture),+ ]);+});++test("Cloud confirmation verifies the retained evidence, account and assigned environment", async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-cloud-preview-",+ );+ const f = await fixture(directory.path);+ let account = "account-a";+ let environmentId = "env-a";+ let reportVersion = 0;+ const selection = { ...f.options, to: "cloud" } as const;+ const deps = {+ ...f.deps,+ credentials: async () => ({+ account_id: account,+ access_token: "synthetic",+ }),+ fetch: async (url: string, options: RequestInit) => {+ expect(options.method ?? "GET").toBe("GET");+ const repositories = new URL(url).pathname.endsWith("/repositories");+ return Response.json({+ object: "page",+ has_more: false,+ next: null,+ data: repositories+ ? [+ {+ id: "repo-a",+ repo_connector_id: "github",+ url: repositoryUrl,+ import_environment_id: environmentId,+ reset_marker: "generation-1",+ },+ ]+ : reportVersion+ ? [+ {+ id: `aif_${"a".repeat(64)}`,+ repo_id: "repo-a",+ repo_connector_id: "github",+ environment_id: environmentId,+ canonical_finding_id: `acf_${"b".repeat(32)}`,+ source: {+ provider: "sonar",+ source_key: new URL(url).searchParams.get("source_key"),+ },+ source_finding_id: "issue-1",+ observation_id: `aio_${"c".repeat(64)}`,+ version: reportVersion,+ title: "Reviewed evidence",+ severity: "high",+ source_updated_at: null,+ created_at: 1,+ updated_at: 2,+ },+ ]+ : [],+ });+ },+ };+ const preview = await prepareSonarImport(selection, deps);+ expect(preview.cloudError).toBeUndefined();+ const alias = join(directory.path, "cloud-capture-alias");+ await symlink(dirname(preview.info.capture), alias, "junction");+ const confirm = {+ ...selection,+ capture: join(alias, basename(preview.info.capture)),+ yes: true,+ dryRun: false,+ };+ expect((await prepareSonarImport(confirm, deps)).cloud).toBeDefined();+ reportVersion = 1;+ expect((await prepareSonarImport(confirm, deps)).cloudError).toContain(+ "--to cloud --dry-run",+ );+ reportVersion = 0;+ const copy = join(selection.cwd, basename(confirm.capture));+ await copyFile(confirm.capture, copy);+ await expect(+ prepareSonarImport({ ...confirm, capture: copy }, deps),+ ).rejects.toThrow("--to cloud --dry-run");+ const second = await fixture(directory.path, "second");+ await expect(+ prepareSonarImport({ ...confirm, cwd: second.options.cwd }, deps),+ ).rejects.toThrow("--to cloud --dry-run");+ account = "account-b";+ expect((await prepareSonarImport(confirm, deps)).cloudError).toContain(+ "--to cloud --dry-run",+ );+ const alternate = await prepareSonarImport(selection, deps);+ expect(alternate.info.capture).not.toBe(preview.info.capture);+ if (process.platform !== "win32") {+ const outsideAlias = join(selection.cwd, basename(preview.info.capture));+ await rm(outsideAlias);+ await symlink(alternate.info.capture, outsideAlias);+ await expect(+ prepareSonarImport({ ...confirm, capture: outsideAlias }, deps),+ ).rejects.toThrow("--to cloud --dry-run");++ // Replacing the reviewed entry itself cannot select a different account's approval.+ await rm(preview.info.capture);+ await symlink(alternate.info.capture, preview.info.capture);+ expect((await prepareSonarImport(confirm, deps)).cloudError).toContain(+ "--to cloud --dry-run",+ );+ }+ account = "account-a";+ environmentId = "env-b";+ expect((await prepareSonarImport(confirm, deps)).cloudError).toContain(+ "--to cloud --dry-run",+ );+ environmentId = "env-a";+ expect((await prepareSonarImport(confirm, deps)).cloud).toBeDefined();+ expect(await readFile(preview.info.capture, "utf8")).toBe(+ await readFile(alternate.info.capture, "utf8"),+ );+ f.git("remote", "set-url", "origin", "git@work:example/project.git");+ const mappedLocal = await prepareSonarImport(+ { ...selection, to: "local", sourceRepositoryUrl: repositoryUrl },+ deps,+ );+ const manual = await prepareSonarImport(+ { ...selection, capture: mappedLocal.info.capture },+ deps,+ );+ expect(manual.cloudError).toBeUndefined();+ expect(+ (+ await prepareSonarImport(+ { ...confirm, capture: manual.info.capture },+ deps,+ )+ ).cloud,+ ).toBeDefined();+});++test("only an explicit Sonar source can map a checkout's SSH alias", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-ssh-alias-");+ const { git, report, options, deps } = await fixture(directory.path);+ git(+ "remote",+ "set-url",+ "origin",+ "https://git.example.invalid/example/project.git",+ );+ git(+ "remote",+ "add",+ "upstream",+ "[email protected]:example/project.git",+ );+ const selected = { ...options, to: "local" } as const;+ const source = {+ repository: options.cwd,+ provider: "sonar",+ sourceKey: "example",+ } as const;+ const normalized = normalizeSonarFindings(report, "", "local");+ const mismatch = "does not match a configured remote";+ await expect(+ prepareNormalizedLocalImport(normalized, source, deps),+ ).rejects.toThrow(mismatch);+ await expect(+ prepareLocalExternalImport(options.capture, source, deps),+ ).rejects.toThrow(mismatch);+ const manual = { ...source, sourceRepositoryUrl: repositoryUrl };+ expect(+ (await prepareLocalExternalImport(options.capture, manual, deps))+ .matchesRepositoryRemote,+ ).toBe(false);+ const captures: string[] = [];+ await expect(+ prepareSonarImport(selected, {+ ...deps,+ onCapture: (path) => captures.push(path),+ }),+ ).rejects.toThrow(mismatch);+ expect(captures).toHaveLength(1);+ await expect(+ prepareSonarImport({ ...selected, capture: captures[0] }, deps),+ ).rejects.toThrow(mismatch);+ const preview = await prepareSonarImport(+ { ...selected, capture: captures[0], sourceRepositoryUrl: repositoryUrl },+ deps,+ );+ expect(preview.info.capture).not.toBe(captures[0]);+ const replay = await prepareSonarImport(+ { ...selected, capture: preview.info.capture, dryRun: false, yes: true },+ deps,+ );+ expect(replay.info.capture).toBe(preview.info.capture);+ expect(replay.local.read).toBe(1);+ git("remote", "set-url", "upstream", "git@another-host:example/project.git");+ await expect(+ prepareSonarImport(+ { ...selected, capture: preview.info.capture, dryRun: false, yes: true },+ deps,+ ),+ ).rejects.toThrow("has not been reviewed for this checkout");+ const renewed = await prepareSonarImport(+ {+ ...selected,+ capture: preview.info.capture,+ sourceRepositoryUrl: repositoryUrl,+ },+ deps,+ );+ expect(renewed.info.capture).not.toBe(preview.info.capture);+});++test("replays a manually bound capture using the native branch as its identity", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-binding-");+ const { report, options, deps } = await fixture(directory.path);+ const { branch, repositoryUrl: url, ...unbound } = report;+ Object.assign(unbound.pages[0]!.issues[0]!, { branch });+ await writeFile(options.capture, JSON.stringify(unbound));+ const selected = { ...options, to: "local" } as const;+ const mapped = await prepareSonarImport(+ { ...selected, sourceRepositoryUrl: url },+ deps,+ );+ const replay = await prepareSonarImport(+ { ...selected, capture: mapped.info.capture },+ deps,+ );+ await writeFile(options.capture, JSON.stringify(report));+ const bound = await prepareSonarImport(selected, deps);+ expect(replay.info.capture).toBe(mapped.info.capture);+ expect(replay.info.branch).toBe(branch);+ expect(replay.info.sourceKey).toBe(bound.info.sourceKey);+});++test("a reviewed mapping follows each remote's primary fetch URL", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-fetch-url-");+ const { git, options, deps } = await fixture(directory.path);+ deps.environment.GIT_CONFIG_GLOBAL = join(directory.path, "global.gitconfig");+ git("config", "--global", "url.git@work:example/.insteadOf", "work:");+ const project = "work:project.git";+ const fork = "git@other:example/fork.git";+ git("remote", "set-url", "origin", project);+ git("config", "--add", "remote.origin.url", fork);+ const selection = { ...options, to: "local" } as const;+ const preview = await prepareSonarImport(+ { ...selection, sourceRepositoryUrl: repositoryUrl },+ deps,+ );+ const confirm = {+ ...selection,+ capture: preview.info.capture,+ dryRun: false,+ yes: true,+ };+ expect((await prepareSonarImport(confirm, deps)).info.capture).toBe(+ preview.info.capture,+ );++ git("config", "--unset-all", "remote.origin.url");+ git("config", "--add", "remote.origin.url", fork);+ git("config", "--add", "remote.origin.url", project);+ await expect(prepareSonarImport(confirm, deps)).rejects.toThrow(+ "has not been reviewed for this checkout",+ );+ await expect(+ prepareSonarImport(+ { ...selection, sourceRepositoryUrl: repositoryUrl },+ deps,+ ),+ ).rejects.toThrow("does not match a configured remote");+});++test("a dry run cannot create the capture directory inside a checkout or its linked Git metadata", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-protected-");+ const { options, deps, git } = await fixture(directory.path, "imports");+ const selected = { ...options, to: "local" } as const;+ deps.environment.CODEX_SECURITY_STATE_DIR = directory.path;+ await expect(prepareSonarImport(selected, deps)).rejects.toThrow();+ expect(+ await stat(join(directory.path, "imports", "sonar")).catch(() => null),+ ).toBeNull();++ const other = join(directory.path, "linked");+ git(+ "-c",+ "user.name=Example",+ "-c",+ "[email protected]",+ "commit",+ "--quiet",+ "--allow-empty",+ "-m",+ "initial",+ );+ git("worktree", "add", "--quiet", "--detach", other);+ const state = join(options.cwd, ".git", "state");+ deps.environment.CODEX_SECURITY_STATE_DIR = state;+ await expect(+ prepareSonarImport({ ...selected, cwd: other }, deps),+ ).rejects.toThrow();+ expect(await stat(state).catch(() => null)).toBeNull();+});++test("rejects a Cloud checkpoint directory inside the checkout before contacting Cloud", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-checkpoints-");+ const { options, deps } = await fixture(+ directory.path,+ "external-finding-publications",+ );+ deps.environment.CODEX_SECURITY_STATE_DIR = directory.path;+ const result = await prepareSonarImport(+ { ...options, to: "cloud" },+ {+ ...deps,+ credentials: async () => {+ throw new Error("Unexpected Cloud call");+ },+ },+ );+ expect(result.cloudError).toContain(options.cwd);+ expect(result.cloud).toBeUndefined();+});++test("rejects an in-checkout state symlink pointing to an outside directory", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-state-link-");+ const { options, deps } = await fixture(directory.path);+ const outside = join(directory.path, "private");+ await mkdir(outside, { mode: 0o700 });+ const link = join(options.cwd, "state");+ await symlink(outside, link, "junction");+ deps.environment.CODEX_SECURITY_STATE_DIR = link;+ await expect(+ prepareSonarImport({ ...options, to: "local" }, deps),+ ).rejects.toThrow();+ expect(await stat(join(outside, "imports")).catch(() => null)).toBeNull();+});++test("reports the saved evidence after preparation fails", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-saved-path-");+ const { options, deps, report } = await fixture(directory.path);+ const captures: string[] = [];+ await expect(+ prepareSonarImport(+ { ...options, to: "cloud", yes: true, dryRun: false },+ {+ ...deps,+ onCapture(path) {+ captures.push(path);+ },+ },+ ),+ ).rejects.toThrow("--to cloud --dry-run");+ expect(captures).toHaveLength(1);+ expect(JSON.parse(await readFile(captures[0]!, "utf8"))).toEqual(report);+});++test("recovers a completed live selection after a Git mapping error", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-git-recovery-");+ const { options, deps, report } = await fixture(directory.path);+ const config = join(options.cwd, ".git", "config");+ const original = await readFile(config);+ await writeFile(config, "[invalid\n");+ const paths: string[] = [];+ await expect(+ prepareSonarImport(+ {+ ...options,+ capture: undefined,+ project: report.project,+ sourceRepositoryUrl: repositoryUrl,+ to: "local",+ },+ {+ ...deps,+ collect: async () => parseSonarCapture(report),+ onCapture: (path) => paths.push(path),+ },+ ),+ ).rejects.toThrow("config");+ expect(paths).toHaveLength(1);+ const capture = paths[0]!;+ expect(JSON.parse(await readFile(capture, "utf8"))).toEqual(report);+ await writeFile(config, original);+ const replay = {+ ...options,+ capture,+ sourceRepositoryUrl: repositoryUrl,+ to: "local",+ } as const;+ await expect(+ prepareSonarImport({ ...replay, dryRun: false, yes: true }, deps),+ ).rejects.toThrow("not been reviewed for this checkout");+ const reviewed = await prepareSonarImport(replay, deps);+ expect(reviewed.info.capture).not.toBe(capture);+ expect(reviewed.local.read).toBe(1);+});++test("recovers live evidence if its checkout-specific capture cannot be written", async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-write-recovery-",+ );+ const { options, deps, report } = await fixture(directory.path);+ const selected = {+ ...options,+ to: "local",+ sourceRepositoryUrl: repositoryUrl,+ } as const;+ const reviewed = (await prepareSonarImport(selected, deps)).info.capture;+ await rm(reviewed);+ await mkdir(reviewed);+ const paths: string[] = [];+ await expect(+ prepareSonarImport(+ { ...selected, capture: undefined, project: report.project },+ {+ ...deps,+ collect: async () => parseSonarCapture(report),+ onCapture: (path) => paths.push(path),+ },+ ),+ ).rejects.toThrow();+ expect(paths).toHaveLength(1);+ expect(basename(paths[0]!)).toMatch(/^[0-9a-f]{64}\.json$/);+ expect(JSON.parse(await readFile(paths[0]!, "utf8"))).toEqual(report);+});++test("rejects a non-finite native JSON number before snapshotting a capture", async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-numeric-evidence-",+ );+ const { report, options, deps } = await fixture(directory.path);+ await writeFile(+ options.capture,+ JSON.stringify(report).replace(+ '"Reviewed evidence"',+ '"Reviewed evidence","value":1e400',+ ),+ );+ await expect(+ prepareSonarImport({ ...options, to: "local" }, deps),+ ).rejects.toThrow("finite JSON numbers");+ expect(+ await stat(deps.environment.CODEX_SECURITY_STATE_DIR).catch(() => null),+ ).toBeNull();+});++test.skipIf(process.platform === "win32")(+ "rejects a pre-existing shared capture directory",+ async () => {+ await using directory = await scopedTemporaryDirectory(+ "sonar-capture-permissions-",+ );+ const { options, deps } = await fixture(directory.path);+ const root = join(+ deps.environment.CODEX_SECURITY_STATE_DIR,+ "imports",+ "sonar",+ );+ await mkdir(root, { recursive: true, mode: 0o700 });+ await chmod(root, 0o777);+ await expect(+ prepareSonarImport({ ...options, to: "local" }, deps),+ ).rejects.toThrow();+ },+);++test("a clean Sonar project needs no Cloud credentials or upload", async () => {+ await using directory = await scopedTemporaryDirectory("sonar-clean-");+ const { report, options, deps } = await fixture(directory.path);+ report.pages[0]!.issues = [];+ report.pages[0]!.paging.total = 0;+ await writeFile(options.capture, JSON.stringify(report));+ let cloudCalls = 0;+ const unexpectedCloudCall = async (): Promise<never> => {+ cloudCalls++;+ throw new Error("Unexpected Cloud call");+ };+ const prepared = await prepareSonarImport(+ { ...options, to: "cloud", dryRun: false, yes: true },+ { ...deps, credentials: unexpectedCloudCall, fetch: unexpectedCloudCall },+ );+ const result = await prepared.import();+ expect(result.cloudError).toBeUndefined();+ expect(result.cloud).toBeUndefined();+ expect(result.local.ready).toBe(0);+ expect(cloudCalls).toBe(0);+});diff --git a/sdk/typescript/tests-ts/support/empty.gitconfig b/sdk/typescript/tests-ts/support/empty.gitconfignew file mode 100644index 000000000..8e609675e--- /dev/null+++ b/sdk/typescript/tests-ts/support/empty.gitconfig@@ -0,0 +1 @@+# Empty global Git config for isolated test repositories.diff --git a/sdk/typescript/tests-ts/support/sonar-import-fixtures.ts b/sdk/typescript/tests-ts/support/sonar-import-fixtures.tsnew file mode 100644index 000000000..4cdfa02e0--- /dev/null+++ b/sdk/typescript/tests-ts/support/sonar-import-fixtures.ts@@ -0,0 +1,16 @@+import { fileURLToPath } from "node:url";++/** Use only the temporary checkout's Git configuration in Sonar import tests. */+export function sonarGitTestEnvironment(base: NodeJS.ProcessEnv = process.env) {+ return {+ ...Object.fromEntries(+ Object.entries(base).filter(+ ([name]) => !name.toUpperCase().startsWith("GIT_"),+ ),+ ),+ GIT_CONFIG_GLOBAL: fileURLToPath(+ new URL("./empty.gitconfig", import.meta.url),+ ),+ GIT_CONFIG_NOSYSTEM: "1",+ };+}