Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

feat(import): ingest GitHub Dependabot repository alerts (#2096)

Michael D'Angeloee3f56d4372c
diff --git a/docs/scanner-imports/github-dependabot.md b/docs/scanner-imports/github-dependabot.md
new file mode 100644
index 000000000..f7dbbea1f
--- /dev/null
+++ b/docs/scanner-imports/github-dependabot.md
@@ -0,0 +1,61 @@
+# Import GitHub Dependabot repository alerts
+
+A Dependabot alert identifies a vulnerable dependency in one repository. Its GHSA
+describes the affected software. GitHub code scanning and published security
+advisories have separate import formats.
+
+## Export one repository
+
+Use a fine-grained token or GitHub App installation with **Dependabot alerts: read**
+for the repository. The GitHub CLI reads the alerts. Codex Security imports the
+saved file offline. Keep the export outside the checkout.
+
+```bash
+set -eu
+umask 077
+out=$(mktemp -d)
+gh api --hostname github.com --method GET --paginate \
+ -H 'Accept: application/vnd.github+json' \
+ -H 'X-GitHub-Api-Version: 2022-11-28' \
+ --jq 'if type == "array" then tojson else error("expected an alert page") end' \
+ 'repos/OWNER/REPO/dependabot/alerts?per_page=100' > "$out/pages.tmp"
+test -s "$out/pages.tmp"
+mv "$out/pages.tmp" "$out/dependabot.jsonl"
+```
+
+Replace the hostname and `OWNER/REPO` in both examples. The command follows every
+page and includes open, fixed, dismissed, and auto-dismissed alerts. Each line
+contains one page, including `[]` for an empty collection. If a request fails,
+check repository access before retrying.
+
+## Preview and import
+
+```bash
+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
+codex-security publish findings "$out/dependabot.jsonl" \
+ --to local --repository ./project --provider github \
+ --source-key github.com/OWNER/REPO/dependabot --dry-run --format json
+```
+
+Review the destination, ready records, and exclusions, then remove `--dry-run`.
+Use `--to cloud` with an authorized repository ID or URL for Cloud publication.
+For a local checkout, the alert repository must match a configured network
+remote when one is available. If the checkout has only filesystem remotes or
+no remote, verify the export belongs to it before importing.
+
+Keep the export and reuse its source key for the same repository. The host,
+repository, and alert number identify an occurrence. Two alerts for the same
+GHSA keep separate histories. A later selection updates the alerts it includes
+and leaves omitted alerts in place.
+
+Each finding records the matched package, ecosystem, manifest path, vulnerable
+version range, first patched version when available, and advisory IDs. The
+native alert retains GitHub’s state and timestamps. An alert identifies a
+manifest dependency without establishing the installed version, an affected
+line, or a Codex assessment. The importer rejects conflicts between alert
+identities, affected packages, or ranges, and requires repository-relative
+manifest paths.
+
+Read local evidence with `codex-security findings imported ./project --format json`.
+See the [GitHub Dependabot alerts endpoint](https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-a-repository)
+and the [GitHub CLI pagination options](https://cli.github.com/manual/gh_api).
diff --git a/docs/scanner-imports/schema-guide.md b/docs/scanner-imports/schema-guide.md
index 8459b020b..221a122c7 100644
--- a/docs/scanner-imports/schema-guide.md
+++ b/docs/scanner-imports/schema-guide.md
@@ -1,7 +1,7 @@
# How saved scanner reports map to imported evidence
-This guide covers the Wiz, Endor Labs, Snyk Open Source, Semgrep Code and GitHub
-**file readers** used by `publish findings`. Acquisition produces the artifact:
+The **reader** selected by `publish findings --provider` interprets a saved
+scanner export. Acquisition produces the artifact:
for example, `snyk test` scans a workspace, while `codex-security import github`
retrieves selected code-scanning alerts. File ingestion reads the saved report.
Use the mappings to decide what one record represents, whether a later export
@@ -25,6 +25,7 @@ to investigate records together, not instructions to merge them.
| [Endor Finding JSON or endorctl SARIF](endor.md) | Finding `uuid` or SARIF `properties["finding-uuid"]` | Namespace, project and context |
| [Snyk Open Source CLI JSON, plugin v1 or SARIF](snyk.md) | CLI: manager, manifest, advisory, package/version and dependency path; plugin: supplied composite; SARIF: advisory, manifest set and project when known | Repository, branch, scan target and format |
| [Semgrep Code CLI/CI JSON or SARIF](semgrep.md) | Fingerprint; otherwise rule, literal path and start/end lines and columns | Organization, project and branch |
+| [GitHub Dependabot repository REST alerts](github-dependabot.md) | Host, repository and alert number | Host, repository and Dependabot family |
| [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 |
@@ -83,8 +84,12 @@ before preparing a fresh submission.
instance state. For GHSA, a repository disclosure identifies its publisher; a
global disclosure has no source repository. Both can carry CVE aliases,
affected ranges and patched versions. Neither proves installation or
- applicability. Raw API pages, Dependabot and secret-scanning alerts are not
- these saved inputs.
+ applicability. Both readers require saved collector output.
+- **GitHub Dependabot.** Use `gh api --paginate` to save native repository
+ alert pages as JSONL for the `github` reader. Each alert identifies the
+ matched package, manifest and vulnerable range. The embedded advisory supplies advisory IDs.
+ Each alert number has its own history, including when several alerts cite the
+ same GHSA. GitHub secret-scanning alerts remain outside the file reader.
## Read the right field
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index 2d8d094df..24965a420 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -1,6 +1,6 @@
---
name: publish-findings
-description: Requires explicit opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Preview and import supported findings from Snyk Open Source, Semgrep Code, OpenGrep, Endor Labs, GitHub, or Wiz into the local workbench or Codex Security Cloud. Use each provider's documented native JSON, SARIF, plugin bundle, JSONL or CSV format, including gzip-compressed reports.
+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.
---
# Publish external findings
@@ -86,10 +86,12 @@ Import native OpenGrep JSON with `--provider opengrep`, `--source-repository-url
## GitHub alerts and advisories
-Acquire 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 an import envelope from MCP summaries; raw MCP/API responses are not accepted by `--provider github`.
+Acquire 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.
The importer uses the user's GitHub CLI authentication and `GH_HOST`; plugin authentication is separate. It defaults to open alerts on the default branch. Use repeated `--github-alert NUMBER` for exact alerts or `--github-ref REF` for another ref. Save complete output without field/token filters or `--full-output`. Reading code-scanning alerts requires a token with Code scanning alerts read permission (classic: `security_events`, or `public_repo` for public repositories), along with repository access.
+For Dependabot, follow the [repository alert export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md) to save the native REST alert records from one repository. The read-only export requires Dependabot alerts read permission. Preview the file with `publish findings FILE --provider github`, the intended destination and a separate source key such as `github.com/example/project/dependabot`.
+
**GHSA import stages advisory evidence for investigation; it does not establish an installed dependency or applicability to the destination repository.** Keep advisories separate from code scanning. `codex-security import github-advisories OWNER/REPO --format json` reads published repository disclosures by default. Repeated `--github-advisory GHSA-xxxx-xxxx-xxxx` selects exact IDs; `--github-state draft|triage|closed` explicitly selects an unpublished list and cannot be combined with exact IDs. Add `--github-advisory-source global` for exact public database IDs. This does not enumerate the global database. Private advisory access needs Repository security advisories read permission and access to those records. Stop on a read failure instead of publishing an incomplete selection.
```sh
@@ -111,7 +113,7 @@ codex-security publish findings /path/to/advisories.json \
Choose the local or Cloud preview for the intended destination. GHSA input supports the same choice: use `--to local --repository /path/to/project` with the advisory file and source key. Follow [local imports](#import-locally) for confirmation and readback or [Cloud publication](#publish-to-cloud) for upload review.
-Use separate stable source keys for the two families. Code-scanning identities include the ref; repository alerts and advisories must match the selected Cloud repository or, when available, a configured local Git remote. Global advisories omit source-repository provenance and are bound to the explicit local or Cloud destination for investigation. Preserve original evidence, package ranges and patches; do not infer installed packages or source locations from an advisory. Missing security severity stays `unknown`. Dismissal, resolution and withdrawal are source state, not Codex assessment. This path does not import Dependabot or secret-scanning alerts or write back to GitHub.
+Use a separate stable source key for each GitHub finding family. Code-scanning identities include the ref; repository alerts and advisories must match the selected Cloud repository or, when available, a configured local Git remote. Global advisories omit source-repository provenance and are bound to the explicit local or Cloud destination for investigation. Preserve original evidence, package ranges and patches; do not infer installed packages or source locations from an advisory. Missing security severity stays `unknown`. Dismissal, resolution and withdrawal are source state, not Codex assessment. Secret-scanning alerts and writeback to GitHub are outside this workflow.
## Publish to Cloud
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index b696090a2..93d40045d 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -679,13 +679,13 @@ repository package vulnerabilities (SCA) only; it does not add SAST, CSPM or
complete code-to-cloud coverage. Both formats support gzip. The acquisition path
still needs validation with an authorized Wiz tenant.
-For GitHub, save complete JSON from `import github` or `import github-advisories`;
-the configured GitHub plugin can help select alerts before collection. The
-[separate readers and mappings](docs/cli.md#import-github-findings-locally-or-to-cloud)
-retain code-scanning evidence or GHSA disclosures. **GHSA import does not
-establish an installed dependency or applicability to the repository.** This
-integration does not import Dependabot or secret-scanning alerts or write back
-to GitHub.
+For GitHub code scanning and GHSA advisories, save complete JSON from
+`import github` or `import github-advisories`, respectively. **GHSA import
+does not establish an installed dependency or applicability to the repository.**
+For Dependabot, save the native REST alert records from one repository using the
+[Dependabot export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md).
+The GitHub file reader accepts all three families. Secret-scanning alerts and
+writeback to GitHub are outside its scope.
Use `publish findings FILE --to local --repository PATH --provider wiz
--source-key KEY` to store the same vendor evidence in the local workbench SQLite
@@ -701,7 +701,7 @@ Use `--provider endor` with native Endor Finding JSON; existing endorctl SARIF i
accepted as a lossy compatibility format. See
[Endor imports](docs/cli.md#import-endor-labs-findings).
-For saved GitHub code-scanning alerts or GHSA advisories, use
+For saved GitHub code-scanning alerts, GHSA advisories, or Dependabot alerts, use
`--provider github` with a separate stable source key for each finding family.
See [local imports](docs/cli.md#import-vendor-findings-locally).
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index d64f87140..cf4448a4f 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1306,7 +1306,8 @@ Wiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-finding
[Endor Labs Finding JSON and SARIF](#import-endor-labs-findings),
[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),
[OpenGrep native JSON](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md),
-and [saved GitHub alerts and GHSA advisories](#import-github-findings-locally-or-to-cloud):
+[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):
```bash
codex-security publish findings selected-wiz.json \
@@ -2434,10 +2435,12 @@ Acquire code-scanning findings with the existing `import github` collector and
save its complete JSON output. In Codex, the official
[GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github)
can help select the repository, alert numbers and ref through GitHub's MCP
-server; pass that selection to the collector. This integration reads
-code-scanning alerts and GHSA advisories. It does not import Dependabot or
-secret-scanning alerts or write back to GitHub. Preview local storage with a
-repository path:
+server. Pass that selection to the collector. For Dependabot, use
+the [repository alert export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md)
+to save the native REST records from one repository and preview them with
+`--provider github`. For GHSA disclosures, use the
+[advisory collector](#import-ghsa-advisories-separately).
+The following example previews local storage of a code-scanning export.
```bash
codex-security import github example/project --format json > /path/outside/repository/alerts.json
@@ -2458,8 +2461,8 @@ The importer fetches every page, retrieves alert details, and retains the select
ref's instance. It writes the saved input for publication; no website download or
hand-written JSON mapping is needed. Use `--github-alert NUMBER` repeatedly for
selected alerts or `--github-ref REF` for another ref. Defaults are open alerts on
-the default branch. MCP list calls are paginated separately, and raw MCP/API
-responses are not the saved import format accepted by `--provider github`.
+the default branch. MCP list calls are paginated separately. Code-scanning
+imports require the saved collector output, which includes the selected instance.
The importer uses GitHub CLI authentication (`gh auth login`) and `GH_HOST`;
the plugin's connection does not sign in `gh`. Reading alerts requires
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 847d4010f..c43434cd9 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -71,7 +71,9 @@ const distModules = [
"git-remote",
"github",
"github-advisories",
+ "github-dependabot-findings",
"github-findings",
+ "github-identifiers",
"host-records-protocol",
"index",
"import-scan",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 37db9ad43..bd4eb7661 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -219,6 +219,7 @@ import {
ScanCostLimitExceededError,
ScanInterruptedError,
} from "./errors.js";
+import { GHSA_ID } from "./github-identifiers.js";
import {
GITHUB_ADVISORY_STATES,
importGitHubAdvisories,
@@ -3545,15 +3546,15 @@ export async function main(
function registerFindingPublication() {
publication.command("findings", {
description:
- "Preview and import selected Wiz, Snyk, Semgrep Code, OpenGrep, Endor, or GitHub findings locally or to Cloud.",
- hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For OpenGrep, supply native JSON and --source-repository-url; imports use the semgrep storage provider and preserve OpenGrep as the scanner origin. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
+ "Preview and import a saved scanner report locally or to Cloud.",
+ hint: "Choose the reader with --provider and keep --source-key stable for reimports. See the scanner import guide for accepted formats, repository requirements and export examples: https://github.com/openai/codex-security/blob/main/docs/scanner-imports/schema-guide.md. Gzip is supported. --to local stores unassessed evidence without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
destructive: true,
mcp: false,
args: z.object({
file: z
.string()
.describe(
- "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; OpenGrep native JSON; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",
+ "Saved report in a format accepted by the selected reader.",
),
}),
options: z.object({
@@ -3566,7 +3567,7 @@ export async function main(
provider: z
.enum(EXTERNAL_FINDINGS_READERS)
.describe(
- "Report reader; OpenGrep uses the semgrep storage provider.",
+ "Select the file reader for this report. OpenGrep findings use the semgrep storage provider.",
),
sourceRepositoryUrl: optionValue("--source-repository-url")
.optional()
@@ -3956,7 +3957,7 @@ export async function main(
githubAdvisory: z
.array(
optionValue("--github-advisory").regex(
- /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu,
+ GHSA_ID,
"GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",
),
)
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index d56c7e8a2..4163473cc 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -22,6 +22,7 @@ import type {
} from "./external-import-models.js";
import { parseGitRemote } from "./git-remote.js";
import { isRecord } from "./record.js";
+import { dependabotRepository } from "./github-dependabot-findings.js";
import {
bundledPluginRoot,
canonicalConfigPath,
@@ -492,6 +493,7 @@ export async function prepareNormalizedLocalImport(
requireIdentity(options.sourceKey, "Source key");
const current = structuredClone(input);
validateExternalReport(current.report);
+ let dependabotSource: string | undefined;
const identities = new Set<string>();
for (const finding of current.findings) {
requireIdentity(finding.source_finding_id, "Source finding id");
@@ -502,6 +504,22 @@ export async function prepareNormalizedLocalImport(
identities.add(finding.source_finding_id);
if (!isRecord(finding.evidence))
throw new CodexSecurityError("Imported evidence must be an object.");
+ if (options.provider !== "github") continue;
+ const native = dependabotRepository(finding);
+ if (!native) continue;
+ const claimed = finding.evidence.details?.repository?.url;
+ if (
+ claimed &&
+ cloudRepositoryUrlKey(claimed) !== cloudRepositoryUrlKey(native)
+ )
+ throw new CodexSecurityError(
+ "The normalized repository does not match the original Dependabot alert.",
+ );
+ if (dependabotSource && dependabotSource !== native)
+ throw new CodexSecurityError(
+ "Select Dependabot alerts from only one GitHub host and repository.",
+ );
+ dependabotSource = native;
}
const { repository, options: workbenchOptions } = await localContext(
options.repository,
@@ -517,6 +535,11 @@ export async function prepareNormalizedLocalImport(
if (sources.get(source.url)?.platform !== "github")
sources.set(source.url, source);
}
+ if (dependabotSource)
+ sources.set(dependabotSource, {
+ url: dependabotSource,
+ platform: "github",
+ });
await requireMatchingRepository(
repository,
options.provider,
diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.ts
index 1779b6392..19db12b22 100644
--- a/sdk/typescript/src/external-findings-publish.ts
+++ b/sdk/typescript/src/external-findings-publish.ts
@@ -32,6 +32,7 @@ import {
} from "./external-findings-read.js";
import { canonicalJson } from "./record.js";
import { wizCsvRepositoryUrl } from "./wiz-csv.js";
+import { dependabotRepository } from "./github-dependabot-findings.js";
import { snykRepositoryUrls } from "./snyk-findings.js";
import { endorRepositoryUrls } from "./endor-findings.js";
import type {
@@ -742,6 +743,9 @@ async function preparePublicationInput(
...(options.provider === "endor"
? endorRepositoryUrls(finding.evidence.source_data)
: []),
+ options.provider === "github"
+ ? dependabotRepository(finding)
+ : undefined,
];
for (const sourceRepository of sourceRepositories)
if (
@@ -857,9 +861,6 @@ async function preparePublicationInput(
};
const preview: ExternalPublicationPreview = {
...parsed,
- ...(parsed.report === undefined
- ? {}
- : { report: structuredClone(parsed.report) }),
findings: submissionFindings(requests),
cloudApiUrl,
cloudUrl: cloudFindingsUrl(environment, destination.id),
@@ -870,7 +871,7 @@ async function preparePublicationInput(
requests,
};
return {
- preview,
+ preview: structuredClone(preview),
async publish() {
progress({ phase: "waiting", completed: 0 });
const result = (
diff --git a/sdk/typescript/src/github-advisories.ts b/sdk/typescript/src/github-advisories.ts
index 6391c1f4e..d7456e6e5 100644
--- a/sdk/typescript/src/github-advisories.ts
+++ b/sdk/typescript/src/github-advisories.ts
@@ -1,4 +1,8 @@
import type { Octokit } from "@octokit/core";
+import {
+ CANONICAL_GHSA_ID,
+ githubRepositoryParts,
+} from "./github-identifiers.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { requireExternalImports } from "./external-imports-feature.js";
import { createAuthenticatedGitHub } from "./github.js";
@@ -55,11 +59,10 @@ export async function importGitHubAdvisories(
const environment = dependencies.environment ?? process.env;
requireExternalImports(environment);
const repository = options.repository.trim();
- const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);
- if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
+ const parts = githubRepositoryParts(repository);
+ if (!parts)
throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
- const owner = parts[1]!;
- const repo = parts[2]!;
+ const [owner, repo] = parts;
const ids = [
...new Set(
(options.advisoryIds ?? []).map((id) =>
@@ -70,7 +73,7 @@ export async function importGitHubAdvisories(
),
),
];
- if (ids.some((id) => !/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u.test(id)))
+ if (ids.some((id) => !CANONICAL_GHSA_ID.test(id)))
throw new CodexSecurityError(
"GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",
);
diff --git a/sdk/typescript/src/github-dependabot-findings.ts b/sdk/typescript/src/github-dependabot-findings.ts
new file mode 100644
index 000000000..533606cf9
--- /dev/null
+++ b/sdk/typescript/src/github-dependabot-findings.ts
@@ -0,0 +1,349 @@
+import { z } from "zod";
+import { GHSA_ID, githubRepositoryParts } from "./github-identifiers.js";
+import { CodexSecurityError, errorMessage } from "./errors.js";
+import {
+ type ExternalImportTarget,
+ validateExternalEvidence,
+} from "./external-import-contract.js";
+import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
+import { isGitHubCloudHost } from "./git-remote.js";
+import { isRecord } from "./record.js";
+import { record, relativePath, requiredText, text } from "./scanner-import.js";
+
+export function isGitHubDependabotAlert(
+ value: unknown,
+): value is Record<string, unknown> {
+ return (
+ isRecord(value) &&
+ ("security_vulnerability" in value ||
+ ("dependency" in value && "security_advisory" in value) ||
+ [value["url"], value["html_url"]].some(
+ (url) =>
+ typeof url === "string" &&
+ /^\/(?:[^/]+\/[^/]+\/security\/dependabot|(?:api\/v3\/)?repos\/[^/]+\/[^/]+\/dependabot\/alerts)\/\d+$/iu.test(
+ URL.parse(url)?.pathname ?? "",
+ ),
+ ))
+ );
+}
+
+function webIdentity(url: string) {
+ const match =
+ /^(https?):\/\/([^/?#@\\\s]+)\/([^/?#]+\/[^/?#]+)\/security\/dependabot\/([1-9]\d*)$/iu.exec(
+ url,
+ );
+ if (!match || !githubRepositoryParts(match[3]!)) return null;
+ const parsed = URL.parse(url);
+ if (
+ !parsed ||
+ (parsed.protocol === "http:" && isGitHubCloudHost(parsed.hostname))
+ )
+ return null;
+ const host = match[2]!.toLowerCase();
+ const repository = match[3]!.toLowerCase();
+ const origin = `${parsed.protocol}//${host}`;
+ const number = match[4]!;
+ const apiBase = isGitHubCloudHost(parsed.hostname)
+ ? `https://api.${host}`
+ : `${origin}/api/v3`;
+ const repositoryUrl = `${origin}/${repository}`;
+ const apiRepo = `${apiBase}/repos/${repository}`;
+ return {
+ repository,
+ repositoryUrl,
+ apiRepo,
+ number,
+ sourceId: `${host}/${repository}/dependabot/${number}`,
+ htmlUrl: `${repositoryUrl}/security/dependabot/${number}`,
+ apiUrl: `${apiRepo}/dependabot/alerts/${number}`,
+ };
+}
+
+// Normalized SDK evidence may link to either REST or the web UI.
+function alertUrlIdentity(url: unknown) {
+ if (typeof url !== "string") return null;
+ const web = webIdentity(url);
+ if (web) return web;
+ const api =
+ /^(https?:\/\/)([^/?#@\\\s]+)\/(api\/v3\/)?repos\/([^/]+\/[^/]+)\/dependabot\/alerts\/([1-9]\d*)$/iu.exec(
+ url,
+ );
+ if (!api) return null;
+ const host = api[3] ? api[2] : api[2]!.replace(/^api\./iu, "");
+ const parsed = webIdentity(
+ `${api[1]}${host}/${api[4]}/security/dependabot/${api[5]}`,
+ );
+ return parsed?.apiUrl === url.toLowerCase() ? parsed : null;
+}
+
+function checkSourceFamily(alert: Record<string, unknown>) {
+ if (
+ alert["source"] === "github-code-scanning" ||
+ alert["source"] === "github-security-advisory"
+ )
+ throw new Error(
+ "Dependabot alert conflicts with its GitHub source family.",
+ );
+}
+
+function checkNativeClaims(
+ alert: Record<string, unknown>,
+ occurrence: NonNullable<ReturnType<typeof webIdentity>>,
+) {
+ if ("number" in alert && alert["number"] !== Number(occurrence.number))
+ throw new Error(
+ "Dependabot alert number must match the repository alert URL.",
+ );
+ if (
+ ("url" in alert &&
+ text(alert["url"])?.toLowerCase() !== occurrence.apiUrl) ||
+ ("html_url" in alert &&
+ text(alert["html_url"])?.toLowerCase() !== occurrence.htmlUrl)
+ )
+ throw new Error(
+ "Dependabot API url and html_url must identify the same host, repository and alert number.",
+ );
+ if ("repository" in alert) {
+ const declared = record(alert["repository"], "Dependabot repository");
+ if (
+ text(declared["full_name"])?.toLowerCase() !== occurrence.repository ||
+ ("html_url" in declared &&
+ text(declared["html_url"])?.toLowerCase() !==
+ occurrence.repositoryUrl) ||
+ ("url" in declared &&
+ text(declared["url"])?.toLowerCase() !== occurrence.apiRepo)
+ )
+ throw new Error(
+ "Dependabot repository metadata conflicts with its alert URLs.",
+ );
+ }
+}
+
+function identity(alert: Record<string, unknown>) {
+ checkSourceFamily(alert);
+ const number = alert["number"];
+ if (typeof number !== "number" || !Number.isSafeInteger(number) || number < 1)
+ throw new Error("Dependabot alert number must be a positive safe integer.");
+ const url = requiredText(alert["html_url"], "Dependabot html_url");
+ const parsed = webIdentity(url);
+ if (!parsed || parsed.number !== String(number))
+ throw new Error(
+ "Dependabot html_url must identify the repository and alert number.",
+ );
+ requiredText(alert["url"], "Dependabot API url");
+ checkNativeClaims(alert, parsed);
+ return {
+ repositoryUrl: parsed.repositoryUrl,
+ sourceId: parsed.sourceId,
+ url,
+ };
+}
+
+export function dependabotRepository({
+ source_finding_id: id,
+ evidence: { source_data: sourceData, url },
+}: ExternalFinding): string | undefined {
+ const native = isGitHubDependabotAlert(sourceData) ? sourceData : null;
+ const raw =
+ native &&
+ (alertUrlIdentity(native["html_url"]) ?? alertUrlIdentity(native["url"]));
+ const projected = alertUrlIdentity(url);
+ const occurrence = raw ?? projected;
+ const structuredId =
+ /^[^/]+\/[^/]+\/[^/]+\/(?:dependabot|code-scanning|security-advisory)\//u.test(
+ id,
+ );
+ if (!occurrence) {
+ if (/^[^/]+\/[^/]+\/[^/]+\/dependabot\/[1-9]\d*$/u.test(id))
+ throw new CodexSecurityError(
+ "The normalized Dependabot occurrence needs the original alert or its repository alert URL.",
+ );
+ return;
+ }
+ if (isRecord(sourceData)) checkSourceFamily(sourceData);
+ if (native) checkNativeClaims(native, occurrence);
+ // A caller may have stored this occurrence under an opaque ID before native imports existed.
+ if ((structuredId || id === "") && id !== occurrence.sourceId)
+ throw new CodexSecurityError(
+ "The normalized source finding ID does not match the original Dependabot alert.",
+ );
+ if (raw && projected && raw.htmlUrl !== projected.htmlUrl)
+ throw new CodexSecurityError(
+ "The normalized alert URL does not match the original Dependabot alert.",
+ );
+ return occurrence.repositoryUrl;
+}
+
+function selectedAlerts(input: unknown) {
+ const selection = Array.isArray(input) ? input : [input];
+ const hasPages = selection.some(Array.isArray);
+ if (hasPages && !selection.every(Array.isArray))
+ throw new Error(
+ "Dependabot input must not mix alert records and page arrays.",
+ );
+ const rows: unknown[] = hasPages ? selection.flat() : selection;
+ if (!rows.every(isGitHubDependabotAlert))
+ throw new Error(
+ "Expected complete native Dependabot repository alerts, not mixed families, page shapes or API envelopes.",
+ );
+ return rows;
+}
+
+// Parse only the matched vulnerability projection. Keep the complete upstream alert as evidence.
+const nonblank = z.string().regex(/\S/u);
+const matchedVulnerability = z.object({
+ package: z.object({ name: nonblank, ecosystem: nonblank }),
+ vulnerable_version_range: nonblank,
+ first_patched_version: z.object({ identifier: nonblank }).nullable(),
+ severity: z.enum(["critical", "high", "medium", "low"]),
+});
+
+function evidence(alert: Record<string, unknown>, url: string) {
+ const dependency = record(alert["dependency"], "Dependabot dependency");
+ const advisory = record(
+ alert["security_advisory"],
+ "Dependabot security_advisory",
+ );
+ const {
+ package: { name, ecosystem },
+ vulnerable_version_range: range,
+ first_patched_version: patch,
+ severity,
+ } = matchedVulnerability.parse(alert["security_vulnerability"]);
+ if ("package" in dependency) {
+ const observed = record(
+ dependency["package"],
+ "Dependabot dependency package",
+ );
+ if (observed["name"] !== name || observed["ecosystem"] !== ecosystem)
+ throw new Error(
+ "Dependabot dependency and matched vulnerability packages disagree.",
+ );
+ }
+ const path = dependency["manifest_path"] ?? null;
+ if (path !== null) {
+ const filename = relativePath(path)?.split("/").at(-1);
+ if (
+ typeof path !== "string" ||
+ /^[a-z][a-z\d+.-]*:/iu.test(path) ||
+ !filename ||
+ filename === "."
+ )
+ throw new Error(
+ "Dependabot manifest_path must identify a repository-relative file.",
+ );
+ }
+ const ghsa = requiredText(advisory["ghsa_id"], "Dependabot GHSA ID");
+ if (!GHSA_ID.test(ghsa))
+ throw new Error("Dependabot security_advisory must identify a GHSA.");
+ const affected = advisory["vulnerabilities"];
+ if (
+ !Array.isArray(affected) ||
+ !affected.some(
+ (entry) =>
+ isRecord(entry) &&
+ isRecord(entry["package"]) &&
+ entry["package"]["name"] === name &&
+ entry["package"]["ecosystem"] === ecosystem &&
+ entry["vulnerable_version_range"] === range,
+ )
+ )
+ throw new Error(
+ "Dependabot advisory does not cover the matched package and vulnerable range.",
+ );
+ const state = alert["state"];
+ if (
+ typeof state !== "string" ||
+ !["open", "dismissed", "auto_dismissed", "fixed"].includes(state)
+ )
+ throw new Error(
+ "Dependabot alert state must be open, dismissed, auto_dismissed or fixed.",
+ );
+ const updated =
+ Date.parse(requiredText(alert["updated_at"], "Dependabot updated_at")) /
+ 1000;
+ if (!Number.isFinite(updated) || updated < 0)
+ throw new Error("Dependabot updated_at must be a valid timestamp.");
+ const advisoryIds = new Set([ghsa]);
+ const cve = text(advisory["cve_id"]);
+ if (cve) advisoryIds.add(cve);
+ const identifiers = advisory["identifiers"];
+ if (Array.isArray(identifiers)) {
+ for (const item of identifiers) {
+ const value = isRecord(item) && text(item["value"]);
+ if (!value) continue;
+ if (
+ (item["type"] === "GHSA" || /^GHSA-/iu.test(value)) &&
+ value.toUpperCase() !== ghsa.toUpperCase()
+ )
+ throw new Error(
+ "Dependabot advisory identifiers disagree on the GHSA.",
+ );
+ advisoryIds.add(value);
+ }
+ }
+ return {
+ title: requiredText(advisory["summary"], "Dependabot advisory summary"),
+ description: text(advisory["description"]),
+ severity,
+ url,
+ advisory_ids: [...advisoryIds],
+ packages: [
+ {
+ name,
+ ecosystem,
+ manifest_path: path,
+ vulnerable_version_range: range,
+ fixed_versions: patch ? [patch.identifier] : [],
+ },
+ ],
+ locations: path ? [{ path }] : [],
+ source_updated_at: Math.floor(updated),
+ source_data: structuredClone(alert),
+ };
+}
+
+export function normalizeGitHubDependabotAlerts(
+ input: unknown,
+ target: ExternalImportTarget = "cloud",
+): ExternalFindings {
+ const alerts = selectedAlerts(input);
+ const result: ExternalFindings = {
+ read: alerts.length,
+ findings: [],
+ excluded: [],
+ };
+ const ids = new Set<string>();
+ let sourceRepository: string | undefined;
+ for (const [index, alert] of alerts.entries()) {
+ const { repositoryUrl, sourceId, url } = identity(alert);
+ if (sourceRepository !== undefined && sourceRepository !== repositoryUrl)
+ throw new CodexSecurityError(
+ "Select Dependabot alerts from only one GitHub host and repository.",
+ );
+ sourceRepository = repositoryUrl;
+ if (ids.has(sourceId))
+ throw new CodexSecurityError(
+ `Duplicate source finding id ${JSON.stringify(sourceId)}. Select each Dependabot alert once.`,
+ );
+ ids.add(sourceId);
+ const inputEvidence = evidence(alert, url);
+ try {
+ if (target === "cloud" && Buffer.byteLength(sourceId) > 512)
+ throw new Error(
+ "Source finding ID exceeds the Cloud limit of 512 UTF-8 bytes.",
+ );
+ result.findings.push({
+ source_finding_id: sourceId,
+ evidence: validateExternalEvidence(inputEvidence, target),
+ });
+ } catch (error) {
+ result.excluded.push({
+ position: index + 1,
+ source_finding_id: sourceId,
+ reason: errorMessage(error),
+ });
+ }
+ }
+ return result;
+}
diff --git a/sdk/typescript/src/github-findings.ts b/sdk/typescript/src/github-findings.ts
index f998cdd45..74eea32b2 100644
--- a/sdk/typescript/src/github-findings.ts
+++ b/sdk/typescript/src/github-findings.ts
@@ -1,10 +1,15 @@
import type { ExternalImportTarget } from "./external-import-contract.js";
import { hash } from "node:crypto";
+import { GHSA_ID, githubRepositoryParts } from "./github-identifiers.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { validateExternalEvidence } from "./external-import-contract.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import type { ImportedGitHubCodeScanningAlert } from "./github.js";
import type { ImportedGitHubAdvisory } from "./github-advisories.js";
+import {
+ isGitHubDependabotAlert,
+ normalizeGitHubDependabotAlerts,
+} from "./github-dependabot-findings.js";
import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
function object(value: unknown): Record<string, unknown> | undefined {
@@ -15,10 +20,9 @@ function object(value: unknown): Record<string, unknown> | undefined {
function repositoryName(value: unknown): string {
const repository = text(value);
- const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository ?? "");
- if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
+ if (!repository || !githubRepositoryParts(repository))
throw new Error("GitHub repository must be OWNER/REPO.");
- return repository!;
+ return repository;
}
function sourceUrl(value: string): {
@@ -160,7 +164,7 @@ function advisoryFinding(
if (
!advisory ||
!id ||
- !/^GHSA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/iu.test(id) ||
+ !GHSA_ID.test(id) ||
text(advisory["ghsa_id"])?.toUpperCase() !== id.toUpperCase()
)
throw new Error(
@@ -324,10 +328,17 @@ export async function readGitHubFindings(
): Promise<ExternalFindings> {
try {
const payload = parseJsonOrJsonl(await readScannerText(path));
- return normalizeRecords(
- Array.isArray(payload) ? payload : [payload],
- target,
- );
+ const rows = Array.isArray(payload) ? payload : [payload];
+ if (
+ (rows.length > 0 && rows.every(Array.isArray)) ||
+ rows.some((row) =>
+ Array.isArray(row)
+ ? row.some(isGitHubDependabotAlert)
+ : isGitHubDependabotAlert(row),
+ )
+ )
+ return normalizeGitHubDependabotAlerts(payload, target);
+ return normalizeRecords(rows, target);
} catch (cause) {
throw new CodexSecurityError(
`Could not read GitHub findings as UTF-8 JSON or JSONL: ${errorMessage(cause)}`,
diff --git a/sdk/typescript/src/github-identifiers.ts b/sdk/typescript/src/github-identifiers.ts
new file mode 100644
index 000000000..186657b5d
--- /dev/null
+++ b/sdk/typescript/src/github-identifiers.ts
@@ -0,0 +1,11 @@
+export const CANONICAL_GHSA_ID = /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/u;
+// File imports and CLI arguments also accept the original mixed-case spelling.
+export const GHSA_ID = new RegExp(CANONICAL_GHSA_ID, "iu");
+
+export function githubRepositoryParts(
+ value: string,
+): [string, string] | undefined {
+ const match = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(value);
+ if (match && !match.slice(1).some((part) => /^\.{1,2}$/u.test(part)))
+ return [match[1]!, match[2]!];
+}
diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.ts
index 2d734f343..957e4ab16 100644
--- a/sdk/typescript/src/github.ts
+++ b/sdk/typescript/src/github.ts
@@ -1,6 +1,7 @@
import { execFile as execFileCallback } from "node:child_process";
import { promisify } from "node:util";
import { Octokit } from "@octokit/core";
+import { githubRepositoryParts } from "./github-identifiers.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { resolveTrustedExecutable } from "./trusted-executable.js";
import { isGitHubCloudHost } from "./git-remote.js";
@@ -101,15 +102,10 @@ export async function importGitHubCodeScanningAlerts(
): Promise<ImportedGitHubCodeScanningAlert[]> {
options.signal?.throwIfAborted();
const repository = options.repository.trim();
- const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);
- if (
- parts === null ||
- parts.slice(1).some((part) => /^\.{1,2}$/u.test(part))
- ) {
+ const parts = githubRepositoryParts(repository);
+ if (!parts)
throw new CodexSecurityError("GitHub repository must be OWNER/REPO.");
- }
- const owner = parts[1]!;
- const repo = parts[2]!;
+ const [owner, repo] = parts;
const numbers = [...new Set(options.alertNumbers ?? [])];
if (numbers.some((number) => !Number.isSafeInteger(number) || number < 1)) {
throw new CodexSecurityError(
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index fdf590145..7d5cadd70 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -249,6 +249,7 @@ export {
readGitHubFindings,
} from "./github-findings.js";
export { importGitHubAdvisories } from "./github-advisories.js";
+export { normalizeGitHubDependabotAlerts } from "./github-dependabot-findings.js";
export type {
GitHubAdvisoryImportOptions,
ImportedGitHubAdvisory,
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 51ae8beee..8f251cf36 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -39,6 +39,7 @@ import type {
} from "../src/external-import-models.js";
import { main } from "../src/cli.js";
import { dependencies } from "./cli-fixtures.js";
+import { githubDependabotAlert } from "./support/github-dependabot-fixtures.js";
import {
importedAlert,
importedAdvisory,
@@ -254,6 +255,103 @@ test("a Wiz Raw Event export explains the finding-report path before contacting
expect(contactedCloud).toBe(false);
});
+test("Dependabot publishes on the existing GitHub provider and rejects foreign repositories before POST", async () => {
+ const input = { ...githubDependabotAlert(), source: "extra" };
+ const correct = await fixture([input]);
+ const selection = {
+ ...options,
+ provider: "github" as const,
+ sourceKey: "github.com/example/project/dependabot",
+ };
+ const first = await prepareExternalPublication(
+ correct.file,
+ selection,
+ correct.deps,
+ );
+ expect(first.preview.requests[0]!.source.provider).toBe("github");
+ expect(correct.posts).toHaveLength(0);
+ first.preview.requests[0]!.items[0]!.evidence.url =
+ "https://github.com/example/other/security/dependabot/1";
+ correct.state.loseResponse = true;
+ await expect(first.publish()).rejects.toThrow();
+ expect(JSON.parse(correct.posts[0]!).items[0].evidence.url).toBe(
+ input.html_url,
+ );
+ const retry = await prepareExternalPublication(
+ correct.file,
+ selection,
+ correct.deps,
+ );
+ expect(retry.preview.resumed).toBe(true);
+ expect((await retry.publish()).counts.created).toBe(1);
+ expect(correct.posts[1]).toBe(correct.posts[0]);
+ const replay = await prepareExternalPublication(
+ correct.file,
+ selection,
+ correct.deps,
+ );
+ expect((await replay.publish()).counts.unchanged).toBe(1);
+ const foreign = await fixture([input], "https://github.com/example/other");
+ await expect(
+ prepareExternalPublication(foreign.file, selection, foreign.deps),
+ ).rejects.toThrow(/does not match/i);
+ const native = await readGitHubFindings(correct.file);
+ await expect(
+ prepareNormalizedExternalPublication(native, selection, foreign.deps),
+ ).rejects.toThrow(/does not match/i);
+ const projected = structuredClone(native);
+ delete projected.findings[0]!.evidence.source_data;
+ await expect(
+ prepareNormalizedExternalPublication(projected, selection, foreign.deps),
+ ).rejects.toThrow(/does not match/i);
+ expect(
+ (
+ await prepareNormalizedExternalPublication(
+ projected,
+ selection,
+ correct.deps,
+ )
+ ).preview.requests,
+ ).toHaveLength(1);
+ projected.findings[0]!.evidence.url = input.url;
+ projected.findings[0]!.evidence.source_data = {
+ security_vulnerability: input.security_vulnerability,
+ };
+ projected.findings[0]!.source_finding_id = "alert-1";
+ const compatible = await prepareNormalizedExternalPublication(
+ projected,
+ selection,
+ correct.deps,
+ );
+ expect((await compatible.publish()).counts.created).toBe(1);
+ expect(
+ (
+ await (
+ await prepareNormalizedExternalPublication(
+ projected,
+ selection,
+ correct.deps,
+ )
+ ).publish()
+ ).counts.unchanged,
+ ).toBe(1);
+ await expect(
+ prepareNormalizedExternalPublication(projected, selection, foreign.deps),
+ ).rejects.toThrow(/does not match/i);
+ const conflicting = structuredClone(native);
+ conflicting.findings[0]!.evidence.url = githubDependabotAlert(2).html_url;
+ await expect(
+ prepareNormalizedExternalPublication(conflicting, selection, correct.deps),
+ ).rejects.toThrow(/alert URL/i);
+ const relabeled = structuredClone(native);
+ relabeled.findings[0]!.source_finding_id =
+ "github.com/example/other/dependabot/2";
+ await expect(
+ prepareNormalizedExternalPublication(relabeled, selection, foreign.deps),
+ ).rejects.toThrow(/source finding ID/i);
+ expect(foreign.posts).toHaveLength(0);
+});
+
async function fixture(
records: unknown = [normalized()],
repositoryUrl = "https://github.com/example/project",
diff --git a/sdk/typescript/tests-ts/github-dependabot-findings.test.ts b/sdk/typescript/tests-ts/github-dependabot-findings.test.ts
new file mode 100644
index 000000000..03968e221
--- /dev/null
+++ b/sdk/typescript/tests-ts/github-dependabot-findings.test.ts
@@ -0,0 +1,572 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { gzipSync } from "node:zlib";
+import { expect, test } from "bun:test";
+import {
+ dependabotRepository,
+ normalizeGitHubDependabotAlerts,
+} from "../src/github-dependabot-findings.js";
+import {
+ normalizeGitHubAdvisories,
+ readGitHubFindings,
+} from "../src/github-findings.js";
+import { githubDependabotAlert } from "./support/github-dependabot-fixtures.js";
+import {
+ importedAdvisory,
+ importedAlert,
+} from "./support/github-import-fixtures.js";
+import {
+ removeTemporaryDirectory,
+ temporaryDirectory,
+} from "./support/temporary-directories.js";
+
+function retainedRepository(
+ source_data: unknown,
+ source_finding_id = "opaque",
+ url?: string | null,
+) {
+ return dependabotRepository({
+ source_finding_id,
+ evidence: {
+ title: "Example",
+ severity: "unknown",
+ url,
+ source_data: source_data as Record<string, unknown> | undefined,
+ },
+ });
+}
+
+test("matches the affected dependency, retains the original alert, and never invents an installed version or revision", () => {
+ const alert = githubDependabotAlert();
+ alert.security_advisory.vulnerabilities.push({
+ ...alert.security_vulnerability,
+ package: { ecosystem: "npm", name: "unrelated-package" },
+ });
+ const original = structuredClone(alert);
+ const result = normalizeGitHubDependabotAlerts(alert);
+ expect(result.excluded).toEqual([]);
+ expect(result.findings).toHaveLength(1);
+ const finding = result.findings[0]!;
+ expect(finding).toMatchObject({
+ source_finding_id: "github.com/example/project/dependabot/1",
+ evidence: {
+ title: alert.security_advisory.summary,
+ severity: "high",
+ url: alert.html_url,
+ source_updated_at: 1767225600,
+ packages: [
+ {
+ name: "synthetic-widget",
+ ecosystem: "npm",
+ manifest_path: "app/package-lock.json",
+ installed_version: null,
+ vulnerable_version_range: "< 2.0.1",
+ fixed_versions: ["2.0.1"],
+ },
+ ],
+ advisory_ids: ["GHSA-2345-6789-cfgh", "CVE-2099-12345"],
+ locations: [{ path: "app/package-lock.json", line: null }],
+ branch: null,
+ code_revision: null,
+ },
+ });
+ expect(finding.evidence.packages).toHaveLength(1);
+ expect(finding.evidence.source_data).toEqual(original);
+ expect(finding.evidence).not.toHaveProperty("details");
+ expect(finding.evidence).not.toHaveProperty("assessment");
+ expect(alert).toEqual(original);
+ alert.dependency.package.name = "changed-after-normalization";
+ alert.security_advisory.identifiers.length = 0;
+ expect(finding.evidence.source_data).toEqual(original);
+});
+
+test("extra metadata cannot hide a native alert or contradict its family", () => {
+ const raw = { ...githubDependabotAlert(), source: "extra" };
+ for (const target of ["local", "cloud"] as const) {
+ const occurrence = normalizeGitHubDependabotAlerts(raw, target)
+ .findings[0]!;
+ expect(occurrence.evidence.source_data).toEqual(raw);
+ expect(dependabotRepository(occurrence)).toBe(
+ "https://github.com/example/project",
+ );
+ expect(retainedRepository(raw, "alert-2")).toBe(
+ "https://github.com/example/project",
+ );
+ for (const source of ["github-code-scanning", "github-security-advisory"]) {
+ const contradictory = { ...raw, source };
+ expect(() =>
+ normalizeGitHubDependabotAlerts(contradictory, target),
+ ).toThrow(/family/i);
+ expect(() => retainedRepository(contradictory)).toThrow(/family/i);
+ }
+ }
+});
+
+test("does not attribute unrelated advisory packages, ranges, or GHSA aliases", () => {
+ const alert = githubDependabotAlert();
+ const native = alert.security_advisory;
+ const match = alert.security_vulnerability;
+ for (const changed of [
+ { vulnerabilities: [] },
+ {
+ vulnerabilities: [
+ { ...match, package: { ...match.package, name: "different" } },
+ ],
+ },
+ {
+ vulnerabilities: [
+ { ...match, package: { ...match.package, ecosystem: "pip" } },
+ ],
+ },
+ { vulnerabilities: [{ ...match, vulnerable_version_range: ">= 10.0" }] },
+ { identifiers: [{ type: "GHSA", value: "GHSA-2222-3333-4444" }] },
+ ]) {
+ for (const target of ["cloud", "local"] as const)
+ expect(() =>
+ normalizeGitHubDependabotAlerts(
+ {
+ ...alert,
+ security_advisory: { ...native, ...changed },
+ },
+ target,
+ ),
+ ).toThrow(/advisory/i);
+ }
+});
+
+test("uses the matched vulnerability package when the dependency omits it", () => {
+ const alert = githubDependabotAlert();
+ const withoutPackage = {
+ ...alert,
+ dependency: { manifest_path: alert.dependency.manifest_path },
+ };
+ for (const target of ["cloud", "local"] as const) {
+ const result = normalizeGitHubDependabotAlerts(
+ [withoutPackage, githubDependabotAlert(2)],
+ target,
+ );
+ expect(result.excluded).toEqual([]);
+ expect(result.findings).toHaveLength(2);
+ expect(result.findings[0]!.evidence.packages![0]).toMatchObject({
+ ...alert.security_vulnerability.package,
+ manifest_path: alert.dependency.manifest_path,
+ });
+ expect(result.findings[0]!.evidence.source_data).toEqual(withoutPackage);
+ }
+});
+
+test.each([
+ "file:///etc/passwd",
+ "https://example.test/lock",
+ "file:outside",
+ "git+ssh://example.test/lock",
+ ".",
+ "project/.",
+ "project/",
+])(
+ "never projects a URI or directory as a checkout manifest: %s",
+ (manifest_path) => {
+ const raw = githubDependabotAlert();
+ raw.dependency.manifest_path = manifest_path;
+ for (const target of ["local", "cloud"] as const)
+ expect(() => normalizeGitHubDependabotAlerts(raw, target)).toThrow(
+ /repository-relative/i,
+ );
+ },
+);
+
+test("preserves a Git manifest path containing a literal backslash", () => {
+ const alert = githubDependabotAlert();
+ const path = "legacy\\client/package-lock.json";
+ alert.dependency.manifest_path = path;
+ for (const target of ["local", "cloud"] as const) {
+ const { findings } = normalizeGitHubDependabotAlerts(alert, target);
+ expect(findings[0]!.evidence.packages![0]!.manifest_path).toBe(path);
+ expect(findings[0]!.evidence.locations![0]!.path).toBe(path);
+ }
+});
+
+test.each(["open", "fixed", "dismissed", "auto_dismissed"])(
+ "keeps %s as source state even for a withdrawn advisory",
+ (state) => {
+ const alert = githubDependabotAlert();
+ alert.state = state;
+ alert.security_advisory.withdrawn_at = alert.updated_at;
+ alert.security_vulnerability.first_patched_version = null;
+ alert.dependency.version_requirement = "= 1.2.0";
+ const finding = normalizeGitHubDependabotAlerts(alert).findings[0]!;
+ expect(finding.source_finding_id).toBe(
+ "github.com/example/project/dependabot/1",
+ );
+ expect(finding.evidence.source_data).toMatchObject({ state });
+ expect(finding.evidence).not.toHaveProperty("details");
+ expect(finding.evidence.packages![0]).toMatchObject({
+ installed_version: null,
+ fixed_versions: [],
+ });
+ },
+);
+
+test("retains raw repository, status and CWEs without treating the alert as a GHSA disclosure", () => {
+ const alert = githubDependabotAlert(
+ 3,
+ "Example/Project",
+ "git.example.test:8443",
+ );
+ const cwes = [
+ { cwe_id: "CWE-79", name: "Synthetic" },
+ { cwe_id: "NVD-CWE-noinfo" },
+ ];
+ const selected = {
+ ...alert,
+ repository: { full_name: "Example/Project" },
+ state: "dismissed",
+ security_advisory: { ...alert.security_advisory, cwes },
+ };
+ for (const target of ["local", "cloud"] as const) {
+ const finding = normalizeGitHubDependabotAlerts(selected, target)
+ .findings[0]!;
+ expect(finding.evidence).not.toHaveProperty("details");
+ expect(finding.evidence.source_data).toEqual(selected);
+ expect(dependabotRepository(finding)).toBe(
+ "https://git.example.test:8443/example/project",
+ );
+ expect(finding.evidence.packages![0]!.installed_version).toBeNull();
+ for (const scope of ["repository", "global"] as const) {
+ const disclosure = normalizeGitHubAdvisories(
+ [importedAdvisory(scope)],
+ target,
+ ).findings[0]!;
+ expect(disclosure.evidence.advisory_ids).toContain(
+ selected.security_advisory.ghsa_id,
+ );
+ expect(disclosure.evidence.details).toMatchObject({
+ kind: "advisory",
+ advisory: { source: scope },
+ });
+ expect(disclosure.source_finding_id).not.toBe(finding.source_finding_id);
+ }
+ }
+});
+
+test("scopes identity by host, repo and alert number, never by GHSA or manifest", () => {
+ const first = githubDependabotAlert(1, "Example/Project");
+ const second = githubDependabotAlert(2);
+ const stored = normalizeGitHubDependabotAlerts([first, second]).findings;
+ expect(stored.map((row) => row.source_finding_id)).toEqual([
+ "github.com/example/project/dependabot/1",
+ "github.com/example/project/dependabot/2",
+ ]);
+ first.state = "fixed";
+ first.dependency.manifest_path = "moved/package-lock.json";
+ expect(
+ normalizeGitHubDependabotAlerts(first).findings[0]!.source_finding_id,
+ ).toBe(stored[0]!.source_finding_id);
+ expect(() =>
+ normalizeGitHubDependabotAlerts([
+ [first],
+ [{ ...first, state: "dismissed" }],
+ ]),
+ ).toThrow(/duplicate/i);
+ expect(() =>
+ normalizeGitHubDependabotAlerts([
+ first,
+ githubDependabotAlert(1, "example/another"),
+ ]),
+ ).toThrow(/one GitHub host and repository/);
+ expect(() =>
+ normalizeGitHubDependabotAlerts([
+ first,
+ githubDependabotAlert(1, "example/project", "git.example.test"),
+ ]),
+ ).toThrow(/one GitHub host and repository/);
+});
+
+test.each([
+ "github.com",
+ "tenant.ghe.com",
+ "git.example.test",
+ "git.example.test:443",
+ "git.example.test:8443",
+])("checks API, web, repository slug and explicit port for %s", (host) => {
+ const alert = githubDependabotAlert(17, "Example/Project", host);
+ const declared = {
+ full_name: "example/project",
+ html_url: `https://${host}/Example/Project`,
+ url: alert.url.replace(/\/dependabot\/alerts\/17$/, ""),
+ };
+ const row = { ...alert, repository: declared };
+ expect(retainedRepository(row)).toBe(`https://${host}/example/project`);
+ expect(
+ normalizeGitHubDependabotAlerts(row).findings[0]!.source_finding_id,
+ ).toBe(`${host}/example/project/dependabot/17`);
+ for (const bad of [
+ { ...row, number: 18 },
+ { ...row, url: alert.url + "?next=test" },
+ {
+ ...row,
+ html_url: alert.html_url.replace(host, "unrelated.example.test"),
+ },
+ { ...row, url: alert.url.replace("Example/Project", "Example/Other") },
+ { ...row, url: alert.url.replace("/alerts/17", "/alerts/18") },
+ { ...row, repository: { ...declared, full_name: "example/other" } },
+ {
+ ...row,
+ repository: {
+ ...declared,
+ html_url: "https://git.example.test/example/other",
+ },
+ },
+ { ...row, repository: { ...declared, url: declared.url + "/other" } },
+ ])
+ expect(() => retainedRepository(bad)).toThrow();
+});
+
+test("checks the normalized occurrence ID against the original Dependabot alert", () => {
+ const alert = githubDependabotAlert(
+ 17,
+ "Example/Project",
+ "git.example.test:443",
+ );
+ const finding = normalizeGitHubDependabotAlerts(alert).findings[0]!;
+ const raw = finding.evidence.source_data;
+ expect(dependabotRepository(finding)).toBe(
+ "https://git.example.test:443/example/project",
+ );
+ for (const wrong of [
+ "github.com/example/project/dependabot/17",
+ "git.example.test/example/project/dependabot/17",
+ "git.example.test:443/example/other/dependabot/17",
+ "git.example.test:443/example/project/code-scanning/17",
+ "git.example.test:443/example/project/dependabot/18",
+ "",
+ ])
+ expect(() => retainedRepository(raw, wrong)).toThrow(
+ /source finding ID.*original Dependabot alert/i,
+ );
+ for (const unrelated of [importedAlert(), importedAdvisory()]) {
+ expect(() =>
+ retainedRepository(
+ unrelated,
+ finding.source_finding_id,
+ finding.evidence.url,
+ ),
+ ).toThrow(/source family/i);
+
+ expect(() =>
+ retainedRepository(unrelated, finding.source_finding_id),
+ ).toThrow();
+ expect(
+ retainedRepository(unrelated, "unrelated-occurrence"),
+ ).toBeUndefined();
+ }
+});
+
+test("normalized callers may keep opaque IDs, REST links and partial metadata", () => {
+ for (const host of [
+ "github.com",
+ "tenant.ghe.com",
+ "git.example.test:8443",
+ ]) {
+ const alert = githubDependabotAlert(12, "example/project", host);
+ for (const url of [alert.url, alert.html_url]) {
+ for (const data of [
+ alert,
+ { security_vulnerability: alert.security_vulnerability },
+ undefined,
+ ])
+ expect(retainedRepository(data, "alert-12", url)).toBe(
+ `https://${host}/example/project`,
+ );
+ expect(() =>
+ retainedRepository(
+ { security_vulnerability: {}, number: 13 },
+ "alert-12",
+ url,
+ ),
+ ).toThrow(/alert number/i);
+ }
+ }
+});
+
+test("rejects credential-bearing links, foreign API origins, and repo traversal", () => {
+ const alert = githubDependabotAlert();
+ for (const html_url of [
+ alert.html_url + "#state",
+ alert.html_url.replace("https://", "https://login@"),
+ alert.html_url.replace("/example/project/", "/example/../"),
+ alert.html_url.replace("project", "project%2Fother"),
+ ])
+ expect(() =>
+ normalizeGitHubDependabotAlerts({ ...alert, html_url }),
+ ).toThrow();
+ const enterprise = githubDependabotAlert(
+ 1,
+ "example/project",
+ "git.example.test:443",
+ );
+ for (const url of [
+ enterprise.url.replace(":443", ""),
+ enterprise.url.replace("/api/v3", ""),
+ enterprise.url.replace("git.example.test", "api.github.com"),
+ ])
+ expect(() =>
+ normalizeGitHubDependabotAlerts({ ...enterprise, url }),
+ ).toThrow();
+ for (const unrelated of [
+ importedAdvisory(),
+ importedAlert(),
+ { action: "published", security_advisory: {} },
+ {},
+ null,
+ ])
+ expect(retainedRepository(unrelated)).toBeUndefined();
+});
+
+test("handles unambiguous slurped arrays and rejects incomplete page or record shapes", () => {
+ const alerts = Array.from({ length: 501 }, (_, index) =>
+ githubDependabotAlert(index + 1),
+ );
+ const paged = Array.from({ length: 6 }, (_, index) =>
+ alerts.slice(index * 100, (index + 1) * 100),
+ );
+ expect(normalizeGitHubDependabotAlerts(paged)).toEqual(
+ normalizeGitHubDependabotAlerts(alerts),
+ );
+ for (const empty of [[], [[]]])
+ expect(normalizeGitHubDependabotAlerts(empty)).toEqual({
+ read: 0,
+ findings: [],
+ excluded: [],
+ });
+ const first = alerts[0]!;
+ expect(normalizeGitHubDependabotAlerts([[first], []])).toEqual(
+ normalizeGitHubDependabotAlerts([first]),
+ );
+ for (const invalid of [
+ null,
+ [first, [first]],
+ [[first], [null]],
+ [[[first]]],
+ [first, importedAdvisory()],
+ { alerts: [first] },
+ { ...first, security_vulnerability: undefined },
+ { ...first, dependency: null },
+ { ...first, dependency: { package: null } },
+ {
+ ...first,
+ dependency: { ...first.dependency, manifest_path: "../other/lock" },
+ },
+ {
+ ...first,
+ dependency: {
+ ...first.dependency,
+ package: { ecosystem: "npm", name: "another" },
+ },
+ },
+ {
+ ...first,
+ security_advisory: { ...first.security_advisory, ghsa_id: "not-an-id" },
+ },
+ {
+ ...first,
+ security_vulnerability: {
+ ...first.security_vulnerability,
+ first_patched_version: {},
+ },
+ },
+ { ...first, updated_at: "invalid" },
+ { ...first, state: "closed" },
+ { ...first, number: Number.MAX_SAFE_INTEGER + 1 },
+ ])
+ expect(() => normalizeGitHubDependabotAlerts(invalid)).toThrow();
+});
+
+test("keeps destination limits distinct without truncating original data", () => {
+ const alert = {
+ ...githubDependabotAlert(),
+ vendor_extra: "x".repeat(270000),
+ };
+ expect(normalizeGitHubDependabotAlerts(alert, "cloud")).toMatchObject({
+ read: 1,
+ findings: [],
+ excluded: [
+ {
+ position: 1,
+ source_finding_id: "github.com/example/project/dependabot/1",
+ },
+ ],
+ });
+ expect(
+ normalizeGitHubDependabotAlerts(alert, "local").findings[0]!.evidence
+ .source_data,
+ ).toEqual(alert);
+ const longIdentity = githubDependabotAlert(1, "example/" + "x".repeat(510));
+ expect(
+ normalizeGitHubDependabotAlerts(longIdentity).excluded[0]?.reason,
+ ).toContain("512");
+ expect(
+ normalizeGitHubDependabotAlerts(longIdentity, "local").findings,
+ ).toHaveLength(1);
+});
+
+test("file reader dispatches native lists, selected JSONL and gzip while preserving existing GitHub families", async () => {
+ const root = await temporaryDirectory("github-dependabot-");
+ try {
+ const file = join(root, "alerts");
+ const alerts = [githubDependabotAlert(1), githubDependabotAlert(2)];
+ for (const data of [
+ JSON.stringify(alerts),
+ alerts.map((item) => JSON.stringify(item)).join("\n"),
+ alerts.map((item) => JSON.stringify([item])).join("\n"),
+ gzipSync(JSON.stringify(alerts.map((item) => [item]))),
+ ]) {
+ await writeFile(file, data);
+ expect(await readGitHubFindings(file)).toEqual(
+ normalizeGitHubDependabotAlerts(alerts),
+ );
+ }
+ await writeFile(
+ file,
+ JSON.stringify([importedAlert(), importedAdvisory()]),
+ );
+ const existing = await readGitHubFindings(file);
+ expect(existing.excluded).toEqual([]);
+ expect(existing.findings.map((row) => row.source_finding_id)).toEqual([
+ expect.stringContaining("/code-scanning/"),
+ expect.stringContaining("/security-advisory/"),
+ ]);
+ for (const repository of ["dependabot/alerts", "security/dependabot"]) {
+ const saved = importedAlert();
+ const url = saved.url.replace(saved.repository, repository);
+ await writeFile(
+ file,
+ JSON.stringify({
+ ...saved,
+ repository,
+ url,
+ alert: { ...saved.alert, html_url: url },
+ }),
+ );
+ const codeScanning = await readGitHubFindings(file);
+ expect(codeScanning.excluded).toEqual([]);
+ expect(codeScanning.findings[0]!.source_finding_id).toContain(
+ `/${repository}/code-scanning/12/`,
+ );
+ }
+ await writeFile(file, JSON.stringify([importedAlert(), []]));
+ const legacyWithMalformedSibling = await readGitHubFindings(file);
+ expect(legacyWithMalformedSibling.findings).toHaveLength(1);
+ expect(legacyWithMalformedSibling.excluded).toHaveLength(1);
+ for (const invalid of [
+ JSON.stringify([alerts[0], importedAlert()]),
+ '{"number":1',
+ JSON.stringify([alerts[0], [alerts[1]]]),
+ ]) {
+ await writeFile(file, invalid);
+ await expect(readGitHubFindings(file)).rejects.toThrow();
+ }
+ } finally {
+ await removeTemporaryDirectory(root);
+ }
+});
diff --git a/sdk/typescript/tests-ts/github-dependabot-local.test.ts b/sdk/typescript/tests-ts/github-dependabot-local.test.ts
new file mode 100644
index 000000000..95e474069
--- /dev/null
+++ b/sdk/typescript/tests-ts/github-dependabot-local.test.ts
@@ -0,0 +1,204 @@
+import { expect, test } from "bun:test";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { gzipSync } from "node:zlib";
+import { prepareLocalExternalImport } from "../src/external-findings-import.js";
+import {
+ listLocalExternalFindings,
+ prepareNormalizedLocalImport,
+} from "../src/external-findings-local.js";
+import { normalizeGitHubDependabotAlerts } from "../src/github-dependabot-findings.js";
+import { localFindingsFixture } from "./external-findings-local-helpers.js";
+import { githubDependabotAlert } from "./support/github-dependabot-fixtures.js";
+
+test("two Dependabot alerts for one advisory retain separate repository histories", async () => {
+ const fixture = await localFindingsFixture({
+ remote: "[email protected]:example/project.git",
+ });
+ try {
+ const path = join(fixture.root, "dependabot.json.gz");
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "github.com/example/project/dependabot",
+ };
+ const dependencies = { environment: fixture.environment };
+ const prepare = async (findings: unknown[]) => {
+ await writeFile(path, gzipSync(JSON.stringify(findings)));
+ return prepareLocalExternalImport(path, options, dependencies);
+ };
+ const importCounts = async (alerts: unknown[]) => {
+ const prepared = await prepare(alerts);
+ return (await prepared.import()).counts;
+ };
+ const first = { ...githubDependabotAlert(1), source: "extra" };
+ const second = githubDependabotAlert(2);
+ const saved = await prepare([first, second]);
+ expect((await saved.import()).counts.created).toBe(2);
+ expect((await importCounts([second, first])).unchanged).toBe(2);
+ const fixed = {
+ ...first,
+ state: "fixed",
+ fixed_at: "2026-01-03T00:00:00Z",
+ };
+ expect((await importCounts([fixed])).updated).toBe(1);
+ expect(await importCounts([])).toEqual({
+ created: 0,
+ updated: 0,
+ unchanged: 0,
+ });
+ const records = await listLocalExternalFindings(options, dependencies);
+ expect(records.map((record) => record.version).sort()).toEqual([1, 2]);
+ expect(
+ records.every(({ assessment }) => assessment.state === "not_assessed"),
+ ).toBe(true);
+ const other = {
+ ...githubDependabotAlert(3, "example/other"),
+ source: "extra",
+ };
+ await expect(prepare([other])).rejects.toThrow(/configured remote/);
+ const altered = structuredClone(saved.preview);
+ altered.findings[0]!.evidence.details = {
+ kind: "sast",
+ repository: { url: "https://github.com/example/other" },
+ };
+ await expect(
+ prepareNormalizedLocalImport(altered, options, dependencies),
+ ).rejects.toThrow(/original Dependabot alert/i);
+ const relabeled = structuredClone(saved.preview);
+ relabeled.findings.splice(1);
+ relabeled.findings[0]!.source_finding_id =
+ saved.preview.findings[1]!.source_finding_id;
+ await expect(
+ prepareNormalizedLocalImport(relabeled, options, dependencies),
+ ).rejects.toThrow(/occurrence|source finding|identity|alert ID/i);
+ const foreign = normalizeGitHubDependabotAlerts(other, "local");
+ await expect(
+ prepareNormalizedLocalImport(foreign, options, dependencies),
+ ).rejects.toThrow(/configured remote/);
+ expect(await listLocalExternalFindings(options, dependencies)).toEqual(
+ records,
+ );
+ } finally {
+ await fixture.dispose();
+ }
+});
+
+test("normalized local imports bind projected Dependabot occurrences to a single repository", async () => {
+ const fixture = await localFindingsFixture();
+ try {
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "alerts",
+ };
+ const deps = { environment: fixture.environment };
+ const first = normalizeGitHubDependabotAlerts(
+ githubDependabotAlert(1),
+ "local",
+ );
+ const second = normalizeGitHubDependabotAlerts(
+ githubDependabotAlert(2, "example/other"),
+ "local",
+ );
+ delete first.findings[0]!.evidence.source_data;
+ await expect(
+ prepareNormalizedLocalImport(
+ {
+ ...first,
+ read: 2,
+ findings: [...first.findings, ...second.findings],
+ },
+ options,
+ deps,
+ ),
+ ).rejects.toThrow(/one GitHub host and repository/);
+ first.findings[0]!.source_finding_id =
+ second.findings[0]!.source_finding_id;
+ await expect(
+ prepareNormalizedLocalImport(first, options, deps),
+ ).rejects.toThrow(/source finding ID/);
+ } finally {
+ await fixture.dispose();
+ }
+});
+
+test("replaying normalized Dependabot evidence keeps the caller's stored ID", async () => {
+ const fixture = await localFindingsFixture({
+ remote: "https://github.com/example/project",
+ });
+ try {
+ const alert = githubDependabotAlert();
+ const selection = normalizeGitHubDependabotAlerts(alert, "local");
+ const finding = selection.findings[0]!;
+ finding.source_finding_id = "alert-1";
+ finding.evidence.url = alert.url;
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "alerts",
+ };
+ const deps = { environment: fixture.environment };
+ const importCounts = async () => {
+ const prepared = await prepareNormalizedLocalImport(
+ selection,
+ options,
+ deps,
+ );
+ return (await prepared.import()).counts;
+ };
+ expect((await importCounts()).created).toBe(1);
+ finding.evidence.source_data = {
+ security_vulnerability: alert.security_vulnerability,
+ };
+ expect((await importCounts()).updated).toBe(1);
+ expect((await importCounts()).unchanged).toBe(1);
+ expect(
+ (await listLocalExternalFindings(options, deps)).map(
+ (row) => row.sourceFindingId,
+ ),
+ ).toEqual(["alert-1"]);
+ } finally {
+ await fixture.dispose();
+ }
+});
+
+test("binds offline HTTP Enterprise alert URLs without changing the repository scheme", async () => {
+ const repository = "git.example.test/example/project";
+ const fixture = await localFindingsFixture({
+ remote: `http://${repository}`,
+ });
+ try {
+ const alert = githubDependabotAlert(
+ 1,
+ "example/project",
+ "git.example.test",
+ );
+ const http = {
+ ...alert,
+ html_url: alert.html_url.replace("https:", "http:"),
+ url: alert.url.replace("https:", "http:"),
+ };
+ const normalized = normalizeGitHubDependabotAlerts(http, "local");
+ const options = {
+ repository: fixture.repository,
+ provider: "github" as const,
+ sourceKey: "alerts",
+ };
+ const deps = { environment: fixture.environment };
+ expect(
+ (await prepareNormalizedLocalImport(normalized, options, deps)).preview
+ .findings[0]!.evidence.url,
+ ).toBe(http.html_url);
+ delete normalized.findings[0]!.evidence.source_data;
+ normalized.findings[0]!.evidence.url = alert.html_url;
+ await expect(
+ prepareNormalizedLocalImport(normalized, options, deps),
+ ).rejects.toThrow(/does not match a configured remote/);
+ expect(() =>
+ normalizeGitHubDependabotAlerts({ ...http, url: alert.url }, "local"),
+ ).toThrow(/API url and html_url/);
+ } finally {
+ await fixture.dispose();
+ }
+});
diff --git a/sdk/typescript/tests-ts/support/github-dependabot-fixtures.ts b/sdk/typescript/tests-ts/support/github-dependabot-fixtures.ts
new file mode 100644
index 000000000..f3f8fab5b
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/github-dependabot-fixtures.ts
@@ -0,0 +1,61 @@
+export function githubDependabotAlert(
+ number = 1,
+ repository = "example/project",
+ host = "github.com",
+) {
+ const hostname = new URL(`https://${host}`).hostname;
+ const api =
+ hostname === "github.com" || hostname.endsWith(".ghe.com")
+ ? `https://api.${host}`
+ : `https://${host}/api/v3`;
+ const pkg = { ecosystem: "npm", name: "synthetic-widget" };
+ const vulnerability = {
+ package: { ...pkg },
+ severity: "high",
+ vulnerable_version_range: "< 2.0.1",
+ first_patched_version: { identifier: "2.0.1" } as {
+ identifier: string;
+ } | null,
+ };
+ const created = "2026-01-01T00:00:00Z";
+ return {
+ number,
+ state: "open",
+ dependency: {
+ package: { ...pkg },
+ manifest_path: "app/package-lock.json",
+ version_requirement: "^1.2.0" as string | null,
+ scope: "runtime",
+ relationship: "transitive",
+ },
+ security_advisory: {
+ ghsa_id: "GHSA-2345-6789-cfgh",
+ cve_id: "CVE-2099-12345",
+ summary: "Synthetic dependency advisory",
+ description: "Synthetic fixture for import tests.",
+ severity: "critical",
+ identifiers: [
+ { type: "GHSA", value: "GHSA-2345-6789-cfgh" },
+ { type: "CVE", value: "CVE-2099-12345" },
+ ],
+ vulnerabilities: [structuredClone(vulnerability)],
+ cvss: { score: 0, vector_string: null },
+ cwes: [{ cwe_id: "CWE-79", name: "Synthetic weakness" }],
+ references: [],
+ published_at: created,
+ updated_at: created,
+ withdrawn_at: null as string | null,
+ },
+ security_vulnerability: vulnerability,
+ html_url: `https://${host}/${repository}/security/dependabot/${number}`,
+ url: `${api}/repos/${repository}/dependabot/alerts/${number}`,
+ created_at: created,
+ updated_at: created,
+ dismissed_at: null as string | null,
+ dismissed_by: null,
+ dismissed_reason: null as string | null,
+ dismissed_comment: null as string | null,
+ fixed_at: null as string | null,
+ auto_dismissed_at: null as string | null,
+ };
+}