feat(imports): publish Guardian findings and clarify scanner evidence (#2377)

* docs(imports): correct scanner results and ticket intake checks

* refactor(imports): reuse scanner severity mappings

* feat(imports): publish selected Semgrep Guardian findings to Cloud

* feat(cli): show readable imported findings in the terminal

* docs(imports): explain scanner fields and source references

---------

Co-authored-by: Michael D'Angelo <269034524+mldangelo-oai@users.noreply.github.com>
This commit is contained in:
Michael D'Angelo
2026-11-08 07:40:48 -08:00
committed by GitHub
co-authored by Michael D'Angelo
parent 8e5860b2d2
commit 6e677445f9
40 changed files with 640 additions and 248 deletions
+22 -22
View File
@@ -9,24 +9,24 @@ The `--provider` value selects the reader for a saved report. To see which
readers your installed CLI supports, run `codex-security publish findings --help`.
The guides cover local and Cloud imports unless an input is marked local only.
| Guide | `--provider` | Supported input |
| ----------------------------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md) | `inspector` | Inspector2 `ListFindings` JSON for one Code Security repository |
| [AWS Continuum](continuum.md) | `continuum` | Summaries or selected code finding details for one verified repository |
| [Black Duck SCA](blackduck.md) | `blackduck` | BOM-6 vulnerable components for one project version |
| [Checkmarx SAST](checkmarx.md) | `checkmarx` | Checkmarx One CLI JSON or self-managed CxSAST XML for one scan |
| [Endor Labs](endor.md) | `endor` | Native Finding JSON, or self-contained `endorctl` SARIF with finding UUIDs |
| [GitHub code scanning](github-code-scanning.md) | `github` | Alerts selected for one repository and Git ref |
| [GitHub Dependabot](github-dependabot.md) | `github` | Dependency alerts exported from one repository |
| [GitHub Security Advisories](github-security-advisories.md) | `github` | Selected repository or global advisories |
| [OpenGrep](opengrep.md) | `opengrep` | Native scan JSON, optionally gzip-compressed |
| [Semgrep](semgrep.md) | `semgrep` | CLI/CI JSON, SARIF, or Platform Web API reports. Guardian selections support local import only. |
| [Snyk](snyk.md) | `snyk` | CLI JSON, plugin exports, SARIF, or monitored Code and Open Source issues |
| [SonarQube Cloud](sonar.md) | `sonar` | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |
| [Tenable One](tenable.md) | `tenable` | Selected Code Repository inventory findings (local only) |
| [Trivy](trivy.md) | `trivy` | Native schema-v2 repository or filesystem JSON, optionally gzip-compressed |
| [Veracode Static Analysis](veracode.md) | `veracode` | Findings API pages for one application's policy flaws |
| [Wiz](wiz.md) | `wiz` | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |
| Guide | `--provider` | Supported input |
| ----------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md) | `inspector` | Inspector2 `ListFindings` JSON for one Code Security repository |
| [AWS Continuum](continuum.md) | `continuum` | Summaries or selected code finding details for one verified repository |
| [Black Duck SCA](blackduck.md) | `blackduck` | BOM-6 vulnerable components for one project version |
| [Checkmarx SAST](checkmarx.md) | `checkmarx` | Checkmarx One CLI JSON or self-managed CxSAST XML for one scan |
| [Endor Labs](endor.md) | `endor` | Native Finding JSON, or self-contained `endorctl` SARIF with finding UUIDs |
| [GitHub code scanning](github-code-scanning.md) | `github` | Alerts selected for one repository and Git ref |
| [GitHub Dependabot](github-dependabot.md) | `github` | Dependency alerts exported from one repository |
| [GitHub Security Advisories](github-security-advisories.md) | `github` | Selected repository or global advisories |
| [OpenGrep](opengrep.md) | `opengrep` | Native scan JSON, optionally gzip-compressed |
| [Semgrep](semgrep.md) | `semgrep` | CLI/CI JSON, SARIF, selected Guardian findings, or Platform Web API reports |
| [Snyk](snyk.md) | `snyk` | CLI JSON, plugin exports, SARIF, or monitored Code and Open Source issues |
| [SonarQube Cloud](sonar.md) | `sonar` | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |
| [Tenable One](tenable.md) | `tenable` | Selected Code Repository inventory findings (local only) |
| [Trivy](trivy.md) | `trivy` | Native schema-v2 repository or filesystem JSON, optionally gzip-compressed |
| [Veracode Static Analysis](veracode.md) | `veracode` | Findings API pages for one application's policy flaws |
| [Wiz](wiz.md) | `wiz` | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |
## Preview a report
@@ -60,8 +60,7 @@ from the preview for your destination](sonar.md#import-and-verify).
**Save locally.** Remove `--dry-run` and confirm. In automation, use `--yes`
after reviewing the preview.
**Send to Cloud.** Tenable One reports and Semgrep Guardian selections support
local import only. For a Cloud-supported report, keep the file, provider,
**Send to Cloud.** Tenable One reports support local import only. For a Cloud-supported report, keep the file, provider,
source key, and scanner options from your local preview. Change the destination
to `--to cloud`, and pass the connected repository URL or Cloud ID to
`--repository`. Preview again with `--dry-run --format json`. [Cloud setup](../../sdk/typescript/docs/cli.md#preview-and-publish)
@@ -89,8 +88,9 @@ For a Cloud import, check the receipt for the destination shown in the preview.
| Repository publisher (environments in `requests`) | Check each receipt, the verified and unacknowledged counts, failures, and exclusions. |
To inspect published findings in Codex, [connect the Cloud app](../../sdk/typescript/README.md#read-existing-cloud-findings)
and ask for imported findings in the destination repository. For a private import,
ask for your private import history.
and ask for imported findings in the destination repository. If the scanner has no
filter in the findings view, use the source and finding IDs from your receipt to
identify the record. For a private import, ask for your private import history.
If the repository publisher requires a reported severity, the preview excludes
findings whose severity the scanner left unknown. You can keep those findings
+4 -3
View File
@@ -44,8 +44,9 @@ name identify each occurrence. Package URLs and origin coordinates identify
the package. For a GitHub dependency, a `pkg:github/owner/repo@tag` package URL
supplies the dependency's owner, repository name and installed tag or commit.
`--source-repository-url` identifies the repository Black Duck scanned.
`advisory_ids` keeps `vulnerabilityName` and any distinct
`relatedVulnerability` verbatim, including Black Duck resource URLs.
The first entry in `evidence.advisory_ids` is `vulnerabilityName`. A second
entry identifies the related vulnerability, exactly as Black Duck reported it.
If that entry is a URL, it points to a Black Duck resource.
Look in the original row for CWE, matched-files links and remediation
status. The reader leaves fix verification, Git revision and source location
@@ -154,4 +155,4 @@ out=$(mktemp -d) &&
Keep the original rows and collection total. If the BOM changes during
pagination, export it again after the scan finishes.
[Black Duck Python client](https://github.com/blackducksoftware/hub-rest-api-python) · [Vulnerable BOM component example](https://github.com/blackducksoftware/hub-client-go/blob/5f78f7257c00fe9cebabf1bf89a6fc36a4d1f095/hubapi/testdata/vulnerableBomComponents.json)
[Black Duck Python client](https://github.com/blackducksoftware/hub-rest-api-python) · [Example BOM rows from a partial collection](https://github.com/blackducksoftware/hub-client-go/blob/5f78f7257c00fe9cebabf1bf89a6fc36a4d1f095/hubapi/testdata/vulnerableBomComponents.json)
+12 -6
View File
@@ -20,9 +20,10 @@ codex-security publish findings "$report" --to local --repository . \
```
For CxSAST, use the XML path and a key such as `cxsast/example-instance/example-project/main/sast`.
Check `report.scanId`, the SAST findings and any exclusions. A confirmed local import
with exclusions saves the accepted findings and exits with status 1. Use the same
file for confirmation and retries. [Save or publish and verify](README.md#save-or-publish-and-verify).
Check `report.scanId`, the SAST findings and any exclusions. If the preview
contains both findings and exclusions, a confirmed local import saves the
accepted findings and exits with status 1. Use the same file for confirmation
and retries. [Save or publish and verify](README.md#save-or-publish-and-verify).
## Collect an existing scan with Codex
@@ -70,6 +71,11 @@ CxSAST uses the project, query, path similarity ID and ordered path nodes,
or the reported result location for a path without nodes. Moving a node can
create a new occurrence. [Checkmarx similarity IDs](https://docs.checkmarx.com/en/34965-205026-similarity-id.html)
Findings start as `not_assessed` and retain the native severity, triage state,
paths and snippets in `evidence.source_data`. A scan may cover a directory or
archive. Verify how its paths map to the checkout before investigating a finding.
The finding title is the Checkmarx query name. The scan ID, severity, rule,
CWE (when supplied) and Checkmarx triage state appear in the imported evidence.
To trace a Checkmarx One result, read `evidence.source_data.row.data.nodes`.
For CxSAST, read `evidence.source_data.nodes` in order. If you use the
original `DeepLink` under `evidence.source_data.result`, check its server
against the CxSAST instance where you exported the scan.
The scan may cover a directory or archive. Its paths stay in the scanner
evidence until you establish how they map to the checkout.
+8 -7
View File
@@ -75,11 +75,12 @@ Check the repository, finding ARNs, paths, and exclusions. In a
multi-repository environment, a customer-supplied path can begin with a
repository name. The reader keeps that prefix. For local repeat imports, a summary replaces richer evidence already saved for the same ARN and source key. Use the detail export to keep locations, mitigation and validation evidence. To save locally, remove `--dry-run` and confirm.
### Publish to your Cloud inbox
<a id="publish-to-your-cloud-inbox"></a>
For an inbox import, sign in to a Cloud workspace with the GitHub repository
connected and support for Continuum private import jobs. If you need locations,
mitigation, or validation evidence, publish the detailed `get-code-finding` export first. A later upload
### Publish to Cloud
If you need locations, mitigation, or validation evidence, publish the detailed
`get-code-finding` export first. For private inbox imports, a later upload
with changed evidence for the same ARN can return `source_order_unknown`.
Preview the file and source key using your connected repository URL.
@@ -91,9 +92,9 @@ codex-security publish findings "$report" --to cloud --repository "$repo" \
--dry-run --format json
```
Confirm the account, repository, expected finding ARNs and `privateImport`
in the preview. Remove `--dry-run`, rerun and confirm to upload. Check the
receipt, then open a finding in your inbox and compare its source ID with the AWS ARN. [Verify the import](README.md#verify-the-import)
Check the account, repository and finding ARNs. The preview identifies the inbox
(`privateImport`) or repository environments (`requests`) that will receive them.
Remove `--dry-run` and confirm. Match the resulting source IDs to the Continuum ARNs. [Verify the import](README.md#verify-the-import)
## Detail, summaries, and repeat imports
+3 -1
View File
@@ -83,7 +83,9 @@ The local workbench keeps findings omitted from later exports. Use a separate
source key if you want to retain both formats' evidence for a finding.
[Imported finding identity and evidence](schema-guide.md)
SARIF keeps finding links, direct repository paths and reported SAST or
For SARIF, `source_finding_id` is the Endor finding UUID and `evidence.url`
is the vendor's `finding-url` when supplied. Use the URL to open the finding in
Endor. Use `locations` for direct repository paths and reported SAST or
Secrets lines. Look in the original evidence for diagnostic levels, CVSS and
indexed or base-relative artifact references. If the report includes repository
URLs, they must match a comparable local Git remote when available, or the
+4 -1
View File
@@ -55,7 +55,10 @@ selected Cloud repository. If the preview matches,
## Identity and evidence
The host, repository, alert number and ref identify a finding. The same alert
on two refs keeps separate evidence. Missing security severity stays `unknown`.
on two refs keeps separate evidence. The finding URL opens the GitHub alert.
The file, line and commit come from the selected instance. Severity comes from
the rule’s security rating. A SARIF level such as `error` leaves a missing
security rating `unknown`.
A GitHub dismissal applies to the entire alert, even when a selected ref's
instance is open or fixed. A GitHub connection in Codex can select records.
+4 -2
View File
@@ -66,8 +66,10 @@ alerts for the same GHSA keep separate histories. Repeat imports update the
alerts you include and keep the ones you omit.
Each finding records the matched package, ecosystem, manifest path, affected
version range, advisory IDs and first patched version when available. The
native alert retains GitHub's state and timestamps. The reader requires
version range, advisory IDs and first patched version when available. The URL
opens the repository alert. Severity comes from the matched package vulnerability,
which can differ from the advisory’s overall severity. The native alert retains
GitHub’s state and timestamps. The reader requires
repository-relative manifest paths and rejects conflicting alert identities,
packages or ranges.
@@ -72,7 +72,9 @@ matches, [save locally or publish to Cloud and verify the result](README.md#save
## Identity and evidence
Repository and global advisories have distinct finding IDs, even when they
share a GHSA ID and source key. A global advisory has no source repository.
share a GHSA ID and source key. The finding URL opens the selected disclosure.
A repository advisory links to that repository’s advisory page. A global advisory
links to the advisory database and has no source repository.
Compare the affected package ranges with the versions installed in your
checkout to decide whether the advisory applies.
+12 -9
View File
@@ -71,11 +71,12 @@ requested ARN appears once, with no other ARNs or exclusions. If the selected
rows lack repository evidence, export those ARNs again with the missing fields.
To save the selected findings in your local workbench, remove `--dry-run` and confirm.
### Publish to your Cloud inbox
<a id="publish-to-your-cloud-inbox"></a>
For an inbox import, sign in to a Cloud workspace with the GitHub repository
connected and support for Inspector private import jobs. Preview the same file
and source key using the connected repository URL. If the local preview required a project ARN, add
### Publish to Cloud
Preview the same file and source key using the connected repository URL.
If the local preview required a project ARN, add
`--inspector-project-arn` with the same verified ARN to the command below.
```sh
@@ -86,10 +87,10 @@ codex-security publish findings "$report" --to cloud --repository "$repo" \
--dry-run --format json
```
Confirm the account, repository, expected finding ARNs and `privateImport`
in the preview. Remove `--dry-run`, rerun and confirm to upload. Check the
receipt, then open a finding in your inbox and compare its source ID with the
AWS ARN. Retry with the same report, source key, Git URL, and any project ARN.
Check the account, repository and finding ARNs. The preview identifies the inbox
(`privateImport`) or repository environments (`requests`) that will receive them.
Remove `--dry-run` and confirm. Match the resulting source IDs to the Inspector ARNs.
Retry with the same report, source key, Git URL, and any project ARN.
A private import with changed evidence for the same ARN can return
`source_order_unknown`. [Verify the import](README.md#verify-the-import)
@@ -103,7 +104,9 @@ evidence. New closed or suppressed findings start as `not_assessed`.
Code findings expose detector information, CWEs, and the reported source line
range. When those fields exceed Cloud limits, you can read them in
`evidence.source_data.finding`. Package findings use the primary vulnerability ID as their advisory
and keep dependency versions. Related vulnerability IDs remain available in
and keep dependency versions. Their evidence URL opens the advisory supplied by
Inspector when available. The finding ARN identifies the occurrence in AWS.
Related vulnerability IDs remain available in
`evidence.source_data.finding.packageVulnerabilityDetails.relatedVulnerabilities`.
[AWS code findings](https://docs.aws.amazon.com/inspector/v2/APIReference/API_CodeVulnerabilityDetails.html) · [AWS package findings](https://docs.aws.amazon.com/inspector/v2/APIReference/API_PackageVulnerabilityDetails.html)
+10 -5
View File
@@ -37,8 +37,10 @@ codex-security publish findings "$opengrep_report" --to local --repository . \
Check the findings, exclusions and `report.errors`, even if the findings list
is empty. A zero-result report with scanner errors fails the import. In the
Cloud preview, check `excluded` again. If the traces grouped at one occurrence
exceed the 256 KiB evidence limit, Cloud excludes that entire occurrence.
Cloud preview, compare `findings` and `excluded` by `source_finding_id`.
An oversized trace can be excluded while other traces for the same occurrence
are retained. If the remaining group still exceeds 256 KiB, the reader
excludes the whole occurrence.
Keep `--provider opengrep` for both destinations.
[Save or publish and verify](README.md#save-or-publish-and-verify).
@@ -49,9 +51,12 @@ Both destinations store `semgrep` as the provider and `OpenGrep` in
Moving a match or changing the spelling of a Windows path can create a new
record. [Imported evidence](schema-guide.md)
The reader groups traces at the same occurrence. It keeps the rule level,
snippets, ignored state and fingerprints when present. Severity is `unknown`
because OpenGrep levels such as `ERROR` describe rule matches.
The title is the rule ID and the description is the rule's message. The reader
groups traces at the same occurrence and keeps snippets, ignored state and
fingerprints when present. OpenGrep levels such as `ERROR` describe rule
matches, so the vulnerability severity is `unknown`. The local workbench
and private Cloud inbox accept that value. A Cloud repository publisher that
requires a known severity excludes these findings in the preview.
## Diagnostics and coverage
+20 -10
View File
@@ -48,15 +48,19 @@ inspect the reader’s exclusions or input error before retrying.
Imported records start with `assessment.state` set to `not_assessed`. The
[evidence schema](../../sdk/typescript/schemas/external-findings.schema.json)
defines the fields the reader can populate.
defines the fields under `evidence`. Read the normalized fields first. Use the
saved vendor record to investigate a detail the scanner did not expose there.
| Field | How to use it |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`, `severity` | Required source evidence. Severity can be `unknown`. A scanner verdict or suppression can be reported alongside it. |
| `packages[]` | Compare an observed `installed_version` with the reported `vulnerable_version_range` and `fixed_versions`. An advisory may supply only a range or fix. |
| `locations[]`, `code_revision` | Navigate to a reported repository path and line at the scanned revision when available. `details.code.end_line` extends the first location. |
| `details` | Optional context for `sast`, `secret`, `iac` or `advisory` findings. For GHSA, `details.advisory.source` distinguishes repository and global disclosures. |
| `source_data` | The vendor fields retained for this record. Keep the original export when you need scan-wide diagnostics or inventory. |
| Field | How to use it |
| ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`, `description`, `severity` | The title identifies what the scanner reported. An optional description explains the finding. Severity can be `unknown`. |
| `url` | Open the scanner finding or advisory supplied by the reader. This link can lead to a vendor portal that requires sign-in. |
| `details.repository.url`, `details.file_url` | Open the source repository or the reported file. A repository link alone does not identify a file or revision. |
| `advisory_ids[]`, `details.weakness_ids[]`, `details.rule` | CVE and GHSA IDs identify vulnerabilities or advisories. CWEs classify weaknesses. A rule ID identifies the scanner check. |
| `packages[]` | Compare an observed `installed_version` with the reported `vulnerable_version_range` and `fixed_versions`. An advisory may supply only a range or fix. |
| `locations[]`, `code_revision` | Navigate to a reported repository path and line at the scanned revision when available. `details.code.end_line` extends the first location. |
| `details` | Optional context for `sast`, `secret`, `iac` or `advisory` findings. For GHSA, `details.advisory.source` distinguishes repository and global disclosures. |
| `source_data` | The vendor fields retained for this record. Keep the original export when you need scan-wide diagnostics or inventory. |
Use finite JSON numbers in evidence and report metadata. Supply integers outside
JavaScript’s safe range as strings to preserve their value. In SDK inputs, use
@@ -71,8 +75,14 @@ readers also apply the Cloud size limit to the evidence they return.
## Operate the two destinations
**Local.** Run `codex-security findings imported PATH --format json` with the
repository path from the preview. Each record includes
**Local.** Run `codex-security findings imported PATH` with the repository path
from the preview. In a terminal, the list shows the source key and finding ID,
severity and title. It also shows the first reported package and location,
the primary reference, and a distinct file link when available. Installed,
affected and fixed package versions appear when the scanner supplied them. If the reported
scanner differs from the stored provider, both appear (for example, OpenGrep
and `semgrep`). A rule-ID title can include a short scanner message. Pass `--format json` for
all locations and the complete saved evidence. Each record includes
`sourceKey`, `sourceFindingId`, `version`, `evidence` and `assessment`.
**Private Cloud inbox.** Check the format, size and digest under
+16 -7
View File
@@ -6,7 +6,7 @@ source of finding IDs.
| Starting point | What to collect | Destination |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| [CLI or CI report](#quick-start) | A Code-only JSON or self-contained SARIF 2.1.0 file, optionally gzipped. Native JSON keeps Semgrep severity and available snippets. | Local or Cloud |
| [Guardian in Codex](#import-selected-guardian-findings) | Selected Code or Supply Chain findings through the connected Guardian account. | Local only |
| [Guardian in Codex](#import-selected-guardian-findings) | Selected Code or Supply Chain findings through the connected Guardian account. | Local or Cloud |
| [Selected Web API IDs](#existing-platform-findings) | Original project response and SAST findings pages for one full Git ref. Use the SDK to save a selection or [import it directly](#import-selected-semgrep-platform-sast-findings-with-the-sdk). | Local or Cloud |
| [Whole Platform project](#collect-a-platform-project-and-branch) | All findings for one project, full ref and product using a Web API token. | Local or Cloud |
@@ -78,17 +78,17 @@ repository references in the third argument's `sourceRepositories`. Use
## Import selected Guardian findings
Guardian captures can be saved only to the local workbench. Sign in to
Sign in to
[Semgrep Guardian for Codex](https://docs.semgrep.dev/semgrep-guardian/quickstart).
Ask Codex to import the selected Code or Supply Chain findings from Guardian
into the local workbench. Specify the deployment, repository and full Git ref.
into the local workbench or the matching Cloud repository. Specify the deployment, repository and full Git ref.
Guardian handles authentication through its existing connection.
Codex calls `get_semgrep_sast_findings` or `get_semgrep_supply_chain_findings`
with that scope. If you already selected rows from that tool, Codex can reuse
the successful response. It saves the exact string IDs and original selected
rows from `structuredContent.findings`. Guardian returns only the repository
name, so confirm its SCM URL against the checkout before saving the capture.
name, so verify its SCM URL before saving the capture. The importer checks that URL against the checkout or the selected Cloud repository.
A missing or ambiguous selected ID stops the import. Guardian defaults to 20
open or reviewing results and returns at most 1,000 per call.
@@ -121,19 +121,28 @@ await writeFile("guardian.json", JSON.stringify(capture), {
});
```
Preview the local import. After review, repeat the command without `--dry-run` and confirm. Reuse the same file and source key for a retry.
Preview the selected findings for the intended destination.
```sh
codex-security publish findings /path/to/private/guardian.json --provider semgrep \
--to local --repository /path/to/project --source-key example/project/topic --dry-run --format json
```
For Cloud, replace `--to local --repository /path/to/project` with
`--to cloud --repository https://github.com/example/project`, using the URL
or Cloud ID of the repository you verified. After reviewing the destination,
findings and exclusions, repeat without `--dry-run` and confirm. Keep the
same capture and source key for a retry.
For normalized SDK imports, select the `semgrep` provider and keep each generated
Guardian ID with its original finding and collection scope. The repository URL
in each finding must agree with the report's mapping.
Guardian records retain the original MCP fields. The summary omits end lines,
CWEs, package versions and fix versions. Guardian and Web API records keep
In the preview, check the rule and message in `evidence.title` and
`evidence.description`, the selected ref in `branch`, and the file and
starting line in `locations`. The verified SCM URL identifies the repository.
The original Guardian row is in `source_data.finding`. Guardian supplies
no end line, CWE IDs, package versions or fix versions in this summary. Guardian and Web API records keep
separate identities even when their IDs look identical. To verify a pair,
identify the same occurrence independently by deployment, mapped project,
product, full ref, rule and location. Then compare the complete ID strings,
+3 -2
View File
@@ -90,8 +90,9 @@ violations.
[Install the plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex) · [Studio export scope](https://github.com/snyk/studio-recipes/blob/3752dd05a462184dcce44af3c247f287b41e35de/plugins/codex/skills/snyk-findings-export/SKILL.md#L15-L20) · [Evo MCP tools](https://docs.snyk.io/agent-security/evo-by-snyk/platform-surfaces/evo-mcp-server#policies-and-issues)
The bundle keeps collection context, ignored status and each selected MCP
record. The mapper can shorten descriptions and omit alternate dependency
paths. Paths are relative to the scan target. The reader records a commit
record. Use `evidence.advisory_ids` for the Snyk advisory and its CVE aliases.
The export can shorten descriptions and omit alternate dependency paths.
Paths are relative to the scan target. The reader records a commit
only for a clean workspace with a known revision.
[SCA mapper](https://github.com/snyk/studio-mcp/blob/main/internal/oss/map.go)
+6 -3
View File
@@ -79,9 +79,12 @@ comparable remote must match if the checkout has any. Preview again if a
fetch URL changes.
Each issue key identifies one record within its source and repository.
Reimport updates its evidence, including file ranges and available data flows.
In a monorepo, repository-relative locations require a verified Sonar project
base directory.
The title is the rule name when available, otherwise the rule key. The
description is the issue message. Severity comes from the security impact,
or the native severity for a legacy vulnerability. The capture supplies a
link to that issue on the selected branch or pull request. The primary file
range requires a verified project base directory. Other flow locations and
their messages remain in the original issue under `evidence.source_data.issue.flows`.
## Use a native JSON export
+10 -1
View File
@@ -42,4 +42,13 @@ codex-security publish findings "$reports/selection.json" --provider tenable \
--source-key "TENANT_ALIAS/$asset_id" --dry-run --format json
```
Check the preview against your selection. Remove `--dry-run` and confirm to save, then run `codex-security findings imported "$checkout" --format json`. The saved record retains Tenable's exact finding ID and state. Its Codex assessment starts as `not_assessed`. With the same source key, changed evidence updates that record and identical evidence preserves its version.
Check the preview against your selection. The repository URL identifies the code
repository mapped to the Tenable asset. For a reported code location, check
`evidence.locations`. The vendor description is in `evidence.description`.
The original state and optional solution are in `evidence.source_data.finding`.
Remove `--dry-run` and confirm to save. Run
`codex-security findings imported "$checkout" --format json` to read back
the exact Tenable finding ID and its initial `not_assessed` Codex assessment.
Reusing the source key updates changed evidence and preserves the version of
an identical finding.
+1
View File
@@ -27,6 +27,7 @@ Use credential-free repository URLs. If the importer reports ambiguous or confli
## Read the evidence and repeat an import
- Each finding retains its native vulnerability, exact `FixedVersion` expression and, when available, the matched package and declaration lines. Ambiguous archive paths stay in the raw evidence.
- Open `evidence.url` for Trivy's primary advisory. Other advisory links are in `evidence.source_data.vulnerability.References`. A line in `locations` points to the package declaration when Trivy supplied one.
- A package can appear many times in the same lockfile. Cloud projects the first 100 locations per finding. The full list of declaration ranges is in `source_data.package.Locations`.
- Trivy can scan uncommitted files. Its reported commit stays in `source_data.report.Metadata.Commit`. Imported findings start as `not_assessed`, including when Trivy reports an upstream fix.
- Changes to severity, installed version or declaration line update the same occurrence. A different manifest or package path identifies a separate occurrence. Duplicate identities are excluded as a group. Omitted findings stay open.
+9 -7
View File
@@ -43,15 +43,17 @@ from the same application and context.
The API origin, application, context and native `issue_id` identify a policy
flaw. Build number, source line, CWE and Pipeline flaw ID are separate fields.
The original row keeps the numeric severity, CWE, description, status,
mitigation and resolution. The reader accepts the numeric CWE and category name
defined in the Findings API schema, as well as expanded CWE and category objects
in HAL exports. [Findings API schema](https://api.swaggerhub.com/apis/Veracode/veracode-findings_api_specification/2.1)
The finding title uses the category name, then the CWE name or ID when a name
is missing. The description and status come from the flaw. The original
row retains the Veracode severity (0–5), CWE, mitigation and resolution.
The reader accepts numeric CWEs and category names as well as expanded CWE
and category objects in HAL exports. [Findings API schema](https://api.swaggerhub.com/apis/Veracode/veracode-findings_api_specification/2.1)
If you export with a numeric category filter, the rows must include category
IDs so the reader can verify the selection. Veracode reports the static analysis
path, line and module. Check the path against the checkout yourself. The import
supplies no column or Git commit.
IDs so the reader can verify the selection. To locate a flaw, use its
`issue_id` in the application identified by `applicationUrl`. The module,
file path and line in `row.finding_details` refer to the analyzed artifact.
Check that path against the checkout before citing a source location.
A Veracode resolution records upstream status. Assess the fix separately.
The workbench keeps flaws omitted from later exports.
+3 -2
View File
@@ -60,8 +60,9 @@ JSON can contain a single finding, an array of selected findings, a detailed
vulnerability report or a complete `data.vulnerabilityFindings.nodes`
collection. JSONL can hold one package record per line. Preserve `id`, `name`,
`detailedName`, `vulnerableAsset.id` and `vendorSeverity` or `severity`, plus
available package, image and repository metadata. Use the Wiz finding ID for
identity. Many package occurrences can share a CVE.
available package, image and repository metadata. JSON uses `vendorSeverity`
when present, then `severity`. A reported `NONE` becomes `unknown`. The Wiz
finding ID identifies the occurrence. Many occurrences can share a CVE.
For GitHub Enterprise branch assets, keep `vulnerableAsset.cloudProviderURL`
and either `nativeType: "github#repositoryBranch"` or both
@@ -16,24 +16,43 @@ const agent = readPluginFile(`${skillRoot}/agents/openai.yaml`);
const plugin = JSON.parse(readPluginFile(".codex-plugin/plugin.json"));
assert.match(skill, /references\/ticket-intake\.md/);
assert.match(
ticketIntake,
/\bsearchJiraIssuesUsingJql`?\s+for\s+collections\b|\bfor\s+collections,\s+use\s+`?searchJiraIssuesUsingJql\b/i,
const paragraphs = ticketIntake.split(/\n\s*\n/u);
const paragraphWords = paragraphs.map(
(paragraph) => new Set(paragraph.match(/\w+/g)),
);
for (const [tool, ...fields] of [
["searchJiraIssuesUsingJql", "nextPageToken", "isLast"],
["listJiraIssueComments", "startAt", "isLast"],
["list_issues", "parentId"],
]) {
assert.ok(
paragraphWords.some(
(words) => words.has(tool) && fields.every((field) => words.has(field)),
),
`Expected the ${tool} instructions to include ${fields.join(", ")}`,
);
}
assert.match(ticketIntake, /natural-language search[\s\S]*discover[\s\S]*JQL/);
assert.match(ticketIntake, /exhaust[\s\S]*pag(?:es|ination)/i);
assert.match(ticketIntake, /workitem search .*--fields "\$fields" --paginate/);
assert.match(ticketIntake, /workitem view .*--fields "\$fields"/);
const searchArgs =
ticketIntake.match(/`acli jira workitem search ([^`]+)`/u)?.[1] ?? "";
const viewArgs =
ticketIntake.match(/`acli jira workitem view ([^`]+)`/u)?.[1] ?? "";
assert.match(searchArgs, /(?:^|\s)--jql\s+"\$jql"(?=\s|$)/u);
assert.match(searchArgs, /(?:^|\s)--paginate(?=\s|$)/u);
assert.match(viewArgs, /(?:^|\s)"\$key"(?=\s|$)/u);
for (const args of [searchArgs, viewArgs]) {
assert.match(args, /(?:^|\s)--fields\s+"\$fields"(?=\s|$)/u);
assert.match(args, /(?:^|\s)--json(?=\s|$)/u);
}
assert.match(ticketIntake, /missing connector|connector.*unavailable/i);
assert.match(ticketIntake, /authentication|reauthorize/i);
assert.match(ticketIntake, /insufficient permission|request access/i);
assert.match(ticketIntake, /not found|inaccessible/i);
assert.match(ticketIntake, /transient/i);
const provenance =
ticketIntake
.split(/\n\s*\n/u)
.find((paragraph) => paragraph.includes("normalized_input.references")) ??
"";
paragraphs.find((paragraph) =>
paragraph.includes("normalized_input.references"),
) ?? "";
for (const field of [
"issue key",
"URL",
@@ -24,7 +24,7 @@ For a finding link, accept the selected Cloud `webOrigin` with the path `/codex/
## List and inspect findings
When the findings list or detail tool offers `api_version`, select `v2` for requests that include imported scanner findings. The default `v1` view covers native findings. For an imported-only list, also set `source` to `imported` if exposed. Use `provider` to filter scanner occurrences. To list grouped issues with published evidence from a scanner, use `defense_factory_canonical_findings_list` with `published_evidence_provider`. Scope grouped issues to a repository with its stable ID in `repo_id`. Use the provider values advertised by each tool. If you filter returned evidence locally, follow every page in the requested scope and say how you filtered it.
When the findings list or detail tool offers `api_version`, select `v2` for requests that include imported scanner findings. The default `v1` view covers native findings. For an imported-only list, also set `source` to `imported` if exposed. Use `provider` to filter scanner occurrences. To list grouped issues with published evidence from a scanner, use `defense_factory_canonical_findings_list` with `published_evidence_provider`. Scope grouped issues to a repository with its stable ID in `repo_id`. Use the provider values advertised by each tool. If the scanner has no filter value, list imported findings within the requested repository and inspect the returned provider and scanner origin where available. For example, OpenGrep uses the Semgrep provider and identifies itself in `details.scanner_origin`. Follow every page for a complete answer. If the evidence available to the caller cannot identify the scanner, report that limit.
Use `defense_factory_findings_list` with the discovered repository URL in `repo` and the user's filters; `repo` accepts comma-separated URLs, not repository IDs. Workflow tools use the returned repository ID in `repo_id`. Filters may include severity (`criticality`), lifecycle `status`, `source`, `q`, `path_prefix`, `start_at`, `end_at`, `scan_id`, `review_run_id`, `validated`, `has_patch`, `author`, and `assignee`; use the tool's current schema for available filters and their accepted values. `assignee` accepts comma-separated recorded user emails and is separate from commit authorship. Do not invent an assigned-team filter.
@@ -15,7 +15,7 @@ Use the same acquisition format for repeated imports. Check the provider's ident
## Import locally
Use the checkout path with `--repository`. A saved report can be imported locally offline. Use this destination for Tenable One Code Repository captures and selected Semgrep Guardian findings. [Supported inputs by provider](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#choose-your-scanner)
Use the checkout path with `--repository`. A saved report can be imported locally offline. Use this destination for Tenable One Code Repository captures. [Supported inputs by provider](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#choose-your-scanner)
```sh
codex-security publish findings /path/to/selected-wiz-findings.json \
@@ -102,7 +102,7 @@ For a user-requested new scan, use the installed Semgrep CLI from the source rep
For a selection of existing Code or Supply Chain findings in Codex, use the signed-in [Semgrep Guardian plugin](https://docs.semgrep.dev/semgrep-guardian/quickstart). Call its `get_semgrep_sast_findings` or `get_semgrep_supply_chain_findings` tool with the selected `deployment_name`, `repository_name` and full `ref`. Preserve any state and severity filters used for that selection. Reuse an existing successful tool result when its scope is explicit. If a selected ID is missing, report it and check the query scope and filters with the user. A project-wide fetch is a separate request.
Save a private JSON capture outside the checkout with `format: "semgrep-guardian-selection/v1"`, the verified `sourceRepositoryUrl`, the MCP `request` (tool `name` and `arguments`), the exact selected string `findingIds`, and `structuredContent: { findings: [...] }` containing the original selected tool rows. Match IDs exactly and keep the tool's repository, ref and evidence. Guardian returns a repository name, so confirm its mapping to the selected checkout URL. Use the [Guardian preview command](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-guardian-findings) and confirm the selection locally. Guardian handles sign-in for this workflow. Guardian and Web API IDs remain separate even when the strings match.
Save a private JSON capture outside the checkout with `format: "semgrep-guardian-selection/v1"`, the verified `sourceRepositoryUrl`, the MCP `request` (tool `name` and `arguments`), the exact selected string `findingIds`, and `structuredContent: { findings: [...] }` containing the original selected tool rows. Match IDs exactly and keep the tool's repository, ref and evidence. Guardian returns a repository name, so verify its SCM URL for the local checkout or selected Cloud repository. Use the [Guardian preview command](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-guardian-findings) for the intended destination and confirm after reviewing the selection. Guardian handles sign-in for this workflow. Guardian and Web API IDs remain separate even when the strings match.
For a whole project and ref, use the [Web API collector](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#collect-a-platform-project-and-branch) with its read-capable token. If the user supplies [saved Web API responses](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#existing-platform-findings), use the IDs from those records. Preview Web API findings against the requested local or Cloud repository.
@@ -163,9 +163,11 @@ Obtain explicit confirmation for this concrete upload, including skipped records
### Upload and report
Read the structured result even when the process exits nonzero. Progress appears on stderr. For a private inbox import, check `privateJob.status`, the job counts, errors and unprocessed records. A completed job can have `verified: 0`. For the repository publisher, report verified and unacknowledged records from the item receipts. For either destination, include exclusions, failures and any `savedSubmission` checkpoint. [Result fields and exit codes](https://github.com/openai/codex-security/blob/main/sdk/typescript/docs/cli.md#results-and-exit-codes)
Read the structured result even when the process exits nonzero. Progress appears on stderr. For a private inbox import, check `privateJob.status`, the job counts, errors and unprocessed records. A completed job can have `verified: 0`.
A receipt confirms ingestion of scanner evidence. A private finding can then be assessed against the repository and published to shared Findings. Link to the returned `cloudUrl` when available.
For the repository publisher, report `verified` for findings the CLI confirmed by readback and `unacknowledged` for records without a receipt. Use `failures` to identify records the publisher rejected. For either destination, include exclusions and any `savedSubmission` checkpoint. [Result fields and exit codes](https://github.com/openai/codex-security/blob/main/sdk/typescript/docs/cli.md#results-and-exit-codes)
A private finding can be assessed against the repository and published to shared Findings. Link to the returned `cloudUrl` when available.
### Resume an interrupted upload
@@ -6,7 +6,11 @@ Retrieve the requested content before normalization. Do not infer inaccessible t
By default, use the native [Atlassian](app://asdk_app_6a83901dde988191b3f3cefdcc19acfa) app for Jira. Resolve identity and site with `atlassianUserInfo` and `getAccessibleAtlassianResources`; keep that connection and site for the selected set. Ask when the source is ambiguous.
Use `getJiraIssue` for exact issues and `searchJiraIssuesUsingJql` for collections. Exhaust the JQL result pages by following `nextPageToken` until `isLast` is true. When the request includes comments, use `listJiraIssueComments` and advance `startAt` until `isLast` is true. Preserve each comment’s visibility and whether it is an internal note. Use only read operations for intake. Discover deferred metadata through `discover` and `executeRead`.
Use `getJiraIssue` for a single issue. For collections, use `searchJiraIssuesUsingJql` and follow `nextPageToken` until `isLast` is true.
When the request includes comments, use `listJiraIssueComments` and advance `startAt` until `isLast` is true. Preserve each comment’s visibility and whether it is an internal note.
Use only read operations for intake. Discover deferred metadata through `discover` and `executeRead`.
Use natural-language search to discover a site, project, issue family, or first key from a vague request, then use JQL or exact fetches. Keep user-supplied JQL intact. Order queries you build by a stable field and preserve the JQL as provenance. Jira text search tokenizes punctuation: if an exact marker gives no results, search a stable token and filter summaries for the exact family when those fields are authorized.
+10 -5
View File
@@ -1467,13 +1467,18 @@ directory. Each imported record starts as `not_assessed`. Unknown revisions and
locations stay unknown. Repository-scoped sources are checked against comparable
configured Git remotes as described in the provider guide. Reimporting the same
source key and finding ID reports created, updated, or unchanged records.
Records omitted from the new selection stay stored. An import with exclusions
exits with status 1. Local imports can retain evidence that exceeds Cloud's per-finding limits.
Records omitted from the new selection stay stored. Local imports can retain
evidence that exceeds Cloud's per-finding limits.
If a report contains both ready and excluded records, the local dry run exits
with status 0. After confirmation, the import stores the ready records and
exits with status 1. If all records are excluded, both commands exit with
status 2. A clean empty report exits with status 0 in either mode and stores
no findings.
Preview the same file and source key again for the intended destination before
publishing. Semgrep Guardian captures support local import only. Both Web API
formats, a selected SAST capture and a full project collection, support local
and Cloud import. Choose the [Semgrep import method](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md) that matches your source.
publishing. Semgrep Guardian selections, Web API SAST selections and full
project collections support both destinations. Choose the [Semgrep import method](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md) that matches your source.
## Import Trivy dependency findings
+2 -3
View File
@@ -11,11 +11,11 @@ import {
normalizeRecords,
readScannerJson,
record,
reportableScannerSeverity,
requiredText,
stableId,
text,
} from "./scanner-import.js";
import { FailureSeveritySchema } from "./scan-settings.js";
import {
declaredScannerRepositoryUrl,
repositoryScopeValidator,
@@ -417,14 +417,13 @@ function normalizeReport(
row["componentName"],
"Black Duck component name",
);
const severity = text(vulnerability["severity"])?.toLowerCase();
const related = text(vulnerability["relatedVulnerability"]);
const { packages, enrichment } = blackDuckPackages(row);
return validateEnrichedExternalEvidence(
{
title: `${advisory} in ${name}`,
description: text(vulnerability["description"]),
severity: FailureSeveritySchema.safeParse(severity).data ?? "unknown",
severity: reportableScannerSeverity(vulnerability["severity"]),
advisory_ids:
related && related !== advisory ? [advisory, related] : [advisory],
packages,
+72 -8
View File
@@ -127,7 +127,10 @@ import {
} from "./external-findings-publish.js";
import { prepareLocalExternalImport } from "./external-findings-import.js";
import { validateInspectorProjectMapping } from "./inspector-findings.js";
import { listLocalExternalFindings } from "./external-findings-local.js";
import {
listLocalExternalFindings,
type StoredExternalFinding,
} from "./external-findings-local.js";
import type { collectSonarIssues } from "./sonar-collector.js";
import { prepareSonarImport } from "./sonar-import.js";
import {
@@ -713,6 +716,62 @@ function publicationIssueUrl(value: string | undefined): string | undefined {
return value;
}
function renderImportedFindings(
repository: string,
findings: readonly StoredExternalFinding[],
width: number,
): string {
const lines = [
`${formatItemCount(findings.length, "imported finding")} in ${diagnosticValue(repository)}`,
];
for (const { provider, sourceKey, sourceFindingId, evidence } of findings) {
lines.push("", `[${evidence.severity}] ${diagnosticValue(evidence.title)}`);
if (evidence.title === evidence.details?.rule?.id) {
const message = evidence.description?.trim().split(/[\r\n]/u, 1)[0];
if (message && message !== evidence.title)
lines.push(
fitProgressLine(` Message: ${diagnosticValue(message)}`, width),
);
}
const scanner = evidence.details?.scanner_origin?.trim();
if (scanner && scanner.toLowerCase() !== provider.toLowerCase())
lines.push(` Scanner: ${diagnosticValue(scanner)}`);
lines.push(
` Source: ${diagnosticValue(provider)} (${diagnosticValue(sourceKey)}) Finding ID: ${diagnosticValue(sourceFindingId)}`,
);
const pkg = evidence.packages?.[0];
if (pkg) {
const parts = [` Package: ${diagnosticValue(pkg.name)}`];
if (pkg.installed_version)
parts.push(`Installed: ${diagnosticValue(pkg.installed_version)}`);
if (pkg.vulnerable_version_range)
parts.push(
`Affected: ${diagnosticValue(pkg.vulnerable_version_range)}`,
);
if (pkg.fixed_versions?.length)
parts.push(`Fixed: ${diagnosticValue(pkg.fixed_versions.join(", "))}`);
lines.push(parts.join(" "));
}
const location = evidence.locations?.[0];
if (location)
lines.push(
` Location: ${diagnosticValue(location.path)}${location.line == null ? "" : `:${location.line}`}`,
);
if (evidence.url)
lines.push(` Reference: ${diagnosticValue(evidence.url)}`);
const fileUrl = evidence.details?.file_url;
if (fileUrl && fileUrl !== evidence.url)
lines.push(` File: ${diagnosticValue(fileUrl)}`);
}
if (findings.length)
lines.push(
"",
"Scanner evidence is unassessed. Use --format json for all fields and saved scanner data.",
);
return `${lines.join("\n")}\n`;
}
function renderExternalPublicationSummary(
result: ExternalPublicationResult,
): string {
@@ -2471,6 +2530,10 @@ export async function main(
options.signal,
);
}, selection);
const useInteractiveHistory = (format: string) =>
format === "toon" &&
output.isTTY === true &&
!argv.some((argument) => OUTPUT_OPTION.test(argument));
const presentHistory = (
result: JsonObject | undefined,
command: HistoryCommand,
@@ -2481,12 +2544,7 @@ export async function main(
showLinkedFindings?: boolean;
} = {},
): JsonObject | undefined => {
if (
result === undefined ||
format !== "toon" ||
output.isTTY !== true ||
argv.some((argument) => OUTPUT_OPTION.test(argument))
) {
if (result === undefined || !useInteractiveHistory(format)) {
return result;
}
renderedOutput = renderScanHistory(result, command, {
@@ -2649,6 +2707,12 @@ export async function main(
signal: controller.signal,
},
);
if (useInteractiveHistory(format))
renderedOutput = renderImportedFindings(
repository,
findings,
output.columns || 96,
);
return { repository, findings };
} catch (error) {
if (controller.signal.aborted) {
@@ -4469,7 +4533,7 @@ export async function main(
.command("semgrep", {
description:
"Read a full Semgrep Platform project and ref through the Web API.",
hint: "Requires SEMGREP_APP_TOKEN with Web API access. Import the saved --format json output with publish findings --provider semgrep and --to local or --to cloud. Use --to local for a selected Guardian MCP capture.",
hint: "Requires SEMGREP_APP_TOKEN with Web API access. Import the saved --format json output with publish findings --provider semgrep and --to local or --to cloud. Selected Guardian MCP captures also support both destinations.",
destructive: false,
mcp: false,
args: z.object({
+4 -8
View File
@@ -12,6 +12,7 @@ import {
readScannerJson,
record,
relativePath,
reportableScannerSeverity,
requiredText,
sarifRunRepositories,
sarifRunResults,
@@ -209,13 +210,6 @@ function normalizeReport(
...strings([asRecord(malware?.["meta"])?.["name"]]),
...strings(asRecord(malware?.["spec"])?.["aliases"]),
]);
const level = text(spec["level"])
?.replace(/^FINDING_LEVEL_/u, "")
.toLowerCase();
const severity =
level && ["critical", "high", "medium", "low"].includes(level)
? level
: "unknown";
// A recommended version can refer to an introducing dependency; retain it in source_data.
const packages = name
? (paths.length ? paths : [null]).map((path) => ({
@@ -247,7 +241,9 @@ function normalizeReport(
]
.filter(Boolean)
.join("\n\n") || text(meta["description"]),
severity,
severity: reportableScannerSeverity(
text(spec["level"])?.replace(/^FINDING_LEVEL_/u, ""),
),
branch:
context["type"] === "CONTEXT_TYPE_REF" ? text(context["id"]) : null,
code_revision: text(
@@ -51,7 +51,7 @@ import {
tenableSourceRepository,
} from "./tenable-findings.js";
import {
guardianFindingSourceData,
guardianFindingRepository,
guardianSelectionFormat,
} from "./semgrep-guardian-findings.js";
import {
@@ -997,10 +997,10 @@ export async function prepareLocalImport(
);
if (source) sources.set(source, { url: source, platform: "github" });
}
const guardian = guardianFindingSourceData(finding);
const guardian = guardianFindingRepository(finding, "local");
const url = evidence.details?.repository?.url;
if (guardian) {
const source = addGuardianSource(guardian["sourceRepositoryUrl"]);
const source = addGuardianSource(guardian);
if (
(guardianReport &&
!semgrepReferenceMatches(guardianReport, source.url)) ||
+36 -10
View File
@@ -32,9 +32,11 @@ import {
} from "./private-finding-import.js";
import { readCloudCredentials } from "./cloud-publish.js";
import type { LocalExternalImportOptions } from "./external-findings-import.js";
import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";
import { tenableReportFormat } from "./tenable-findings.js";
import {
guardianFindingId,
guardianFindingRepository,
guardianSelectionFormat,
} from "./semgrep-guardian-findings.js";
import {
@@ -159,6 +161,7 @@ import type {
FindingImportRequest,
FindingImportReceipt,
ImportRepository,
Provider,
SourceReportSummary,
} from "./external-import-models.js";
@@ -693,13 +696,16 @@ function storedFindingId(finding: ExternalFinding): string {
return "";
}
function rejectLocalOnlyFindings(input: ExternalFindings): void {
function checkFindingProvider(
input: ExternalFindings,
provider: Provider,
): void {
function checkFormat(format: unknown) {
if (format === tenableReportFormat)
requireCloudReader({ provider: "tenable" });
if (format === guardianSelectionFormat)
if (format === guardianSelectionFormat && provider !== "semgrep")
throw new CodexSecurityError(
"Semgrep Guardian findings require a local import.",
"Use the semgrep provider for Guardian findings.",
);
}
checkFormat(ownData(ownData(input, "report"), "format"));
@@ -752,7 +758,8 @@ export async function prepareExternalPublication(
const hosted =
isRecord(report) &&
(semgrep
? isSemgrepPlatformFormat(report["format"])
? isSemgrepPlatformFormat(report["format"]) ||
report["format"] === guardianSelectionFormat
: isSnykRestFormat(report["format"]));
if (!semgrep && !hosted)
fileRepositories = () => snykFileRepositories(report);
@@ -793,7 +800,7 @@ export async function prepareExternalPublication(
: await normalize();
} else {
const parsed = await readExternalFindings(path, settings);
rejectLocalOnlyFindings(parsed.findings);
checkFindingProvider(parsed.findings, provider);
input =
parsed.publication ??
normalizedPublicationInput(parsed.findings, provider);
@@ -898,11 +905,20 @@ function hostedRepositoryMatcher(
isSemgrepPlatformEvidence(finding, provider),
);
const claims = new Set<string>();
let original: string | undefined;
let original =
input.report?.["format"] === guardianSelectionFormat
? declaredScannerRepositoryUrl(input.report["repositoryUrl"], "Guardian")
: undefined;
const nativeRows = [];
for (const finding of input.findings) {
const typed = finding.evidence.details?.repository?.url;
if (typed) claims.add(typed);
const guardian = guardianFindingRepository(finding, "cloud");
if (guardian) {
original ??= guardian;
claims.add(guardian);
continue;
}
const data = finding.evidence.source_data;
const sarif = semgrepSarifRepositories(finding, hasNativeSource);
for (const { url } of sarif)
@@ -1327,7 +1343,7 @@ function normalizedPublicationInput(
: undefined;
if (reader) native = reader.snapshot;
const original = historicalPublication(native);
if (original) rejectLocalOnlyFindings(original.parsed);
if (original) checkFindingProvider(original.parsed, provider);
try {
validatePublicationFindings(current, validateExternalEvidence);
} catch (error) {
@@ -1340,7 +1356,7 @@ function normalizedPublicationInput(
// Only the old selection can be reviewed when fresh validation failed.
current = { read: original.parsed.read, findings: [], excluded: [] };
}
rejectLocalOnlyFindings(current);
checkFindingProvider(current, provider);
const identity = publicationIdentity(current, provider);
return {
current,
@@ -2230,7 +2246,7 @@ async function preparePublicationInput(
!verifiableLegacyMetadata(originalParsed, true)
)
throw unmatchedPreviousNumbers();
rejectLocalOnlyFindings({ ...parsed, findings: saved });
checkFindingProvider({ ...parsed, findings: saved }, options.provider);
const approvedScope = content.inputProjection?.semgrepPartialScopeDigest;
if (
approvedScope !== undefined &&
@@ -2274,7 +2290,7 @@ async function preparePublicationInput(
!verifiableLegacyMetadata(originalParsed, false)
)
throw unmatchedPreviousNumbers();
rejectLocalOnlyFindings({ ...parsed, findings: saved });
checkFindingProvider({ ...parsed, findings: saved }, options.provider);
content.legacyApproval = true;
content.inputProjection = {
...content.inputProjection,
@@ -3126,6 +3142,11 @@ async function preparePublicationInput(
`Finding ${JSON.stringify(id)} belongs to ${JSON.stringify(url)}, which does not match the selected Cloud repository ${JSON.stringify(destination.url)}. Verify the source repository mapping before publishing.`,
);
}
if (report?.["format"] === guardianSelectionFormat)
requireDestination(
"Guardian source",
declaredScannerRepositoryUrl(report["repositoryUrl"], "Guardian"),
);
// An immutable retry may refer to an earlier repository name. Additional
// file declarations outside its saved findings authorize no new writes.
if (!historical)
@@ -3190,6 +3211,11 @@ async function preparePublicationInput(
);
for (const finding of findings) {
const { source_finding_id: id, evidence } = finding;
const guardian = guardianFindingRepository(finding, "cloud");
if (guardian) {
requireDestination(id, guardian);
requireDestination(id, evidence.details?.repository?.url);
}
checkRetainedTrivyProvider(provider, finding);
if (trivyReportUrls) {
const remote = trivyRepositoryUrl(
@@ -8,6 +8,7 @@ import {
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import { isGitHubCloudHost } from "./git-remote.js";
import { isRecord } from "./record.js";
import { REPORTABLE_SEVERITIES } from "./scan-settings.js";
import {
trackReaderSelection,
record,
@@ -201,7 +202,7 @@ 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"]),
severity: z.enum(REPORTABLE_SEVERITIES),
});
function evidence(alert: Record<string, unknown>, url: string) {
+9 -11
View File
@@ -25,7 +25,12 @@ import {
canSnapshotWithoutGetters,
cloneWithoutGetters,
} from "./record.js";
import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
import {
parseJsonOrJsonl,
readScannerText,
scannerSeverity,
text,
} from "./scanner-import.js";
import {
rememberPreviousSelection,
@@ -59,14 +64,6 @@ function sourceTimestamp(value: unknown): number | null {
return Math.floor(seconds);
}
function severity(value: unknown): string {
// SARIF error/warning/note are not vulnerability severity ratings.
return typeof value === "string" &&
["critical", "high", "medium", "low", "informational"].includes(value)
? value
: "unknown";
}
function codeScanningPrefix(
{ parsed, host }: ReturnType<typeof sourceUrl>,
repository: string,
@@ -143,7 +140,8 @@ function codeScanningFinding(record: Record<string, unknown>): {
text(rule?.["name"]) ??
text(rule?.["description"]) ??
`GitHub code-scanning alert #${number}`,
severity: severity(rule?.["security_severity_level"]),
// SARIF error, warning and note describe diagnostics. Use the security rating.
severity: scannerSeverity(text(rule?.["security_severity_level"])),
description:
[...new Set([message, description].filter(Boolean))].join("\n\n") ||
null,
@@ -264,7 +262,7 @@ function advisoryFinding(record: Record<string, unknown>): {
source_finding_id: advisorySourceId(host, selection, repository.name, id),
evidence: {
title: text(advisory["summary"]) ?? id,
severity: severity(advisory["severity"]),
severity: scannerSeverity(text(advisory["severity"])),
description: text(advisory["description"]),
url,
advisory_ids: [...new Set(advisoryIds)],
+2 -5
View File
@@ -23,6 +23,7 @@ import {
record,
repositoryFilePath,
requiredText,
scannerSeverity,
strings,
text,
} from "./scanner-import.js";
@@ -586,11 +587,7 @@ function evidence(
code?.detectorName ??
id,
description: requiredText(description, "Inspector description"),
severity: ["critical", "high", "medium", "low", "informational"].includes(
level,
)
? level
: "unknown",
severity: scannerSeverity(level),
url: text(pkg?.sourceUrl),
advisory_ids:
previousProjection && pkg?.relatedVulnerabilities
+9 -1
View File
@@ -6,7 +6,7 @@ import { gunzip } from "node:zlib";
import validSemver from "semver/functions/valid.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import { SCAN_SEVERITIES } from "./scan-settings.js";
import { REPORTABLE_SEVERITIES, SCAN_SEVERITIES } from "./scan-settings.js";
import { asRecord, isRecord } from "./record.js";
import { previousAdmission } from "./external-import-contract.js";
import { rememberPreviousSelection } from "./reader-selection.js";
@@ -226,6 +226,14 @@ export function sarifRunRepositories(
});
}
/** Normalize scanners whose reported severities range from low to critical. */
export function reportableScannerSeverity(value: unknown) {
const level = text(value)?.toLowerCase();
return (
REPORTABLE_SEVERITIES.find((severity) => severity === level) ?? "unknown"
);
}
export function scannerSeverity(value: string | null | undefined) {
return SCAN_SEVERITIES.find((severity) => severity === value) ?? "unknown";
}
+1 -2
View File
@@ -176,10 +176,9 @@ export function normalizeSemgrepFindings(
): ExternalFindings {
const document = record(input, "Semgrep report");
if (document["format"] === guardianSelectionFormat) {
if (target !== "local")
throw new Error("Import Guardian selections into the local workbench.");
return normalizeGuardianSelection(
document,
target,
options.sourceRepositoryUrl,
options.sourceRepositories,
);
+57 -41
View File
@@ -1,4 +1,7 @@
import { validateExternalEvidence } from "./external-import-contract.js";
import {
type ExternalImportTarget,
validateExternalEvidence,
} from "./external-import-contract.js";
import { CodexSecurityError } from "./errors.js";
import type {
ExternalFinding,
@@ -25,30 +28,53 @@ export const guardianSelectionFormat = "semgrep-guardian-selection/v1";
export const guardianFindingId = /^semgrep-guardian:[0-9a-f]{64}$/u;
function guardianId(scope: Record<string, unknown>, id: unknown) {
function guardianScope(data: Record<string, unknown>) {
const tool = data["tool"];
if (
tool !== "get_semgrep_sast_findings" &&
tool !== "get_semgrep_supply_chain_findings"
)
throw new Error("Select a Guardian SAST or Supply Chain findings tool.");
const deployment = requiredText(data["deployment"], "Guardian deployment");
const repository = requiredText(data["repository"], "Guardian repository");
const ref = requiredText(data["ref"], "Guardian Git ref");
requireSemgrepFullRef(ref);
return { tool, deployment, repository, ref };
}
function guardianId(scope: ReturnType<typeof guardianScope>, id: unknown) {
return stableId("semgrep-guardian", [
scope["deployment"],
scope["repository"],
scope["tool"],
scope["ref"],
id,
scope.deployment,
scope.repository,
scope.tool,
scope.ref,
requiredText(id, "Guardian finding ID"),
]);
}
export function guardianFindingSourceData({
source_finding_id,
evidence,
}: ExternalFinding) {
export function guardianFindingRepository(
{ source_finding_id, evidence }: ExternalFinding,
target: ExternalImportTarget,
) {
const data = evidence.source_data ?? {};
const generated = guardianFindingId.test(source_finding_id);
if (data["format"] !== guardianSelectionFormat && !generated) return;
const row = record(data["finding"], "Original Guardian finding");
requireGuardianRowScope(data, row);
if (source_finding_id !== guardianId(data, row["id"]))
const scope = guardianScope(data);
requireGuardianRowScope(scope, row);
if (evidence.branch != null && evidence.branch !== scope.ref)
throw new CodexSecurityError(
"The Guardian finding branch does not match the selected ref.",
);
if (source_finding_id !== guardianId(scope, row["id"]))
throw new CodexSecurityError(
"The normalized finding ID does not match the original Guardian finding.",
);
return data;
return declaredScannerRepositoryUrl(
data["sourceRepositoryUrl"],
"Guardian",
target,
);
}
type GuardianTool =
@@ -69,47 +95,36 @@ interface GuardianRequest {
function selectionScope(request: unknown, findingIds: unknown) {
const tool = record(request, "Guardian tool request");
const name = tool["name"];
if (
name !== "get_semgrep_sast_findings" &&
name !== "get_semgrep_supply_chain_findings"
)
throw new Error("Select a Guardian SAST or Supply Chain findings tool.");
const args = record(tool["arguments"], "Guardian tool arguments");
const deployment = requiredText(
args["deployment_name"],
"Guardian deployment",
);
const repository = requiredText(
args["repository_name"],
"Guardian repository",
);
const ref = requiredText(args["ref"], "Guardian Git ref");
requireSemgrepFullRef(ref);
const scope = guardianScope({
tool: tool["name"],
deployment: args["deployment_name"],
repository: args["repository_name"],
ref: args["ref"],
});
const ids = new Set(
array(findingIds, "Guardian finding IDs").map((id) =>
requiredText(id, "Guardian finding ID"),
),
);
if (!ids.size) throw new Error("Select at least one Guardian finding ID.");
return { tool: name, deployment, repository, ref, ids };
return { ...scope, ids };
}
function requireGuardianRowScope(
scope: Record<string, unknown>,
scope: ReturnType<typeof guardianScope>,
row: Record<string, unknown>,
): void {
const id = row["id"];
const repository = record(row["repository"], "Guardian finding repository");
if (
repository["name"] !== scope["repository"] ||
(row["ref"] != null && row["ref"] !== scope["ref"])
repository["name"] !== scope.repository ||
(row["ref"] != null && row["ref"] !== scope.ref)
)
throw new Error(
`Guardian finding ${id} does not match the selected repository and ref.`,
);
const expected =
scope["tool"] === "get_semgrep_sast_findings" ? "sast" : "sca";
const expected = scope.tool === "get_semgrep_sast_findings" ? "sast" : "sca";
if (
row["issueType"] != null &&
text(row["issueType"])
@@ -197,6 +212,7 @@ export async function collectSelectedSemgrepGuardianFindings(
export function normalizeGuardianSelection(
document: Record<string, unknown>,
target: ExternalImportTarget,
declaredUrl?: string,
references: readonly ExternalSourceRepository[] = [],
) {
@@ -204,13 +220,13 @@ export function normalizeGuardianSelection(
const url = declaredScannerRepositoryUrl(
document["sourceRepositoryUrl"],
"Guardian",
"local",
target,
);
const repositoryBinding = selectionRepository(url, references);
const repositoryBinding = selectionRepository(url, references, target);
if (
declaredUrl !== undefined &&
repositoryBinding.key(
declaredScannerRepositoryUrl(declaredUrl, "Guardian", "local"),
declaredScannerRepositoryUrl(declaredUrl, "Guardian", target),
) !== repositoryBinding.key(url)
)
throw new Error(
@@ -257,12 +273,12 @@ export function normalizeGuardianSelection(
finding,
},
},
"local",
target,
);
},
// Guardian's string ID has not been verified against Web API occurrence IDs.
(finding) => guardianId(scope, finding["id"]),
"local",
target,
{ report: { format: guardianSelectionFormat, repositoryUrl: url } },
);
}
+5 -14
View File
@@ -20,6 +20,7 @@ import {
optionalArray,
readScannerJson,
record,
reportableScannerSeverity,
requiredText,
sarifRunRepositories,
sarifRunContextSelector,
@@ -118,9 +119,6 @@ export function normalizeSnykFindingsExport(
finding["remediation"] ?? {},
"Snyk remediation",
);
const severity = text(
record(finding["severity"], "Snyk severity")["value"],
)?.toLowerCase();
const revision = text(sourceTarget["revision"]);
return validateExternalEvidence(
{
@@ -128,11 +126,9 @@ export function normalizeSnykFindingsExport(
description: text(
record(finding["description"] ?? {}, "Snyk description")["text"],
),
severity: ["critical", "high", "medium", "low"].includes(
severity ?? "",
)
? severity
: "unknown",
severity: reportableScannerSeverity(
record(finding["severity"], "Snyk severity")["value"],
),
advisory_ids: [
...new Set([
requiredText(rule["id"], "Snyk advisory ID"),
@@ -485,7 +481,6 @@ export function normalizeSnykJson(
vulnerability["identifiers"] ?? {},
"Snyk identifiers",
);
const severity = text(vulnerability["severity"])?.toLowerCase();
return validateExternalEvidence(
{
title: requiredText(
@@ -493,11 +488,7 @@ export function normalizeSnykJson(
"Snyk vulnerability title",
),
description: text(vulnerability["description"]),
severity: ["critical", "high", "medium", "low"].includes(
severity ?? "",
)
? severity
: "unknown",
severity: reportableScannerSeverity(vulnerability["severity"]),
advisory_ids: [
...new Set([
requiredText(vulnerability["id"], "Snyk advisory ID"),
+2 -5
View File
@@ -8,13 +8,13 @@ import {
normalizeHostedGitRepositoryUrl,
} from "./hosted-git-repository.js";
import { isRecord } from "./record.js";
import { REPORTABLE_SEVERITIES } from "./scan-settings.js";
import {
array,
normalizeRecords,
readScannerJson,
record,
relativePath,
reportableScannerSeverity,
requiredText,
stableId,
strings,
@@ -517,13 +517,10 @@ function normalizeReport(
if (!lines.size) locations.push({ path: declaration, line: null });
for (const line of lines) locations.push({ path: declaration, line });
}
const severity = text(vulnerability["Severity"])?.toLowerCase();
return validateExternalEvidence(
{
title: text(vulnerability["Title"]) ?? `${advisory} in ${name}`,
severity:
REPORTABLE_SEVERITIES.find((level) => level === severity) ??
"unknown",
severity: reportableScannerSeverity(vulnerability["Severity"]),
description: text(vulnerability["Description"]),
url: text(vulnerability["PrimaryURL"]),
advisory_ids: [
@@ -365,6 +365,17 @@ test("CLI imports OpenGrep evidence locally without assessing it", async () => {
},
},
});
const terminal = createCliTest(main, { stdout: true });
expect(
await terminal.runCli(["findings", "imported", "example project"], f.deps),
).toBe(0);
const display = terminal.stdout.text();
expect(display).toContain(`[unknown] ${findings[0].evidence.title}`);
expect(display).toContain("Message: Synthetic finding");
expect(display).toContain("Scanner: OpenGrep");
expect(display).toContain(
`Source: semgrep (example/opengrep) Finding ID: ${findings[0].sourceFindingId}`,
);
});
test("local dry runs and imports reject an entirely excluded report before opening the workbench", async () => {
@@ -463,6 +474,81 @@ test.each(["SIGINT", "SIGTERM"] as const)(
},
);
test.each([true, false])(
"imported readback summarizes only reported package versions on a terminal (installed version: %s)",
async (hasInstalledVersion) => {
const repository = resolve("workspace", "project");
const deps = dependencies({ currentDirectory: repository });
const pkg = {
name: "example-package",
vulnerable_version_range: "<2.0.0",
...(hasInstalledVersion
? { installed_version: "1.5.0", fixed_versions: ["2.0.0", "2.1.0"] }
: {}),
};
const reference = "https://example.test/alerts/42";
const fileUrl = hasInstalledVersion
? "https://example.test/project/blob/test-fixture/src/app.ts"
: reference;
deps.listLocalExternalFindings = async () => [
{
repository,
id: "external-1",
version: 1,
provider: "github",
sourceKey: "example/project",
sourceFindingId: "42",
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "2026-01-01T00:00:00Z",
assessment: { state: "not_assessed" },
evidence: {
title: "Dependency\nissue",
severity: "high",
packages: [pkg],
locations: hasInstalledVersion
? [{ path: "src/app.ts", line: 12 }]
: [],
url: reference,
details: { kind: "advisory", file_url: fileUrl },
source_data: { vendorField: "raw details" },
},
},
];
const args = ["findings", "imported"];
const interactive = createCliTest(main, { stdout: true });
expect(await interactive.runCli(args, deps)).toBe(0);
const text = interactive.stdout.text();
expect(text).toContain("[high] Dependency issue");
expect(text).toContain("github (example/project) Finding ID: 42");
const packageLine = text
.split("\n")
.find((line) => line.includes("Package:"));
expect(packageLine?.trim()).toBe(
hasInstalledVersion
? "Package: example-package Installed: 1.5.0 Affected: <2.0.0 Fixed: 2.0.0, 2.1.0"
: "Package: example-package Affected: <2.0.0",
);
expect(text).toContain(`Reference: ${reference}`);
if (hasInstalledVersion) {
expect(text).toContain("Location: src/app.ts:12");
expect(text).toContain(`File: ${fileUrl}`);
} else {
expect(text).not.toContain("Location:");
expect(text).not.toContain("File:");
}
expect(text).not.toContain("vendorField");
const explicit = createCliTest(main, { stdout: true });
expect(await explicit.runCli([...args, "--format", "json"], deps)).toBe(0);
const stored = JSON.parse(explicit.stdout.text()).findings[0].evidence;
expect(stored.packages).toEqual([pkg]);
expect(stored.source_data.vendorField).toBe("raw details");
const piped = createCliTest(main, { stdout: false });
expect(await piped.runCli(args, deps)).toBe(0);
expect(piped.stdout.text()).toContain("vendorField");
},
);
test("imported readback resolves its repository argument and supports structured output", async () => {
const deps = dependencies({ currentDirectory: resolve("workspace") });
deps.listLocalExternalFindings = async ({ repository }, settings) => {
@@ -1264,7 +1264,7 @@ test("a projected Snyk issue resumes its approved private repository after a ren
async function privateUploadFixture(
raw: unknown,
provider: "endor" | "snyk" | "wiz",
provider: "endor" | "semgrep" | "snyk" | "wiz",
repositoryUrl?: string,
) {
const f = await fixture(raw, repositoryUrl);
@@ -1752,7 +1752,100 @@ test("an undefined optional Snyk context permits generic SDK evidence", async ()
).rejects.toThrow("Expected a versioned Snyk REST report context");
});
test("a saved selection with Guardian evidence cannot resume a Cloud upload", async () => {
test.each(["sast", "sca"])(
"Guardian %s files publish and replay only at their selected repository",
async (product) => {
const url = "https://github.com/example/project";
const repository = "example/project";
const ref = "refs/heads/topic";
const id = "09007199254740993";
const report = {
format: "semgrep-guardian-selection/v1",
sourceRepositoryUrl: url,
request: {
name:
product === "sast"
? "get_semgrep_sast_findings"
: "get_semgrep_supply_chain_findings",
arguments: {
deployment_name: "example",
repository_name: repository,
ref,
},
},
findingIds: [id],
structuredContent: {
findings: [
{
id,
ref,
repository: { name: repository },
issueType: product,
severity: "HIGH",
rulePath: "example.rule",
message: "Example finding",
filePath: "src/app.ts",
line: 3,
},
],
},
};
const f = await fixture(report, url);
const binding = { ...options, provider: "semgrep" as const };
const local = normalizeSemgrepFindings(report, {}, "local");
const prepare = () => prepareExternalPublication(f.file, binding, f.deps);
const prepared = await prepare();
expect(prepared.preview.findings).toEqual(local.findings);
await f.loseResponse(prepared);
expect((await (await prepare()).publish()).verified).toBe(1);
const unscored = structuredClone(report);
unscored.structuredContent.findings[0]!.severity = "UNSPECIFIED";
const inbox = await privateUploadFixture(unscored, "semgrep", url);
const headers = inbox.f.state.catalogHeaders;
headers["Codex-Security-Repository-Import-Severities"] = "high";
delete headers["Codex-Security-Private-Import-Providers"];
await expect(inbox.prepareFile()).rejects.toMatchObject({
selection: { findings: [], excluded: [{ position: 1 }] },
});
headers["Codex-Security-Private-Import-Providers"] = "semgrep";
const privatePreview = (await inbox.prepareFile()).preview;
expect(privatePreview.privateImport?.format).toBe("security.findings.v1");
expect(privatePreview.findings[0]!.evidence.severity).toBe("unknown");
const elsewhere = await fixture(report, "https://github.com/other/project");
await expect(
prepareExternalPublication(elsewhere.file, binding, elsewhere.deps),
).rejects.toThrow(/repository/iu);
await expect(
prepareNormalizedExternalPublication(
{ ...local, report: undefined },
binding,
elsewhere.deps,
),
).rejects.toThrow(/repository/iu);
expect(elsewhere.posts).toHaveLength(0);
const missingSource = structuredClone(local);
delete missingSource.findings[0]!.evidence.source_data![
"sourceRepositoryUrl"
];
await expect(
prepareNormalizedExternalPublication(missingSource, binding, f.deps),
).rejects.toThrow(/Guardian --source-repository-url/u);
const wrongRef = structuredClone(local);
wrongRef.findings[0]!.evidence.branch = "refs/heads/other";
await expect(
prepareNormalizedExternalPublication(wrongRef, binding, f.deps),
).rejects.toThrow(/selected ref/u);
const changed = {
...local,
findings: [{ ...local.findings[0]!, source_finding_id: "another-id" }],
};
await expect(
prepareNormalizedExternalPublication(changed, binding, f.deps),
).rejects.toThrow(/original Guardian finding/);
},
);
test("a saved selection with Guardian evidence cannot resume under another provider", async () => {
const f = await fixture([normalized()]);
const prepare = () => prepareExternalPublication(f.file, options, f.deps);
const path = await f.loseResponse(await prepare());
@@ -1766,9 +1859,7 @@ test("a saved selection with Guardian evidence cannot resume a Cloud upload", as
);
const bytes = JSON.stringify(saved);
await writeFile(path, bytes);
await expect(prepare()).rejects.toThrow(
/Guardian findings require a local import/,
);
await expect(prepare()).rejects.toThrow(/semgrep provider/);
expect(f.posts).toHaveLength(1);
expect(await readFile(path, "utf8")).toBe(bytes);
});
@@ -2,6 +2,7 @@ import { expect, mock, test } from "bun:test";
import { prepareNormalizedLocalImport } from "../src/external-findings-local.js";
import { prepareNormalizedExternalPublication } from "../src/external-findings-publish.js";
import { collectSelectedSemgrepGuardianFindings } from "../src/semgrep-guardian-findings.js";
import { stableId } from "../src/scanner-import.js";
import { normalizeSemgrepFindings } from "../src/semgrep-findings.js";
import { collectSemgrepPlatformFindings } from "../src/semgrep-platform-collector.js";
import { isolatedGitReportFixture } from "./external-findings-local-helpers.js";
@@ -157,22 +158,7 @@ test("Guardian Supply Chain retains its summary and checks the operator's checko
},
};
const normalized = normalizeSemgrepFindings(sca, {}, "local");
expect(() => normalizeSemgrepFindings(sca)).toThrow(/local workbench/);
await expect(
prepareNormalizedExternalPublication(
{
...normalized,
report: {},
findings: [{ ...normalized.findings[0]!, source_finding_id: "custom" }],
},
{ repository: project, provider: "semgrep", sourceKey: "example/topic" },
{
credentials: async () => {
throw new Error("Unexpected credential lookup");
},
},
),
).rejects.toThrow(/local import/);
expect(normalizeSemgrepFindings(sca).findings).toEqual(normalized.findings);
expect(normalized.findings[0]!.evidence).toMatchObject({
locations: [],
source_data: { finding: sca.structuredContent.findings[0] },
@@ -270,6 +256,43 @@ test("normalized Guardian imports verify the original finding against the select
}
});
test("normalized Guardian rows require a real selection scope even with a matching hash", async () => {
await using fixture = await isolatedGitReportFixture(
"guardian.json",
{ provider: "semgrep", sourceKey: "test" },
{ remote: sourceRepositoryUrl },
);
const normalized = normalizeSemgrepFindings(capture, {}, "local");
for (const [override, nativeId, error] of [
[{ tool: "list_findings" }, id, /Guardian SAST or Supply Chain/],
[{ deployment: null }, id, /Guardian deployment/],
[{ repository: "" }, id, /Guardian repository/],
[{ ref: "main" }, id, /fully qualified Semgrep ref/],
[{}, 12, /Guardian finding ID/],
[{}, " ", /Guardian finding ID/],
] as const) {
const input = structuredClone(normalized);
const finding = input.findings[0]!;
const data = finding.evidence.source_data!;
Object.assign(data, override);
// Each malformed row agrees with its stored scope and ID. A matching hash alone is insufficient.
data["finding"] = {
id: nativeId,
repository: { name: data["repository"] },
ref: data["ref"],
};
finding.evidence.branch = String(data["ref"]);
finding.source_finding_id = stableId("semgrep-guardian", [
data["deployment"],
data["repository"],
data["tool"],
data["ref"],
nativeId,
]);
await expect(fixture.prepareNormalized(input)).rejects.toThrow(error);
}
});
test("normalized Guardian repository claims use the checkout's HTTP port identity", async () => {
await using fixture = await isolatedGitReportFixture(
"guardian.json",
@@ -296,7 +319,7 @@ test("normalized Guardian repository claims use the checkout's HTTP port identit
);
});
test("SDK exports containing Guardian findings fail before Cloud credential lookup", async () => {
test("SDK exports containing Guardian findings require their original provider", async () => {
const guardian = normalizeSemgrepFindings(capture, {}, "local");
const normalized = {
read: 1,
@@ -325,12 +348,12 @@ test("SDK exports containing Guardian findings fail before Cloud credential look
input,
{
repository: project,
provider: "semgrep",
provider: "wiz",
sourceKey: "example/topic",
},
{ credentials },
),
).rejects.toThrow(/local import/);
).rejects.toThrow(/semgrep provider/);
}
expect(credentials).not.toHaveBeenCalled();
});
+11 -2
View File
@@ -51,7 +51,13 @@ test("the reader preserves vendor state and optional severity and locations", as
await fixture.writeJson({
...report,
findings: [
{ ...row, severity: "INFO", state: "FIXED" },
{
...row,
severity: "INFO",
state: "FIXED",
description: "Outdated dependency",
solution: "Update the dependency",
},
{
...row,
finding_id: "00018",
@@ -63,8 +69,11 @@ test("the reader preserves vendor state and optional severity and locations", as
const { findings } = await readTenableFindings(fixture.file, repositoryUrl);
expect(findings[0]!.evidence).toMatchObject({
severity: "informational",
description: "Outdated dependency",
locations: [],
source_data: { finding: { state: "FIXED" } },
source_data: {
finding: { state: "FIXED", solution: "Update the dependency" },
},
});
expect(findings[1]!.evidence).toMatchObject({
severity: "unknown",