Merge updated dependency scanner into dependency progress

This commit is contained in:
Codex
2026-11-13 18:48:11 -08:00
154 changed files with 10439 additions and 1017 deletions
+1
View File
@@ -11,6 +11,7 @@
*.yaml text eol=lf
*.yml text eol=lf
plugins/codex-security/scripts/dispatch_inventory_tool text eol=lf
plugins/codex-security/scripts/launch_codex_security_mcp text eol=lf
# Bundled dependencies contain intentional whitespace in strings and comments.
+13 -10
View File
@@ -1,13 +1,17 @@
<!-- release-version: 0.9.1 -->
<!-- release-version: 0.10.0 -->
<!-- release-section: highlights:start -->
## Highlights
- The npm package includes Developer ID-signed native addons for Apple Silicon and Intel Macs. This lets Codex Desktop load the addon when preparing review items.
- Deep Scan runs independent Standard reviews in batches. Workers can share leads and verify each other's evidence. The final report groups observations that have the same fix and retains the source locations from each review. [Deep Scan guide](https://github.com/openai/codex-security/blob/main/sdk/typescript/docs/cli.md#configure-deep-scans)
- External scanner imports are enabled by default in the CLI, SDK, and plugin. You can preview supported reports, save findings locally, and publish supported findings to Cloud. The scanner guides list the accepted formats and which inputs are local-only. [Scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md)
- `scans logs` finds sessions faster in large compressed histories. The GitHub Action also includes scan scope limitations in its job summary, including when a scan returns zero findings.
Codex Security 0.10.0 gives clearer guidance when a patch is blocked, lets interrupted Standard scans resume, and adds a budget for batch scans.
- **Blocked patch results.** The patch prompt asks whether any files changed, what stopped the fix, and what to do next. When a fix depends on work outside the checkout, the result explains why the external change is needed and where it belongs when known. [#2609](https://github.com/openai/codex-security/pull/2609)
- **Standard scan setup.** Standard scans start with the vulnerability audit and load host-specific instructions when needed. Focused investigators receive their own briefs, and scan history records the file count from the scan's inventory. [#2046](https://github.com/openai/codex-security/pull/2046)
- **Resume interrupted Standard scans.** Run `codex-security scans resume SCAN_ID` to continue from a saved checkpoint in the original Codex session. The resumed scan retains its usage and budget. [#2610](https://github.com/openai/codex-security/pull/2610)
- **Batch scan budgets.** Set `--max-total-cost` on bulk or component scans to share one estimated budget across repositories or components, including retries and recoveries. In-flight work can exceed the estimate. [#2592](https://github.com/openai/codex-security/pull/2592)
- **Scanner imports and publication.** Import saved ArmorCode SAST findings into the local workbench. SDK callers can publish selected workbench finding versions to Cloud using retained evidence. [#2608](https://github.com/openai/codex-security/pull/2608) · [#2603](https://github.com/openai/codex-security/pull/2603)
- **Hosted remediation.** A hosted patch or verification that ends at a different commit reports `revision_changed` and retains its execution receipt. Retry from the requested revision. [#2583](https://github.com/openai/codex-security/pull/2583)
<!-- release-section: highlights:end -->
@@ -15,10 +19,9 @@
## Upgrade notes
- **Deep Scan budgets.** `--stop-after-no-new` now counts consecutive completed Standard reviews that add no findings. If you depend on a particular run length, review this threshold alongside `--max-discovery-runs` and `--max-time`. [Deep Scan settings](https://github.com/openai/codex-security/blob/main/docs/project-configuration.md#deep-settings-and-limits)
- **Scanner imports.** Remove `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS` from launch scripts. A legacy value of `0` no longer disables imports. [Scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md)
- **Linux Compose deployments.** The bundled seccomp profile restricts direct socket families and blocks `ptrace`, `process_vm_readv`, and `process_vm_writev`. If a custom tool needs one of these operations, test it against your deployment's profile before upgrading. [Container guide](https://github.com/openai/codex-security/blob/main/docker/README.md)
- **Source builds.** Sparse SDK checkouts must include `plugins/codex-security/mcp-app/src/deep-scan-settings.ts`. Upgrade or roll back the bundled plugin as a unit. [Source build change](https://github.com/openai/codex-security/pull/2452)
- **Package verification.** The source package checker rejects sparse tar entries. If an unsigned candidate was built with a sparse-aware archiver, recreate it with `pnpm pack` from `sdk/typescript`. Use the original published archive for release recovery. [Package verification change](https://github.com/openai/codex-security/pull/2456)
- **POSIX paths through symlinks.** Paths such as `link/../repo` now follow filesystem traversal. To resume an older bulk campaign whose source was normalized differently, enter its exact saved source path in the CSV. Use a new output directory to scan the corrected physical target. [#1709](https://github.com/openai/codex-security/pull/1709)
- **MCP registration scripts.** Pass `--all` if you relied on selecting all clients after automatic detection found none, or pass `--agent NAME` for one client. Use `--package NAME` for bare npm package names previously passed to `--command`. [#2591](https://github.com/openai/codex-security/pull/2591)
- **Archived scanner captures and Cloud retries.** Recollect Semgrep Platform v1 and Snyk REST v1 captures with the current collectors. Finish interrupted Cloud submissions with the client that created them. If the outcome is uncertain, check the inbox job or repository records before submitting again. [#2602](https://github.com/openai/codex-security/pull/2602)
- **Patch follow-ups with scan budgets.** Run patch preparation separately when a scan has a cost limit. The scan rejects an explicit patch follow-up and skips its interactive patch offer. [#2592](https://github.com/openai/codex-security/pull/2592)
<!-- release-section: upgrades:end -->
+4 -4
View File
@@ -1,13 +1,13 @@
{
"baseVersion": "0.9.0",
"baseCommit": "7cc6bae5003503e826aef70cb96fd042ea3d436a",
"baseVersion": "0.9.1",
"baseCommit": "fe1089ab514599931ff0ce77a82dc8c4a99201ea",
"sections": {
"highlights": {
"generatedHash": "1a95122d50517aa00b5e2dc8becaf9fb60a852238723dce499111c9504a991b2",
"generatedHash": "4fa570e8af948774ab39639217e66b43dd6337597fdb7bd93e5c21360cb62721",
"humanOwned": true
},
"upgrades": {
"generatedHash": "f0e089f37da057fc30882ef40dfe50f6b52abdc17018bf2d70c34afb22c66fe2",
"generatedHash": "d1fd76f2356f3404cad92b5de6d52c81497e8d3431ec0ca8419824d957d8741e",
"humanOwned": true
}
}
+10
View File
@@ -221,6 +221,16 @@ jobs:
- name: Install ripgrep
if: matrix.os == 'ubuntu-latest'
run: .github/scripts/install-ripgrep.sh
- name: Warm campaign executable lookup
if: matrix.os == 'ubuntu-latest'
working-directory: sdk/typescript
# The first campaign reads tool headers across PATH on a cold runner.
# Do that I/O before Bun starts the first campaign test's timeout.
run: |
bun --eval '
import helpers from "./_bundled_plugin/mcp/helpers.mjs";
helpers.inventoryToolPath(process.env.PATH, process.cwd(), [], "campaign").cleanup();
'
- name: Test
working-directory: sdk/typescript
env:
+2 -2
View File
@@ -161,10 +161,10 @@ cs scans logs SCAN_ID
```
Without an ID, `scans show` selects the latest completed scan, while `scans logs`
selects the latest scan of any status. An interrupted Deep Scan still marked
selects the latest scan of any status. An interrupted Standard or Deep Scan still marked
`running` can use `cs scans resume SCAN_ID` with its original checkout, output,
session, and state directory. Completed, failed, and canceled scans need a new
attempt with `cs scans rerun SCAN_ID`. A rerun uses the current checkout and may
need the original custom prompt files supplied again. See
[resume requirements](../sdk/typescript/docs/cli.md#resuming-an-interrupted-deep-scan)
[resume requirements](../sdk/typescript/docs/cli.md#resuming-an-interrupted-scan)
and [runtime troubleshooting](../sdk/typescript/docs/cli.md#troubleshooting).
+11
View File
@@ -419,6 +419,17 @@ values, insert defaults, or discard unknown wrapper keys. Completion inside
existing checks. CLI `scan --schema --json` and result artifact schemas remain
separate contracts.
### Deep Scan sandbox qualification
The CLI dry run and SDK `preflight()` are configuration checks, not sandbox
qualification. They do not start a Deep Scan worker or execute a command under
its generated permissions, so they cannot establish that the worker enforces
filesystem, credential-store, or network restrictions. The documented CLI and
SDK preflight surfaces do not export that generated policy or run a synthetic
command under it. Do not use either preflight result as evidence of worker
isolation. See the [security policy](../SECURITY.md) for the limits of read-only
worker execution and inherited tools.
## Saved reruns
New recipes retain resolved native configuration, scope, auth choice, finding
+28 -21
View File
@@ -3,38 +3,45 @@
Preview a scanner report with the CLI, then save the findings in the local
workbench or send a supported report to Codex Security Cloud.
In Codex, ask to import a saved report or fetch selected findings with an
available CLI, API, or MCP connection. You can publish selected findings from
the local workbench in a later session using their stored IDs and versions.
[Walk through acquisition, local import, and publication in Codex](workbench.md)
## Choose your input
| Starting point | Command |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Saved vendor report | `codex-security publish findings FILE --provider PROVIDER --source-key KEY --repository . --to local --dry-run` previews the evidence. Remove `--dry-run` to save it. |
| Codex Security findings export | `codex-security scan import FILE` saves findings from a .csv or .json file as a completed scan. Use `--input-format` for other filenames and `--json` for JSON output. |
| Live provider | `codex-security import --help` lists the GitHub, Semgrep, Snyk and Sonar collectors. The Sonar collector can also replay its saved capture. |
| Live provider | `codex-security import --help` lists the Continuum, GitHub, Semgrep, Snyk and Sonar collectors. The Sonar collector can also replay its saved capture. |
## Choose your scanner
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.
The guides cover local and Cloud imports unless a row limits its scope.
| 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 |
| Guide | `--provider` | Supported input |
| ----------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md) | `inspector` | Inspector2 `ListFindings` JSON for one Code Security repository |
| [ArmorCode](armorcode.md) | `armorcode` | Findings API JSON for one repository (local verified, Cloud unverified) |
| [AWS Continuum](continuum.md) | `continuum` | Code issues with linked evidence, or saved findings and patches |
| [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 |
| [CrowdStrike](crowdstrike.md) | `crowdstrike` | FCS CLI 4.x IaC scan JSON (local only) |
| [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
@@ -70,7 +77,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 support local import only. For a Cloud-supported report, keep the file, provider,
**Send to Cloud.** Tenable One and CrowdStrike 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)
+53
View File
@@ -0,0 +1,53 @@
# Import ArmorCode findings
Import a saved response from ArmorCode's `POST /api/findings` endpoint into the
local workbench. Cloud publication of ArmorCode findings is unverified. The reader
accepts the API's `data.findings` envelope, as well as a top-level `findings`
array for exported reports. Each finding needs a stable numeric or string `id`
and a `title`. Reuse the same source key for repeat imports from the same
ArmorCode organization and finding selection.
Choose SAST findings for one repository in ArmorCode. Set `ARMORCODE_QUERY` to
the path of the JSON request body for that selection. Severity and status
filters alone can return findings from multiple repositories. From the checkout
root, save the response in a private temporary directory outside the checkout.
```sh
report_dir=$(mktemp -d "${TMPDIR:-/tmp}/armorcode.XXXXXX")
curl --fail-with-body -X POST "https://$HOST_URL/api/findings" \
-H 'accept: application/json' \
-H "authorization: Bearer $ARMORCODE_API_KEY" \
-H 'content-type: application/json' \
--data-binary "@$ARMORCODE_QUERY" > "$report_dir/armorcode-findings.json"
```
Preview the same file against the selected checkout.
```sh
codex-security publish findings "$report_dir/armorcode-findings.json" \
--to local --repository . --provider armorcode \
--source-key ORG_ID/APP_ID --dry-run --format json
```
If any SAST row omits its repository URL, verify the report's repository in
ArmorCode and add `--source-repository-url URL` to the command. The import
checks declared repository URLs against the checkout's configured remotes.
A conflicting repository in the report causes the import to fail.
The import preserves the complete source record as evidence. It maps severity,
description, mitigation, finding URLs, CVE identifiers, file path and line
number, and the last-updated timestamp when present. The evidence URL uses the
source scanner's `url` when present. ArmorCode's `findingUrl` remains in the
retained source record. Findings whose `scanType` contains `SAST` also expose
their source status, scanner origin and verdict, rule IDs, CWE IDs, and
mitigation as typed SAST details. A record's `sourceRepositoryUrl`,
`repositoryUrl`, or repository URL is projected when present. Unknown severities
are retained as `unknown`. The local assessment starts as `not_assessed`.
Repeated IDs in a single input are excluded as ambiguous. Repeat imports with
the same provider, source key and finding ID update the existing observation.
Review the preview's findings, exclusions, repository and source key. Remove
`--dry-run` to save the findings, then run
`codex-security findings imported . --format json` to read them back.
Records omitted from a later import remain stored. Use the normalized field
names above when an export uses different field names.
+225 -43
View File
@@ -1,9 +1,8 @@
# Import AWS Continuum code findings
# Import AWS Continuum code issues and findings
Use `GetCodeFinding` JSON to import selected findings with their locations
and mitigation. When AWS has run validation, the export also includes the
validation result. Use `ListCodeFindings` JSON for summaries from an
environment dedicated to one repository.
Import Continuum issues to create one Codex Security record per issue ARN. The
issue provides exploitability and severity analysis, supporting details, and an
initial patch when available.
## Quick start
@@ -12,17 +11,137 @@ repository supplied the scanned code, including the archive for an S3 source.
For a finding from another scanner, you can also check its repository in that
scanner. [AWS Continuum code sources](https://docs.aws.amazon.com/continuum/latest/userguide/cv-getting-started.html)
**Saved report.** Set `report` to a native detail response, an array of detail responses, or a complete list response with its `items` array. Then [preview the report](#preview-and-import).
**Saved report.** Set `report` to a saved issue export, a finding capture with
patches, a native finding detail, an array of captures or details, or a complete
finding list. Then [preview the report](#preview-and-import).
```sh
report=/private/path/continuum.json
```
### Export findings for one repository
<a id="export-findings-for-one-repository"></a>
<a id="export-issues-for-one-repository"></a>
To create a report, sign in to the environment's AWS account and Region with
AWS CLI v2.38.5 or later, the first release with `aws continuum`. Choose one
export.
### Export issues from an environment
Install AWS CLI v2.38.5 or later outside the checkout. Sign in to the
environment's AWS account and Region. The export needs permissions for
`GetEnvironment`, `GetIntegration`, `ListCodeIssues`, `GetCodeIssue`,
`GetCodeFinding`, `ListCodeIssueArtifacts`, and `GetCodeIssueArtifact`.
[AWS Continuum permissions](https://docs.aws.amazon.com/service-authorization/latest/reference/list_continuum.html)
Pass the short Continuum environment ID to `codex-security import continuum`.
The command requires exactly one configured Git repository and records it as
`sourceRepositoryUrl`. S3 sources are allowed alongside that repository. An
environment with zero or multiple Git repositories fails before collection.
The command collects all issue pages, issue details, linked findings, and
`EVIDENCE` and `VALIDATION_EVIDENCE` attachments across the environment.
It also collects `PATCH` artifacts when Git is the only source. If the environment includes S3 sources,
use the [selected-finding collector](#collect-a-finding-with-patches) and the
exact AWS source name to capture patches for the Git repository. Before
publishing, verify that the issues belong to the recorded repository.
Use `--aws-profile PROFILE` to select AWS credentials, including a profile
that assumes a role in the environment's account. Use `--aws-region REGION`
to select the environment's Region. When omitted, the AWS CLI uses its usual
credential and Region settings. Keep AWS profiles, aliases, and custom models
outside the checkout. The CLI launches AWS from its installation directory
and filters the environment passed to AWS and its credential helpers.
```sh
report=
out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
codex-security import continuum "$ENVIRONMENT_ID" --format json > "$out/continuum.tmp" &&
mv "$out/continuum.tmp" "$out/continuum-issues.json" &&
report="$out/continuum-issues.json"
```
### Preview and import
Preview the report with a source key for this environment and repository.
The importer uses the repository URL saved in the issue export. For a saved
report without a repository URL, add
`--source-repository-url URL` with the verified Git URL.
```sh
codex-security publish findings "$report" --to local --repository . \
--provider continuum \
--source-key "continuum/$ENVIRONMENT_ID/example/project" \
--dry-run --format json
```
Check the repository, source ARNs, paths, and exclusions. To save locally,
remove `--dry-run` and confirm.
<a id="publish-to-your-cloud-inbox"></a>
### Publish to Cloud
Preview the file and source key using your connected repository URL.
```sh
repo=https://github.com/example/project
codex-security publish findings "$report" --to cloud --repository "$repo" \
--provider continuum \
--source-key "continuum/$ENVIRONMENT_ID/example/project" \
--dry-run --format json
```
Check the account, repository and source 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. A private inbox upload with changed evidence for the same ARN can return
`source_order_unknown`. [Verify the import](README.md#verify-the-import)
## Identity, evidence, and repeat imports
Issue imports use the issue ARN. The primary location can show its linked
finding's snippet and end line. When the issue summary is empty, the first
linked mitigation in issue order supplies remediation instructions. Validation
is stored alongside each contributing finding in `evidence.source_data.findings`.
The export keeps the AWS artifact responses in `issues[].issue.artifacts`.
The importer checks patch SHA-256 and byte count and stores matching patches
in `evidence.source_data.patches`. Each entry in `evidence.source_data.evidence_artifacts`
retains its artifact ID and type. `EVIDENCE` carries `body.prevalidationSignals`.
`VALIDATION_EVIDENCE` carries `body.validationEvidence`, including source
analysis, flow verdicts, or executed proof when supplied. If AWS returns the
validation artifact as `body.raw`, the importer preserves it in that form. The
observation's `details.scanner_verdict` uses the AWS exploitability verdict for
signals whose subject is the issue. Conflicting issue-level verdicts appear as
`MIXED`.
In Cloud, up to 100 locations are navigable. If the full linked evidence exceeds
the Cloud record size limit, publication tries to keep each linked finding's
verdict with the snippet and remediation. A record whose issue evidence still
exceeds the Cloud limit is reported as an exclusion. The original export retains
the complete linked findings and evidence attachments. Use the same source key
when repeating an issue import. Issue imports use `updatedAt` when available and
fall back to `statusUpdatedAt`. Previous imports keyed by finding ARN remain
separate records.
Finding summaries and details use the finding ARN. In the local workbench,
importing a detail response under the same source key updates the existing
summary. In a private Cloud inbox, retrying identical evidence under the same
source key preserves the finding.
Finding imports use `statusUpdatedAt` for the source update time when available.
Dependency findings expose affected package names and concrete versions.
Cloud can show up to 100 structured packages per finding. The full list,
including version ranges, remains in `evidence.source_data.finding` alongside
the AWS status and validation results. [AWS detail fields](https://docs.aws.amazon.com/continuum/latest/APIReference/API_GetCodeFinding.html)
## Import individual findings or legacy summaries
Use these AWS CLI exports when you want finding records identified by their
finding ARN. Pass the saved report to the same
[preview and publish commands](#preview-and-import) with the verified
`--source-repository-url URL`.
Use detail exports to keep locations, mitigation, and validation evidence.
A local summary import replaces richer evidence saved for the same finding
ARN and source key. In a multi-repository environment, the reader preserves
any repository prefix on a customer-supplied path.
**One finding.** Set `FINDING_ID` to the Continuum ID of the finding you
verified. In an environment with several repositories, use this command to
@@ -61,51 +180,114 @@ out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
report="$out/continuum.json"
```
### Preview and import
### Collect a finding with patches
Preview the report with the verified Git URL and a source key for this
environment and repository.
Pass the verified short finding ID to `import continuum --finding-id`. The CLI
uses your signed-in AWS CLI to read the finding, follow its created or duplicate
issue ID, and retrieve its `PATCH` artifacts. This mode needs
`continuum:GetCodeFinding`, `continuum:ListCodeIssueArtifacts`, and
`continuum:GetCodeIssueArtifact`.
[AWS issue artifacts](https://docs.aws.amazon.com/continuum/latest/APIReference/API_ListCodeIssueArtifacts.html)
Pass the absolute path of the local checkout that owns the finding as
`--source-root`, including when you run from another directory. The CLI applies
the same AWS launch checks and accepts the same `--aws-profile` and
`--aws-region` overrides as the bulk export.
Omit `--repository-name` when the environment contains exactly one Git
repository and no S3 sources. The CLI verifies this with
`continuum:GetEnvironment` before collecting the finding and can then include
patches that have no repository name.
For other environments, pass `--repository-name "$AWS_SOURCE_NAME"` with
the exact source name AWS assigns to the repository. The collector keeps
patches with that exact name and prints the IDs of unnamed patches to stderr.
[AWS patch fields](https://docs.aws.amazon.com/continuum/latest/APIReference/API_PatchBody.html)
```sh
codex-security publish findings "$report" --to local --repository . \
--provider continuum --source-repository-url https://github.com/example/project \
--source-key "continuum/$ENVIRONMENT_ID/example/project" \
--dry-run --format json
report=
source_root=/absolute/path/to/checkout
out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
codex-security import continuum "$ENVIRONMENT_ID" --finding-id "$FINDING_ID" \
--source-root "$source_root" --format json > "$out/continuum.tmp" &&
mv "$out/continuum.tmp" "$out/continuum.json" &&
report="$out/continuum.json"
```
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.
If the finding has no linked issue or no matching patches, the collector saves
the native finding detail. If an AWS read fails, retry the export before import.
<a id="publish-to-your-cloud-inbox"></a>
Publish this report with `publish findings --provider continuum` and the verified
`--source-repository-url`. The record is identified by the finding ARN.
### Publish to Cloud
The local import retains exact patch bytes and artifact descriptors in
`evidence.source_data.patches`. Cloud retains the descriptors and marks
oversized bodies with `contentOmitted: "cloud_evidence_limit"`.
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.
## Use imported evidence in the matching checkout
Set `SOURCE_ARN` to the imported issue or finding ARN and `SOURCE_KEY` to the
key used at import. Select that record's evidence for the next step.
```sh
repo=https://github.com/example/project
codex-security publish findings "$report" --to cloud --repository "$repo" \
--provider continuum --source-repository-url "$repo" \
--source-key "continuum/$ENVIRONMENT_ID/example/project" \
--dry-run --format json
out=$(mktemp -d "${TMPDIR:-/tmp}/continuum.XXXXXX") &&
codex-security findings imported . --format json > "$out/imported.json" &&
jq -e --arg arn "$SOURCE_ARN" --arg key "$SOURCE_KEY" \
'.findings[] | select(.provider == "continuum" and .sourceKey == $key and .sourceFindingId == $arn) | .evidence' \
"$out/imported.json" > "$out/finding.json" &&
finding="$out/finding.json"
```
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)
```mermaid
flowchart LR
A[Continuum finding and linked patches] --> C[Selected finding capture]
C --> F[One finding file]
C --> I[Import to local workbench]
E[Issue export with validation evidence and eligible patches] --> I
I -->|Select stored evidence| F
F --> S[Attack-path scoring]
F --> B0[validate on original checkout]
F --> P[patch in writable checkout]
P -->|Resulting diff| V[verify-fix on edited checkout]
F --> V
```
## Detail, summaries, and repeat imports
### Score an imported issue
Both formats use the finding ARN. In the local workbench, importing a detail
response under the same source key updates the existing summary. In a private Cloud inbox,
retrying identical evidence under the same source key preserves the finding.
From the matching checkout with the Codex Security plugin enabled, pass the
selected issue to the standalone attack-path skill. It can use observations
in the AWS artifacts to establish or rule out reachability for the affected
flow.
The importer uses `statusUpdatedAt` for the source update time when available.
Dependency findings expose affected package names and concrete versions.
Cloud can show up to 100 structured packages per finding. The full list,
including version ranges, remains in `evidence.source_data.finding` alongside
the AWS status and validation results. [AWS detail fields](https://docs.aws.amazon.com/continuum/latest/APIReference/API_GetCodeFinding.html)
```sh
codex exec --ephemeral -s read-only \
"Use \$codex-security:attack-path-analysis to score the imported issue at $finding"
```
To rescore a matching finding in an existing Codex Security scan, use the
same evidence file as context for that finding.
```sh
codex-security classify-severity --scan "$SCAN_ID" --finding-id "$CODEX_FINDING_ID" \
--knowledge-base "$finding"
```
### Patch and verify one finding
Use the selected evidence file or set `finding` to a single-finding collector capture.
`validate` assesses the original checkout. When an AWS patch is available,
`patch` starts from that diff and adapts it to the current code as needed.
```sh
codex-security validate "$finding"
codex-security patch "$finding"
```
Review the resulting diff and run the relevant regression tests. Use the same
finding file for an independent read-only check of the edited checkout.
`verify-fix` reports `fixed`, `still_vulnerable`, or `inconclusive` with evidence.
```sh
git diff
codex-security verify-fix "$finding"
```
+94
View File
@@ -0,0 +1,94 @@
# Import CrowdStrike findings locally
Use a saved JSON report from `fcs scan iac` in the CrowdStrike Falcon Cloud Security (FCS) CLI 4.x. The reader imports each detection in `rule_detections` as one misconfiguration or secret finding. It works offline and does not run the FCS CLI. Reports in the older `violations` format and image scan reports are not supported. CrowdStrike reports support local import only.
## Create the report
FCS writes each detection's `file` relative to the directory where the CLI runs, not relative to `--path`. Run the scan from the root of the directory you will import into, and write the report outside it. The output directory must exist, and its name must not contain a dot.
```sh
cd /path/to/project
reports=$(mktemp -d "${TMPDIR:-/tmp}/fcs-report-XXXXXX")
fcs scan iac --path . --report-formats json --output-path "$reports"
report=$(find "$reports" -name '*-scan-results.json')
```
FCS exits with a nonzero code when detections match `--fail-on`, which by default is any detection. The report is saved if the output shows `Results saved to file`. A scan of a subdirectory, such as `--path infra`, also gives correct paths when it runs from the root.
The [FCS GitHub Action](https://github.com/CrowdStrike/fcs-action) runs the CLI from the workspace root. When `path` is a directory in a checkout at the workspace root, its JSON report matches a checkout of the same commit. Set `report_formats: json` and an `output_path`, upload that directory as a workflow artifact, and download it outside your checkout.
### Scan a remote repository
A `git::` scan clones the default branch, and the report does not record the commit. FCS has no branch or commit option, but the URL accepts `?ref=` with a branch, tag or commit. Pin the scan to a commit and check out the same commit.
```sh
repository_url=https://github.com/example/project
checkout=/path/to/project
reports=$(mktemp -d "${TMPDIR:-/tmp}/fcs-report-XXXXXX")
commit=$(git ls-remote "$repository_url.git" HEAD | cut -f1)
fcs scan iac --path "git::$repository_url.git?ref=$commit" \
--report-formats json --output-path "$reports"
report=$(find "$reports" -name '*-scan-results.json')
git clone --quiet "$repository_url.git" "$checkout"
git -C "$checkout" checkout --quiet --detach "$commit"
```
To scan another branch, replace `HEAD` with `refs/heads/BRANCH`. Paths start at the repository root. If the URL ends with a subdirectory, such as `.git//infra?ref=...`, paths start at that subdirectory. Use `"$checkout/infra"` as `--repository`. If the checkout is at a different commit, the import stops at the first file that changed.
A report of a `git::https://` URL names its repository. The import records that URL, without the subdirectory or `?ref=`, as the findings' repository. If you also pass `--source-repository-url`, both must name the same repository, or the import stops. If the scanned URL has a user name and token, FCS keeps them in the report's `flags.path`. The import does not store that field, but keep the report private.
## Preview, save and read back
The project does not need to be a Git checkout.
```sh
codex-security publish findings "$report" --provider crowdstrike --to local \
--repository /path/to/project --source-key example/project/main \
--dry-run --format json
```
Every detection's file must exist in `--repository` with the content that FCS scanned, which the report records as `file_sha256`. If a file is missing or changed, the import stops and names it, because the reported lines might no longer be correct. Select the directory and commit that FCS scanned, or scan again from its root. Different line endings also count as a change, for example in a Windows checkout of a report from a Linux CI runner.
Add `--source-repository-url https://github.com/example/project` to record the repository of a local scan. With a repository URL, findings get typed `iac` or `secret` details. If you pass the URL and `--repository` is a Git checkout, the URL must match one of its fetch remotes. Without a URL, each finding has a title, severity, description and location, and `evidence.source_data` keeps the native FCS rule and detection.
Remove `--dry-run` and confirm to save. Run `codex-security findings imported /path/to/project --format json` to read back the findings and their initial `not_assessed` Codex assessment. To check a finding against the code, see [Work with imported findings](README.md#work-with-imported-findings).
## Read the evidence
This shortened report has one detection. The reader keeps its file and line as the finding location.
```json
{
"fcs_version": "4.3.0",
"path": ".",
"scan_uuid": "00000000-0000-4000-8000-000000000001",
"rule_detections": [
{
"rule_name": "Sensitive Port Is Exposed To Entire Network",
"rule_uuid": "00000000-0000-4000-8000-000000000002",
"rule_category": "Networking and Firewall",
"severity": "High",
"platform": "Terraform",
"detections": [
{
"file": "infra/main.tf",
"line": 4,
"resource_type": "aws_security_group",
"resource_name": "example",
"reason": "aws_security_group[example] 'SSH' (Port:22) is public",
"recommendation": "aws_security_group[example] 'SSH' (Port:22) should not be public"
}
]
}
]
}
```
- With a repository URL, `details.kind` is `secret` for the Secret Management rule category and `iac` for all others. `details.configuration.actual` is the FCS `reason`, and `details.configuration.expected` is its `recommendation`. FCS names the attribute that holds a secret, not its value.
- A detection in a local Terraform module points to the module file. FCS also reports a copy at the module call, and both are imported.
- A detection in a registry or Git module names the calling file. Its location is the call line from `module_remediation`, or no line if FCS does not state one.
- `evidence.source_data` keeps the FCS version, the native rule without its detection list, and the one detection. For a `git::` scan, it also keeps the scanned URL without `?ref=`. A saved preview imports only if each finding's location matches its retained detection.
## Repeat an import
FCS has no stable detection ID. The reader identifies a detection by rule UUID, file, line, resource type and name, reason and module path. Keep the same source key for one project and branch. When a later scan reports a detection on a different line, it is imported as a new finding, and the earlier finding stays stored.
+3 -1
View File
@@ -24,9 +24,11 @@ which changes can give an occurrence a different ID.
| Report | What identifies one record |
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md), [Endor Labs](endor.md), [SonarQube Cloud](sonar.md) | Inspector finding ARN, Endor Finding UUID or Sonar issue key. Endor native JSON and SARIF use the same UUID. |
| [AWS Continuum](continuum.md) | Continuum finding ARN. A list summary and a detailed response for that ARN identify the same finding. |
| [ArmorCode](armorcode.md) | ArmorCode finding ID (`id`) within the source key. |
| [AWS Continuum](continuum.md) | Issue ARN for issue exports. For finding exports, a list summary and a detailed response share the finding ARN. |
| [Tenable One](tenable.md) | Exact Tenable `finding_id` within the local checkout and a stable tenant/asset source key. Use the Code Repository asset UUID in the key. |
| [Checkmarx SAST](checkmarx.md) | Checkmarx One uses the similarity ID and result hash. CxSAST scopes the similarity ID and ordered flow to the project and query. |
| [CrowdStrike](crowdstrike.md) | FCS IaC rule UUID, file, line, resource type and name, reason and module path. A detection on a new line gets a new ID. |
| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |
| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |
| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |
+127
View File
@@ -0,0 +1,127 @@
# Import with Codex and publish from the workbench
Open the target checkout in Codex with the Codex Security plugin enabled and its matching `@openai/codex-security` SDK available. Say what to collect, identify the repository or upstream project, and specify any ref or finding IDs that matter. Codex can choose a tool and write the findings to your local workbench from that one request. To inspect the results before saving, ask for a preview only. [Plugin setup](../agent-workflows.md#get-started)
```mermaid
flowchart LR
Request["Import findings for this checkout"] --> Codex
Codex -->|Fresh scan| CLI["Installed scanner CLI"]
Codex -->|Existing upstream findings| Hosted["Authenticated collector, MCP tool or vendor API"]
Codex -->|Existing scan| File["Saved report or CI artifact"]
CLI --> Reader["Built-in reader or agent-written parser"]
Hosted --> Reader
File --> Reader
Reader --> Preview["Review scope, findings and exclusions"]
Preview -->|Save locally| DB[("SQLite workbench")]
DB --> IDs["Import ID and finding versions"]
```
## Run a scanner or import a saved result
> Run Trivy on this checkout and import its dependency findings.
Codex checks for the executable, runs the scanner in the selected directory, and imports its native report. These are the equivalent terminal commands from the checkout root. The last command previews the import. Remove `--dry-run` and confirm to save it.
```sh
reports=$(mktemp -d)
trivy fs --scanners vuln --format json --output "$reports/trivy.json" .
cs publish findings "$reports/trivy.json" --provider trivy --source-key acme/payments/fs \
--repository . --trivy-scan-root . --to local --dry-run --format json
```
> Run Semgrep with `./rules.yml` and import the matches.
Codex can run `semgrep scan --config ./rules.yml --json-output "$reports/semgrep.json" .` and feed the export to the Semgrep reader. If you say “import the Semgrep report from yesterday’s CI run,” it reads that artifact. For OpenGrep, it uses the OpenGrep reader and includes scanner errors in the preview. [Semgrep formats](semgrep.md) · [OpenGrep formats](opengrep.md)
## Collect existing upstream findings
The following commands show what Codex can run for each built-in collector. You can also run them yourself. The Continuum, GitHub, Snyk and Semgrep commands return reports on stdout. Codex can save the report privately and import it with the matching reader and a stable source key. Sonar returns a replayable capture and can write directly to the workbench.
| What you ask Codex | Collector and what happens |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| “Import Continuum issues from environment E for this checkout.” | `cs import continuum E --format json` requires exactly one Git repository and records it in the report. S3 sources may also be present. Verify scope with `cs publish findings --dry-run`. [Continuum](continuum.md) |
| “Import GitHub code-scanning alert 17 from acme/payments.” | `cs import github acme/payments --github-alert 17 --format json` uses the signed-in `gh` CLI to fetch the alert and its instance. |
| “Import published repository advisories for acme/payments.” | `cs import github-advisories acme/payments --format json` uses `gh` to fetch published advisories. For a global advisory, give its exact GHSA ID and use `--github-advisory-source global --github-advisory ID`. |
| “Import monitored Snyk Code issues for project P in organization O into this checkout.” | `cs import snyk P --org O --snyk-product code --source-repository-url https://github.com/acme/payments --format json` uses `SNYK_TOKEN` to page through the Snyk API. |
| “Import the Semgrep Platform SAST backlog for acme/payments on main in deployment acme.” | `cs import semgrep acme/payments --deployment acme --ref refs/heads/main --format json` uses the Web API with `SEMGREP_APP_TOKEN` to collect the project and ref. |
| “Import Sonar issue ISSUE_A from project payments on main.” | `cs import sonar --sonar-project payments --sonar-branch main --sonar-issue ISSUE_A --dry-run --format json` uses the active `sonar` login. Codex reads the returned capture path and can save it with `cs import sonar "$capture" --yes`. [Sonar capture and Cloud replay](sonar.md#import-and-verify) |
> Import Guardian SAST findings `101` and `103` for acme/payments on `refs/heads/main` in deployment acme.
Codex inspects the connected tools and calls `get_semgrep_sast_findings` with the requested scope, retaining the selected rows and their exact string IDs. For Guardian Supply Chain it calls `get_semgrep_supply_chain_findings`. For the separate hosted Semgrep Platform MCP, it verifies the project’s SCM URL and uses `IssuesService_ListIssues` with the project, ref and SAST IDs. A missing connection or ID is reported. The two services have separate ID namespaces. [Guardian and hosted MCP examples](semgrep.md)
**Check a hosted collection.** For GitHub, match the requested alert number and ref, or the advisory’s GHSA ID and publication state. For a Snyk or Semgrep backlog, use a two-page fixture and verify that both pages belong to the selected project. Replay the Sonar capture after disconnecting the vendor CLI and compare issue keys. For MCP, return two neighboring string IDs, request one, and verify the tool arguments and the single stored ID.
## Other scanner inputs
For a saved export, say which checkout and report to use. For an upstream read, identify the account, repository and selection. These requests use the same local preview and import. [All readers and supported report formats](README.md#choose-your-scanner)
| What you say | What Codex calls or reads | What to check in QA |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| “Import Dependabot alerts for acme/payments.” | Pages through `GET /repos/acme/payments/dependabot/alerts` via the GitHub connection or an authorized REST client. | Two alerts sharing one advisory retain distinct alert numbers. [Dependabot](github-dependabot.md) |
| “Run OpenGrep with rules.yml and import the results.” | Runs `opengrep scan` with JSON output and uses the `opengrep` reader. | A parse error alongside a match remains in `report.errors`; the match records OpenGrep as its scanner. [OpenGrep](opengrep.md) |
| “Scan package.json for Snyk dependency issues.” | Runs the signed-in `snyk test --file=package.json` with JSON file output and imports the native dependency report. | A findings exit code of 1 still produces findings with the reported dependency paths. [Snyk CLI](snyk.md#native-cli-json) |
| “Import Wiz package occurrences A and B for this repo.” | Fetches those occurrences through the connected Wiz tool or reads a detailed package vulnerability export. | Compare the stored Wiz occurrence IDs with A and B, including when both share a CVE. [Wiz](wiz.md) |
| “Get Inspector findings for this Code Security repository in us-east-1.” | Runs `aws inspector2 list-findings` for the account and exact `CODE_REPOSITORY` resource. | A fixture containing EC2 findings imports only the eligible repository findings, identified by finding ARN. [Inspector](inspector.md) |
| “Import Continuum finding F from environment E.” | Collects the detailed finding and linked PATCH artifacts for the verified repository. | Match the stored ARN and any `source_data.patches` to the AWS finding and issue artifacts. [Continuum](continuum.md) |
| “Import this Black Duck project version’s vulnerable components.” | Reads the complete BOM-6 collection for that version and verifies the Git repository. | The stored `source_data.projectVersionUrl` identifies the selected version. [Black Duck](blackduck.md) |
| “Import completed Checkmarx scan S for payments.” | Exports Checkmarx One JSON with `cx results show`, or reads the self-managed CxSAST scan’s XML. | The retained scan ID is S and the result’s ordered path nodes match the export. [Checkmarx](checkmarx.md) |
| “Get Endor Findings A and B from this project and namespace.” | Filters `endorctl api list --resource Finding` to the project, scan context and requested UUIDs. | The preview contains both requested finding UUIDs once. [Endor Labs](endor.md) |
| “Import Veracode STATIC policy flaws for application A.” | Reads the application’s Findings API pages for `scan_type=STATIC`, retaining pagination and application links. | A flaw on the last page retains its native `issue_id` and application URL. [Veracode](veracode.md) |
| “Import Tenable findings A and B from this Code Repository asset.” | Uses the Inventory export or existing CSVs, selects the asset and finding UUIDs, and checks the Git remote before saving locally. | Only A and B belong to the import. Cloud preview identifies Tenable as local-only. [Tenable One](tenable.md) |
For the fresh-scan examples above, check the manifest path and installed version for Trivy and the rule ID and source line for Semgrep. For a CI artifact, edit the affected source file after the scan and check that the preview retains the line recorded in the report.
## Import an unfamiliar format
> Import this AcmeScanner JSON for acme/payments. Use its occurrence keys and show me any rows you skip.
For an unfamiliar format, Codex inspects sample records and writes a parser. It emits `{ read, findings, excluded }` with a stable string `source_finding_id` and evidence for each finding. It passes the result to `prepareNormalizedLocalImport(data, { provider, sourceKey, repository, sourceRepositoryUrl })`, inspects `.preview`, then calls `.import()` for the requested write. A nonempty import records its membership, including findings already stored at the same version. Tenable and custom provider names can be used locally. [SDK import contract](../../sdk/typescript/docs/sdk.md#import-external-findings)
## Publish in a later session
> Publish the high-severity findings from my Trivy and Semgrep imports for acme/payments to its connected Cloud repository.
Codex uses the import history and the requested severity to select stored finding IDs and versions. You can also give it an import ID to select the whole batch. The vendor login and original report are no longer needed. Codex calls `prepareStoredFindingsPublication(selection, { repository: cloudRepository })` and shows the destination, source groups, evidence and exclusions. A group is one provider and source key. Cloud eligibility depends on the provider, selected evidence and destination.
```mermaid
flowchart LR
DB[("Workbench")] --> Pins["Select import or exact finding versions"]
Pins --> Preview["Preview groups and exclusions"]
Preview --> Approval["User confirms the displayed upload"]
Approval --> Group["Publish each approved source group"]
Group -->|Acknowledged| Receipt["Record receipt against local versions"]
Group -->|Connection lost| Retry["Reopen that group's selection and checkpoint"]
Retry -->|Same approved review ID| Group
Retry -->|Changed preview| Preview
```
You can confirm the displayed groups together. Codex retains each approved group’s `.selection` and `.reviewId` and calls `group.publish(savedReviewId)`. If a later group is interrupted, it reopens that group and resumes the existing submission. Completed groups keep their receipts. A changed selection or destination requires reviewing the new preview.
To preview an existing report for upload from the terminal, run `cs publish findings FILE --provider PROVIDER --source-key KEY --repository CLOUD_REPO --to cloud --dry-run` with the report's scanner options. Remove `--dry-run` and confirm to publish. For a Codex Security CSV or JSON export of a completed scan, `cs scan import FILE` saves it in scan history. [CLI input choices](README.md#choose-your-input)
## Test each part
Run these from the repository root after installing the pinned SDK/plugin dependencies and building the SDK and bundled plugin. Use a disposable checkout and private state directory. The publication tests start a local HTTP server and use real SQLite. [Test setup and native payload](../../sdk/typescript/TESTING.md#install-dependencies)
**Local import and selection.** Import the same evidence twice. Expect two import IDs and the same finding version. Change the evidence, then try the first import ID. The SDK should ask for a new selection. Also try a different checkout and a parser row with a missing occurrence ID or a conflicting repository.
```sh
(cd plugins/codex-security/mcp-app && node --experimental-strip-types --test tests/test_external_findings.ts tests/test_workbench_findings.ts)
(cd sdk/typescript && bun test --timeout 60000 tests-ts/local-finding-report.test.ts tests-ts/semgrep-platform-collector.test.ts tests-ts/semgrep-guardian-findings.test.ts)
```
**Publish and resume.** Import Trivy and Guardian, delete the files, and preview a subset across both sources. Drop the response after the server accepts the second source. Resume using that group's original approval. Check that the first group was sent once, the second receives its receipt, and the unselected row has none. Change the destination or remote version and check that the old approval is rejected before any upload.
For each Cloud-supported reader, preview a native file with `prepareExternalPublication`, then import the same file locally. Delete the file and preview the import ID with `prepareStoredFindingsPublication` using the same Cloud repository and source key. Compare the destination, occurrence IDs, evidence, report metadata and exclusions. Publish to a disposable destination and verify a receipt for each accepted local version. For Tenable and a custom provider, check the exclusion reason and zero uploads.
```sh
(cd sdk/typescript && bun test --timeout 60000 tests-ts/external-findings-publish.test.ts tests-ts/stored-finding-projection.test.ts tests-ts/stored-native-private-report.test.ts tests-ts/sonar-import.test.ts)
```
**Codex and CLI.** Run the two-source example and inspect `cs import --help`. In a plugin-enabled session, ask for one finding ID from an MCP response containing two. Verify the actual tool call, repository and ref, then inspect import membership in a fresh process. For a fresh scanner, check the executable invocation. For an unfamiliar format, check the parser's occurrence IDs and exclusions. The routing tests exercise skill discovery. These acquisition checks exercise what the agent does after discovery. [Runnable example](../../examples/normalized-import/README.md) · [Model routing evaluation](../../evals/workflow-routing/README.md)
```sh
node --experimental-strip-types --test evals/workflow-routing/test_*.mts
(cd sdk/typescript && bun test --timeout 60000 tests-ts/cli-help.test.ts tests-ts/cli-external-imports.test.ts tests-ts/cli-local-import.test.ts)
```
@@ -59,7 +59,7 @@ function inspectEvidence(finding, testCase) {
!hasToken(
`${normalized.vulnerable_component} ${normalized.affected_version_or_path}`,
component.version,
"A-Za-z0-9_.-",
"A-Za-z0-9_.!+-",
)
)
failures.push("Wrong or absent resolved version");
+2 -2
View File
@@ -227,8 +227,8 @@ for (const [name, caseIndex, expectedFailure, mutate] of [
0,
"Wrong or absent resolved version",
(finding, fixture) => {
finding.normalized_input.vulnerable_component = `${fixture.input.component.name} 99.0.0`;
finding.normalized_input.affected_version_or_path = `99.0.0 in ${fixture.input.component.source}`;
finding.normalized_input.vulnerable_component = fixture.input.component.name;
finding.normalized_input.affected_version_or_path = `${fixture.input.component.version}+other in ${fixture.input.component.source}`;
},
],
[
+12
View File
@@ -20,6 +20,18 @@ export const cases = [
"Triage this reported vulnerability against this repository: GET /invoices/:id exposes another user's invoice without checking ownership. Assess the claim; do not fix it.",
skill: "triage-finding",
},
{
id: "acquire-scanner-evidence",
request:
"Fetch the two existing Guardian findings I selected on main and preview importing them into this checkout.",
skill: "publish-findings",
},
{
id: "publish-stored-evidence",
request:
"Publish the high-severity scanner findings from yesterday’s local import to the connected Cloud repository.",
skill: "publish-findings",
},
{
id: "dependency-alert",
request:
+1
View File
@@ -3,6 +3,7 @@
| Task | Example |
| --- | --- |
| Scan an app, inspect a finding, patch it and verify the repair | [Invoice Desk walkthrough](invoice-desk/walkthrough.md). Copy only the synthetic app into the scan target. |
| Compare code findings with deployed VPC reachability | [Network reachability sample](network-reachability-sample/README.md) pairs identical vulnerable workers with different security-group and network ACL rules. |
| Supply your own validation test | [Custom validation demo](custom-validation/README.md). Run the local HTTP test on its own or let a model-backed scan invoke it. |
| Scan pull requests and repositories with GitHub Actions | [GitHub Actions with Amazon Bedrock](github-actions/README.md) uses AWS OIDC and saves SARIF and readable reports. |
| Scan Azure Repos from a central pipeline | [Azure Pipelines with Amazon Bedrock](azure-pipelines/README.md) runs manual full or committed-diff scans. |
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
security-events: write
actions: read
env:
CODEX_SECURITY_VERSION: "0.9.1"
CODEX_SECURITY_VERSION: "0.10.0"
BEDROCK_MODEL_ID: ${{ vars.BEDROCK_MODEL_ID }}
# Report-only by default. Set to "high" to fail on high/critical findings.
FAIL_ON_SEVERITY: ""
@@ -0,0 +1,35 @@
# Network reachability sample
This synthetic benchmark tests whether a scanner separates a code vulnerability
from the exposure of each deployed copy. **It intentionally deploys remote code
execution paths. Use only an isolated test account and remove the stack after
collecting evidence.** The stack creates a public EC2 gateway and two private
EC2 workers. All three workers run the *same* `worker.zip`; their deployed
network controls give them different reachability.
| ID | Seeded behavior | Expected internet exposure |
| --- | --- | --- |
| `NR-001` | `/run?cmd=...` injects a shell command on `OpenWorker`. | Reachable through public gateway `/open`. |
| `NR-002` | The identical `/run` code runs on `BlockedWorker`. | Gateway has a route, but the worker security group denies its traffic. |
| `NR-003` | The identical `/run` code runs on `AclBlockedWorker`. | Its security group allows the gateway, but the subnet network ACL denies the request. |
| `NR-004` | `/diagnostic?expr=...` evaluates Python code when enabled. | All worker services disable it, and no gateway route forwards to it. |
The threat model is an unauthenticated internet caller entering through the
gateway. The blocked cases can still matter if deployed network controls
change; `NR-004` would matter if diagnostics were enabled. A source scan should
find the command injection and dynamic evaluation. A deployment-aware result
should assess each workload and route separately. See
[the answer key](qa/expected-findings.json) for the required evidence.
## Local checks
From this directory:
```sh
python3 -m unittest discover -s qa -p 'test_*.py' -v
```
These checks confirm seeded code behavior and gateway routing. They do not
establish AWS reachability. To create and inspect the deployed topology, follow
[the AWS runbook](deployment/README.md). Keep `qa/` and the answer key outside
scanner source inputs.
@@ -0,0 +1 @@
"""Synthetic network reachability benchmark source."""
@@ -0,0 +1,47 @@
"""Public gateway with two fixed paths to the private benchmark workers."""
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.error import URLError
from urllib.parse import urlsplit
from urllib.request import urlopen
TARGETS = {
"/open": os.environ.get("OPEN_WORKER_HOST"),
"/blocked": os.environ.get("BLOCKED_WORKER_HOST"),
"/acl-blocked": os.environ.get("ACL_BLOCKED_WORKER_HOST"),
}
def route_request(path, query, targets=TARGETS, fetch=urlopen):
if path == "/health":
return 200, {"status": "ok"}
host = targets.get(path)
if host is None:
return 404, {"error": "not_found"}
address = f"http://{host}:8080/run"
if query:
address += f"?{query}"
try:
with fetch(address, timeout=2) as response:
return response.status, json.load(response)
except (TimeoutError, URLError):
return 502, {"error": "upstream_unavailable"}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
request = urlsplit(self.path)
status, body = route_request(request.path, request.query)
payload = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
@@ -0,0 +1,49 @@
"""Intentionally vulnerable HTTP worker for a synthetic reachability benchmark."""
import json
import os
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
def route_request(path, query, diagnostics_enabled=None):
if diagnostics_enabled is None:
diagnostics_enabled = os.environ.get("ENABLE_DIAGNOSTIC") == "1"
if path == "/health":
return 200, {"status": "ok"}
if path == "/run":
command = query.get("cmd", ["sample"])[0]
# NR-001/002/003: the same command injection runs on three instances.
result = subprocess.run(
f"printf '%s\\n' {command}",
shell=True,
capture_output=True,
text=True,
timeout=2,
check=False,
)
return 200, {"output": result.stdout, "exit_code": result.returncode}
if path == "/diagnostic":
if not diagnostics_enabled:
return 404, {"error": "not_found"}
expression = query.get("expr", ["1 + 1"])[0]
# NR-004: deployed workers disable this route; the gateway also omits it.
return 200, {"result": str(eval(expression))} # noqa: S307
return 404, {"error": "not_found"}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
request = urlsplit(self.path)
status, body = route_request(request.path, parse_qs(request.query))
payload = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
@@ -0,0 +1,104 @@
# Deploy and score network reachability
Run this fixture only in an isolated AWS test account. The CloudFormation stack
creates four small EC2 instances, a VPC, a public subnet, two private subnets,
security groups, a network ACL, IAM roles, and an S3 gateway endpoint. EC2 and public IPv4
usage incur charges. The public gateway intentionally exposes a benign proof
path to vulnerable code. Keep real data and credentials out of the fixture.
## Deploy
Set a profile and Region for the test account and confirm the identity. Choose
a unique bucket and stack name. Run from the sample root:
```sh
export AWS_PROFILE=<test-profile>
export AWS_REGION=us-east-1
aws sts get-caller-identity
run_dir=$(mktemp -d "${TMPDIR:-/tmp}/reachability.XXXXXX")
artifact_bucket=<unique-test-bucket>
stack_name=<test-stack-name>
external_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
python3 deployment/package.py "$run_dir"
aws s3 mb "s3://$artifact_bucket" --region "$AWS_REGION"
aws s3 cp "$run_dir/gateway.zip" "s3://$artifact_bucket/nr/gateway.zip"
aws s3 cp "$run_dir/worker.zip" "s3://$artifact_bucket/nr/worker.zip"
aws cloudformation deploy \
--template-file deployment/stack.yaml \
--stack-name "$stack_name" --capabilities CAPABILITY_IAM \
--parameter-overrides \
ArtifactBucket="$artifact_bucket" \
GatewayKey=nr/gateway.zip WorkerKey=nr/worker.zip \
ContinuumExternalId="$external_id"
aws cloudformation describe-stacks --stack-name "$stack_name" \
> "$run_dir/stack.json"
```
Keep the run folder private. The three worker instances use the same S3 archive
and have no public addresses. Their private subnets have an S3 gateway endpoint
so boot scripts can fetch that archive without a NAT gateway. The gateway
forwards only `/open`, `/blocked`, and `/acl-blocked` to worker `/run`.
## Verify the deployed path
Read `GatewayUrl` from the stack outputs, then allow time for EC2 user data and
the worker services to start:
```sh
gateway_url=$(aws cloudformation describe-stacks --stack-name "$stack_name" \
--query "Stacks[0].Outputs[?OutputKey=='GatewayUrl'].OutputValue | [0]" \
--output text)
curl -sS -o "$run_dir/health.json" -w '%{http_code}\n' \
"$gateway_url/health" > "$run_dir/health.status"
curl -sS -G -o "$run_dir/open.json" -w '%{http_code}\n' \
--data-urlencode 'cmd=sample; printf BENCHMARK_PROOF' \
"$gateway_url/open" > "$run_dir/open.status"
curl -sS -G -o "$run_dir/blocked.json" -w '%{http_code}\n' \
--data-urlencode 'cmd=sample; printf BENCHMARK_PROOF' \
"$gateway_url/blocked" > "$run_dir/blocked.status"
curl -sS -G -o "$run_dir/acl-blocked.json" -w '%{http_code}\n' \
--data-urlencode 'cmd=sample; printf BENCHMARK_PROOF' \
"$gateway_url/acl-blocked" > "$run_dir/acl-blocked.status"
curl -sS -o "$run_dir/diagnostic.json" -w '%{http_code}\n' \
"$gateway_url/diagnostic?expr=1" > "$run_dir/diagnostic.status"
```
Expected responses after boot: `/open` contains `BENCHMARK_PROOF`,
`/blocked` and `/acl-blocked` return `upstream_unavailable`, and
`/diagnostic` returns `not_found`. All worker services explicitly set
`ENABLE_DIAGNOSTIC=0`; a
private caller also receives `not_found` for that route. Save response status
codes as well as bodies. A blocked response
alone is inconclusive: inspect deployed instance network interfaces, subnet
routes, security-group ingress, and network ACL rules to identify the denied
hop. Confirm all workers run the same archive hash. Save evidence only outside this public
repository.
## Run Continuum
Create an S3 code integration with base path `nr/` using the stack's
`ContinuumIntegrationRoleArn` output and the generated external ID. Create a
code environment and an AWS collector in the same test account and Region.
Update the stack with `ContinuumEnvironmentArn` and `ContinuumCollectorArn`,
then associate the collector using the new
`ContinuumCollectorDataAccessRoleArn` output. The association sequence is the
same as in [the SW-003 AWS runbook](../../security-workflow-sample/deployment/aws/README.md).
Record the collector association, scan ID, discovered EC2 and VPC resources,
finding-to-workload links, reachability assessment, and any runtime proof.
Compare them with [the answer key](../qa/expected-findings.json). If Continuum
cannot map the S3 archives to the EC2 instances, record a source-to-workload
mapping gap instead of treating code inference as deployed proof. Do not
collapse the three identical worker deployments into one exposure result.
## Clean up
After saving private evidence, disassociate and delete the Continuum test
environment, collector, and integration. Then delete the stack and bucket:
```sh
aws cloudformation delete-stack --stack-name "$stack_name"
aws cloudformation wait stack-delete-complete --stack-name "$stack_name"
aws s3 rm "s3://$artifact_bucket" --recursive
aws s3 rb "s3://$artifact_bucket"
```
@@ -0,0 +1,22 @@
"""Package the two code sources uploaded before stack deployment."""
import sys
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile
ROOT = Path(__file__).resolve().parents[1]
def package(output_dir):
output_dir.mkdir(parents=True, exist_ok=True)
for name in ("gateway", "worker"):
archive = output_dir / f"{name}.zip"
with ZipFile(archive, "w", ZIP_DEFLATED) as bundle:
bundle.write(ROOT / "app" / f"{name}.py", f"{name}.py")
print(archive)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("usage: python3 deployment/package.py OUTPUT_DIR")
package(Path(sys.argv[1]))
@@ -0,0 +1,440 @@
AWSTemplateFormatVersion: "2010-09-09"
Description: Synthetic network reachability benchmark with identical private RCE workers
Parameters:
ArtifactBucket:
Type: String
GatewayKey:
Type: String
WorkerKey:
Type: String
ContinuumExternalId:
Type: String
NoEcho: true
ContinuumEnvironmentArn:
Type: String
Default: ""
ContinuumCollectorArn:
Type: String
Default: ""
AmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
InstanceType:
Type: String
Default: t3.micro
Conditions:
HasCollectorAssociation: !And
- !Not [!Equals [!Ref ContinuumEnvironmentArn, ""]]
- !Not [!Equals [!Ref ContinuumCollectorArn, ""]]
Resources:
Vpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.80.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
InternetGateway:
Type: AWS::EC2::InternetGateway
GatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref Vpc
InternetGatewayId: !Ref InternetGateway
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref Vpc
CidrBlock: 10.80.0.0/24
MapPublicIpOnLaunch: true
PrivateSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref Vpc
CidrBlock: 10.80.1.0/24
MapPublicIpOnLaunch: false
AclPrivateSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref Vpc
CidrBlock: 10.80.2.0/24
MapPublicIpOnLaunch: false
PublicRoutes:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref Vpc
PublicDefaultRoute:
Type: AWS::EC2::Route
DependsOn: GatewayAttachment
Properties:
RouteTableId: !Ref PublicRoutes
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicRouteAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref PublicRoutes
PrivateRoutes:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref Vpc
PrivateRouteAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PrivateSubnet
RouteTableId: !Ref PrivateRoutes
AclPrivateRouteAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref AclPrivateSubnet
RouteTableId: !Ref PrivateRoutes
AclPrivateNetworkAcl:
Type: AWS::EC2::NetworkAcl
Properties:
VpcId: !Ref Vpc
AclPrivateNetworkAclAssociation:
Type: AWS::EC2::SubnetNetworkAclAssociation
Properties:
SubnetId: !Ref AclPrivateSubnet
NetworkAclId: !Ref AclPrivateNetworkAcl
AclDenyGatewayHttp:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref AclPrivateNetworkAcl
RuleNumber: 100
Protocol: 6
RuleAction: deny
Egress: false
CidrBlock: 10.80.0.0/24
PortRange:
From: 8080
To: 8080
AclAllowOtherIngress:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref AclPrivateNetworkAcl
RuleNumber: 200
Protocol: -1
RuleAction: allow
Egress: false
CidrBlock: 0.0.0.0/0
AclAllowEgress:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref AclPrivateNetworkAcl
RuleNumber: 100
Protocol: -1
RuleAction: allow
Egress: true
CidrBlock: 0.0.0.0/0
S3Endpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref Vpc
ServiceName: !Sub com.amazonaws.${AWS::Region}.s3
VpcEndpointType: Gateway
RouteTableIds:
- !Ref PrivateRoutes
GatewaySecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Public benchmark gateway
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
CidrIp: 0.0.0.0/0
OpenWorkerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Worker accepts HTTP from gateway security group
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
SourceSecurityGroupId: !Ref GatewaySecurityGroup
BlockedWorkerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Worker with no inbound access
VpcId: !Ref Vpc
SecurityGroupIngress: []
AclBlockedWorkerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Worker whose security group allows the gateway but network ACL denies it
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
SourceSecurityGroupId: !Ref GatewaySecurityGroup
InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: ReadBenchmarkSources
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: s3:GetObject
Resource:
- !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/${GatewayKey}
- !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/${WorkerKey}
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref InstanceRole
ContinuumIntegrationRole:
Type: AWS::IAM::Role
Properties:
Path: /continuum/integrations/
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: continuum.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
sts:ExternalId: !Ref ContinuumExternalId
Policies:
- PolicyName: SourceBucketAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: s3:ListBucket
Resource: !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource: !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/nr/*
ContinuumCollectorDataAccessRole:
Type: AWS::IAM::Role
Condition: HasCollectorAssociation
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: continuum.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !Ref ContinuumEnvironmentArn
Policies:
- PolicyName: CollectorDataAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: continuum:GetCollectorDataAccessAuthorization
Resource: !Ref ContinuumCollectorArn
OpenWorker:
Type: AWS::EC2::Instance
DependsOn:
- S3Endpoint
- PrivateRouteAssociation
Properties:
ImageId: !Ref AmiId
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref InstanceProfile
SubnetId: !Ref PrivateSubnet
SecurityGroupIds:
- !Ref OpenWorkerSecurityGroup
MetadataOptions:
HttpTokens: required
UserData:
Fn::Base64: !Sub |
#!/bin/bash
set -eux
mkdir -p /opt/reachability
aws s3 cp s3://${ArtifactBucket}/${WorkerKey} /tmp/worker.zip
python3 -m zipfile -e /tmp/worker.zip /opt/reachability
cat > /etc/systemd/system/reachability.service <<'UNIT'
[Unit]
Description=Synthetic reachability worker
After=network-online.target
[Service]
Environment=ENABLE_DIAGNOSTIC=0
ExecStart=/usr/bin/python3 /opt/reachability/worker.py
Restart=always
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now reachability.service
BlockedWorker:
Type: AWS::EC2::Instance
DependsOn:
- S3Endpoint
- PrivateRouteAssociation
Properties:
ImageId: !Ref AmiId
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref InstanceProfile
SubnetId: !Ref PrivateSubnet
SecurityGroupIds:
- !Ref BlockedWorkerSecurityGroup
MetadataOptions:
HttpTokens: required
UserData:
Fn::Base64: !Sub |
#!/bin/bash
set -eux
mkdir -p /opt/reachability
aws s3 cp s3://${ArtifactBucket}/${WorkerKey} /tmp/worker.zip
python3 -m zipfile -e /tmp/worker.zip /opt/reachability
cat > /etc/systemd/system/reachability.service <<'UNIT'
[Unit]
Description=Synthetic reachability worker
After=network-online.target
[Service]
Environment=ENABLE_DIAGNOSTIC=0
ExecStart=/usr/bin/python3 /opt/reachability/worker.py
Restart=always
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now reachability.service
AclBlockedWorker:
Type: AWS::EC2::Instance
DependsOn:
- S3Endpoint
- AclPrivateRouteAssociation
- AclPrivateNetworkAclAssociation
- AclDenyGatewayHttp
- AclAllowOtherIngress
- AclAllowEgress
Properties:
ImageId: !Ref AmiId
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref InstanceProfile
SubnetId: !Ref AclPrivateSubnet
SecurityGroupIds:
- !Ref AclBlockedWorkerSecurityGroup
MetadataOptions:
HttpTokens: required
UserData:
Fn::Base64: !Sub |
#!/bin/bash
set -eux
mkdir -p /opt/reachability
aws s3 cp s3://${ArtifactBucket}/${WorkerKey} /tmp/worker.zip
python3 -m zipfile -e /tmp/worker.zip /opt/reachability
cat > /etc/systemd/system/reachability.service <<'UNIT'
[Unit]
Description=Synthetic reachability worker
After=network-online.target
[Service]
Environment=ENABLE_DIAGNOSTIC=0
ExecStart=/usr/bin/python3 /opt/reachability/worker.py
Restart=always
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now reachability.service
Gateway:
Type: AWS::EC2::Instance
DependsOn:
- PublicDefaultRoute
- PublicRouteAssociation
Properties:
ImageId: !Ref AmiId
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref InstanceProfile
SubnetId: !Ref PublicSubnet
SecurityGroupIds:
- !Ref GatewaySecurityGroup
MetadataOptions:
HttpTokens: required
UserData:
Fn::Base64: !Sub |
#!/bin/bash
set -eux
mkdir -p /opt/reachability
aws s3 cp s3://${ArtifactBucket}/${GatewayKey} /tmp/gateway.zip
python3 -m zipfile -e /tmp/gateway.zip /opt/reachability
cat > /etc/systemd/system/reachability.service <<'UNIT'
[Unit]
Description=Synthetic public reachability gateway
After=network-online.target
[Service]
Environment=OPEN_WORKER_HOST=${OpenWorker.PrivateIp}
Environment=BLOCKED_WORKER_HOST=${BlockedWorker.PrivateIp}
Environment=ACL_BLOCKED_WORKER_HOST=${AclBlockedWorker.PrivateIp}
ExecStart=/usr/bin/python3 /opt/reachability/gateway.py
Restart=always
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now reachability.service
Outputs:
GatewayUrl:
Value: !Sub http://${Gateway.PublicIp}:8080
GatewayInstanceId:
Value: !Ref Gateway
OpenWorkerInstanceId:
Value: !Ref OpenWorker
BlockedWorkerInstanceId:
Value: !Ref BlockedWorker
AclBlockedWorkerInstanceId:
Value: !Ref AclBlockedWorker
ContinuumIntegrationRoleArn:
Value: !GetAtt ContinuumIntegrationRole.Arn
ContinuumCollectorDataAccessRoleArn:
Condition: HasCollectorAssociation
Value: !GetAtt ContinuumCollectorDataAccessRole.Arn
@@ -0,0 +1,75 @@
{
"schemaVersion": 1,
"threatModel": "Unauthenticated caller on the public internet, entering through the gateway instance",
"sourceFindings": [
{
"id": "NR-001/002/003",
"category": "OS command injection",
"cwe": ["CWE-78"],
"location": "app/worker.py:route_request:/run",
"rootCause": "The cmd query parameter is interpolated into a subprocess shell command.",
"expectedFix": "Pass fixed command arguments without a shell or reject shell syntax.",
"deploymentAssessments": [
{
"id": "NR-001",
"workload": "OpenWorker",
"internetReachable": true,
"path": "internet -> Gateway:8080 -> /open -> OpenWorker:8080 -> /run",
"requiredEvidence": [
"Gateway has a public address, internet route, and 0.0.0.0/0 ingress on port 8080.",
"Gateway forwards /open to the OpenWorker private address and /run path.",
"OpenWorker security group allows port 8080 from the Gateway security group.",
"The worker service is running and a benign command injection proof succeeds through the public gateway."
]
},
{
"id": "NR-002",
"workload": "BlockedWorker",
"internetReachable": false,
"path": "internet -> Gateway:8080 -> /blocked -X-> BlockedWorker:8080",
"requiredEvidence": [
"The same worker source archive runs on BlockedWorker.",
"Gateway forwards /blocked to the BlockedWorker private address and /run path.",
"BlockedWorker security group has no inbound rule permitting traffic from Gateway.",
"The gateway request fails; the failure alone does not prove the security group is the cause."
]
},
{
"id": "NR-003",
"workload": "AclBlockedWorker",
"internetReachable": false,
"path": "internet -> Gateway:8080 -> /acl-blocked -X-> AclBlockedWorker:8080",
"requiredEvidence": [
"The same worker source archive runs on AclBlockedWorker.",
"Gateway forwards /acl-blocked to the AclBlockedWorker private address and /run path.",
"AclBlockedWorker security group permits port 8080 from Gateway.",
"Its subnet network ACL denies TCP port 8080 from the gateway subnet before a later allow rule.",
"The gateway request fails; the failure alone does not prove the network ACL is the cause."
]
}
]
},
{
"id": "NR-004",
"category": "Dynamic code evaluation",
"cwe": ["CWE-94"],
"location": "app/worker.py:route_request:/diagnostic",
"rootCause": "The worker evaluates the expr query parameter as Python code.",
"internetReachable": false,
"requiredEvidence": [
"All three deployed workers contain the vulnerable /diagnostic route.",
"All worker services set ENABLE_DIAGNOSTIC=0, so the handler returns before evaluation.",
"The public gateway only forwards /open, /blocked, and /acl-blocked to worker /run.",
"No public request path controls the worker URL path."
],
"caveat": "The route becomes exploitable if diagnostics are enabled and a caller can reach a worker."
}
],
"scoringRules": [
"Report source vulnerabilities even when a specific deployment is unreachable.",
"Assess reachability per workload; identical source code does not imply identical exposure.",
"Evaluate subnet routes, security groups, and network ACL rules together.",
"Do not claim that a failed HTTP request alone proves the denying network control.",
"Do not claim deployed resource or runtime proof from source code or the template alone."
]
}
@@ -0,0 +1,68 @@
"""Local behavior checks; AWS security-group claims require a deployed stack."""
import io
import json
import unittest
from app.gateway import route_request as gateway_request
from app.worker import route_request as worker_request
class Response(io.BytesIO):
status = 200
def __enter__(self):
return self
def __exit__(self, *_args):
self.close()
class ReachabilityBehaviorTests(unittest.TestCase):
def test_worker_command_input_executes_a_second_benign_command(self):
status, body = worker_request("/run", {"cmd": ["sample; printf BENCHMARK_PROOF"]})
self.assertEqual(status, 200)
self.assertIn("BENCHMARK_PROOF", body["output"])
def test_gateway_selects_only_fixed_worker_run_paths(self):
requests = []
def fetch(url, timeout):
requests.append((url, timeout))
return Response(json.dumps({"output": "sample"}).encode())
targets = {
"/open": "10.80.1.10",
"/blocked": "10.80.1.11",
"/acl-blocked": "10.80.2.10",
}
for path in ("/open", "/blocked", "/acl-blocked"):
status, _ = gateway_request(path, "cmd=sample", targets, fetch)
self.assertEqual(status, 200)
self.assertEqual(
requests,
[
("http://10.80.1.10:8080/run?cmd=sample", 2),
("http://10.80.1.11:8080/run?cmd=sample", 2),
("http://10.80.2.10:8080/run?cmd=sample", 2),
],
)
status, _ = gateway_request("/diagnostic", "expr=1", targets, fetch)
self.assertEqual(status, 404)
self.assertEqual(len(requests), 3)
def test_worker_diagnostic_code_is_executable_locally(self):
status, body = worker_request(
"/diagnostic", {"expr": ["40 + 2"]}, diagnostics_enabled=True
)
self.assertEqual(status, 200)
self.assertEqual(body["result"], "42")
status, body = worker_request(
"/diagnostic", {"expr": ["40 + 2"]}, diagnostics_enabled=False
)
self.assertEqual(status, 404)
self.assertEqual(body["error"], "not_found")
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
# Import Trivy and Guardian findings offline
Run this from the repository root with the SDK and plugin built. Set `TMPDIR` to a directory outside any Git worktree. The example uses a saved Trivy report and a recorded Guardian tool response, so it needs no vendor credentials.
```sh
demo=$(mktemp -d "${TMPDIR:-/tmp}/stored-findings.XXXXXXXX")
git init -q "$demo/checkout"
git -C "$demo/checkout" remote add origin https://github.com/example/project
export CODEX_SECURITY_STATE_DIR="$demo/state" DEMO_REPOSITORY="$demo/checkout"
cd sdk/typescript
node bin/codex-security.mjs publish findings ../../examples/normalized-import/trivy-report.json \
--to local --repository "$DEMO_REPOSITORY" --provider trivy \
--source-key example/project/main --trivy-scan-root . --yes --format json
node --input-type=module <<'JS'
import { readFile } from "node:fs/promises";
import {
collectSelectedSemgrepGuardianFindings, normalizeSemgrepFindings,
listLocalExternalImports, prepareNormalizedLocalImport,
} from "@openai/codex-security";
const repository = process.env.DEMO_REPOSITORY;
const json = async name => JSON.parse(await readFile("../../examples/normalized-import/" + name, "utf8"));
const selected = await json("guardian-selection.json");
const capture = await collectSelectedSemgrepGuardianFindings(selected, {
callTool: () => json("guardian-response.json"),
});
const local = await prepareNormalizedLocalImport(
normalizeSemgrepFindings(capture, {}, "local"),
{ repository, provider: "semgrep", sourceKey: selected.sourceKey },
);
console.log(local.preview);
await local.import();
console.table(await listLocalExternalImports({ repository }));
JS
```
The history shows two imports. The Guardian request selected string ID `9007199254740993` from a response containing two findings. A live MCP connection supplies the same collector's `callTool`.
In Codex, open the same checkout with the same workbench state and say **“Preview the high-severity findings from these two imports for publication to my Cloud repository.”** Codex reads the stored versions and shows the source groups and exclusions for review. [User walkthrough](../../docs/scanner-imports/workbench.md) · [SDK selection and publication](../../sdk/typescript/docs/sdk.md#import-external-findings)
@@ -0,0 +1,60 @@
# Security workflow sample
This sample supplies **three benchmark examples** for an order API security
workflow: cross-customer order access, reporting SQL injection, and coverage
across a synthetic deployed environment. All identities, orders, and deployment
names are invented. The local API binds to `127.0.0.1`, stores data in memory,
and needs only Python 3.9 or later.
| Directory | Purpose |
| --- | --- |
| `app/` | Standalone source target with the two seeded flaws. |
| `qa/` | Expected findings and local behavior checks. Do not include in a source scan. |
| `deployment/` | Mock topology, two additional source roots, and a Lambda deployment template. |
## Run and verify the fixture
From this directory:
```bash
python3 -m unittest discover -s qa -p 'test_*.py' -v
python3 -m app.server
```
The server prints its loopback address. `app/README.md` lists the API routes and
synthetic bearer tokens. Stop and restart the process to reset its database.
The tests intentionally confirm vulnerable behavior; they are not a scanner
recall score or a secure post-fix test suite.
## Scan the two code findings together
Copy only `app/` into a fresh directory. Keep `qa/`, `deployment/`, and this
guide outside the scanner's source tree. For example, from this directory:
```bash
sample_run="$(mktemp -d "${TMPDIR:-/tmp}/security-workflow.XXXXXX")"
cp -R app "$sample_run/app"
cd "$sample_run"
codex-security scan app --mode standard --effort high --format json \
--output-dir "$sample_run/scan"
```
This command uses the locally configured Codex Security CLI and model access.
Check the saved scan status and scope before comparing findings with
`qa/expected-findings.json`. A completed scan can report zero, one, two, or
additional findings; the fixture does not guarantee discovery.
## Exercise environment coverage
`deployment/inventory.json` models three source roots and their network entry
points. It is useful for checking expected reachability and negative controls
without an AWS account. An actual AWS Continuum exercise needs three connected
code sources, corresponding workloads in an authorized test account, a
collector, and saved scan evidence. The local inventory alone does not
establish what Continuum would find in a live environment. Follow the
[SW-003 AWS runbook](deployment/aws/README.md) to deploy the Lambda variant
and retain observed evidence.
Use [the QA guide](qa/README.md) for the expected scanner results and
disposition rules. No automatic merge runs as part of this sample; that step
requires a separately configured repository policy.
@@ -0,0 +1,30 @@
# Order Report API
This small order service has three synthetic customer accounts and a regional
report. It runs on loopback with Python's standard library; no installation,
external service, or real customer data is needed.
From the directory containing `app/`, run:
```bash
python3 -m app.server
```
Set `PORT=0` to select an available port. Restarting resets the database.
Use `Authorization: Bearer demo-acme`, `demo-beacon`, or `demo-cedar` for the
matching customer. The routes are:
| Route | Response |
| --- | --- |
| `GET /health` | Process readiness |
| `GET /api/orders` | Signed-in customer's order list |
| `GET /api/orders/{id}` | One order |
| `GET /api/reports/orders?region=west` | Regional order report |
The fixed tokens and order records are sample data. The API makes no outbound
requests and writes no database files.
`lambda_handler.py` exposes the same routes through an API Gateway HTTP API
event. The [SW-003 AWS runbook](../deployment/aws/README.md) packages this
adapter with the order service for a test account.
@@ -0,0 +1 @@
"""Synthetic order API for scanner evaluation."""
@@ -0,0 +1,60 @@
"""Process-local order data for the sample API."""
import sqlite3
TOKENS = {
"demo-acme": "acme",
"demo-beacon": "beacon",
"demo-cedar": "cedar",
}
ORDERS = [
("A-101", "acme", "west", "Acme-only notebook", 1200),
("A-102", "acme", "east", "Acme-only pen", 300),
("B-201", "beacon", "west", "Beacon-only lamp", 4200),
("B-202", "beacon", "east", "Beacon-only chair", 7800),
("C-301", "cedar", "west", "Cedar-only mug", 900),
("C-302", "cedar", "east", "Cedar-only desk", 11900),
]
def create_database():
database = sqlite3.connect(":memory:", check_same_thread=False)
database.row_factory = sqlite3.Row
database.execute(
"""
CREATE TABLE orders (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
region TEXT NOT NULL,
description TEXT NOT NULL,
amount_cents INTEGER NOT NULL
)
"""
)
database.executemany(
"INSERT INTO orders VALUES (?, ?, ?, ?, ?)",
ORDERS,
)
database.commit()
return database
def list_orders(database, tenant_id):
return database.execute(
"""
SELECT id, tenant_id, region, description, amount_cents
FROM orders WHERE tenant_id = ? ORDER BY id
""",
(tenant_id,),
).fetchall()
def lookup_order(database, order_id):
return database.execute(
"""
SELECT id, tenant_id, region, description, amount_cents
FROM orders WHERE id = ?
""",
(order_id,),
).fetchone()
@@ -0,0 +1,31 @@
"""API Gateway HTTP API adapter for the synthetic order service."""
import json
from .data import create_database
from .server import route_request
def handler(event, _context):
method = event.get("requestContext", {}).get("http", {}).get("method", "GET")
if method != "GET":
return {
"statusCode": 405,
"headers": {"content-type": "application/json"},
"body": json.dumps({"error": "method not allowed"}),
}
path = event.get("rawPath", "/")
query = event.get("rawQueryString", "")
if query:
path = f"{path}?{query}"
headers = {key.lower(): value for key, value in event.get("headers", {}).items()}
database = create_database()
try:
status, body = route_request(path, headers.get("authorization", ""), database)
finally:
database.close()
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
@@ -0,0 +1,11 @@
"""Order reports for the signed-in account."""
def orders_by_region(database, tenant_id, region):
query = f"""
SELECT id, tenant_id, region, description, amount_cents
FROM orders
WHERE tenant_id = ? AND region = '{region}'
ORDER BY id
"""
return database.execute(query, (tenant_id,)).fetchall()
@@ -0,0 +1,76 @@
"""Loopback HTTP entry point for the order API."""
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, unquote, urlsplit
from .data import TOKENS, create_database, list_orders, lookup_order
from .reports import orders_by_region
class OrderServer(HTTPServer):
def __init__(self, port=0):
self.database = create_database()
super().__init__(("127.0.0.1", port), OrderHandler)
def server_close(self):
super().server_close()
self.database.close()
class OrderHandler(BaseHTTPRequestHandler):
def log_message(self, format_string, *args):
pass
def reply(self, status, body):
encoded = json.dumps(body).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
def do_GET(self):
status, body = route_request(
self.path, self.headers.get("Authorization", ""), self.server.database
)
self.reply(status, body)
def route_request(path, authorization, database):
target = urlsplit(path)
if target.path == "/health":
return 200, {"status": "ok"}
token = authorization.removeprefix("Bearer ")
tenant_id = TOKENS.get(token)
if not authorization.startswith("Bearer ") or tenant_id is None:
return 401, {"error": "unauthorized"}
if target.path == "/api/orders":
return 200, {"orders": [dict(row) for row in list_orders(database, tenant_id)]}
if target.path.startswith("/api/orders/"):
order_id = unquote(target.path.removeprefix("/api/orders/"))
order = lookup_order(database, order_id)
if order is None:
return 404, {"error": "order not found"}
return 200, {"order": dict(order)}
if target.path == "/api/reports/orders":
region = parse_qs(target.query).get("region", [""])[0]
rows = orders_by_region(database, tenant_id, region)
return 200, {"orders": [dict(row) for row in rows]}
return 404, {"error": "not found"}
def create_server(port=0):
return OrderServer(port)
if __name__ == "__main__":
server = create_server(int(os.environ.get("PORT", "4312")))
print(f"http://127.0.0.1:{server.server_port}", flush=True)
try:
server.serve_forever()
finally:
server.server_close()
@@ -0,0 +1,22 @@
# Mock deployment context
`inventory.json` is a synthetic description of three deployed revisions. It
is **not** an AWS Continuum API response or proof of a live AWS deployment.
It lets reviewers check whether a claimed reachability path is supported by
the supplied topology.
The order API has a public ingress to `/api/*`. Each route still requires an
account token. The billing API is private, and its one business function uses
the authorized tenant. The analytics worker has no HTTP listener or ingress;
its unused `legacy_region_export` function is a negative control for
reachability claims.
For an actual AWS Continuum evaluation, create three code sources and matching
workloads in an authorized test account, attach a collector to the environment,
and record the real deployment revision and scan evidence. The AWS runbook uses
Lambda resources, while this mock inventory names EKS resources. Keep the
environment response separate from the scanner input and from the QA answer
key.
Use [the AWS test-account runbook](aws/README.md) to deploy the Lambda variant
and record observed results.
@@ -0,0 +1,189 @@
# SW-003 in an AWS test account
Use a separate test account containing only synthetic data. This directory
deploys the three workloads as Lambda functions in `us-east-1`. The order
function has a public API Gateway HTTP API. Billing is callable only through
IAM, and analytics has an EventBridge schedule without an HTTP route. The
EKS-based `deployment/inventory.json` remains a mock fixture, not an AWS
export.
## Prepare the account
Choose an AWS CLI profile explicitly. Keep the account ID and evidence in a
private run folder outside this public repository:
```sh
export AWS_PROFILE=<test-account-profile>
export AWS_REGION=us-east-1
export EXPECTED_ACCOUNT_ID=<test-account-id>
test "$(aws sts get-caller-identity --query Account --output text)" = \
"$EXPECTED_ACCOUNT_ID"
aws --version
```
Verify that the profile resolves to the intended account before creating
anything. The finding export commands in `docs/scanner-imports/continuum.md`
need AWS CLI 2.38.5 or later; deployment and a console-based scan do not.
## Package and deploy
From the sample root, choose a new globally unique S3 bucket name and a new
CloudFormation stack name. The bucket stores the three source archives that
Lambda runs. Keep the run folder outside the checkout.
```sh
run_dir=$(mktemp -d "${TMPDIR:-/tmp}/sw003.XXXXXX")
artifact_bucket=<new-globally-unique-bucket>
stack_name=<new-stack-name>
integration_external_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
printf '%s\n' "$integration_external_id" > "$run_dir/integration-external-id.txt"
python3 deployment/aws/package.py "$run_dir"
shasum -a 256 "$run_dir"/*.zip > "$run_dir/source-sha256.txt"
aws s3 mb "s3://$artifact_bucket" --region "$AWS_REGION"
for name in order billing analytics; do
aws s3 cp "$run_dir/$name.zip" "s3://$artifact_bucket/sw003/$name.zip"
done
aws cloudformation deploy \
--template-file deployment/aws/lambda-stack.yaml \
--stack-name "$stack_name" --capabilities CAPABILITY_IAM \
--parameter-overrides \
ArtifactBucket="$artifact_bucket" \
OrderKey=sw003/order.zip BillingKey=sw003/billing.zip \
AnalyticsKey=sw003/analytics.zip \
ContinuumExternalId="$integration_external_id"
aws cloudformation describe-stacks --stack-name "$stack_name" \
--output json > "$run_dir/stack.json"
aws cloudformation describe-stack-resources --stack-name "$stack_name" \
--output json > "$run_dir/resources.json"
```
`package.py` archives only `app/`, the billing module, and the analytics
module. It excludes `qa/` and the answer key. Record the archive hashes, the
three Lambda ARNs, API ID and route, and EventBridge rule from the stack
responses. The stack also outputs a Continuum S3 integration role ARN.
## Verify behavior
Get the `OrderApiUrl` output from `stack.json`. Request `/health`, then use the
synthetic `demo-acme` token for the two proof requests:
```sh
api_url=$(aws cloudformation describe-stacks --stack-name "$stack_name" \
--query "Stacks[0].Outputs[?OutputKey=='OrderApiUrl'].OutputValue | [0]" \
--output text)
api_id=$(aws cloudformation describe-stack-resources --stack-name "$stack_name" \
--query "StackResources[?LogicalResourceId=='OrderApi'].PhysicalResourceId | [0]" \
--output text)
billing_arn=$(aws cloudformation describe-stacks --stack-name "$stack_name" \
--query "Stacks[0].Outputs[?OutputKey=='BillingFunctionArn'].OutputValue | [0]" \
--output text)
analytics_arn=$(aws cloudformation describe-stacks --stack-name "$stack_name" \
--query "Stacks[0].Outputs[?OutputKey=='AnalyticsFunctionArn'].OutputValue | [0]" \
--output text)
aws apigatewayv2 get-routes --api-id "$api_id" > "$run_dir/api-routes.json"
aws apigatewayv2 get-integrations --api-id "$api_id" > "$run_dir/api-integrations.json"
aws lambda list-function-url-configs --function-name "$billing_arn" \
> "$run_dir/billing-urls.json"
aws lambda list-function-url-configs --function-name "$analytics_arn" \
> "$run_dir/analytics-urls.json"
curl -sS -o "$run_dir/health.json" -w '%{http_code}\n' \
"$api_url/health" > "$run_dir/health-status.txt"
curl -sS -o "$run_dir/order-proof.json" -w '%{http_code}\n' \
-H 'Authorization: Bearer demo-acme' \
"$api_url/api/orders/B-201" > "$run_dir/order-status.txt"
curl -sS -G -o "$run_dir/report-proof.json" -w '%{http_code}\n' \
-H 'Authorization: Bearer demo-acme' \
--data-urlencode "region=absent' OR 1=1 --" \
"$api_url/api/reports/orders" > "$run_dir/report-status.txt"
```
Check the status codes and JSON before marking either proof as observed.
`order-proof.json` should contain the Beacon order, and `report-proof.json`
should contain rows for all three synthetic tenants. Confirm from the stack
resources and saved AWS responses that neither billing nor analytics has an
API route or Lambda Function URL. Limit that network claim to this sample
stack.
## Run Continuum and score the result
In the Continuum console for the same account and Region, create an S3
integration using the new bucket, the stack's `ContinuumIntegrationRoleArn`
output, and the external ID saved in the private run folder. Set the source
code base path to `sw003/`. Create a code environment from that integration.
Create or select a collector for the test account. Update the stack with the
same parameter values plus `ContinuumEnvironmentArn` and
`ContinuumCollectorArn`. This creates a data-access role whose trust policy
is scoped to the environment and whose permission is scoped to the collector.
Then associate the collector:
```sh
environment_id=<new-environment-id>
environment_arn=<new-environment-arn>
collector_arn=<new-collector-arn>
aws cloudformation deploy \
--template-file deployment/aws/lambda-stack.yaml \
--stack-name "$stack_name" --capabilities CAPABILITY_IAM \
--parameter-overrides \
ArtifactBucket="$artifact_bucket" \
OrderKey=sw003/order.zip BillingKey=sw003/billing.zip \
AnalyticsKey=sw003/analytics.zip \
ContinuumExternalId="$integration_external_id" \
ContinuumEnvironmentArn="$environment_arn" \
ContinuumCollectorArn="$collector_arn"
data_access_role_arn=$(aws cloudformation describe-stacks \
--stack-name "$stack_name" \
--query "Stacks[0].Outputs[?OutputKey=='ContinuumCollectorDataAccessRoleArn'].OutputValue | [0]" \
--output text)
aws continuum associate-collector \
--environment-id "$environment_id" \
--collector-arn "$collector_arn" \
--collector-data-access-role-arn "$data_access_role_arn"
aws continuum list-associated-collectors --environment-id "$environment_id"
```
An initial scan may start when the environment is created. Check
`aws continuum list-code-scans --environment-id "$environment_id"` before
requesting another scan. Confirm that all three archives were ingested;
record any source that was not.
Save the environment ID, scan ID and status, collector association, source
revisions, finding details, and any validation result in the private run
folder. Use `docs/scanner-imports/continuum.md` for finding export commands.
Compare observed results with `qa/expected-findings.json`:
- `SW-001`: the public order route is reachable after authentication. A
`demo-acme` request for `B-201` returns a Beacon order in the vulnerable
deployment. Record the actual request and response before claiming runtime
proof.
- `SW-002`: the public report route reaches the SQL query. A synthetic
`region` value can return rows from other tenants. Keep the query and result
as private evidence.
- `SW-003`: all three deployed resources and source revisions are accounted
for. The billing entry point is private, and the analytics worker has no
HTTP route. Do not infer a live route from its unused
`legacy_region_export` function.
Report code findings, network context, and runtime validation separately. If
Continuum cannot associate an archive with its Lambda deployment, record that
as a mapping gap. A missing finding is a measured miss, not proof that the code
is safe. The sample does not configure automatic merging.
## Clean up
After saving the private run record, remove the sample environment, collector,
integration, stack, and new artifact bucket. Remove Continuum resources in the
console or with the CLI; delete the stack after the environment no longer uses
its IAM roles:
```sh
aws continuum disassociate-collector \
--environment-id "$environment_id" --collector-arn "$collector_arn"
aws continuum delete-environment --environment-id "$environment_id"
aws continuum delete-collector --collector-id <new-collector-id>
aws continuum delete-integration --integration-id <new-integration-id>
aws cloudformation delete-stack --stack-name "$stack_name"
aws cloudformation wait stack-delete-complete --stack-name "$stack_name"
aws s3 rm "s3://$artifact_bucket" --recursive
aws s3 rb "s3://$artifact_bucket"
```
@@ -0,0 +1,208 @@
AWSTemplateFormatVersion: "2010-09-09"
Description: Synthetic SW-003 Lambda workloads in an isolated test account
Parameters:
ArtifactBucket:
Type: String
OrderKey:
Type: String
BillingKey:
Type: String
AnalyticsKey:
Type: String
ContinuumExternalId:
Type: String
NoEcho: true
ContinuumEnvironmentArn:
Type: String
Default: ""
ContinuumCollectorArn:
Type: String
Default: ""
Conditions:
HasCollectorAssociation: !And
- !Not [!Equals [!Ref ContinuumEnvironmentArn, ""]]
- !Not [!Equals [!Ref ContinuumCollectorArn, ""]]
Resources:
ExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
ContinuumIntegrationRole:
Type: AWS::IAM::Role
Properties:
Path: /continuum/integrations/
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: continuum.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
sts:ExternalId: !Ref ContinuumExternalId
Policies:
- PolicyName: SourceBucketAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: s3:ListBucket
Resource: !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource:
- !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/sw003/*
- !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/context/*
- Effect: Allow
Action:
- s3:PutObject
- s3:GetObject
- s3:GetObjectVersion
Resource: !Sub arn:${AWS::Partition}:s3:::${ArtifactBucket}/continuum-patches/*
ContinuumCollectorDataAccessRole:
Type: AWS::IAM::Role
Condition: HasCollectorAssociation
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: continuum.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !Ref ContinuumEnvironmentArn
Policies:
- PolicyName: CollectorDataAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: continuum:GetCollectorDataAccessAuthorization
Resource: !Ref ContinuumCollectorArn
OrderFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: app.lambda_handler.handler
Role: !GetAtt ExecutionRole.Arn
Code:
S3Bucket: !Ref ArtifactBucket
S3Key: !Ref OrderKey
Timeout: 5
MemorySize: 128
BillingFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: service.handler
Role: !GetAtt ExecutionRole.Arn
Code:
S3Bucket: !Ref ArtifactBucket
S3Key: !Ref BillingKey
Environment:
Variables:
AUTHORIZED_TENANT_ID: acme
Timeout: 5
MemorySize: 128
AnalyticsFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: worker.handler
Role: !GetAtt ExecutionRole.Arn
Code:
S3Bucket: !Ref ArtifactBucket
S3Key: !Ref AnalyticsKey
Timeout: 5
MemorySize: 128
OrderApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: sw003-order-api
ProtocolType: HTTP
OrderIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref OrderApi
IntegrationType: AWS_PROXY
IntegrationUri: !GetAtt OrderFunction.Arn
PayloadFormatVersion: "2.0"
OrderRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref OrderApi
RouteKey: $default
Target: !Join ["/", [integrations, !Ref OrderIntegration]]
OrderStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId: !Ref OrderApi
StageName: $default
AutoDeploy: true
OrderInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref OrderFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${OrderApi}/*/*
AnalyticsSchedule:
Type: AWS::Events::Rule
Properties:
ScheduleExpression: rate(1 day)
State: ENABLED
Targets:
- Arn: !GetAtt AnalyticsFunction.Arn
Id: analytics
AnalyticsInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref AnalyticsFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt AnalyticsSchedule.Arn
Outputs:
OrderApiUrl:
Value: !Sub https://${OrderApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}
OrderFunctionArn:
Value: !GetAtt OrderFunction.Arn
BillingFunctionArn:
Value: !GetAtt BillingFunction.Arn
AnalyticsFunctionArn:
Value: !GetAtt AnalyticsFunction.Arn
ContinuumIntegrationRoleArn:
Value: !GetAtt ContinuumIntegrationRole.Arn
ContinuumCollectorDataAccessRoleArn:
Condition: HasCollectorAssociation
Value: !GetAtt ContinuumCollectorDataAccessRole.Arn
@@ -0,0 +1,41 @@
"""Package only the three source roots used by the Lambda deployment."""
import sys
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile
ROOT = Path(__file__).resolve().parents[2]
ARTIFACTS = {
"order": {
"app/__init__.py": ROOT / "app/__init__.py",
"app/data.py": ROOT / "app/data.py",
"app/reports.py": ROOT / "app/reports.py",
"app/server.py": ROOT / "app/server.py",
"app/lambda_handler.py": ROOT / "app/lambda_handler.py",
},
"billing": {
"service.py": ROOT / "deployment/services/billing/service.py",
},
"analytics": {
"worker.py": ROOT / "deployment/services/analytics/worker.py",
},
}
def package(output_dir):
output_dir.mkdir(parents=True, exist_ok=True)
archives = []
for name, files in ARTIFACTS.items():
archive = output_dir / f"{name}.zip"
with ZipFile(archive, "w", ZIP_DEFLATED) as bundle:
for archive_path, source in files.items():
bundle.write(source, archive_path)
archives.append(archive)
return archives
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("usage: python3 deployment/aws/package.py OUTPUT_DIR")
for path in package(Path(sys.argv[1])):
print(path)
@@ -0,0 +1,38 @@
{
"schemaVersion": 1,
"kind": "synthetic-deployment-inventory",
"environment": "sample-production",
"services": [
{
"name": "order-report-api",
"source": "app",
"revision": "order-report-r1",
"deployment": "eks/order-report",
"ingress": {
"internetExposed": true,
"route": "/api/*",
"authentication": "bearer-token",
"target": "eks/order-report"
}
},
{
"name": "billing-api",
"source": "deployment/services/billing",
"revision": "billing-r1",
"deployment": "eks/billing",
"ingress": {
"internetExposed": false,
"route": "/api/balance",
"authentication": "bearer-token",
"target": "eks/billing"
}
},
{
"name": "analytics-worker",
"source": "deployment/services/analytics",
"revision": "analytics-r1",
"deployment": "scheduled/analytics",
"ingress": null
}
]
}
@@ -0,0 +1,29 @@
"""Synthetic scheduled analytics worker with no HTTP listener."""
import sqlite3
def summarize_orders(database, tenant_id):
return database.execute(
"SELECT COUNT(*) FROM orders WHERE tenant_id = ?",
(tenant_id,),
).fetchone()[0]
def legacy_region_export(database, region):
query = f"SELECT * FROM orders WHERE region = '{region}'"
return database.execute(query).fetchall()
def handler(_event, _context):
"""Scheduled Lambda entry point that never calls the legacy export."""
database = sqlite3.connect(":memory:")
try:
database.execute("CREATE TABLE orders (tenant_id TEXT, region TEXT)")
database.executemany(
"INSERT INTO orders VALUES (?, ?)",
[("acme", "west"), ("acme", "east"), ("beacon", "west")],
)
return {"acme_order_count": summarize_orders(database, "acme")}
finally:
database.close()
@@ -0,0 +1,21 @@
"""Synthetic internal balance service."""
import os
BALANCES = {
"acme": 500,
"beacon": 800,
"cedar": 1200,
}
def balance_for_account(authorized_tenant_id):
return {
"tenant_id": authorized_tenant_id,
"balance_cents": BALANCES[authorized_tenant_id],
}
def handler(_event, _context):
"""IAM-only Lambda entry point; tenant comes from deployment configuration."""
return balance_for_account(os.environ.get("AUTHORIZED_TENANT_ID", "acme"))
@@ -0,0 +1,45 @@
# Security workflow sample QA
This directory is the answer key. Keep it, `deployment/`, and the top-level
guide outside a source-only scan of `app/`.
## Expected scanner results
| ID | Root cause and proof | Expected disposition |
| --- | --- | --- |
| `SW-001` | `GET /api/orders/{id}` authenticates the caller, then looks up an order by ID without comparing its tenant. `demo-acme` reads all four seeded Beacon and Cedar orders. The list endpoint remains correctly scoped. | Propose a tenant ownership check. Send the authorization change to developer review. |
| `SW-002` | `GET /api/reports/orders?region=...` passes user input into SQL text. A crafted synthetic region changes the predicate and returns all three tenants' rows. Normal `west` filtering returns only Acme's row. | Bind both tenant and region values. Permit automatic merge only if an explicitly configured bot policy accepts the diff and all required tests pass. |
| `SW-003` | The mock inventory names three deployed source roots. The order API is public at the network edge but authenticated; billing is private; analytics has no HTTP route. | Report inventory coverage and supported reachability. Do not claim the unused analytics export is publicly reachable or invent a billing finding. |
`SW-001` and `SW-002` should appear as separate findings from one scan of the
order API. A source-only scanner can infer the code paths and suggest runtime
tests. It cannot claim to have observed the mock deployment or sandbox responses
unless it has actually consumed and tested that evidence.
The `policy_gated_merge` label is a benchmark decision, not a claim that Codex
Security or AWS Continuum automatically merges pull requests. Likewise,
`inventory.json` is a mock fixture, not a real Continuum result.
## Run behavior checks
From the sample root:
```bash
python3 -m unittest discover -s qa -p 'test_*.py' -v
```
The tests start fresh loopback servers, prove the two seeded weaknesses, check
normal and anonymous behavior, and validate the three-source inventory. Passing
tests mean the **vulnerable fixture** behaves as intended. They do not mean a
scanner detected either issue, produced a repair, or validated a real AWS
deployment. The detailed answer key is in `expected-findings.json`.
`test_aws_adapters.py` also checks the Lambda entry points and confirms the
deployment archives exclude the answer key. These tests do not create AWS
resources. If the test environment disallows loopback sockets, run the adapter,
query, request-handler, and inventory cases separately.
To score a real scan, record the scanner version, input revision, scan status,
source scope, findings, proof artifacts, patches, test output, and review/merge
decision. Match findings by root cause and affected route; track duplicates,
misses, uncertain cases, and unexpected findings separately.
@@ -0,0 +1,52 @@
{
"schemaVersion": 1,
"application": "../app",
"findings": [
{
"id": "SW-001",
"category": "Broken object authorization",
"cwe": ["CWE-639"],
"title": "Order lookup omits customer ownership",
"locations": [
{"path": "data.py", "symbol": "lookup_order"},
{"path": "server.py", "symbol": "route_request"}
],
"boundary": "An authenticated customer reads another customer's order by ID.",
"expectedEvidence": "The unscoped lookup returns both beacon and cedar orders to acme.",
"expectedFix": "Enforce tenant ownership in the lookup while preserving same-tenant reads.",
"disposition": "developer_review"
},
{
"id": "SW-002",
"category": "SQL injection",
"cwe": ["CWE-89"],
"title": "Reporting query interpolates the region parameter",
"locations": [
{"path": "reports.py", "symbol": "orders_by_region"},
{"path": "server.py", "symbol": "route_request"}
],
"boundary": "A signed-in customer changes the report predicate and sees another customer's rows.",
"expectedEvidence": "A synthetic region value returns rows outside the caller's tenant.",
"expectedFix": "Bind tenant and region as query parameters while retaining ordinary region filtering.",
"disposition": "policy_gated_merge"
}
],
"environmentCheck": {
"id": "SW-003",
"expectedCoverage": [
"order-report-api",
"billing-api",
"analytics-worker"
],
"expectedReachability": {
"order-report-api": "public_authenticated",
"billing-api": "private",
"analytics-worker": "no_http_route"
},
"expectedFindingIds": ["SW-001", "SW-002"],
"negativeControls": [
"No unsubstantiated finding for the scoped billing balance function.",
"Do not describe analytics legacy_region_export as reachable."
]
}
}
@@ -0,0 +1,67 @@
"""Checks for the entry points used by the AWS Lambda deployment."""
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from urllib.parse import quote
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.lambda_handler import handler as order_handler
from deployment.aws.package import package
from deployment.services.analytics.worker import handler as analytics_handler
from deployment.services.billing.service import handler as billing_handler
class LambdaEntryPoints(unittest.TestCase):
def get(self, path, token=None, query=""):
headers = {"authorization": f"Bearer {token}"} if token else {}
response = order_handler(
{
"rawPath": path,
"rawQueryString": query,
"headers": headers,
"requestContext": {"http": {"method": "GET"}},
},
None,
)
return response["statusCode"], json.loads(response["body"])
def test_order_api_preserves_synthetic_findings(self):
self.assertEqual(self.get("/api/orders")[0], 401)
self.assertEqual(
self.get("/api/orders", "demo-acme")[1]["orders"][0]["id"], "A-101"
)
status, other = self.get("/api/orders/B-201", "demo-acme")
self.assertEqual(status, 200)
self.assertEqual(other["order"]["tenant_id"], "beacon")
query = "region=" + quote("absent' OR 1=1 --", safe="")
status, report = self.get("/api/reports/orders", "demo-acme", query)
self.assertEqual(status, 200)
self.assertEqual(
{row["tenant_id"] for row in report["orders"]},
{"acme", "beacon", "cedar"},
)
def test_negative_controls_have_deployed_entry_points(self):
with patch.dict("os.environ", {"AUTHORIZED_TENANT_ID": "acme"}):
balance = billing_handler({"authorized_tenant_id": "beacon"}, None)
self.assertEqual(balance, {"tenant_id": "acme", "balance_cents": 500})
self.assertEqual(analytics_handler({}, None), {"acme_order_count": 2})
def test_archives_exclude_qa_answer_key(self):
with tempfile.TemporaryDirectory() as directory:
package(Path(directory))
with ZipFile(Path(directory) / "order.zip") as archive:
names = set(archive.namelist())
self.assertIn("app/lambda_handler.py", names)
self.assertNotIn("qa/expected-findings.json", names)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,167 @@
"""Behavior checks for the synthetic security workflow sample."""
import json
import sys
import threading
import unittest
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.data import create_database, list_orders, lookup_order
from app.reports import orders_by_region
from app.server import OrderHandler, create_server
class QueryScenarios(unittest.TestCase):
def test_order_and_report_queries_expose_cross_tenant_rows(self):
database = create_database()
self.addCleanup(database.close)
self.assertEqual(
[row["id"] for row in list_orders(database, "acme")],
["A-101", "A-102"],
)
self.assertEqual(lookup_order(database, "B-201")["tenant_id"], "beacon")
self.assertEqual(
[row["id"] for row in orders_by_region(database, "acme", "west")],
["A-101"],
)
changed = orders_by_region(database, "acme", "absent' OR 1=1 --")
self.assertEqual(
{row["tenant_id"] for row in changed},
{"acme", "beacon", "cedar"},
)
class MemoryRequest:
def __init__(self, request):
self.input = BytesIO(request)
self.output = BytesIO()
def makefile(self, mode, _buffering=None):
return self.input if mode == "rb" else self.output
def sendall(self, data):
self.output.write(data)
class RouteScenariosWithoutSockets(unittest.TestCase):
def test_authenticated_routes_reach_both_flaws(self):
database = create_database()
self.addCleanup(database.close)
server = SimpleNamespace(
database=database, server_name="localhost", server_port=80
)
def get(path, token=None):
authorization = f"Authorization: Bearer {token}\r\n" if token else ""
request = MemoryRequest(
f"GET {path} HTTP/1.1\r\nHost: localhost\r\n"
f"{authorization}\r\n".encode()
)
OrderHandler(request, ("127.0.0.1", 1), server)
head, body = request.output.getvalue().split(b"\r\n\r\n", 1)
status = int(head.split(b"\r\n", 1)[0].split()[1])
return status, json.loads(body)
self.assertEqual(get("/api/orders")[0], 401)
own_status, own = get("/api/orders", "demo-acme")
self.assertEqual(own_status, 200)
self.assertEqual(len(own["orders"]), 2)
other_status, other = get("/api/orders/B-201", "demo-acme")
self.assertEqual(other_status, 200)
self.assertEqual(other["order"]["tenant_id"], "beacon")
region = quote("absent' OR 1=1 --", safe="")
report_status, report = get(f"/api/reports/orders?region={region}", "demo-acme")
self.assertEqual(report_status, 200)
self.assertEqual(len(report["orders"]), 6)
class SecurityWorkflowScenarios(unittest.TestCase):
def setUp(self):
self.server = create_server()
self.worker = threading.Thread(target=self.server.serve_forever)
self.worker.start()
self.origin = f"http://127.0.0.1:{self.server.server_port}"
def tearDown(self):
self.server.shutdown()
self.worker.join(timeout=5)
self.server.server_close()
def get(self, path, token=None):
headers = {}
if token is not None:
headers["Authorization"] = f"Bearer {token}"
request = Request(self.origin + path, headers=headers)
try:
with urlopen(request, timeout=5) as response:
return response.status, json.load(response)
except HTTPError as error:
with error:
return error.code, json.load(error)
def test_order_lookup_crosses_customer_boundary(self):
self.assertEqual(self.get("/health"), (200, {"status": "ok"}))
self.assertEqual(self.get("/api/orders")[0], 401)
status, own_list = self.get("/api/orders", "demo-acme")
self.assertEqual(status, 200)
self.assertEqual(
{order["id"] for order in own_list["orders"]}, {"A-101", "A-102"}
)
self.assertEqual(self.get("/api/orders/A-101", "demo-acme")[0], 200)
for order_id, tenant_id in [
("B-201", "beacon"),
("B-202", "beacon"),
("C-301", "cedar"),
("C-302", "cedar"),
]:
with self.subTest(order_id=order_id):
status, body = self.get(f"/api/orders/{order_id}", "demo-acme")
self.assertEqual(status, 200)
self.assertEqual(body["order"]["tenant_id"], tenant_id)
def test_report_region_input_changes_sql_predicate(self):
status, normal = self.get("/api/reports/orders?region=west", "demo-acme")
self.assertEqual(status, 200)
self.assertEqual([order["id"] for order in normal["orders"]], ["A-101"])
self.assertEqual(
self.get("/api/reports/orders?region=absent", "demo-acme"),
(200, {"orders": []}),
)
region = quote("absent' OR 1=1 --", safe="")
status, changed = self.get(f"/api/reports/orders?region={region}", "demo-acme")
self.assertEqual(status, 200)
self.assertEqual(len(changed["orders"]), 6)
self.assertEqual(
{order["tenant_id"] for order in changed["orders"]},
{"acme", "beacon", "cedar"},
)
class DeploymentInventoryScenario(unittest.TestCase):
def test_inventory_names_three_distinct_source_roots(self):
inventory = json.loads((ROOT / "deployment/inventory.json").read_text())
services = inventory["services"]
self.assertEqual(
{service["name"] for service in services},
{"order-report-api", "billing-api", "analytics-worker"},
)
self.assertEqual(len({service["source"] for service in services}), 3)
for service in services:
self.assertTrue((ROOT / service["source"]).is_dir())
self.assertTrue(services[0]["ingress"]["internetExposed"])
self.assertFalse(services[1]["ingress"]["internetExposed"])
self.assertIsNone(services[2]["ingress"])
if __name__ == "__main__":
unittest.main()
+3 -4
View File
@@ -53751,13 +53751,12 @@ function parseInputs(read, workspace) {
}
return n;
};
const list = (name) => str(name).split(/\r?\n/).map((v) => v.trim()).filter(Boolean);
const safeRelative = (name, value) => {
if (value.startsWith("/") || /^[A-Za-z]:/.test(value) || value.includes("\\") || value.split("/").includes("..") || /[\x00-\x1f\x7f]/.test(value))
throw new Error(`${name} must contain literal repository-relative paths, without '..'.`);
throw new Error(`${name} must contain literal repository-relative paths without '..', backslashes or control characters.`);
return value;
};
const paths = [...new Set(list("paths").map((v) => safeRelative("paths", v).split("/").filter((part) => part && part !== ".").join("/") || "."))];
const paths = [...new Set(read("paths").split(/\r?\n/).filter(Boolean).map((v) => safeRelative("paths", v).split("/").filter((part) => part && part !== ".").join("/") || "."))];
const scope = choice("scope", ["repository", "diff"], "repository");
if (scope !== "repository" && paths.length)
throw new Error(`paths cannot be combined with scope: ${scope}. Remove paths to scan changes, or use scope: repository to scan selected paths.`);
@@ -97640,7 +97639,7 @@ async function runAction(actionRoot, overrides = {}) {
setOutput("report-status", "failed");
setOutput("sarif-upload-ready", "false");
try {
inputs = parseInputs((name) => getInput(name), process.env.GITHUB_WORKSPACE ?? "");
inputs = parseInputs((name) => getInput(name, { trimWhitespace: false }), process.env.GITHUB_WORKSPACE ?? "");
const credentials = scanCredentials(inputs.provider, process.env);
const event = await context5();
target = await resolveTarget(inputs, event);
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "codex-security-action",
"version": "0.9.1",
"version": "0.10.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "codex-security-action",
"version": "0.9.1",
"version": "0.10.0",
"dependencies": {
"@actions/artifact": "6.3.1",
"@actions/core": "3.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "codex-security-action",
"version": "0.9.1",
"version": "0.10.0",
"private": true,
"type": "module",
"description": "Run Codex Security in GitHub Actions with explicit scope, budgets, and scan health reporting",
+13 -2
View File
@@ -225,8 +225,10 @@ try {
assert.deepEqual(pathPreflight.target.paths, ['--help']);
// Existing glob, tilde, and colon filenames are literal repository scopes.
const literalFiles = ['src/[slug]/page.tsx', 'src/star*file.ts', 'src/question?file.ts', '~/example.ts', 'module:handler.ts'];
const decoys = ['src/s/page.tsx', 'src/l/page.tsx', 'src/starOtherfile.ts', 'src/questionXfile.ts'];
const literalFiles = ['src/[slug]/page.tsx', 'src/star*file.ts', 'src/question?file.ts', '~/example.ts', 'module:handler.ts',
' leading.ts', 'trailing.ts ', ' '];
const decoys = ['src/s/page.tsx', 'src/l/page.tsx', 'src/starOtherfile.ts', 'src/questionXfile.ts',
'leading.ts', 'trailing.ts'];
for (const path of [...literalFiles, ...decoys]) {
await mkdir(dirname(join(repository, path)), {recursive:true});
await writeFile(join(repository, path), 'export const synthetic = 1;\n');
@@ -254,6 +256,15 @@ try {
const selectedFiles = (await readFile(sourceInput, 'utf8')).trim().split('\n').map(row => JSON.parse(row).path).sort();
assert.deepEqual(selectedFiles, [...literalFiles].sort(), 'Real scope selection must preserve literal names and exclude glob-matching decoys');
const spaces = [' leading.ts', 'trailing.ts ', ' '];
const completedDirectory = join(root, 'literal-completed');
const completedInputs: Record<string, string> = {paths: spaces.join('\n'), 'cyber-access-program':'standard'};
const completedArguments = scanArguments(parseInputs(name => completedInputs[name] ?? '', repository),
{repository}, completedDirectory);
const completed = JSON.parse(run([...completedArguments, '--mock'], 0));
assert.deepEqual(completed.manifest.scan.scope.includePaths, spaces);
assert.equal(completed.sarifPath, join(completedDirectory, 'exports/results.sarif'));
// Preserve the runner-selected virtualenv through Action preflight and the
// pinned CLI's resolver, which otherwise canonicalizes explicit Python paths.
const venv = join(root, 'venv');
+2 -3
View File
@@ -20,14 +20,13 @@ export function parseInputs(read: (name: string) => string, workspace: string) {
}
return n;
};
const list = (name: string) => str(name).split(/\r?\n/).map(v => v.trim()).filter(Boolean);
const safeRelative = (name: string, value: string) => {
if (value.startsWith('/') || /^[A-Za-z]:/.test(value) || value.includes('\\') || value.split('/').includes('..') || /[\x00-\x1f\x7f]/.test(value))
throw new Error(`${name} must contain literal repository-relative paths, without '..'.`);
throw new Error(`${name} must contain literal repository-relative paths without '..', backslashes or control characters.`);
return value;
};
// Match the CLI's scope spelling before constructing arguments or checking reports.
const paths = [...new Set(list('paths').map(v =>
const paths = [...new Set(read('paths').split(/\r?\n/).filter(Boolean).map(v =>
safeRelative('paths', v).split('/').filter(part => part && part !== '.').join('/') || '.'))];
const scope = choice('scope', ['repository', 'diff'], 'repository');
if (scope !== 'repository' && paths.length)
+1 -1
View File
@@ -66,7 +66,7 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc
core.setOutput('report-status', 'failed');
core.setOutput('sarif-upload-ready', 'false');
try {
inputs = parseInputs(name => core.getInput(name), process.env.GITHUB_WORKSPACE ?? '');
inputs = parseInputs(name => core.getInput(name, {trimWhitespace: false}), process.env.GITHUB_WORKSPACE ?? '');
const credentials = scanCredentials(inputs.provider, process.env);
const event = await context();
target = await resolveTarget(inputs, event);
+2 -1
View File
@@ -97,7 +97,8 @@ test('path lists accept literal filenames but reject unsafe locations and option
assert.deepEqual(parse({paths:'src/my folder\nlib'}).paths, ['src/my folder','lib']);
assert.deepEqual(parse({paths:'src/[slug]/page.tsx\nsrc/star*file.ts\nsrc/question?file.ts'}).paths,
['src/[slug]/page.tsx', 'src/star*file.ts', 'src/question?file.ts']);
for (const paths of ['/etc','../other','src/../../other','a\\b','C:/other','x\u0000'])
assert.deepEqual(parse({paths:' leading\r\n \r\ntrailing \n'}).paths, [' leading', ' ', 'trailing ']);
for (const paths of ['/etc','../other','src/../../other','C:/other','a\\b','\tlab\t','x\u0000','x\u001b'])
assert.throws(() => parse({paths}));
});
test('CLI path arguments use normalized, deduplicated repository-relative paths', () => {
+25
View File
@@ -635,6 +635,31 @@ test('disabled summary leaves requested artifact upload and scan outcome intact'
assert.equal(result.outputs['report-status'], 'ready');
});
test('Action path input preserves leading and trailing filename spaces', async t => {
const app = await harness(t);
app.setInput('dry-run', 'true');
const requested = [' leading.txt', ' ', 'trailing.txt '];
const decoys = ['leading.txt', 'trailing.txt'];
for (const filename of [...requested, ...decoys])
await writeFile(join(app.repository, filename), filename);
app.git('add', '.'); app.git('commit', '-qm', 'Literal filename fixtures');
process.env.GITHUB_SHA = app.git('rev-parse', 'HEAD');
app.setInput('paths', requested.join('\r\n'));
const result = await app.run();
assert.equal(result.exitCode, 0, result.logs);
assert.deepEqual(result.args.filter(arg => arg.startsWith('--path=')),
requested.map(path => '--path=./' + path));
});
for (const path of ['slash\\name.txt', '\tname.txt\t']) test('Action rejects an unsupported scan path before setup: ' + JSON.stringify(path), async t => {
const app = await harness(t);
app.setInput('paths', path);
const result = await app.run();
assert.equal(result.exitCode, 1);
assert.equal(result.setups, 0);
assert.match(result.logs, /backslashes or control characters/u);
});
test('scope conflict fails without runtime setup', async (t) => {
const app = await harness(t, 'pr'); app.setInput('paths', 'app.txt'); const result = await app.run();
assert.equal(result.exitCode, 1); assert.equal(result.setups, 0); assert.match(result.logs, /paths cannot be combined/u);
+1
View File
@@ -16,6 +16,7 @@
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_MANAGED_PACKAGE_ROOT",
"CODEX_MCP_NODE_PATH",
"_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"OPENAI_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
+10 -3
View File
@@ -9,6 +9,11 @@ export {
readSealedScanFile,
requireSealedScanFile,
} from "./src/sealed-contract.js";
import { withInventoryToolPaths } from "./src/helpers/inventory-git.js";
export {
inventoryToolPath,
protectedHostPathResolver,
} from "./src/helpers/inventory-git.js";
export { validateTrackingSource } from "./src/helpers/validate-tracking-source.js";
import { parseArgs } from "node:util";
import { isMainThread, parentPort, workerData } from "node:worker_threads";
@@ -105,9 +110,11 @@ function runHelper(): void {
command === "make-hosted-repo-scope-input" ||
command === "make-diff-rank-input"
) {
void inventoryCommand(command, args).then((code) => {
process.exitCode = code;
});
void withInventoryToolPaths(() => inventoryCommand(command, args)).then(
(code) => {
process.exitCode = code;
},
);
} else if (command === "resolve-security-md") {
process.exitCode = resolveSecurityMdCommand(args, posixHome);
} else if (command === "normalize-candidates") {
@@ -103,7 +103,11 @@ export function readFile(path: string | number, label?: string): Buffer {
}
}
export function* readChunks(path: string, label?: string): Iterable<Buffer> {
export function* readChunks(
path: string,
label?: string,
size = 64 * 1024,
): Iterable<Buffer> {
if (process.platform === "win32") {
yield readFile(path, label);
return;
@@ -112,7 +116,7 @@ export function* readChunks(path: string, label?: string): Iterable<Buffer> {
try {
descriptor = openSync(encodePosixPath(path), "r");
while (true) {
const chunk = Buffer.allocUnsafe(64 * 1024);
const chunk = Buffer.allocUnsafe(size);
const length = readSync(descriptor, chunk, 0, chunk.length, null);
if (length === 0) return;
yield chunk.subarray(0, length);
@@ -1,34 +1,51 @@
import {
environmentValue,
isMissingPathError,
readChunks,
resolvedPathText as canonical,
} from "./helper-files";
import {
spawn,
spawnSync,
type SpawnOptions,
type ChildProcessWithoutNullStreams,
} from "node:child_process";
import { randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import {
lstatSync,
mkdirSync,
readdirSync,
readlinkSync,
rmSync,
symlinkSync,
} from "node:fs";
import type { Writable } from "node:stream";
import {
basename,
dirname,
delimiter,
isAbsolute,
parse,
resolve,
sep,
} from "node:path";
import { createRequire } from "node:module";
import { constants } from "node:os";
import { constants, release, tmpdir } from "node:os";
import { spawnWindowsProcess } from "../../../native/windows-process.mjs";
import { nativeTarget } from "../../../native/platform.mjs";
import { decodePosixBytes, encodePosixPath } from "./posix-path";
import {
decodePosixBytes,
encodePosixPath,
resolvePosixPath,
} from "./posix-path";
import { decodeUtf8 } from "./utf8";
import {
ancestors,
append,
executable,
exists,
fsPath,
inside,
linkedParent,
lstat,
@@ -69,15 +86,20 @@ function rawToolValue(value: string): boolean {
return (windows ? /[\ud800-\udfff]/u : /[\udc80-\udcff]/u).test(value);
}
function selectedBundledRipgrep(candidate: string): boolean {
function selectedBundledRipgrep(
candidate: string,
protectedRoot: string,
): boolean {
const codex = environmentValue("CODEX_CLI_PATH");
if (!codex) return false;
try {
const binary = canonical(codex);
if (!isRepositoryPath(protectedRoot, binary)) return false;
return sameFile(
candidate,
append(
append(dirname(dirname(canonical(codex))), "codex-path"),
"rg.exe",
append(dirname(dirname(binary)), "codex-path"),
windows ? "rg.exe" : "rg",
),
);
} catch {
@@ -85,17 +107,414 @@ function selectedBundledRipgrep(candidate: string): boolean {
}
}
function trustedTool(
function protectedToolRoot(target: string): string {
let root = canonical(target);
for (const ancestor of ancestors(root))
if (exists(append(ancestor, ".git"))) root = ancestor;
return root;
}
function isRepositoryPath(root: string, path: string): boolean {
try {
inside(root, path);
return true;
} catch {
return false;
}
}
// The kernel can dispatch a shebang or the POSIX shell can interpret an
// executable text file after ENOEXEC. Only skip inspection for native images.
const nativeImageMagic = new Set(
process.platform === "darwin"
? [
0xfeedface,
0xcefaedfe,
0xfeedfacf,
0xcffaedfe, // Mach-O
0xcafebabe,
0xbebafeca,
0xcafebabf,
0xbfbafeca, // universal binaries
]
: [0x7f454c46],
); // ELF
// Linux reads BINPRM_BUF_SIZE bytes for exec. XNU uses IMG_SHSIZE and also
// treats "#" as a shebang terminator. Arguments are left entirely to the OS.
const macShebang = process.platform === "darwin";
const legacyLinuxShebang =
process.platform === "linux" &&
/^(?:[0-4]\.|5\.0(?:\.|-|$))/u.test(release());
const headerSize = macShebang ? 512 : 256;
function toolHeader(path: string): "native" | "text" | string[] | undefined {
try {
for (const chunk of readChunks(path, undefined, headerSize)) {
if (chunk.length >= 4 && nativeImageMagic.has(chunk.readUInt32BE()))
return "native";
if (chunk[0] !== 35 || chunk[1] !== 33) return "text";
const line = chunk.subarray(2).toString("latin1");
if (macShebang && !/[#\n]/u.test(line)) return "text";
const pattern = macShebang
? /^[ \t]*([^ \t#\n\0]+)/u
: /^[ \t]*([^ \t\n\0]+)/u;
const token = pattern.exec(line);
const names: string[] = [];
if (
token &&
(macShebang ||
chunk.length < headerSize ||
token[0].length < line.length)
)
names.push(token[1]!);
// Older Linux kernels could execute a name truncated at header byte 127.
// Check both spellings on those releases, including vendor backports.
if (legacyLinuxShebang && token && token[0].length > 125) {
const truncated = pattern.exec(line.slice(0, 125))?.[1];
if (truncated) names.push(truncated);
}
return names.length
? names.map((name) => decodePosixBytes(Buffer.from(name, "latin1")))
: "text";
}
return "text";
} catch {
return undefined;
}
}
function interpreterCheck(
cwd: string,
allowsPath: (path: string) => boolean,
shared: boolean,
scripts?: Map<string, string>,
) {
const checked = new Map<string, boolean>();
function allows(path: string, loader = false): boolean {
const prior = checked.get(path);
if (prior !== undefined) return prior;
if (!executable(path)) return true; // Leave missing loaders and EACCES to exec.
const header = toolHeader(path);
if (!header) return false;
if (typeof header === "string") {
if (loader) checked.set(path, true);
return true;
}
checked.set(path, true); // A cycle without a protected path is an OS launch error.
const safe = header.every((interpreter) => {
// A campaign's PATH is reused by children in different working directories.
if (shared && !isAbsolute(interpreter)) return false;
const file = isAbsolute(interpreter)
? interpreter
: append(cwd, interpreter);
// XNU redirects once; Linux can chain interpreter scripts.
return allowsPath(file) && (macShebang || allows(file, true));
});
if (safe && header.length === 1 && isAbsolute(header[0]!))
scripts?.set(path, header[0]!);
checked.set(path, safe);
return safe;
}
return allows;
}
// libuv can return Win32 link targets using the extended drive or UNC spelling.
function windowsLinkPath(path: string): string {
return path
.replace(/^\\\\[?.]\\UNC\\/iu, "\\\\")
.replace(/^\\\\[?.]\\(?=[a-z]:\\)/iu, "");
}
function linkTarget(path: string): string | undefined {
if (sep === "\\") {
let info: ReturnType<typeof lstat>;
try {
info = lstat(path);
} catch (error) {
// Only an absent entry may later materialize in an external directory.
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
throw error;
}
if (!("isNameSurrogate" in info) || !info.isNameSurrogate()) return;
// SDK source paths are UTF-8. An unreadable reparse target cannot be trusted.
if (!path.isWellFormed())
throw new Error("Cannot inspect this Windows link");
return windowsLinkPath(
decodeUtf8(readlinkSync(fsPath(path), { encoding: "buffer" })),
);
}
const name = encodePosixPath(path);
if (lstatSync(name, { throwIfNoEntry: false })?.isSymbolicLink())
return decodePosixBytes(readlinkSync(name, { encoding: "buffer" }));
}
function canonicalComponent(path: string): string {
return sep === "\\"
? windowsLinkPath(canonical(path, false))
: decodePosixBytes(resolvePosixPath(encodePosixPath(path), false));
}
// A campaign can replace files in its checkouts after preparing the workers.
// Check every component owned by the campaign, including intermediate links
// whose current destination is an external executable.
function campaignPathResolver(
isProtected: (path: string) => boolean,
cwd: string,
) {
const resolved = new Map<string, string | null>();
function expand(directory: string, target: string): string | null {
// Win32 normalizes drive-relative and rooted names before filesystem
// lookup. POSIX processes ".." after following the preceding symlink.
const path =
sep === "\\" ? resolve(directory, windowsLinkPath(target)) : target;
const root = parse(path).root;
let parent =
root && sep === "\\" ? canonicalComponent(root) : root || directory;
for (const part of path.slice(root.length).split(sep)) {
if (!part || part === ".") continue;
if (part === "..") {
parent = dirname(parent);
continue;
}
if (isProtected(parent)) return null;
const child = append(parent, part);
if (!resolved.has(child)) {
resolved.set(child, null); // Detect symlink cycles while expanding.
const link = linkTarget(child);
// Filesystems may canonicalize case or DOS short names even without a link.
resolved.set(
child,
link === undefined ? canonicalComponent(child) : expand(parent, link),
);
}
const next = resolved.get(child);
if (!next) return null;
parent = next;
}
return parent;
}
return (path: string) => {
try {
const target = expand(cwd, path);
return target !== null && !isProtected(target) ? target : null;
} catch {
return null;
}
};
}
function campaignPathCheck(
isProtected: (path: string) => boolean,
cwd: string,
) {
const resolvePath = campaignPathResolver(isProtected, cwd);
return (path: string) => resolvePath(path) !== null;
}
// Confirm the dispatcher starts through a link on the actual temporary mount.
// The probe reaches only the system shell, before the operator directory is attached.
function scriptDispatcher(
view: string,
origin: string,
allows: (path: string, link: boolean) => boolean,
) {
const probe = append(view, "sh");
try {
const dispatcher = createRequire(import.meta.url).resolve(
"../scripts/dispatch_inventory_tool",
);
if (
!allows(dispatcher, true) ||
!allows("/bin/sh", true) ||
!executable(dispatcher)
)
return;
symlinkSync("/bin", fsPath(origin));
symlinkSync(dispatcher, fsPath(probe));
const args = ["-c", "exit 73"];
const options = { env: { PATH: "/dev/null" }, stdio: "ignore" } as const;
const env =
allows("/usr/bin/env", true) &&
spawnSync("/usr/bin/env", [probe, ...args], options).status === 73;
if (env || spawnSync(probe, args, options).status === 73)
return { dispatcher, env };
} catch {
// Older or non-executable installations still support direct tool links.
return;
} finally {
rmSync(fsPath(probe), { force: true });
rmSync(fsPath(origin), { force: true });
}
}
function scriptPathDirectory(
directory: string,
isProtected: (path: string) => boolean,
temporary: string[],
scripts: ReadonlyMap<string, string>,
allows: (path: string, link: boolean) => boolean,
): string {
const entries = readdirSync(fsPath(directory), {
withFileTypes: true,
encoding: "buffer",
});
// Bun returns bare names for buffer-encoded directory entries.
const nameOf = (entry: (typeof entries)[number]) =>
decodePosixBytes(Buffer.isBuffer(entry) ? entry : entry.name);
const allowed = entries.filter((entry) => {
const path = append(directory, nameOf(entry));
const kind = Buffer.isBuffer(entry) ? lstat(path) : entry;
const link = kind.isSymbolicLink();
return (!link && !kind.isFile()) || allows(path, link);
});
if (allowed.length === entries.length) return directory;
// Keep safe neighbors in their original PATH position. env and the kernel
// then handle lookup, argument splitting and missing interpreters normally.
let copy: string | undefined;
for (const path of [tmpdir(), "/tmp"]) {
try {
const parent = canonical(path);
if (!parent.includes(delimiter) && !isProtected(parent)) {
const candidate = append(
parent,
`codex-security-tools-${randomUUID()}`,
);
mkdirSync(fsPath(candidate), { mode: 0o700 });
copy = candidate;
break;
}
} catch {
// Another external temporary directory may be usable.
}
}
if (!copy)
throw new Error("No external temporary directory for inventory tools");
temporary.push(copy);
const view = append(copy, "bin"),
origin = append(copy, "origin");
mkdirSync(fsPath(view), { mode: 0o700 });
const systems = new Map<string, string | undefined>();
const retained = allowed.map((entry) => {
const name = nameOf(entry);
const path = append(directory, name);
const loader = scripts.get(path);
// A forwarder would hide execvp's fallthrough for a missing kernel loader.
// Forward only scripts with a system interpreter whose launch we can prove.
if (loader && !systems.has(loader)) {
systems.set(
loader,
executable(loader)
? ["/bin/sh", "/usr/bin/env"].find((system) =>
sameFile(loader, system),
)
: undefined,
);
}
return { name, path, interpreter: loader && systems.get(loader) };
});
const launch = retained.some((tool) => tool.interpreter)
? scriptDispatcher(view, origin, allows)
: undefined;
if (launch) symlinkSync(fsPath(directory), fsPath(origin));
for (const tool of retained) {
const forward =
tool.interpreter === "/bin/sh" ||
(tool.interpreter === "/usr/bin/env" && launch?.env);
const target = launch && forward ? launch.dispatcher : tool.path;
symlinkSync(fsPath(target), fsPath(append(view, tool.name)));
}
return view;
}
function protectedPathBoundary(roots: readonly string[]) {
const key = (path: string) =>
sep === "\\" ? windowsLinkPath(path).toLowerCase() : path;
const boundaries = new Set(roots.map(key));
return (entry: string) => {
for (const parent of ancestors(entry))
if (boundaries.has(key(parent))) return true;
return false;
};
}
export function protectedHostPathResolver(
cwd: string,
roots: readonly string[],
) {
return campaignPathResolver(protectedPathBoundary(roots), cwd);
}
export function inventoryToolPath(
path: string,
cwd: string,
roots: readonly string[],
mode: "native" | "script" | "campaign",
) {
const temporary: string[] = [];
const isProtected = protectedPathBoundary(roots);
const pathAllowed = campaignPathCheck(isProtected, cwd);
// Windows removes unsafe search entries in the SDK, before CreateProcess.
if (windows) return { path, allows: pathAllowed, cleanup() {} };
const scripts = new Map<string, string>();
const interpreterAllowed = interpreterCheck(
cwd,
pathAllowed,
mode === "campaign",
scripts,
);
const allows = (file: string) =>
pathAllowed(file) && interpreterAllowed(file);
const directories = path.split(delimiter).flatMap((entry) => {
try {
const lookup = isAbsolute(entry) ? entry : append(cwd, entry);
if (mode === "campaign" && !pathAllowed(lookup)) return [];
let directory = canonical(lookup);
if (isProtected(directory)) return [];
if (mode !== "native")
directory = scriptPathDirectory(
directory,
isProtected,
temporary,
scripts,
(file, link) => (link ? allows(file) : interpreterAllowed(file)),
);
// A directory containing ":" can be on PATH through an external alias.
if (directory.includes(delimiter))
return lookup.includes(delimiter) ||
isProtected(resolve(lookup)) ||
!pathAllowed(lookup)
? []
: [lookup];
return [directory];
} catch {
return [];
}
});
// An empty POSIX PATH searches the current directory.
return {
path: directories.join(delimiter) || "/dev/null",
allows,
cleanup() {
for (const directory of temporary) {
try {
rmSync(fsPath(directory), { recursive: true, force: true });
} catch {
// Cleanup must not change the tool or campaign's exit status.
}
}
},
};
}
function* trustedTools(
name: "git" | "rg",
target: string,
protectedRoot: string,
rawWindowsLookup = false,
): string | undefined {
let protectedRoot = canonical(target);
for (const ancestor of ancestors(protectedRoot))
if (exists(append(ancestor, ".git"))) protectedRoot = ancestor;
): Generator<string, undefined> {
const configured =
name === "git" ? environmentValue("CODEX_SECURITY_GIT") : undefined;
if (configured === "") return undefined;
if (configured === "") return;
if (configured !== undefined && !isAbsolute(configured))
throw new Error(
"CODEX_SECURITY_GIT must name an absolute trusted executable.",
@@ -129,6 +548,14 @@ function trustedTool(
: [name];
return names.map((name) => append(directory, name));
});
const cwd = name === "git" ? process.cwd() : target;
const pathAllowed = campaignPathCheck(
(path) => isRepositoryPath(protectedRoot, path),
cwd,
);
const interpreterAllowed =
!windows && interpreterCheck(cwd, pathAllowed, false);
let lookupDenied = false;
for (const selected of candidates) {
const candidate =
name === "rg" &&
@@ -141,35 +568,47 @@ function trustedTool(
try {
invocation = append(canonical(dirname(candidate)), basename(candidate));
resolved = canonical(candidate);
} catch {
} catch (error) {
if (
!windows &&
name === "rg" &&
!isRepositoryPath(protectedRoot, resolve(candidate))
) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "EACCES" || code === "EPERM") lookupDenied = true;
else if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
}
continue;
}
if (
!executable(resolved) ||
((windows || name === "git") && !executable(resolved)) ||
(windows &&
(!/\.(exe|com)$/iu.test(candidate) || /\.(bat|cmd)$/iu.test(resolved)))
)
continue;
const inRepository = [resolve(candidate), invocation, resolved].some(
(path) => {
try {
inside(protectedRoot, path);
return true;
} catch {
return false;
}
},
);
if (inRepository && !(name === "rg" && selectedBundledRipgrep(resolved))) {
// POSIX resolves each symlink before a following "..".
const inRepository =
[invocation, resolved].some((path) =>
isRepositoryPath(protectedRoot, path),
) ||
(windows
? isRepositoryPath(protectedRoot, resolve(candidate))
: !pathAllowed(candidate));
if (
(inRepository &&
!(name === "rg" && selectedBundledRipgrep(resolved, protectedRoot))) ||
(interpreterAllowed && !interpreterAllowed(resolved))
) {
if (configured !== undefined)
throw new Error(
"CODEX_SECURITY_GIT must stay outside the protected repository.",
);
continue;
}
return invocation;
yield inRepository ? resolved : invocation;
}
return undefined;
if (lookupDenied)
throw Object.assign(new Error("spawn rg EACCES"), { code: "EACCES" });
}
function windowsToolPaths(searchPath: string): string[] {
@@ -190,13 +629,67 @@ function windowsToolPaths(searchPath: string): string[] {
return paths;
}
type ToolOptions = SpawnOptions & {
cwd?: string;
stdio: ["ignore" | "pipe", "pipe", "pipe"];
};
const inventoryViews = new AsyncLocalStorage<
Map<string, ReturnType<typeof inventoryToolPath>>
>();
export async function withInventoryToolPaths<T>(
run: () => Promise<T>,
): Promise<T> {
const views = new Map<string, ReturnType<typeof inventoryToolPath>>();
try {
return await inventoryViews.run(views, run);
} finally {
for (const view of views.values()) view.cleanup();
}
}
function spawnInventoryTool(
command: string,
args: string[],
options: ToolOptions,
inherited: Record<string, string>,
root: string,
) {
if (windows || inherited.PATH === undefined)
return spawnTool(command, args, options, inherited);
const cwd = options.cwd ?? process.cwd();
const mode =
executable(command) && toolHeader(command) !== "native"
? "script"
: "native";
const views = inventoryViews.getStore();
const key = JSON.stringify([root, cwd, inherited.PATH, mode]);
let view = views?.get(key);
if (!view) {
view = inventoryToolPath(inherited.PATH, cwd, [root], mode);
views?.set(key, view);
}
const PATH = view.path;
try {
const result = spawnTool(
command,
args,
{ ...options, env: { ...(options.env ?? process.env), PATH } },
{ ...inherited, PATH },
);
if (!views) result.child.once("close", view.cleanup);
return result;
} catch (error) {
if (!views) view.cleanup();
throw error;
}
}
function spawnTool(
command: string,
args: string[],
options: SpawnOptions & {
cwd?: string;
stdio: ["ignore" | "pipe", "pipe", "pipe"];
},
options: ToolOptions,
inheritedEnvironment: Record<string, string>,
inputFd: 0 | 3 = 0,
) {
@@ -325,7 +818,8 @@ function inheritedToolPaths(additional: string[] = []): Record<string, string> {
}
function gitProcess(repo: string, args: string[]) {
const command = trustedTool("git", repo);
const root = protectedToolRoot(repo);
const command = trustedTools("git", repo, root).next().value;
if (!command) return undefined;
const env: NodeJS.ProcessEnv = { ...process.env };
const inherited = inheritedToolPaths();
@@ -336,7 +830,7 @@ function gitProcess(repo: string, args: string[]) {
env.GIT_LITERAL_PATHSPECS = "1";
env.GIT_NO_LAZY_FETCH = "1";
env.GIT_ALLOW_PROTOCOL = "";
return spawnTool(
return spawnInventoryTool(
command,
[
"-c",
@@ -349,6 +843,7 @@ function gitProcess(repo: string, args: string[]) {
],
{ env, stdio: ["pipe", "pipe", "pipe"] },
inherited,
root,
);
}
@@ -356,18 +851,43 @@ export async function runRipgrep(
args: string[],
repo: string,
): Promise<ToolResult> {
if (!windows) return runTool("rg", args, repo);
const root = protectedToolRoot(repo);
const inherited = inheritedToolPaths([
"RIPGREP_CONFIG_PATH",
"CODEX_SECURITY_GIT",
]);
const rawWindowsLookup = [repo, ...args, ...Object.values(inherited)].some(
rawToolValue,
const rawWindowsLookup =
windows && [repo, ...args, ...Object.values(inherited)].some(rawToolValue);
let denied: unknown;
for (const command of trustedTools("rg", repo, root, rawWindowsLookup)) {
try {
return await collect(
spawnInventoryTool(
command,
args,
{
cwd: repo,
stdio: ["ignore", "pipe", "pipe"],
},
inherited,
root,
),
);
} catch (error) {
// POSIX PATH lookup continues if a candidate cannot be executed, including
// a script whose interpreter is missing. Preserve actual tool exit statuses.
const code = (error as NodeJS.ErrnoException).code;
if (
windows ||
(code !== "ENOENT" && code !== "EACCES" && code !== "ENOTDIR")
)
throw error;
if (code === "EACCES") denied = error;
}
}
throw (
denied ?? Object.assign(new Error("spawn rg ENOENT"), { code: "ENOENT" })
);
const command = trustedTool("rg", repo, rawWindowsLookup);
if (!command)
throw Object.assign(new Error("spawn rg ENOENT"), { code: "ENOENT" });
return runTool(command, args, repo);
}
export async function runTool(
@@ -1451,6 +1451,7 @@ async function testWorkerRuntimeSettings() {
"PYTHONIOENCODING",
"CODEX_SECURITY_PYTHON_COMMAND",
"PATH",
"_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"HOME",
"NODE_OPTIONS",
"NODE_DEBUG",
@@ -2069,6 +2070,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
path.join(fixture.root, `selected node ${index}`, "node"),
);
const scanGitEnvironments = settings.map((_, index) => {
const tools = path.join(fixture.root, `operator tools ${index}`);
return {
...gitEnvironment,
PATH: [tools, gitEnvironment.PATH].join(path.delimiter),
CODEX_SECURITY_GIT: path.join(tools, "git"),
};
});
await Promise.all(
settings.map(async (_, index) => {
const directory = path.join(
@@ -2123,7 +2133,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
await Promise.all(
executors.map((executor, index) => {
// Snapshot each scan environment independently.
Object.assign(process.env, scanGitEnvironments[index]);
process.env.CODEX_MCP_NODE_PATH = nodePaths[index];
process.env._CODEX_SECURITY_SDK_NODE_SEARCH_PATH = path.dirname(
nodePaths[index],
);
Object.assign(process.env, temporaryEnvironments[index]);
process.env.CODEX_SECURITY_STATE_DIR = path.join(
fixture.root,
@@ -2206,6 +2220,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
workerConfigurations[index].parentSandbox.pluginReadRoot ??
path.join(fixture.root, "ambient-plugin"),
);
assert.equal(
workerLaunch.environment!._CODEX_SECURITY_SDK_NODE_SEARCH_PATH,
path.dirname(nodePaths[index]),
);
assert.equal(
workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,
workerConfigurations[index].path,
@@ -2518,13 +2536,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assert.deepEqual(
invocation.gitEnvironment,
expectedGitEnvironment(
gitEnvironment,
scanGitEnvironments[index],
nodePaths[index],
selectedProvider.environment,
),
);
for (const [name, value] of Object.entries({
...gitEnvironment,
...scanGitEnvironments.at(-1),
CODEX_MCP_NODE_PATH: nodePaths.at(-1),
})) {
assert.equal(process.env[name], value);
@@ -2634,7 +2652,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assert.deepEqual(
preflight.gitEnvironment,
expectedGitEnvironment(
gitEnvironment,
scanGitEnvironments[index],
nodePaths[index],
selectedProvider.environment,
),
@@ -87,6 +87,7 @@ assert.deepEqual(
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_MANAGED_PACKAGE_ROOT",
"CODEX_MCP_NODE_PATH",
"_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"OPENAI_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
@@ -52,21 +52,15 @@ async function fixture(
),
);
// Keep host-installed Node runtimes out of the simulated macOS runtime set.
const tools = path.join(root, "shell-tools");
await mkdir(tools);
for (const name of ["dirname", "od", "tr"]) {
const executable = spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
encoding: "utf8",
}).stdout.trim();
await symlink(executable, path.join(tools, name));
}
const fallback = path.join(root, "fallback-bin");
await mkdir(fallback);
const source = await readFile(
path.join(sourcePluginRoot, "scripts", path.basename(launcher)),
"utf8",
);
await writeFile(
launcher,
source.replace(/^PATH=.*$/m, `PATH="\${PATH}:"${shellQuote(tools)}`),
source.replace(/^ *PATH=.*$/m, ` PATH="\${PATH}:"${shellQuote(fallback)}`),
);
for (const entry of await readdir(path.join(pluginRoot, "mcp"), {
withFileTypes: true,
@@ -156,11 +150,14 @@ process.dlopen = function(module, filename, ...args) {
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_CLI_PATH",
"CODEX_SECURITY_CONFIG_PATH",
"CODEX_SECURITY_PLUGIN_ROOT",
])
delete env[name];
return {
root,
repo,
fallback,
launcher,
addon,
managed,
ordinary,
@@ -192,6 +189,48 @@ process.dlopen = function(module, filename, ...args) {
};
}
launcherTest("SDK launches preserve the supplied search path", async () => {
const { repo, fallback, launcher } = await fixture(false);
const node = path.join(fallback, "node");
await writeFile(
node,
`#!/bin/sh
if [ "\${2:-}" = --helper ]; then
[ -n "$(command -p cat <&3)" ] || exit 1
fi
printf '%s' "$PATH"
`,
{ mode: 0o755 },
);
const run = (args: string[], env: NodeJS.ProcessEnv = {}) =>
spawnSync("/bin/sh", [launcher, ...args], {
env: { PATH: repo, HOME: repo, XDG_CACHE_HOME: repo, ...env },
encoding: "utf8",
});
const plugin = {
CODEX_SECURITY_PLUGIN_ROOT: path.dirname(path.dirname(launcher)),
};
for (const environment of [{}, plugin]) {
const standalone = run(["--stdio"], environment);
assert.equal(standalone.status, 0, standalone.stderr);
assert.equal(standalone.stdout, `${repo}:${fallback}`);
}
const sdk = { ...plugin, _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: "" };
assert.equal(run(["--stdio"], sdk).status, 127);
for (const args of [["--stdio"], ["--helper", "probe"]]) {
for (const selection of [
{ CODEX_MCP_NODE_PATH: node },
{ _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: fallback },
]) {
const selected = run(args, { ...sdk, ...selection });
assert.equal(selected.status, 0, selected.stderr);
assert.equal(selected.stdout, repo);
}
}
});
launcherTest(
"macOS helpers skip managed runtimes that reject the packaged addon",
async () => {
@@ -289,7 +328,7 @@ test(
fixtureLauncher,
source.replace(systemPaths, '"$FIXTURE_SYSTEM_NODE"'),
);
const run = (candidate: string) =>
const run = (candidate: string, inspected?: string) =>
spawnSync("/bin/sh", [fixtureLauncher, "--helper", "database-info"], {
cwd: root,
encoding: "utf8",
@@ -300,6 +339,12 @@ test(
NODE_DEBUG: "module",
CODEX_BROWSER_USE_NODE_PATH: withoutSqlite,
FIXTURE_SYSTEM_NODE: candidate,
...(inspected === undefined
? {}
: {
CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,
_CODEX_SECURITY_SDK_NODE_SEARCH_PATH: inspected,
}),
},
});
const linked = run(systemLink);
@@ -310,6 +355,12 @@ test(
const missing = run(path.join(root, "missing-node"));
assert.notEqual(missing.status, 0);
assert.match(missing.stderr, /node:sqlite/);
const excluded = run(systemLink, "");
assert.notEqual(excluded.status, 0);
assert.match(excluded.stderr, /node:sqlite/);
const selected = run(systemLink, path.dirname(systemLink));
assert.equal(selected.status, 0, selected.stderr);
assert.deepEqual(JSON.parse(selected.stdout), JSON.parse(linked.stdout));
assert.equal(existsSync(marker), false);
},
);
+2
View File
@@ -71,6 +71,7 @@
"scripts/deep_scan_config.py",
"scripts/deep_scan_defaults.json",
"scripts/deep_scan_workbench.py",
"scripts/dispatch_inventory_tool",
"scripts/filesystem_identity.py",
"scripts/finalize_scan_contract.py",
"scripts/finding_preview.py",
@@ -148,6 +149,7 @@
"skills/publish-findings/references/checkmarx-import.md",
"skills/publish-findings/references/wiz-import.md",
"skills/publish-findings/scripts/collect_checkmarx.py",
"skills/publish-findings/scripts/collector_paths.py",
"skills/resolve-dependency-alert/SKILL.md",
"skills/resolve-dependency-alert/agents/openai.yaml",
"skills/security-diff-scan/SKILL.md",
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# The trailing slash preserves directory names ending in newlines through substitution.
set -- "$(CDPATH= cd -P "${0%/*}/../origin" && printf '%s/' "${PWD%/}")${0##*/}" "$@"
case "$1" in
/*) exec "$@" ;;
*) exit 126 ;;
esac
@@ -2,10 +2,13 @@
# Use LF line endings so POSIX can execute this script directly from Windows-built packages.
set -eu
PATH="${PATH:-/usr/bin:/bin}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
export PATH
# The SDK may have removed directories containing repository-owned executables.
if [ -z "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH+x}" ]; then
PATH="${PATH:-/usr/bin:/bin}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
export PATH
fi
launcher_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
launcher_dir=$(CDPATH= cd "$(command -p dirname "$0")" && pwd)
server_path=$launcher_dir/../mcp/server.mjs
if [ "${1:-}" = "--helper" ]; then
server_path=$launcher_dir/../mcp/helpers.mjs
@@ -34,7 +37,7 @@ launch_node() {
trap 'forward_signal HUP 129' HUP
trap 'forward_signal INT 130' INT
trap 'forward_signal TERM 143' TERM
printf '%s\000' "${HOME+x}" "${HOME-}" "$@" | od -An -v -tx1 | tr -d ' \n' | {
printf '%s\000' "${HOME+x}" "${HOME-}" "$@" | command -p od -An -v -tx1 | command -p tr -d ' \n' | {
# BusyBox ash requires a literal close redirection for a closed stdin.
if [ "$helper_stdin_open" = true ]; then
exec 0<&4
@@ -86,6 +89,12 @@ can_load_native() {
# This Linux runtime can still run helpers without SQLite. Prefer a system
# installation if available, without expanding discovery into the caller's PATH.
for system_candidate in /usr/local/bin/node /usr/bin/node /bin/node; do
if [ -n "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH+x}" ]; then
case ":$_CODEX_SECURITY_SDK_NODE_SEARCH_PATH:" in
*":${system_candidate%/*}:"*) ;;
*) continue ;;
esac
fi
if [ -x "$system_candidate" ] &&
_native_probe_output=$("$system_candidate" -e 'require("node:sqlite")' </dev/null 2>&1); then
selected_node=$system_candidate
@@ -106,8 +115,12 @@ do
fi
done
remaining_path=$PATH
while :; do
remaining_path=${PATH-}
if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ] && [ -n "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH:-}" ]; then
# Only Node lookup uses the SDK-inspected fallback directories.
remaining_path=${remaining_path:+$remaining_path:}$_CODEX_SECURITY_SDK_NODE_SEARCH_PATH
fi
while [ -n "$remaining_path" ]; do
path_entry=${remaining_path%%:*}
node_path=${path_entry:-.}/node
if [ -x "$node_path" ] && can_load_native "$node_path"; then
@@ -3,6 +3,8 @@ setlocal DisableDelayedExpansion
set "CODEX_SECURITY_MCP_SCRIPT=%~dp0..\mcp\server.mjs"
if "%~1"=="--helper" (
rem An inherited ERRORLEVEL would shadow the helper exit code.
set "ERRORLEVEL="
set "CODEX_SECURITY_MCP_SCRIPT=%~dp0..\mcp\helpers.mjs"
goto launch
)
@@ -256,6 +256,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
set_scan_thread = subparsers.add_parser("set-scan-thread")
set_scan_thread.add_argument("--scan-id", required=True)
set_scan_thread.add_argument("--thread-id", required=True)
set_scan_thread.add_argument("--time-budget-started-at")
set_scan_cost_limit = add_command("set-scan-cost-limit", "--scan-id")
set_scan_cost_limit.add_argument("--max-cost-usd", required=True, type=float)
+11 -8
View File
@@ -1580,12 +1580,7 @@ def register_cli_scan(
*,
before_archive: Callable[[], None] | None = None,
) -> dict[str, Any]:
"""Register a CLI scan and its selected target before execution begins.
Record the launch recipe and target identity with the new scan. When reusing
an output directory, coordinate archiving with registration so previous results
can still be located. Return the scan ID, contract, and target metadata.
"""
"""Register the scan recipe and target identity, archiving any previous output atomically."""
# A selected plugin may replace __main__ while delegating to this workbench.
before_output_change = before_archive or getattr(
sys, "_codex_security_before_output_change", None
@@ -1793,6 +1788,11 @@ def register_cli_scan(
"contract": scan_contract(scan),
"lifecycle": json.loads(scan["lifecycle_json"]),
**({"phase": scan["phase"]} if mode == "standard" else {}),
**(
{"canSaveTimeBudgetStart": True}
if "maxTimeMinutes" in recipe and mode in {"standard", "diff"}
else {}
),
"scanDir": str(scan_dir),
"scanId": scan_id,
"scopeFileCount": scope_file_count,
@@ -1805,8 +1805,11 @@ def set_scan_thread(connection: sqlite3.Connection, args: argparse.Namespace) ->
scan = require_scan(connection, args.scan_id)
with connection:
connection.execute(
"UPDATE scans SET continuation_thread_id = ?, updated_at = ? WHERE id = ?",
(args.thread_id, now(), scan["id"]),
"""UPDATE scans SET continuation_thread_id = ?1, updated_at = ?2,
recipe_json = CASE WHEN ?3 IS NULL THEN recipe_json
ELSE json_insert(recipe_json, '$.timeBudgetStartedAt', ?3) END
WHERE id = ?4""",
(args.thread_id, now(), getattr(args, "time_budget_started_at", None), scan["id"]),
)
return {"scanId": scan["id"], "threadId": args.thread_id}
@@ -140,8 +140,8 @@ def cli_scan_resume(
) -> dict[str, Any]:
scan = scan_with_progress(connection, scan["id"])
if scan["mode"] != "deep" or scan["recipe_json"] is None:
raise SystemExit("Resume requires a Deep Scan with a saved CLI launch recipe.")
if scan["mode"] not in {"standard", "deep"} or scan["recipe_json"] is None:
raise SystemExit("Resume requires a Standard or Deep Scan with a saved CLI launch recipe.")
if scan["status"] != "running" or scan["canceled_at"] is not None:
raise SystemExit(
"Resume requires a running scan; completed, failed, and canceled scans cannot resume."
@@ -100,7 +100,7 @@ class WindowsResumeTarget:
def prepare_cli_scan_target(
target: Path, diff_target: dict[str, str] | None, mode: str, launch_kind: str
) -> tuple[tuple[str, str | None, int | str, int | str], WindowsResumeTarget | None]:
if os.name == "nt" and mode == "deep" and launch_kind == "scan":
if os.name == "nt" and mode in {"standard", "deep"} and launch_kind == "scan":
from windows_scan_local_files import pinned_resume_checkout
with pinned_resume_checkout(target) as native:
@@ -336,6 +336,12 @@ def collect_scan_usage(
started_at=started_at,
completed_at=stopped_at,
completed_turn_id=completed_turn_id if session.thread_id == thread_id else None,
resume_owner=(
scan["mode"] == "standard"
and "recipe_json" in scan.keys()
and scan["recipe_json"] is not None
and session.thread_id == scan["continuation_thread_id"]
),
is_scan_owner=(
scan["mode"] == "deep"
and session.thread_id == scan["deep_scan_owner_thread_id"]
@@ -926,6 +932,7 @@ def _read_rollout_usage(
completed_at: datetime | None,
completed_turn_id: str | None = None,
is_scan_owner: bool = False,
resume_owner: bool = False,
) -> RolloutUsage:
result = RolloutUsage(_empty_token_usage(), set(), None, {})
total = result.tokens
@@ -947,6 +954,7 @@ def _read_rollout_usage(
started_turns: set[str] = set()
open_turns: set[str] = set()
closed_turns: set[str] = set()
failed_turns: set[str] = set()
measured_turns: set[str] = set()
def past_scan_end(timestamp: datetime, turn_id: object) -> bool:
@@ -1077,6 +1085,8 @@ def _read_rollout_usage(
if timestamp >= started_at:
if terminal_turn_id in started_turns:
closed_turns.add(terminal_turn_id)
if payload.get("type") == "task_complete" and payload.get("error"):
failed_turns.add(terminal_turn_id)
if payload.get("type") == "turn_aborted":
# Later successful work does not recover interrupted request usage.
warnings.add("turn_interrupted")
@@ -1143,6 +1153,20 @@ def _read_rollout_usage(
warnings.add("token_record_incomplete")
result.tokens_updated_at = max(result.tokens_updated_at or timestamp, timestamp)
_add_token_usage(response_usage, usage)
if (
resume_owner
and receipt_turn_id == current_turn_id
and current_turn_id in started_turns
and (open_turns - {current_turn_id} or failed_turns)
):
# Matching thread totals account for turns left open or failed before resume.
cumulative = _usage_counts(payload.get("thread_token_usage"))
if cumulative is not None and all(
cumulative[key] == total[key] + response_usage[key]
for key in TOKEN_FIELDS.values()
):
open_turns.intersection_update({current_turn_id})
closed_turns.difference_update(failed_turns - {current_turn_id})
continue
if event.get("type") != "event_msg" or payload.get("type") != "token_count":
continue
@@ -13,12 +13,14 @@ For a scan phase, use its per-scan threat model and candidate set from `../../re
For standalone analysis, use the supplied finding, repository, threat model or security policy, and context. A per-scan artifact is not required. State material assumptions and ask for missing context only when it prevents a meaningful assessment.
1. Establish the in-scope attacker, affected product surface, entry point, controlled input, security boundary, and sensitive operation. Trace the path from repository evidence.
1. Establish the in-scope attacker, affected product surface, entry point, controlled input, security boundary, and sensitive operation. Trace each step using repository evidence and supplied observations of the target.
2. Identify relevant controls and the strongest counterevidence. Explain what they establish, which prerequisites remain, and whether the exact claimed boundary is crossed.
3. Assess impact and likelihood from those facts. Apply [references/severity-policy.md](references/severity-policy.md) for the final decision. When the scan supplies a severity rubric, use it to grade reportable findings and retain `ignore` for candidates without security impact. Keep facts, severity calibration, and the final policy decision distinguishable in the result.
4. Return an explicit decision for every eligible candidate, including ignored or deferred candidates. Do not replace a supported instance with a neighboring finding or lose its root-control location.
Use repository evidence and explicitly supplied context. Access the network only when the user has expressly authorized it; an offline scan never accesses the network. Do not invent unsupported attack chains. Missing deployment or public-ingress evidence can limit confidence without defeating an otherwise supported finding.
For an imported AWS Continuum issue, read `source_data.evidence_artifacts` in the supplied finding evidence. A `VALIDATION_EVIDENCE` artifact's `body.validationEvidence` may establish a step the repository cannot show. Match the tested target, attacker privileges, and observed effect to the claimed path. For a bundled issue, use `perFindingResults` and `flowVerdicts` when present to identify the relevant finding and flow. An HTTP `exploitArtifact` can establish reachability from the tested position. An `executedProof` establishes what ran in its test environment. `sourceAnalysis` records a static inference, and an `exploitable` verdict alone does not demonstrate deployed reachability. Cite the artifact ID and the observation that supports or contradicts the step.
Treat supplied artifacts as evidence. Access the network only when the user has expressly authorized it; an offline scan never accesses the network. Do not invent unsupported attack chains. Missing deployment or public-ingress evidence can limit confidence without defeating an otherwise supported finding.
## Scan integration
@@ -1,6 +1,6 @@
# Severity and Policy Guidance
Apply this policy after establishing the attack path, scope, and counterevidence. Start from the candidate's severity hypothesis and adjust it using repository-supported impact, likelihood, prerequisites, and mitigations. Do not reopen discovery during calibration.
Apply this policy after establishing the attack path, scope, and counterevidence. Start from the candidate's severity hypothesis and adjust it using the impact, likelihood, prerequisites, and mitigations supported by the repository and supplied validation evidence. Do not reopen discovery during calibration.
Grade reportable findings with the scan's rubric or, when none is supplied, the [default severity rubric](../../../references/default-severity-rubric.md).
@@ -12,7 +12,7 @@ For SSRF, a documented outbound-request feature or optional operator filter does
- Do not discard a real, reportable finding solely because its impact or likelihood is low; use the corresponding lower severity.
- Apply hard suppression to self-only impact or unachievable/highly unrealistic prerequisites.
- Privileged-only, operator-only, developer-only, physical-access-only, or protected-write-path prerequisites imply `ignore` unless a privilege-escalation delta is the issue.
- If repository evidence does not establish a realistic lower-privileged in-scope attacker path, set `ignore`.
- A realistic lower-privileged, in-scope attacker path can be established by repository evidence, supplied validation evidence, or both. Set `ignore` if the evidence does not support such a path.
Private or internal exposure alone does not suppress a supported authorization, identity, trust-boundary, or security-control failure in a real product or production workflow. Missing deployment or ingress evidence can lower confidence or leave facts unknown without defeating an otherwise supported finding.
@@ -35,6 +35,7 @@ Treat the finding as a data-flow and boundary problem, not merely the named inpu
1. Trace the reported path and inspect only the context needed to identify the real shared boundary. Return `no_change` when repository evidence shows that the reported path is already safe; do not make a speculative change.
2. In standard mode, when feasible, run the smallest high-signal reproduction through that boundary and one legitimate control through the same path.
3. Implement the smallest repository-native fix at the shared boundary. Prefer nearby helpers and established APIs. Do not broaden into unrelated redesign, cleanup, or sibling findings.
- If the finding includes a proposed patch for this repository, use it as the starting candidate. For AWS Continuum, read `patches[].patch` from a collector capture or `source_data.patches[].patch` from the stored finding's `evidence`. Compare the hunks with the current checkout. Keep those that enforce the security invariant and adapt or replace those that leave a bypass or break legitimate behavior. If only artifact metadata is available, develop the fix from source.
4. Before verification, challenge the patch rather than defending it: inspect every direct caller of each changed helper and both outcomes of each changed condition. Look for one sibling path, representation, or copy that still reaches the vulnerable sink and one ordinary or default input that the patch newly rejects or reinterprets; revise the implementation if either exists.
5. In standard mode, verify the resulting change:
- inspect the final diff and run the narrowest syntax, import, build, or type check relevant to it
@@ -1,182 +1,46 @@
---
name: publish-findings
description: Preview and import scanner findings, including issues selected in the SonarQube plugin, into the local workbench or Codex Security Cloud.
description: Import findings from scanners, CI reports, vendor CLIs, APIs, or connected tools into the local workbench. Publish a selection of stored vendor findings to Codex Security Cloud.
---
# Publish external findings
Use `codex-security import sonar` for [live SonarQube Cloud issues](#sonarqube-cloud-issues) or a capture saved by that command. Use `codex-security publish findings` for native scanner exports, including Sonar `/api/issues/search` pages with `--provider sonar`. Select the requested destination. The CLI owns source mapping, persistence, and Cloud authentication and retries. Do not implement another store or uploader or put credentials in command arguments.
Use this workflow for third-party scanner evidence. For “publish these findings,” start with the local workbench. For “import,” acquire the requested records and store them locally. For “import and publish,” publish the selection returned by the import. Use the “Import external findings” section of `docs/sdk.md` in the installed `@openai/codex-security` package. For a global npm install, its directory is `$(npm root --global)/@openai/codex-security`. Run SDK snippets from that trusted directory with absolute paths to the checkout and reports.
## Select the evidence
Use a supplied report, connected tool or signed-in CLI that provides the requested native records for the selected account, repository and ref. Follow the [scanner import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md) to narrow broader reports and verify the selection in the JSON preview. Use a direct API only when the provider guide supports its response for the selected destination. Otherwise ask for a supported report. A fresh scan produces new findings. Keep the original records and complete the requested pagination. A JSON summary or a different product's API response is not interchangeable with the documented report. Use SARIF or CSV only when the installed provider reader supports that profile and native JSON is unavailable or the user supplies that format. Do not convert a richer JSON report to SARIF for import.
Identify whether the user wants a fresh scan, a previous scan or CI artifact, existing upstream issues, or records already in the workbench. Carry forward the selected repository, project, ref, products, filters, and exact finding IDs. A local scan can produce different findings from a hosted backlog or an earlier build.
Use the same acquisition format for repeated imports. Check the provider's identity rules before switching formats: another format can create a separate record or replace a richer snapshot with less detail. Importing findings does not reconcile equivalent vulnerabilities across formats. `--format json` controls command output, not the input report format; readers detect their supported inputs.
For a fresh scan, look for the relevant executable in the environment where it will run. Inspect its help when needed. For an existing hosted selection, inspect the tools actually available in this session or use a signed-in vendor CLI or authorized read API. Verify access with a scoped read or a documented status command. Use the vendor’s credential store or supported environment variables and keep credentials out of command arguments and imported evidence. Reuse a complete previous result from the same scope. Follow pagination, retain native records, and explain missing IDs or incomplete coverage. Ask for a missing account or repository only when the selection cannot be resolved from the available evidence.
| Source | Acquisition guidance |
| --- | --- |
| Trivy | For a fresh filesystem vulnerability scan, run `trivy fs --scanners vuln --format json --output REPORT.json .` from the chosen directory. For an earlier scan, read its repository or filesystem schema-v2 JSON or gzip artifact. Supply the checkout-relative `--trivy-scan-root` for filesystem reports. |
| Semgrep CLI or CI | For a fresh Code scan, use the installed CLI with the selected rules, e.g. `semgrep scan --config RULES --json-output REPORT.json .`. For an existing CI job, use its Code JSON or self-contained SARIF artifact. |
| Semgrep Guardian MCP | Use the connected Guardian tool `get_semgrep_sast_findings` or `get_semgrep_supply_chain_findings` with the deployment, repository, full ref, and selected filters. Match exact string finding IDs. Preserve the original request and selected tool rows in the [Guardian capture](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-guardian-findings). |
| Semgrep hosted AppSec Platform MCP | Use `semgrep_account` and `ProjectsService_GetProject` to verify the project SCM URL. Use `IssuesService_ListIssues` scoped to that project, full ref, and `ISSUE_TYPE_SAST`, and retain the selected string issue IDs and original rows. Follow the [hosted MCP capture format](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-code-findings-from-the-hosted-mcp). Guardian and hosted Platform IDs use distinct namespaces. |
| Semgrep Platform Web API | For a whole project and ref use `codex-security import semgrep PROJECT --deployment DEPLOYMENT --ref REF --format json`. For selected SAST IDs use the original project response and selected findings pages. |
| GitHub | The signed-in GitHub CLI collector `codex-security import github OWNER/REPO` accepts repeated `--github-alert NUMBER` or a `--github-ref REF`. Use `import github-advisories` for advisories. For Dependabot, export full paginated repository REST alert objects through the available GitHub connection. Keep separate source keys for these three families. |
| Snyk | For a monitored Open Source project use `codex-security import snyk PROJECT_ID --org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a monitored Code project. For a fresh dependency scan use native `snyk test` JSON or the signed-in Snyk plugin's SCA export from the requested root. Keep acquisition formats in distinct namespaces. |
| AWS Continuum | Use `codex-security import continuum ENVIRONMENT_ID --format json` to collect all environment issues, linked findings, and issue-level `EVIDENCE` and `VALIDATION_EVIDENCE` artifacts. The environment must have exactly one Git repository, which the report records. S3 sources may also be present. Override the AWS CLI defaults with `--aws-profile` and `--aws-region` as needed. Verify that the issues belong to the intended repository before importing with `publish findings --provider continuum`. Supply the verified `--source-repository-url` for saved reports without a repository URL. For attack-path scoring, give `$attack-path-analysis` the selected issue's stored `.evidence`, including its validation artifacts. [Continuum guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md) |
| Checkmarx | Export a completed Checkmarx One scan as CLI JSON or self-managed CxSAST as XML. Follow the [collector instructions](references/checkmarx-import.md) for the selected product, scan, and verified owning project. |
| Wiz | Use the connected Wiz tools or API to retrieve the selected repository findings by occurrence ID, or use a detailed report. JSON covers multiple finding families. Detailed CSV covers repository package vulnerabilities. [Wiz input profiles](references/wiz-import.md) |
| AWS Continuum patches | Run `codex-security import continuum ENVIRONMENT_ID --finding-id FINDING_ID --source-root CHECKOUT --repository-name AWS_SOURCE_NAME --format json` for one finding. Use an absolute checkout path and the exact AWS source name. Omit `--repository-name` when the environment has exactly one Git repository and no S3 sources. The CLI verifies that with `GetEnvironment` before collecting the finding. Publish the JSON with `--provider continuum` and the verified `--source-repository-url`. [Continuum guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md#collect-a-finding-with-patches) |
| CrowdStrike FCS | Use a saved FCS CLI 4.x `fcs scan iac` JSON report, such as a CI artifact from the [FCS GitHub Action](https://github.com/CrowdStrike/fcs-action). For a fresh scan, run the installed `fcs` CLI from the directory to import into: `fcs scan iac --path . --report-formats json --output-path DIR`, where `DIR` is an existing private directory outside it whose name has no dot. For a remote `git::` URL, add `?ref=COMMIT` and import into a checkout of that commit, or into its subdirectory for a `//subdir` suffix. A nonzero exit can mean that detections matched `--fail-on` or that the scan failed; import only the `*-scan-results.json` file named in `Results saved to file`. If `fcs` is not on `PATH`, do not install it or pass Falcon credentials in arguments; ask for a saved report. Import with `--to local` only. The directory does not need to be a Git checkout, but each detection's file must have the content that FCS scanned. Add `--source-repository-url` only for a verified URL. A `git::https://` report already names its repository, and a different URL stops the import. [CrowdStrike guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/crowdstrike.md) |
| Other built-in readers | OpenGrep accepts native scan JSON including scanner errors. Endor uses `endorctl` Finding JSON with complete records. Inspector uses Inspector2 ListFindings for one Code Security repository. Black Duck uses BOM-6 vulnerable components for one project version. Veracode uses paginated STATIC policy findings for one application. Tenable uses a selected Code Repository inventory capture and verified HTTPS clone URL. [Provider guides and identity rules](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#choose-your-scanner) |
### SonarQube Cloud issues
Retrieve existing Sonar issues with the signed-in `sonar` CLI. The Sonar plugin can supply selected issue keys; collect full issue and flow evidence for that same project, branch or pull request. Preview with `codex-security import sonar --sonar-project PROJECT --sonar-branch BRANCH --sonar-issue KEY --dry-run --format json` (repeat `--sonar-issue` for more keys). Use the preview's saved capture for an approved import. For findings already stored in the workbench, select them directly. [Sonar workflow](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/sonar.md#import-and-verify)
## 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. [Supported inputs by provider](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#choose-your-scanner)
Use the matching native SDK reader or the existing CLI, for example `codex-security publish findings REPORT.json --to local --provider trivy --source-key PROJECT/BRANCH --repository CHECKOUT --trivy-scan-root . --dry-run --format json`. Use a source key stable across repeated imports of this selection. Review the repository, evidence, exclusions and scanner errors. For the requested write, drop `--dry-run` and use `--yes` when approved. Keep the import ID and finding versions from the result. A partial import exits with code 1. Check the saved findings and report the exclusions before retrying.
```sh
codex-security publish findings /path/to/selected-wiz-findings.json \
--to local --repository /path/to/project --provider wiz \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
Show the repository, source namespace, normalized evidence, and exclusions. For a zero-record preview, report whether the input is empty or failed and stop. After confirmation, repeat without `--dry-run`, adding `--yes`. Keep approval when the user already approved this preview and the input and destination are unchanged.
Read the stored evidence with `codex-security findings imported /path/to/project --format json`; the repository defaults to the current directory. Report created, updated, unchanged, and excluded counts, including exclusion reasons when the command exits 1.
Local records remain unassessed source evidence, separate from `findings list` and completed scans. Repeated imports use the same repository/provider/source-key/source-ID identity; omitted records remain stored. When a source repository URL and local Git remotes are available, the URL must match a remote. Local import does not publish to Cloud or automatically investigate or patch findings.
## Trivy dependency vulnerabilities
Use `--provider trivy` with a saved schema-v2 repository or filesystem report (JSON or gzip). Preview with a stable project/branch source key and `--trivy-scan-root` relative to the checkout (`.` for the whole checkout). Omit the root only when the report's Git metadata corroborates a remote repository scan. Check the source, package paths and exclusions before importing. Trivy's `fixed` status identifies an available upstream fix. [Trivy import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/trivy.md)
## Amazon Inspector repository findings
Use `--provider inspector` and `--source-repository-url` with a complete Inspector2 ListFindings export for one Code Security repository. If it contains only a project ARN and name, pass the full `--inspector-project-arn ARN` verified for that Git URL in the SCM integration. Supply the same ARN when resuming a pending Cloud submission. Self-managed GitLab is supported locally.
## AWS Continuum code findings
Use `--provider continuum` and `--source-repository-url` for an AWS Continuum for Code Vulnerabilities export. Verify which repository owns each selected finding. Use `aws continuum get-code-finding` for a selected ID, or `list-code-findings` with automatic pagination when every row belongs to the requested repository. Reuse the same source key for that environment and repository. [Continuum import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md)
## Black Duck SCA project-version vulnerabilities
Use `--provider blackduck` for a BOM-6 vulnerable-components export from one project version. Supply `--source-repository-url` after verifying the project version maps to that repository. Keep the same source key on replay and preview the destination before importing.
## Checkmarx SAST
Use `--provider checkmarx` for a Checkmarx One CLI JSON or self-managed CxSAST XML report. To retrieve a completed scan, follow the [Checkmarx collection instructions](references/checkmarx-import.md). Collection retrieves the full scan. If the user wants a subset, ask for a filtered vendor export. Before fetching CxSAST XML, verify the scan ID, project and owning team on the selected server.
Preview the report for the verified repository and ref with `--dry-run --format json`. After confirmation, use the same report path and source key for the import and any retries.
## Veracode Static Analysis policy findings
Use `--provider veracode` with all Findings API pages for one application’s STATIC policy findings. Verify that the application maps to the repository named by `--source-repository-url`. Keep the source key stable for that application and preview the import before writing.
## Endor Labs findings
Use authenticated `endorctl` for one verified project and context. Omit `--field-mask` to keep complete native Finding objects. Replace `/path/to/private/reports` with a private directory outside the checkout.
```sh
out=$(mktemp -d "/path/to/private/reports/endor.XXXXXX") &&
endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \
--filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \
--list-all --output-type json > "$out/findings.tmp" &&
mv "$out/findings.tmp" "$out/endor-findings.json" &&
printf '%s\n' "$out/endor-findings.json"
```
Preview the completed file with `--provider endor` and a stable source key such as `YOUR_NAMESPACE/PROJECT_UUID/main`. Match the project to the destination repository. For another branch or scan context, change the filter and use a distinct source key. The [official Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit) can help with setup and investigation; its summaries, counts and field-masked results do not replace complete Finding objects. The [CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api) supplies the export. The importer reads that saved file; it does not maintain an Endor API connection or write changes back to Endor.
Native JSON retains severity, scanned commit, package and advisory data, and primary SAST/AI SAST locations. Existing self-contained endorctl SARIF is a lossy compatibility format that retains finding UUIDs and links; unavailable severity or revisions stay unknown. Both formats use the Endor UUID within the selected repository and source key as identity. Importing SARIF after native JSON updates the same record by replacing its evidence snapshot, not merging it: native detail absent from SARIF is removed from that snapshot. Use native JSON consistently for ongoing imports. Keep the original evidence and inspect exclusions. Imported records remain unassessed source evidence. Follow the [local](#import-locally) or [Cloud](#publish-to-cloud) workflow for the chosen destination.
## Wiz findings
Read [Wiz import formats](references/wiz-import.md#finding-formats) before preparing input. Use an authorized [Wiz MCP](https://www.wiz.io/blog/introducing-wiz-mcp) or Wiz API connection; a configured plugin may provide it, but do not assume an official Codex plugin is available. Prefer supported native JSON. Inspect actual records, finish the requested pagination, and save only the selected evidence with its original occurrence IDs. A supplied export is also supported. Summaries, Wiz Issues, and local CLI scan results are not automatically supported finding records.
Validate the acquisition path against actual responses from an authorized Wiz tenant; local parser checks do not establish that qualification. Direct CSV input covers repository package vulnerabilities (SCA) only, not SAST or cloud posture findings, and does not provide a complete Wiz code-to-cloud integration.
Use a stable Wiz tenant/finding namespace as `--source-key`; a project filter does not create a new identity. Confirm the selected assets or builds belong to the destination repository. Do not infer source branches or revisions from the current checkout, invent missing evidence, or import vendor credentials, unrelated records, or local assessments as original scanner evidence. Do not retrieve or test credentials or apply suggested fixes.
## Snyk findings
For an existing monitored Open Source or Code project, follow the [Snyk Issues API import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md#existing-issues-from-snyk). With a read-authorized `SNYK_TOKEN`, run `codex-security import snyk PROJECT_ID --org ORG_ID --source-repository-url URL --format json`. Add `--snyk-product code` for a Code project and `--snyk-api-origin` for a regional deployment. Save the complete successful JSON output, preview with `publish findings --provider snyk` and the requested `--to local` or `--to cloud` destination, then confirm the import.
Prefer the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex) when available. Ask its `snyk-findings-export` skill for **SCA only from the repository’s Git root** and save the `snyk-findings-export/v1` bundle. It scans the current workspace through local MCP; it cannot list existing platform projects or retrieve earlier findings. Do not substitute a fresh scan for a request to read a platform backlog. Authentication, relevant Snyk access and the project's package tooling are required.
Import the bundle with `--provider snyk`, choosing `--to local --repository /path/to/project` or `--to cloud --repository https://github.com/example/project`. Use a stable repository/branch/scan-target/acquisition namespace such as `github.com/example/project/main/root/plugin-sca`. Check the bundle's scan outcomes, collection completeness and limitations alongside the preview. Only Open Source SCA vulnerability records are supported; other categories are explicit exclusions. Preserve the native MCP record and unavailable fields. MCP descriptions may be shortened and alternate dependency paths omitted; do not reconstruct missing evidence. Plugin v1 paths are target-relative without a Git-root offset, so the importer keeps them in original evidence instead of repository locations. Use a distinct source key for each scan target. Ignore status is a source policy decision, not a Codex assessment or a fix.
For CLI automation, prefer `snyk test --file=package.json --json-file-output=snyk-open-source.json` from the selected repository root. Exit 1 means vulnerabilities were found; stop on other nonzero exits instead of importing a stale file. The existing `--provider snyk` autodetects native JSON (one project or an `--all-projects` array), plugin JSON and Open Source SARIF. Native JSON preserves per-dependency-path records and remediation fields; do not use `--group-issues`. Project errors stop import. Native JSON paths also lack a Git-root offset and stay in original evidence. These workspace scan formats import Open Source SCA vulnerabilities.
Use one format consistently per repository, branch and scan target, with a stable source key such as `github.com/example/project/main/root/native-sca`. Plugin, native JSON and SARIF have distinct identities; use separate keys when switching, without claiming cross-format deduplication or removal of older records. Existing `snyk test --sarif-file-output=snyk-open-source.sarif` reports remain a compatibility path. SARIF groups advisory occurrences and exposes one package coordinate, so prefer JSON for acquisition. Its target-relative manifest paths lack a Git-root offset and stay in original evidence with synthetic line numbers, without being projected as repository locations or package manifest paths.
Retain package versions, reported fixed versions, provenance and original evidence without claiming a fix was applied. Known repository claims must match the selected Cloud repository or, when available, a configured local Git remote. Resolve an unknown repository with the user; never infer that an export belongs to the current checkout. Follow [local imports](#import-locally) for preview, confirmation and readback or [Cloud publication](#publish-to-cloud) for upload authorization. Snyk workspace reports and monitored-project exports support local and Cloud import.
## Semgrep Code
Prefer native Code/SAST CLI or CI JSON for this reader; use self-contained SARIF 2.1.0 as a compatibility path. JSON retains the original severity better than SARIF. Select SAST rules or Code-only CI output; identifiable non-SAST records are excluded, but SARIF may omit the product metadata needed to distinguish Secrets.
For a user-requested new scan, use the installed Semgrep CLI from the source repository root with the selected SAST rules: `semgrep scan --config /path/to/sast-rules.yaml --json-output /path/to/semgrep.json .`. Existing CI jobs can produce the same artifact using `--json-output`; authenticated `semgrep ci --code` follows the job's policy and baseline scope. Explain that this generates fresh scan findings, and do not substitute it for a request to retrieve existing Platform findings.
For selected rule-based Code findings from the hosted Semgrep AppSec Platform MCP, call `semgrep_account` and match the project's SCM URL to the requested repository. Fetch the project with `ProjectsService_GetProject` and the requested string issue IDs with `IssuesService_ListIssues`, scoped to the project ID, full ref and `ISSUE_TYPE_SAST`. Copy the original selected issue rows into a private capture with `deploymentId`, `project`, `ref`, `findingIds` and `issues`. Follow the [hosted MCP SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-code-findings-from-the-hosted-mcp) to preview and save to the verified local checkout or the explicitly selected Cloud destination. Verify the private inbox job or the connected repository’s receipts and readback, as shown in the preview.
For a selection of existing Code or Supply Chain findings from Guardian, 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 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.
Import the native report with `--provider semgrep`, a stable organization/project/branch `--source-key`, and `--source-repository-url` identifying the actual source repository. Use `--to local --repository /path/to/project` for local storage or `--to cloud --repository URL_OR_ID` for Cloud. The source URL is checked against configured local Git remotes or the Cloud destination. Preview with `--dry-run --format json` before confirming the import.
Keep supplied fingerprints. Reimporting the same fingerprint after code moves updates the existing source record with the new range. If the fingerprint is absent or `requires login`, the fallback uses rule, literal path and range: movement creates a second retained record, and the earlier record remains stored. Do not infer a merge or deletion. Read the persisted evidence with `codex-security findings imported /path/to/project --format json` before assessment. Source rule, CWE, snippets, traces and status are vendor evidence, not Codex assessments. Do not infer a report revision from the current checkout. Resolve scan errors and review all exclusions before uploading; do not remove error metadata to force acceptance.
## OpenGrep
Import native OpenGrep JSON with `--provider opengrep`, `--source-repository-url`, and a stable OpenGrep-specific `--source-key`. Preview the destination and scan diagnostics before importing. Local and Cloud imports use the Semgrep provider and retain OpenGrep as the scanner origin.
## SonarQube Cloud issues
For “import these Sonar findings,” carry over the Sonar project, branch or PR, and the exact issue keys selected in the [SonarQube plugin for Codex](https://www.sonarsource.com/blog/now-available-sonarqube-plugin-for-codex/). Use the keys from the underlying Sonar result. If only a formatted table remains, resolve the selected rows against the same project and ref and ask about ambiguous matches. A rule can occur more than once. Never turn a selection into a project-wide import.
From the intended checkout, preview the selection using the developer's authenticated `sonar` CLI. Use `--sonar-pull-request` in place of `--sonar-branch` for a PR. Omit `--sonar-issue` only when the user wants the project's open security issues. If the project has no verified SCM binding, confirm the repository URL that belongs to the project and pass it with `--source-repository-url`.
```sh
codex-security import sonar --sonar-project example_project --sonar-branch main \
--sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json
```
Pass `--to cloud` at preview time if the user also requested Cloud publication. Show the selected issues and exclusions, the local repository, and any Cloud destination as described under [Publish to Cloud](#publish-to-cloud). The preview returns a private evidence file in `capture`. After confirmation, run `codex-security import sonar CAPTURE --yes` for local import. For Cloud, use the exact `capture` from the successful Cloud preview and add `--to cloud`. If the account, repository, or environment changes, show a fresh preview and ask for confirmation. If Cloud is unavailable, finish the requested local import and report the Cloud error. For a request to publish an existing import, start with its capture. Report the saved path so the developer can resume.
Sonar authentication is required only for a live fetch. If the local CLI lacks a login, direct the user to `sonar auth login` and keep the selection. A hosted MCP connection can help identify issues, but its issue summaries omit flow evidence. Use the signed-in CLI or a saved Codex Security Sonar capture to complete the import. If `codex-security` is absent, ask the user to install it from a trusted directory and invoke that installed executable in the checkout.
## GitHub alerts and 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 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.
Save the selected collector’s output in a private file outside the checkout. After collection succeeds, use `--provider github` and the [local](#import-locally) or [Cloud](#publish-to-cloud) workflow for the requested destination. Keep a separate stable source key for each family, such as `github.com/example/project/code-scanning` or `github.com/example/project/security-advisories`.
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.
For an unfamiliar format, inspect actual rows and write a parser in the language appropriate to the source. Pass the findings, read count and exclusions to `prepareNormalizedLocalImport` with the checkout, provider and source key. Give each occurrence a stable source ID, preserve relevant native evidence and repository identity, and account for every selected row with either evidence or a numbered exclusion. Report skipped or missing items. A repeated import can include unchanged findings; the import ID identifies the entire stored selection.
## Publish to Cloud
Resolve the user's destination to a connected GitHub or GitHub Enterprise repository URL or Cloud repository ID, including custom Enterprise hosts. Confirm the intended Cloud account and authorized repository environment before running a preview that can contact Cloud. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
Use `listLocalExternalImports({ repository })` to find an import by its timestamp, including imports of unchanged findings. Call `prepareStoredFindingsPublication(selection, { repository: cloudRepository })` with that import ID or the selected finding IDs and versions. Show the account, destination, evidence and exclusions. After the user confirms the preview, call `group.publish(group.reviewId)` for each approved group.
For an alternate Cloud deployment, configure the [deployment settings](#deployment-settings) before previewing. Keep the selected deployment and login throughout the upload.
### Preview and approve
```sh
codex-security publish findings /path/to/selected-wiz-findings.json \
--to cloud --repository https://github.com/example/project --provider wiz \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
When the preview returns `status: "empty"`, report that there is nothing to upload. For a nonempty preview, show the endpoint, account, repository, source key, severity counts and exclusions. The `privateImport` entry describes the report for the user’s private inbox. For the repository publisher, `requests` identifies the environments that will receive the records. Identify the evidence file and make the complete JSON preview available for inspection without pasting a large report into the conversation. Explain that vendor evidence is not a Codex assessment.
Obtain explicit confirmation for this concrete upload, including skipped records. Then run the same command without `--dry-run`, adding `--yes`. Authorization to inspect or assess findings alone does not authorize sending them to Cloud. Keep approval when the user already approved this preview and the input and destination are unchanged.
### 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` 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
Preview the original file again with the same source key, repository, account, endpoint and state directory. If `resumed` is true, the CLI reuses the saved submission. If a reset or changed destination requires a new submission, review the new preview before confirming. [Retry a Cloud submission](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/schema-guide.md#retry-a-cloud-submission)
### Deployment settings
Set `CODEX_SECURITY_CLOUD_BASE_URL` to the deployment's API root for preview and upload. Use its login and an isolated state directory for tests. If the user or Cloud page supplies an app URL, set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL. This setting controls the returned UI link. The API root and login still determine routing and authentication.
Check the preview's `cloudApiUrl` and any `cloudUrl` against the intended API endpoint and app. Saved retries are scoped to the deployment. `CODEX_SECURITY_CLOUD_PUBLISH_URL` applies only to native scan publication.
For a private inbox, check the import job status and counts. For repository requests, check verification, unacknowledged records and failures. Keep each approved group’s selection, destination and review ID. On interruption, reprepare the interrupted and unstarted groups, using the saved review IDs. For an earlier client’s pending upload, finish with its original build or verify which findings reached Cloud before preparing another submission. Report completed groups from their receipts. A changed review ID requires a fresh preview. [Cloud receipts and retry behavior](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/schema-guide.md#retry-a-cloud-submission)
@@ -1,6 +1,6 @@
interface:
display_name: "Publish Findings"
short_description: "Import vendor findings locally or to Cloud"
default_prompt: "Use $publish-findings to preview selected vendor findings for my repository and import them to my chosen destination."
short_description: "Import and publish stored scanner findings"
default_prompt: "Use $publish-findings to import the selected scanner findings or publish a selection from my local workbench."
policy:
allow_implicit_invocation: true
@@ -32,6 +32,6 @@ Use native Java, a released CxFlow JAR (1.6.37+), and a trusted SAST-only profil
## Preview and import
Pass the successful helper's printed path as the quoted file argument to `codex-security publish findings` in the next tool call. Use `--provider checkmarx`, the requested destination, verified `--source-repository-url`, a stable product/tenant/project/ref `--source-key`, and `--dry-run --format json`. Review the scope, findings and exclusions. Verify native paths against the checkout before opening source files.
Pass the successful helper's printed path as the quoted file argument to `codex-security publish findings` in the next tool call. Use `--provider checkmarx --to local --repository CHECKOUT`, the verified `--source-repository-url`, a stable product/tenant/project/ref `--source-key`, and `--dry-run --format json`. Review the scope, findings and exclusions. Verify native paths against the checkout before opening source files.
After confirmation, reuse that file and those options for [local import](../SKILL.md#import-locally), [Cloud publication](../SKILL.md#publish-to-cloud) and retries. Remove the helper’s temporary directory after readback unless the operator wants it retained. Keep operator-supplied files. [User guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md)
After confirmation, reuse that file and those options for the [local import](../SKILL.md#import-locally). Use its stored selection for [Cloud publication](../SKILL.md#publish-to-cloud) and retries. Remove the helper’s temporary directory after readback unless the operator wants it retained. Keep operator-supplied files. [User guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/checkmarx.md)
@@ -6,7 +6,6 @@ import os
import re
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
@@ -16,63 +15,9 @@ from email.parser import BytesHeaderParser
from pathlib import Path
from xml.parsers import expat
def is_link(info: os.stat_result) -> bool:
return stat.S_ISLNK(info.st_mode) or (
os.name == "nt" and info.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT
)
def source_root(target: Path | None) -> Path | None:
if target is not None and (not target.is_absolute() or not target.is_dir()):
raise ValueError("Select an existing absolute source directory.")
source = (target or Path.cwd()).resolve()
# A nested checkout or submodule is still part of the enclosing source tree.
for parent in (*reversed(source.parents), source):
marker = parent / ".git"
try:
info = marker.lstat()
if stat.S_ISDIR(info.st_mode) and not is_link(info):
info = (marker / "HEAD").lstat()
except (FileNotFoundError, NotADirectoryError):
continue
if stat.S_ISREG(info.st_mode) or is_link(info):
return parent
return source if target is not None else None
def in_source(path: Path, source: Path | None) -> bool:
if source is None:
return False
if path.is_relative_to(source):
return True
identity = source.stat()
current = Path()
parts = list(reversed(path.absolute().parts))
active_links = set()
while parts:
part = parts.pop()
if isinstance(part, Path):
# The link target's components have all been checked.
active_links.remove(part)
continue
current = current.parent if part == ".." else current / part
if current == source:
return True
try:
info = current.lstat()
except (FileNotFoundError, NotADirectoryError):
continue
if os.path.samestat(info, identity):
return True
if is_link(info):
if current in active_links:
raise OSError(f"Symbolic link loop at {current}")
active_links.add(current)
parts.append(current)
parts.extend(reversed(current.readlink().parts))
current = current.parent
return False
# Isolated Python does not put the installed script directory on sys.path.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from collector_paths import in_source, source_root # noqa: E402
def installed_file(value: str, source: Path | None) -> Path:
@@ -0,0 +1,63 @@
"""Identify the selected source checkout and paths it controls."""
import os
import stat
from pathlib import Path
def is_link(info: os.stat_result) -> bool:
return stat.S_ISLNK(info.st_mode) or (
os.name == "nt" and info.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT
)
def source_root(target: Path | None) -> Path | None:
if target is not None and (not target.is_absolute() or not target.is_dir()):
raise ValueError("Select an existing absolute source directory.")
source = (target or Path.cwd()).resolve()
# A nested checkout or submodule is still part of the enclosing source tree.
for parent in (*reversed(source.parents), source):
marker = parent / ".git"
try:
info = marker.lstat()
if stat.S_ISDIR(info.st_mode) and not is_link(info):
info = (marker / "HEAD").lstat()
except (FileNotFoundError, NotADirectoryError):
continue
if stat.S_ISREG(info.st_mode) or is_link(info):
return parent
return source if target is not None else None
def in_source(path: Path, source: Path | None) -> bool:
if source is None:
return False
if path.is_relative_to(source):
return True
identity = source.stat()
current = Path()
parts = list(reversed(path.absolute().parts))
active_links = set()
while parts:
part = parts.pop()
if isinstance(part, Path):
# The link target's components have all been checked.
active_links.remove(part)
continue
current = current.parent if part == ".." else current / part
if current == source:
return True
try:
info = current.lstat()
except (FileNotFoundError, NotADirectoryError):
continue
if os.path.samestat(info, identity):
return True
if is_link(info):
if current in active_links:
raise OSError(f"Symbolic link loop at {current}")
active_links.add(current)
parts.append(current)
parts.extend(reversed(current.readlink().parts))
current = current.parent
return False
@@ -532,8 +532,10 @@ def test_resume_verification_failure_rolls_back_the_created_handle(
with closing(workbench_db.connect()) as connection:
old_id = None
previous_identity = None
if archive:
old_id = register("standard", connection=connection)["scanId"]
previous_identity = windows_scan_local_files.deep_resume_output_identity(output)
connection.execute("UPDATE scans SET status = 'failed' WHERE id = ?", (old_id,))
connection.commit()
previous_file.write_bytes(b"original result")
@@ -560,13 +562,14 @@ def test_resume_verification_failure_rolls_back_the_created_handle(
with pytest.raises(OSError) as failure:
register(archive=archive, connection=connection)
assert (getattr(failure.value, "winerror", None) or failure.value.errno) == 32
assert not retained.exists()
assert not list(output.parent.glob(f"{output.name}.previous-*"))
rows = connection.execute("SELECT id, scan_dir FROM scans").fetchall()
if archive:
assert windows_scan_local_files.deep_resume_output_identity(output) == previous_identity
assert [tuple(row) for row in rows] == [(old_id, str(output))]
assert previous_file.read_bytes() == b"original result"
else:
assert not retained.exists()
assert rows == []
assert list(output.iterdir()) == []
assert register(archive=archive, connection=connection)["scanDir"] == str(output)
@@ -0,0 +1,52 @@
"""Account for interrupted and resumed turns of a Standard scan."""
from datetime import datetime
from pathlib import Path
import pytest
from test_workbench_scan_usage import (
_event,
_measure_rollout,
_response_event,
_rollout,
_token_event,
)
from workbench_test_support import usage_counts as _counts
@pytest.mark.parametrize("cumulative_input", [30, 31, None])
def test_resumed_owner_reconciles_crash_and_failed_reconnect_only_with_matching_thread_usage(
workbench_api, tmp_path: Path, cumulative_input: int | None
) -> None:
at = datetime.fromisoformat("2026-01-01T00:00:00+00:00")
thread_id = "scan-parent"
resumed = _response_event(at, thread_id, "second", 10, 2, turn_id="resumed")
if cumulative_input is None:
del resumed["payload"]["thread_token_usage"]
else:
resumed["payload"]["thread_token_usage"] = _token_event(at, cumulative_input, 5)["payload"][
"info"
]["total_token_usage"]
events = [
_event(at, "event_msg", {"type": "task_started", "turn_id": "crashed"}),
_response_event(at, thread_id, "first", 20, 3, turn_id="crashed"),
_event(at, "event_msg", {"type": "task_started", "turn_id": "reconnect"}),
_event(
at,
"event_msg",
{
"type": "task_complete",
"turn_id": "reconnect",
"error": {"message": "Connection failed"},
},
),
_event(at, "event_msg", {"type": "task_started", "turn_id": "resumed"}),
resumed,
_event(at, "event_msg", {"type": "task_complete", "turn_id": "resumed"}),
]
rollout = _rollout(tmp_path, thread_id, events)
usage = _measure_rollout(workbench_api["scan_usage"], rollout, at, at, resume_owner=True)
assert usage.tokens == _counts(30, 0, 5)
assert usage.warnings == (
set() if cumulative_input == 30 else {"token_record_missing", "turn_in_progress"}
)
+69 -16
View File
@@ -725,8 +725,8 @@ Choose the next step from the recorded reason:
start a new scan with the intended scope, including for plugin scans without
a recipe. Retained findings can still be reviewed, but absence of findings
from a stopped run is inconclusive.
- **A Deep Scan was interrupted and is still recorded as `running`:** it may
support [resume](#resuming-an-interrupted-deep-scan) with the original checkout,
- **A Standard or Deep Scan was interrupted and is still recorded as `running`:** it may
support [resume](#resuming-an-interrupted-scan) with the original checkout,
artifacts, and session. Completed, failed, and canceled scans cannot resume.
For example, after identifying an omitted API directory:
@@ -957,7 +957,7 @@ behavior are unchanged.
The SDK setting is `maxTimeMinutes`; project files use `scan.max_time_minutes`.
Each launched scan or rerun gets its own allowance after setup, and reconnects
do not reset it. Standard scans still do not support resume. For batch and
do not reset it. [Resumed Standard scans](#resuming-an-interrupted-scan) keep the original deadline. For batch and
component scans, the project setting applies separately to each scan attempt,
not to planning, result matching, or the total campaign.
@@ -1409,6 +1409,22 @@ including during recovery. Run post-scan prompts separately. A resumed scan also
limit and includes prior recorded usage in its cost estimate.
Bulk scans use clean shallow checkouts and support repository/path scopes.
Bulk checkout, scan, and recovery processes select host tools outside every local
source and campaign checkout. Inventory uses an external ripgrep executable or
the copy shipped with the selected Codex installation.
On POSIX, campaign processes and script-based inventory tools search readable
tool directories. Launchers must be readable so their shebang interpreters can
be checked. Use an absolute interpreter path for campaign scripts, including
`#!/usr/bin/env sh`, because workers run in different directories. If a directory
contains an ineligible executable, its other tools remain available through a
temporary PATH. Scripts using the system `/bin/sh` or `/usr/bin/env` run from
their installed location when the packaged dispatcher can start. Keep other
prefix-sensitive tools, including Python virtual environments, in directories
where every entry can be used. On Windows, the campaign omits a tool directory
from the child PATH if its Git, ripgrep, or Node executable link passes through a
selected source.
CSV scopes are literal paths relative to each checkout, including names such
as `~/src`.
Configured diff or working-tree scopes are rejected unless every affected row
@@ -1541,13 +1557,13 @@ Supply the validation prompt again when rerunning.
Choose the command by what you want to keep. [Scanner guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md) list the accepted vendor formats.
| Input and goal | Command | Service contacted | Where to find the result |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------ | --------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Save vendor evidence for a checkout | `publish findings FILE --to local` | None | `findings imported PATH` lists unassessed local findings. |
| Publish a supported vendor report | [`publish findings FILE --to cloud`](#publish-findings-to-cloud) | Codex Security Cloud | The receipt identifies the private inbox job or repository records. |
| Collect upstream records to a file | `import github`, `import github-advisories`, `import semgrep` or `import snyk` | Selected vendor | Redirect the complete `--format json` output to a private file, then preview it with `publish findings`. |
| Collect live Sonar issues | [`import sonar --dry-run`](#import-sonarqube-cloud-issues) | SonarQube Cloud during collection | The `capture` field gives a private file path. Replay it to save locally or save locally and publish to Cloud. |
| Save Codex Security findings CSV or JSON as a completed scan | [`scan import`](#import-findings-as-a-saved-scan) | None | `scans list --scan-root DIR --json` shows imports under the artifact root. |
| Input and goal | Command | Service contacted | Where to find the result |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Save vendor evidence for a checkout | `publish findings FILE --to local` | None | `findings imported PATH` lists unassessed local findings. |
| Publish a supported vendor report | [`publish findings FILE --to cloud`](#publish-findings-to-cloud) | Codex Security Cloud | The receipt identifies the private inbox job or repository records. |
| Collect upstream records to a file | `import continuum`, `import github`, `import github-advisories`, `import semgrep` or `import snyk` | Selected vendor | Redirect the complete `--format json` output to a private file, then preview it with `publish findings`. |
| Collect live Sonar issues | [`import sonar --dry-run`](#import-sonarqube-cloud-issues) | SonarQube Cloud during collection | The `capture` field gives a private file path. Replay it to save locally or save locally and publish to Cloud. |
| Save Codex Security findings CSV or JSON as a completed scan | [`scan import`](#import-findings-as-a-saved-scan) | None | `scans list --scan-root DIR --json` shows imports under the artifact root. |
For `publish findings`, `--to` is required. With `--to local`, `--repository`
takes a checkout path. Select the reader with `--provider` and give the source a stable `--source-key`.
@@ -1564,8 +1580,13 @@ codex-security publish findings /private/path/endor-findings.json --provider end
After reviewing the findings and exclusions, rerun the command without
`--dry-run` and confirm. [Save or publish and verify](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#save-or-publish-and-verify).
When you pass `--source-repository-url` to `publish findings`, the command warns
on stderr to verify that every finding belongs to the repository you specify.
For Tenable One Code Repository findings, use `--provider tenable --to local` and set `--source-repository-url` to the checkout’s verified HTTPS remote. [Tenable export and import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/tenable.md)
For CrowdStrike FCS CLI 4.x IaC reports, use `--provider crowdstrike --to local` and select the directory where FCS ran with `--repository`. It does not need to be a Git checkout, but each scanned file must be unchanged since the scan. Add `--source-repository-url` to record the repository; it must match a fetch remote when the directory is a Git checkout. A `git::https://` report names its repository, and a different `--source-repository-url` stops the import. [CrowdStrike import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/crowdstrike.md)
Local readback uses `findings imported [PATH]`. The path defaults to the current
directory. Each imported record starts as `not_assessed`. Unknown revisions and
locations stay unknown. Repository-scoped sources are checked against comparable
@@ -1596,6 +1617,31 @@ Use `--provider endor` for one Endor project and context. The
[Endor Labs guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/endor.md) covers native Finding JSON,
SARIF compatibility, and the local preview.
## Collect AWS Continuum issues
`import continuum ENVIRONMENT_ID --format json` writes one report to standard
output after collecting every issue page and fetching each issue's linked
findings, prevalidation signals (`EVIDENCE`), and validation results
(`VALIDATION_EVIDENCE`). Install AWS CLI v2.38.5 or later outside the checkout.
The command requires exactly one configured Git repository and records it in the
report. It collects patches when Git is the only source.
S3 sources are allowed alongside that repository.
Collection covers the whole environment. Pass the short
Continuum environment ID. Optional
`--aws-profile PROFILE` and `--aws-region REGION` override the AWS CLI's
credential and Region selection. Preview and import the report separately
with `publish findings FILE --provider continuum`. Pass
`--source-repository-url URL` when the report has no saved repository URL.
For one finding and its generated patches, add `--finding-id FINDING_ID` and
`--source-root CHECKOUT` with the absolute checkout path. The CLI uses
`GetEnvironment` to verify that the environment has exactly one Git repository
and no S3 sources before including unnamed patches. Pass
`--repository-name AWS_SOURCE_NAME` for other environments to keep patches
with that exact AWS source name. This mode accepts the same AWS profile and
Region overrides and writes the finding-based JSON format for `publish findings`.
[Continuum import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md)
## Import SonarQube Cloud issues
`import sonar --dry-run` writes a private evidence copy for both live and saved inputs and returns its path. Preview
@@ -2136,7 +2182,7 @@ in the workbench, without changing sealed report timestamps.
| `scans list [REPOSITORY]` | List scans; `--scan-root DIR` filters artifact roots. |
| `scans show [SCAN_ID]` | Show a scan; defaults to latest completed. |
| `scans logs [SCAN_ID]` | Show session events; defaults to latest, including active. |
| `scans resume SCAN_ID` | Continue an interrupted Deep Scan. |
| `scans resume SCAN_ID` | Continue an interrupted Standard or Deep Scan. |
| `scans rerun [SCAN_ID]` | Rerun a saved recipe in its checkout. |
| `scans match --all` | Match completed scans in this repository generation, including linked worktrees. |
| `scans compare [BEFORE] [AFTER]` | Compare scans; defaults to latest two completed. |
@@ -2232,7 +2278,7 @@ work on all supported Node.js versions, including logs, feedback attachments,
usage accounting, and saved-session discovery for resume. A bundled decoder
reads concatenated frames and reports truncated streams as collection errors.
### Resuming an interrupted Deep Scan
### Resuming an interrupted scan
```bash
codex-security scans list --scan-root /path/to/security-scans
@@ -2240,7 +2286,7 @@ codex-security scans resume SCAN_ID
```
The terminal list shows the full scan ID and labels the last activity of a
`running` scan after 24 hours without an update. For a Deep Scan with a saved
`running` scan after 24 hours without an update. For a Standard or Deep Scan with a saved
launch recipe and its original session, it also shows the resume command to use after interruption.
The scan must still be `running`, with its original checkout, output directory,
@@ -2252,15 +2298,22 @@ output. It lets the workbench verify the original output even before the first
checkpoint. If an older scan stopped with an empty output, start a new scan with
`codex-security scans rerun SCAN_ID`.
New Windows Deep Scans also record the checkout's native volume and file ID
New Windows Standard and Deep Scans also record the checkout's native volume and file ID
when the filesystem supplies them. Validation and remediation verify the same
checkout identity. An older scan can resume across Python
versions when its saved checkout identity can be verified. If the workbench
cannot verify it, resume with the Python runtime that started the scan or use
`codex-security scans rerun SCAN_ID` to start a new scan.
Resume retains scan ID, completed workers, artifacts, accumulated cost, and saved
settings/instructions. Knowledge-bearing scans save their extracted documents in
Resume keeps the scan ID, saved settings and instructions, completed workers, artifacts,
and accumulated cost. A Standard scan continues in its original Codex session with
the same `--max-cost` limit and `--max-time` deadline. Only one CLI or SDK call
can run it at a time. If the connection fails after the session is saved, the CLI
prints the resume command. Work since the last checkpoint may need to be repeated.
Use `scans rerun` for canceled or failed scans, including authentication failures.
For custom validation, rerun with the original validation instructions.
Knowledge-bearing scans save their extracted documents in
the private `.scan-knowledge.json` continuation file beside the scan artifacts.
Resume verifies and uses that snapshot even if the original files changed or were
deleted. Preserve it with the scan directory; canonical reports do not embed its
+14 -3
View File
@@ -308,6 +308,10 @@ console.log(plan);
`preflight()` checks local inputs without starting Codex or using the network. The returned `stateDirectory` identifies the checked storage root, including when the final scan directory will be allocated automatically.
It does not verify credentials, model access, Python, or the plugin. The CLI
equivalent is `scan --dry-run`.
Neither preflight starts a Deep Scan worker or executes a command under its
generated permissions, so neither qualifies the worker sandbox. See [Deep Scan
sandbox qualification](../../../docs/project-configuration.md#deep-scan-sandbox-qualification)
for the boundary and the limits of what these checks establish.
### Set investigation time
@@ -767,11 +771,18 @@ Omit `issueKeys` to collect the project's open security issues. An empty list is
If you know the source repository, pass its Git URL in `options.sourceRepositoryUrl`
to check the Sonar binding before fetching issues.
For AWS Continuum code findings, use `readContinuumFindings(path, sourceRepositoryUrl)`
with a saved list or detail response, or `normalizeContinuumFindings(input, sourceRepositoryUrl)`
with parsed JSON. Verify the repository for the selected findings before passing its Git URL.
For AWS Continuum, use `readContinuumFindings(path, sourceRepositoryUrl)` with a
saved issue export or finding response. Use
`normalizeContinuumFindings(input, sourceRepositoryUrl)` with parsed JSON.
Issue exports with a saved repository URL can omit the second argument.
For other reports, pass the verified source repository URL.
[Continuum import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/continuum.md)
Pass `"local"` as the third argument to retain full patch contents in collector
captures. The Cloud projection records `contentOmitted: "cloud_evidence_limit"`
when the patch contents exceed the evidence budget. Available patches are in
`evidence.source_data.patches`.
For a saved Checkmarx One CLI JSON or CxSAST XML report, use
`readCheckmarxFindings(path, sourceRepositoryUrl, "local")` to inspect its evidence.
To prepare a local import, pass `provider: "checkmarx"` and the verified
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@openai/codex-security",
"version": "0.9.1",
"version": "0.10.0",
"description": "TypeScript SDK and CLI for Codex Security",
"license": "Apache-2.0",
"author": "OpenAI",
@@ -55,6 +55,7 @@
"publishConfig": {
"access": "public",
"executableFiles": [
"_bundled_plugin/scripts/dispatch_inventory_tool",
"_bundled_plugin/scripts/launch_codex_security_mcp"
]
},
@@ -390,7 +390,8 @@
"sonar",
"continuum",
"checkmarx",
"trivy"
"trivy",
"armorcode"
],
"title": "Provider",
"type": "string"
+1
View File
@@ -198,6 +198,7 @@ const posixMcpLauncher =
"package/_bundled_plugin/scripts/launch_codex_security_mcp";
for (const [path, name] of [
["package/bin/codex-security.mjs", "CLI"],
["package/_bundled_plugin/scripts/dispatch_inventory_tool", "inventory tool"],
[posixMcpLauncher, "MCP"],
]) {
const permissions =
@@ -12,17 +12,16 @@ const script = fileURLToPath(
export function installFixtureSpawn(executable) {
const spawn = childProcess.spawn;
childProcess.spawn = (command, args, options) =>
spawn(
childProcess.spawn = (command, args, options) => {
const selected = options?.env?.PACKAGE_DEEP_EXECUTABLE ?? executable;
return spawn(
command,
win32.toNamespacedPath(command) ===
win32.toNamespacedPath(
options?.env?.PACKAGE_DEEP_EXECUTABLE ?? executable,
)
win32.toNamespacedPath(command) === win32.toNamespacedPath(selected)
? [script, ...args]
: args,
options,
);
};
syncBuiltinESMExports();
return () => {
childProcess.spawn = spawn;
@@ -10,6 +10,7 @@ const distModules = [
"artifact-export",
"auth",
"bulk-scan-discovery",
"bundled-plugin",
"cli",
"cli-argument",
"cli-daybreak",
@@ -35,8 +36,11 @@ const distModules = [
"external-findings-import",
"external-findings-read",
"scanner-import",
"armorcode-findings",
"inspector-findings",
"continuum-findings",
"continuum-collector",
"continuum-aws",
"checkmarx-evidence",
"checkmarx-findings",
"checkmarx-one",
@@ -71,6 +75,7 @@ const distModules = [
"wiz-csv",
"veracode-findings",
"tenable-findings",
"crowdstrike-findings",
"wiz-findings",
"codex-prompt",
"codex-sdk-environment",
+153 -41
View File
@@ -193,6 +193,7 @@ import {
} from "./custom-validation-prompt.js";
import {
AuthenticationRequiredError,
CodexConnectionError,
CodexSecurityError,
ConfigurationError,
InvalidTargetError,
@@ -270,10 +271,14 @@ import {
} from "./version.js";
import { SCAN_MODES } from "./scan-modes.js";
import { readSavedScanLifecycle } from "./saved-scan-bootstrap.js";
import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
import {
bundledCodexSdkEnvironment,
definedEnvironment,
} from "./codex-sdk-environment.js";
import {
canonicalConfigPath,
acquireCodexSecurityCredentialHomeLock,
acquireScanExecutionLock,
withCredentialHomeLock,
writeCredentialHomeConfig,
bootstrapPlugin,
@@ -295,6 +300,8 @@ import {
prepareCodexSecurityCredentialHome,
preserveCodexSecurityPluginRegistration,
pluginExecutionEnvironment,
SDK_NODE_SEARCH_PATH,
sdkNodeSearchPath,
environmentWithGit,
pluginMetadata,
planOutputArchive,
@@ -340,6 +347,7 @@ import {
} from "./targets.js";
import { startHeadDriftMonitor } from "./target-drift.js";
import {
campaignExecutable,
inspectTrustedExecutable,
isWithin,
type InspectedExecutable,
@@ -377,6 +385,7 @@ interface PreparedRuntime {
}
interface PreparedSession {
toolRoots: readonly string[];
pricingContext?: ScanPricingContext;
safetyIdentifier?: string;
runtime: PreparedRuntime;
@@ -2721,6 +2730,7 @@ export class CodexSecurity {
let latestMeasurement: Readonly<ScanUsageMeasurement> | null = null;
let notifiedLimit: number | undefined;
let scanDir = "";
let releaseStandardScan: (() => void) | undefined;
let targetPathsFile: string | null = null;
let stagedPluginRoot: string | undefined;
let stagedPluginDirectory: string | undefined;
@@ -2899,10 +2909,11 @@ export class CodexSecurity {
),
};
const hosted = this.#dependencies.hostedScan !== undefined;
for (const root of [
session.toolRoots = [
(await gitMarkerRoot(repo, signal, "outermost")) ?? repo,
...(knowledgeBase?.protectedRoots ?? []),
]) {
];
for (const root of session.toolRoots) {
git = await inspectTrustedExecutable("git", git.environment, root);
if (this.#dependencies.hostedScan !== undefined) {
// Match the hosted MCP launchers' PATH-based tool lookups.
@@ -2947,6 +2958,16 @@ export class CodexSecurity {
);
requireOutputOutsideRepository(protectedRoot, scanDir);
requireModelSafeOutputDir(scanDir);
if (
!hosted &&
mode === "standard" &&
(normalized.kind === "repository" || normalized.kind === "paths")
) {
releaseStandardScan = await acquireScanExecutionLock(
stateDirectory,
scanDir,
);
}
if (!options.archiveExisting && options.resumeScanId === undefined) {
notifyObserver(options, "onOutputDirReady")(scanDir);
}
@@ -3436,6 +3457,7 @@ export class CodexSecurity {
// The registered recipe now owns the private snapshot, including after completion.
savedProviderProfile = undefined;
const registeredScanId = registration["scanId"];
let timeBudgetStartedAt: string | undefined;
const resumeThreadId =
options.resumeScanId === undefined
? undefined
@@ -3455,6 +3477,10 @@ export class CodexSecurity {
"The workbench returned mismatched scan resume context.",
);
}
const originalStart =
savedRecipe["timeBudgetStartedAt"] ?? registration["startedAt"];
if (typeof originalStart === "string")
timeBudgetStartedAt = originalStart;
const savedSession = await findScanSession(
runtime.codexHome,
resumeThreadId,
@@ -3945,7 +3971,9 @@ export class CodexSecurity {
}
if (options.resumeScanId !== undefined) {
prompt +=
"\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan.";
mode === "deep"
? "\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan."
: "\nContinue this Standard scan from the saved scan-manifest.json, findings.json, and review checkpoints in its output directory. Keep existing evidence, validation decisions, finding IDs, and surface IDs. Finish outstanding work and finalize the same scan.";
}
if (
falsePositiveExamples.length > 0 &&
@@ -4122,13 +4150,14 @@ export class CodexSecurity {
runtime.plugin.pluginRoot,
);
checkOpen();
prompt += `\n\n${renderScanTimeBudgetPolicy(
timePolicy,
scanTimeBudget(
options.maxTimeMinutes,
(this.#dependencies.now ?? Date.now)(),
),
)}`;
const timing = scanTimeBudget(
options.maxTimeMinutes,
timeBudgetStartedAt === undefined
? (this.#dependencies.now ?? Date.now)()
: Date.parse(timeBudgetStartedAt),
);
timeBudgetStartedAt = timing.startedAt;
prompt += `\n\n${renderScanTimeBudgetPolicy(timePolicy, timing)}`;
}
tracker.beginParentTurn(resumeThreadId !== undefined);
const events = directDeepScan
@@ -4196,7 +4225,13 @@ export class CodexSecurity {
try {
await workbench(
workbenchOptions,
workbenchArgs("set-scan-thread", { scanId, threadId }),
workbenchArgs("set-scan-thread", {
scanId,
threadId,
...(registration["canSaveTimeBudgetStart"] === true && {
timeBudgetStartedAt,
}),
}),
);
} catch (error) {
notifyObserver(
@@ -4741,9 +4776,38 @@ export class CodexSecurity {
);
}
}
// A failed attachment must not turn a resumable coordinator into a terminal failure.
// Deep Scan orchestration persists its own terminal failures and cancellations.
if (activeScan !== null && options.resumeScanId === undefined) {
if (
activeScan !== null &&
releaseStandardScan !== undefined &&
!signal.aborted &&
options.validationPrompt === undefined &&
scanTurnStatus !== null &&
terminalTurnStatus !== "completed" &&
failure instanceof CodexConnectionError
) {
const saved = await workbench(
{ ...activeScan.options, signal: undefined },
workbenchArgs("get-cli-scan-resume", {
scanId: activeScan.id,
allowUnavailable: true,
}),
).catch(() => null);
if (saved?.["scanId"] === activeScan.id) {
failure = new ScanInterruptedError(
`${errorMessage(failure)}\nResume when connected: codex-security scans resume ${activeScan.id}`,
scanDir,
{ cause: failure },
);
activeScan = null;
runPostScan = null;
}
}
// A resumed Deep Scan persists its own terminal status.
if (
activeScan !== null &&
(options.resumeScanId === undefined ||
releaseStandardScan !== undefined)
) {
if (
options.validationPrompt !== undefined &&
customValidation.status !== "complete"
@@ -4825,6 +4889,7 @@ export class CodexSecurity {
warnCleanupFailed(options, error);
}
observeSettledScan(options, activeScan);
releaseStandardScan?.();
}
}
@@ -5229,15 +5294,20 @@ export class CodexSecurity {
pluginVersion: session.runtime.plugin.version,
providerFamily: requestContext.metadata["codex_security_provider"],
});
const pluginPaths = {
...runtimePaths,
[SDK_NODE_SEARCH_PATH]:
process.platform === "win32"
? undefined
: await sdkNodeSearchPath(session.toolRoots),
};
const hosted = this.#dependencies.hostedScan;
if (hosted !== undefined) {
const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
const environment = {
...definedEnvironment(
environmentWithGit(session.runtime.environment, git),
),
...runtimePaths,
};
const environment = definedEnvironment({
...environmentWithGit(session.runtime.environment, git),
...pluginPaths,
});
const model = scanModelConfiguration(session.effectiveConfig);
return {
environment,
@@ -5369,7 +5439,7 @@ export class CodexSecurity {
),
...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
CODEX_HOME: runtime.codexHome,
...runtimePaths,
...pluginPaths,
};
for (const name of Object.keys(environment)) {
if (name.toUpperCase() === SAFETY_IDENTIFIER_ENV)
@@ -5434,6 +5504,22 @@ export class CodexSecurity {
sdkEnvironment,
);
}
const executable = codexPathOverride ?? environment["CODEX_CLI_PATH"]!;
const campaign = campaignExecutable(executable, () =>
codexPathOverride === undefined
? bundledCodexSdkEnvironment(executable, sdkEnvironment)
: sdkEnvironment,
);
if (campaign) {
const selected = await campaign;
// Pin the SDK launch so it cannot prepend its unfiltered bundled tools again.
codexPathOverride = selected.executable;
environment["CODEX_CLI_PATH"] = selected.executable;
sdkEnvironment = definedEnvironment({
...selected.environment,
CODEX_CLI_PATH: selected.executable,
});
}
const codexOptions: CodexOptions & { nativeProfile?: string } = {
...(codexPathOverride === undefined
? {}
@@ -5535,6 +5621,7 @@ export class CodexSecurity {
signal,
});
return {
toolRoots: protectedRoots,
runtime,
runtimeHome,
effectiveConfig,
@@ -5750,6 +5837,7 @@ export class CodexSecurity {
return {
runtime,
safetyIdentifier: options.safetyIdentifier,
toolRoots: protectedRoots,
runtimeHome,
effectiveConfig,
preflightConfig,
@@ -6152,7 +6240,7 @@ export class CodexSecurity {
): Promise<LocalScanInputs> {
if (
options.resumeScanId !== undefined &&
(options.mode !== "deep" ||
((options.mode !== "deep" && options.mode !== "standard") ||
!options.outputDir ||
options.archiveExisting ||
options.parentScanId !== undefined ||
@@ -6160,7 +6248,7 @@ export class CodexSecurity {
options.mock)
) {
throw new CodexSecurityError(
"Resume requires the original Deep Scan output directory without archive, rerun, or workflow options.",
"Resume requires the original Standard or Deep Scan output directory without archive, rerun, or workflow options.",
);
}
if (
@@ -6600,6 +6688,10 @@ export async function runScanEvents(
);
}
if (status !== "completed") {
if (lastStreamError !== null) {
const error = codexTurnError(lastStreamError);
if (error instanceof CodexConnectionError) throw error;
}
throw new IncompleteScanError(
lastStreamError ??
"Codex Security event stream ended before the turn completed.",
@@ -6707,6 +6799,13 @@ export async function runScanEvents(
}
}
function codexTurnError(error: unknown): CodexSecurityError {
const classification = classifyConnectionFailure(error);
return classification === "network_error" || classification === "timeout"
? new CodexConnectionError(errorMessage(error), { cause: error })
: new CodexSecurityError(errorMessage(error), { cause: error });
}
async function readCodexTurn(options: {
thread: Pick<CodexThreadLike, "id">;
events: AsyncGenerator<ScanEvent>;
@@ -6724,12 +6823,22 @@ async function readCodexTurn(options: {
join(await bundledPluginRoot(), "scripts", "codex_session.mjs"),
).href
);
async function* transportEvents() {
try {
yield* options.events;
} catch (error) {
const failure = codexTurnError(error);
if (failure instanceof CodexConnectionError) throw failure;
throw error;
}
}
return readCodexSessionTurn({
...options,
events: transportEvents(),
onEvent: async (event: ScanEvent) => {
await options.onEvent?.(event);
if (event.type === "turn.failed") {
throw new CodexSecurityError(turnFailureMessage(event["error"]));
throw codexTurnError(turnFailureMessage(event["error"]));
}
if (event.type === "error" && typeof event["message"] === "string") {
const message = event["message"];
@@ -6742,8 +6851,7 @@ async function readCodexTurn(options: {
}
const reconnect = reconnectAttempt(message);
if (reconnect !== null) options.onReconnect?.(message, reconnect);
else if (!waitingForNetwork(message))
throw new CodexSecurityError(message);
else if (!waitingForNetwork(message)) throw codexTurnError(message);
}
},
});
@@ -7608,6 +7716,14 @@ function turnFailureMessage(error: unknown): string {
return "The Codex Security scan turn failed without a readable error message.";
}
/** @internal Exclude endpoint URLs and TOML parser locations when choosing recovery advice. */
export function connectionAdviceDetail(error: unknown): string {
const message = (
error instanceof Error ? error.message : String(error)
).replace(/\bhttps?:\/\/[^\s"'`<>]+/giu, "");
return /\.toml:\d+:\d+:/iu.test(message) ? "" : message;
}
export function classifyConnectionFailure(
error: unknown,
):
@@ -7617,7 +7733,7 @@ export function classifyConnectionFailure(
| "network_error"
| "timeout"
| "unknown" {
const message = error instanceof Error ? error.message : String(error);
const message = connectionAdviceDetail(error);
if (/\b(?:sqlite3?|database|workbench)\b/iu.test(message)) {
return "unknown";
}
@@ -7642,14 +7758,14 @@ export function classifyConnectionFailure(
return "rate_limited";
}
if (
/\b401\b|\bunauthori[sz]ed\b|\binvalid[_ -](?:api[_ -]?key|authentication|token|credentials?)\b|\b(?:expired|revoked)[_ -](?:api[_ -]?key|token|credentials?)\b|\b(?:api[_ -]?key|token|credentials?)(?: has)? (?:expired|been revoked)\b/iu.test(
/\b401\b|\bunauthori[sz]ed\b|(?<![\w./\\-])(?:invalid[._ -](?:api[._ -]?key|authentication|token|credentials?)|(?:expired|revoked)[._ -](?:api[._ -]?key|token|credentials?)|(?:api[._ -]?key|token|credentials?)(?:[._ -]has)?[._ -](?:expired|been[._ -]revoked))(?!\.?[\w/\\-])/iu.test(
message,
)
) {
return "unauthorized";
}
if (
/\b403\b|\bforbidden\b|\bpermission denied\b|\b(?:model|organization|project) access\b|\b(?:access denied|do not have access|not authorized|insufficient permissions)\b|\bmodel[_ -]?not[_ -]?found\b/iu.test(
/\b403\b|\bforbidden\b|\bpermission denied\b|\b(?:model|organization|project) access\b|\b(?:access denied|do not have access|not authorized|insufficient permissions)\b|(?<![\w./\\-])model(?:[._ -]?not[._ -]?found|[._ -]access)(?!\.?[\w/\\-])/iu.test(
message,
)
) {
@@ -7662,7 +7778,12 @@ export function classifyConnectionFailure(
) {
return "network_error";
}
if (/\b(?:timed? out|timeout)\b/iu.test(message)) return "timeout";
if (
/(?<![\w./\\-])(?:request[.-])?(?:timed?[._ -]out|timeout)(?!\.?[\w/\\-])/iu.test(
message,
)
)
return "timeout";
return "unknown";
}
@@ -8351,16 +8472,7 @@ function standaloneFindingForPrompt(finding: string | object): string {
return jsonForPrompt(finding);
}
/** @internal */
export function definedEnvironment(
environment: ProcessEnvironment,
): Record<string, string> {
return Object.fromEntries(
Object.entries(environment).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
}
export { definedEnvironment };
function withoutCodexHome(
environment: ProcessEnvironment,
+192
View File
@@ -0,0 +1,192 @@
import type { ExternalImportTarget } from "./external-import-contract.js";
import { validateExternalEvidence } from "./external-import-contract.js";
import type { ExternalFindings } from "./external-findings.js";
import type { ExternalFindingEvidence } from "./external-import-models.js";
import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";
import { isRecord } from "./record.js";
import {
normalizeRecords,
record,
requiredText,
text,
} from "./scanner-import.js";
type ArmorCodeFinding = Record<string, unknown>;
function armorCodeId(value: unknown): string {
if (typeof value === "string")
return requiredText(value, "ArmorCode finding ID");
if (typeof value === "number" && Number.isSafeInteger(value))
return String(value);
throw new Error("ArmorCode finding ID must be text or a safe integer.");
}
function stringValues(value: unknown): string[] {
const values = Array.isArray(value) ? value : value == null ? [] : [value];
return values.flatMap((item) => {
if (typeof item === "string" && item.trim()) return [item];
if (typeof item === "number" && Number.isSafeInteger(item))
return [String(item)];
return [];
});
}
/** Recover the source repository independently of the finding's scan type. */
export function armorCodeRepositoryUrl(
finding: ArmorCodeFinding | null | undefined,
target: ExternalImportTarget,
): string | undefined {
const repository = finding?.["repository"];
const url =
text(finding?.["sourceRepositoryUrl"]) ??
text(finding?.["repositoryUrl"]) ??
text(isRecord(repository) ? repository["url"] : repository);
return url
? declaredScannerRepositoryUrl(url, "ArmorCode", target)
: undefined;
}
/** Normalize stable finding records while retaining the original ArmorCode row. */
export function normalizeArmorCodeFindings(
input: unknown,
target: ExternalImportTarget = "cloud",
sourceRepositoryUrl?: string,
): ExternalFindings {
const document = Array.isArray(input)
? { findings: input }
: record(input, "ArmorCode report");
const raw =
document["findings"] ??
document["issues"] ??
(isRecord(document["data"]) ? document["data"]["findings"] : undefined);
if (!Array.isArray(raw))
throw new Error("ArmorCode report must contain a findings array.");
const report = { ...document };
delete report["findings"];
delete report["issues"];
if (isRecord(report["data"])) {
const data = { ...report["data"] };
delete data["findings"];
if (Object.keys(data).length) report["data"] = data;
else delete report["data"];
}
const declaredUrl =
sourceRepositoryUrl === undefined
? undefined
: declaredScannerRepositoryUrl(sourceRepositoryUrl, "ArmorCode", target);
return normalizeRecords(
raw as ArmorCodeFinding[],
(finding) => {
const severity = (text(finding["severity"]) ?? "unknown").toLowerCase();
const locations = Array.isArray(finding["locations"])
? finding["locations"]
: finding["location"]
? [finding["location"]]
: text(finding["filePath"])
? [{ path: finding["filePath"], line: finding["lineNumber"] }]
: [];
const description = text(
finding["description"] ??
finding["details"] ??
finding["toolDescription"],
);
const mitigation = text(finding["mitigation"]);
const lastUpdated = finding["lastUpdated"];
const isSast =
Array.isArray(finding["scanType"]) &&
finding["scanType"].some(
(value) =>
typeof value === "string" && value.toLowerCase() === "sast",
);
const ruleIds = stringValues(finding["ruleId"]);
const weaknessIds = [
...stringValues(finding["cwe"]),
...stringValues(finding["cwesStrings"]),
];
const repositoryUrl =
armorCodeRepositoryUrl(finding, target) ?? declaredUrl;
if (isSast && !repositoryUrl)
throw new Error(
"ArmorCode SAST evidence requires its source repository. For a single-repository report, supply its verified --source-repository-url.",
);
const evidence: ExternalFindingEvidence = {
title: requiredText(
finding["title"] ?? finding["name"] ?? finding["findingName"],
"ArmorCode finding title",
),
severity: ([
"critical",
"high",
"medium",
"low",
"informational",
].includes(severity)
? severity
: "unknown") as ExternalFindingEvidence["severity"],
description: isSast
? description
: description && mitigation
? `${description}\n\nMitigation: ${mitigation}`
: (description ?? mitigation),
// ArmorCode's findingUrl remains available in source_data; url points
// to the originating scanner when ArmorCode provides both links.
url: text(finding["url"] ?? finding["findingUrl"]),
...(Array.isArray(finding["cve"]) && {
advisory_ids: finding["cve"].filter(
(value): value is string => typeof value === "string",
),
}),
locations: locations.flatMap((value) => {
if (!isRecord(value)) return [];
const path = text(
value["path"] ?? value["filePath"] ?? value["file"],
);
if (!path) return [];
const line =
value["line"] ?? value["startLine"] ?? value["lineNumber"];
return [
{
path,
line:
Number.isSafeInteger(line) && Number(line) > 0
? Number(line)
: null,
},
];
}),
...(typeof lastUpdated === "number" &&
Number.isSafeInteger(lastUpdated) && {
source_updated_at: Math.floor(lastUpdated / 1000),
}),
...(isSast && {
details: {
kind: "sast",
...(repositoryUrl && { repository: { url: repositoryUrl } }),
source_status: text(
finding["status"] ?? finding["toolFindingStatus"],
),
scanner_origin: text(finding["source"]),
scanner_verdict: text(finding["toolStatusOriginal"]),
...(ruleIds.length > 0 && { rule: { id: ruleIds.join(", ") } }),
...(weaknessIds.length > 0 && {
weakness_ids: [...new Set(weaknessIds)],
}),
...(mitigation && { remediation_instructions: mitigation }),
},
}),
source_data: structuredClone(finding),
};
validateExternalEvidence(evidence, target);
return evidence;
},
(finding) =>
armorCodeId(
finding["source_finding_id"] ??
finding["findingId"] ??
finding["id"] ??
finding["finding_id"],
),
target,
{ report },
);
}
+2 -1
View File
@@ -10,6 +10,7 @@ import type { JsonObject } from "./config.js";
import { resolveConfigPath } from "./config-path.js";
import { CodexSecurityError } from "./errors.js";
import { relativePathIsOutside as isOutsidePath } from "./targets.js";
import { campaignCommandEnvironment } from "./trusted-executable.js";
import {
type PluginPythonOptions,
bundledPluginRoot,
@@ -162,7 +163,7 @@ export async function runArtifactHelper(
...args,
],
{
env: environment,
env: (await campaignCommandEnvironment(environment)) ?? environment,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
signal: options.signal,
+30
View File
@@ -0,0 +1,30 @@
import { lstat, realpath } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { PluginBootstrapError } from "./errors.js";
export function bundledPluginCandidates(moduleDirectory: string): string[] {
return [
resolve(moduleDirectory, "_bundled_plugin"),
resolve(moduleDirectory, "../_bundled_plugin"),
];
}
export async function hasPluginManifest(root: string): Promise<boolean> {
return await lstat(join(root, ".codex-plugin", "plugin.json")).then(
(metadata) => metadata.isFile(),
() => false,
);
}
export async function bundledPluginRoot(): Promise<string> {
const moduleDirectory = dirname(fileURLToPath(import.meta.url));
for (const candidate of bundledPluginCandidates(moduleDirectory)) {
if (await hasPluginManifest(candidate)) {
return await realpath(candidate);
}
}
throw new PluginBootstrapError(
"The bundled Codex Security plugin is missing.",
);
}
+10
View File
@@ -315,6 +315,16 @@ export function formatCliHelp(text: string, columns = 80): string | undefined {
label: "Live provider",
description: "Choose a collector below.",
},
{
label: "CLI, API, or MCP source",
description:
"Ask Codex to import it using the publish-findings skill.",
},
{
label: "Workbench findings",
description:
"Ask Codex to publish a stored import or selected finding versions.",
},
{
label: "Saved vendor report",
description:
+132 -25
View File
@@ -94,6 +94,7 @@ export { exportEnvironment } from "./artifact-export.js";
import { parse as parseToml } from "smol-toml";
import {
classifyConnectionFailure,
connectionAdviceDetail,
CodexSecurity,
DEFAULT_DEPENDENCIES as DEFAULT_CLIENT_DEPENDENCIES,
environmentValue,
@@ -140,6 +141,13 @@ import {
type ExternalPublicationResult,
} from "./external-findings-publish.js";
import { prepareLocalExternalImport } from "./external-findings-import.js";
import {
collectContinuumFinding,
collectContinuumIssues,
continuumEnvironmentId,
continuumFindingId,
continuumImportOutput,
} from "./continuum-collector.js";
import { validateInspectorProjectMapping } from "./inspector-findings.js";
import {
readLocalExternalFindings,
@@ -1531,6 +1539,8 @@ interface CliDependencies {
publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select"> &
Partial<Pick<BulkScanPrompt, "checkbox">>;
externalPublicationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "confirm">;
collectContinuumIssues?: typeof collectContinuumIssues;
collectContinuumFinding?: typeof collectContinuumFinding;
collectSonarIssues?: typeof collectSonarIssues;
prepareLocalExternalImport?: typeof prepareLocalExternalImport;
readLocalExternalFindings?: typeof readLocalExternalFindings;
@@ -3153,11 +3163,12 @@ export async function main(
},
})
.command("resume", {
description: "Resume an interrupted Deep Scan in its original session.",
description:
"Resume an interrupted Standard or Deep Scan in its original session.",
examples: [{ args: { scanId: "SCAN_ID" } }],
hint: "Execution failures keep available scan results under data in failed full-output JSON, JSONL, YAML, or TOON envelopes.",
args: z.object({
scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),
scanId: z.string().min(1).describe("Interrupted scan identifier."),
}),
options: z.object({
showCost: SHOW_COST_OPTION,
@@ -4160,7 +4171,7 @@ export async function main(
},
},
],
hint: "Choose your scanner with --provider. Reuse --source-key for later imports from the same source. See the scanner import guide for supported formats, repository setup, and export examples: https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md. Gzip files are supported. Use --to local to save unassessed findings without a Cloud login. Use --full-output with --format json or --format jsonl.",
hint: "Choose your scanner with --provider. Reuse --source-key for later imports from the same source. For findings already in the workbench, use the SDK's prepareStoredFindingsPublication. The installed @openai/codex-security package includes the workflow in docs/sdk.md under Import external findings. See the scanner import guide for supported formats, repository setup, and export examples: https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md. Gzip files are supported. Use --to local to save unassessed findings without a Cloud login. Use --full-output with --format json or --format jsonl.",
destructive: true,
args: z.object({
file: z
@@ -4179,7 +4190,7 @@ export async function main(
provider: z
.enum(EXTERNAL_FINDINGS_READERS)
.describe(
"Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url.",
"Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url. CrowdStrike requires --to local.",
),
sourceRepositoryUrl: optionValue("--source-repository-url")
.optional()
@@ -4229,6 +4240,10 @@ export async function main(
exitCode,
});
}
if (options.sourceRepositoryUrl !== undefined)
writeDiagnostic(
"codex-security: warning: Use --source-repository-url only after verifying that every finding belongs to the repository you specify.\n",
);
const controller = new AbortController();
const removeSignals = listenForAbort(dependencies, controller);
const structured = formatExplicit && format !== "toon";
@@ -4554,7 +4569,8 @@ export async function main(
},
});
const imports = Cli.create("import", {
description: "Collect findings from GitHub, Semgrep, Snyk or Sonar.",
description:
"Collect findings from Continuum, GitHub, Semgrep, Snyk or Sonar.",
}).command("github", {
examples: [{ args: { repository: "owner/repo" } }],
description: "Read GitHub code scanning alerts without changing GitHub.",
@@ -4640,7 +4656,7 @@ export async function main(
},
});
async function collectHostedFindings<T>(
provider: "GitHub advisory" | "Semgrep" | "Snyk",
provider: "Continuum" | "GitHub advisory" | "Semgrep" | "Snyk",
fail: (error: { code: string; message: string; exitCode: number }) => never,
run: (signal: AbortSignal) => Promise<T>,
) {
@@ -4656,9 +4672,9 @@ export async function main(
? `${provider} import ${interrupted === 130 ? "canceled" : "terminated"}.`
: message;
const terminalDiagnostic =
provider === "Semgrep" || provider === "Snyk"
? escapeTerminalText(diagnostic)
: diagnostic;
provider === "GitHub advisory"
? diagnostic
: escapeTerminalText(diagnostic);
errorOutput.write(`codex-security: ${terminalDiagnostic}\n`);
if (argv.includes("--full-output")) {
structuredError = true;
@@ -4686,6 +4702,100 @@ export async function main(
format === "md" || (format === "toon" && output.isTTY === true);
}
imports
.command("continuum", {
examples: [
{ args: { environmentId: "abc123" } },
{
args: { environmentId: "abc123" },
options: {
findingId: "def456",
sourceRoot: "/absolute/path/to/checkout",
repositoryName: "example/project",
},
},
],
description:
"Read all AWS Continuum issues or collect one finding with its repository's patches.",
hint: "Requires AWS CLI v2.38.5 or later installed outside the checkout. Bulk collection requires exactly one Git repository and allows S3 sources. For one finding, pass --finding-id and --source-root. The CLI checks for one Git repository and no S3 sources when --repository-name is omitted. Save --format json output for publish findings --provider continuum.",
destructive: false,
args: z.object({ environmentId: continuumEnvironmentId }),
options: z
.object({
awsProfile: optionValue("--aws-profile")
.optional()
.describe(
"AWS CLI profile (default: use the AWS CLI's configured credentials).",
),
awsRegion: optionValue("--aws-region")
.optional()
.describe(
"AWS Region (default: use the AWS CLI's configured Region).",
),
findingId: continuumFindingId.optional(),
sourceRoot: optionValue("--source-root")
.refine(isAbsolute, {
message: "--source-root must be an absolute path.",
})
.optional()
.describe(
"Absolute path of the selected checkout for --finding-id.",
),
repositoryName: optionValue("--repository-name")
.optional()
.describe(
"Exact AWS source name for the selected finding's repository. Required unless the environment has one Git repository and no S3 sources.",
),
})
.refine(
(options) =>
options.findingId !== undefined ||
(options.sourceRoot === undefined &&
options.repositoryName === undefined),
{
message:
"--source-root and --repository-name require --finding-id.",
},
)
.refine(
(options) =>
options.findingId === undefined || options.sourceRoot !== undefined,
{ message: "--finding-id requires --source-root." },
),
output: continuumImportOutput.optional(),
run: ({ args, options, error, format }) => {
setTerminalOutputFormat(format);
return collectHostedFindings<Record<string, unknown>>(
"Continuum",
error,
(signal) => {
const selection = {
environmentId: args.environmentId,
profile: options.awsProfile,
region: options.awsRegion,
cwd: dependencies.currentDirectory(),
environment: dependencies.environment,
signal,
};
if (options.findingId === undefined)
return (
dependencies.collectContinuumIssues ?? collectContinuumIssues
)(selection);
return (
dependencies.collectContinuumFinding ?? collectContinuumFinding
)({
...selection,
findingId: options.findingId,
sourceRoot: options.sourceRoot!,
repositoryName: options.repositoryName,
warn: (message) =>
errorOutput.write(
`codex-security: ${escapeTerminalText(message)}\n`,
),
});
},
);
},
})
.command("github-advisories", {
examples: [{ args: { repository: "owner/repo" } }],
description: "Read GitHub security advisories without changing GitHub.",
@@ -9046,10 +9156,10 @@ async function runDependencyScan(
`Coverage: ${result.coverage.status}\n` +
`Artifacts: ${result.outputDir}`,
);
for (const diagnostic of [
for (const diagnostic of new Set([
...result.coverage.limitations,
...result.diagnostics,
]) {
])) {
writeDiagnostic(`codex-security: ${diagnostic}`);
}
if (verbose) {
@@ -11571,19 +11681,19 @@ export function skillCommandFailure(
detail: string,
authentication: ScanAuthentication | null = null,
): string {
// Paths may contain provider error codes as filenames. Keep the original for display.
// Exclude paths and parser locations from advice, but keep the original diagnostic for display.
const containsParserError =
/\b(?:syntax\s*error|pars(?:e|er|ing)|unexpected token|at (?:line|column) \d+)\b/iu.test(
detail,
);
// Keep a neutral token so a quoted provider/model remains a named model in the message.
const withoutPaths = detail
.replace(/\bhttps?:\/\/[^\s"'`<>]+/giu, "")
.replace(/[^\s"'`()<>,]+/gu, (token) =>
const withoutPaths = connectionAdviceDetail(detail).replace(
/[^\s"'`()<>,]+/gu,
(token) =>
/[/\\]/u.test(token) && !/^HTTP\/\d+(?:\.\d+)?$/iu.test(token)
? "[path]"
: token,
);
);
const diagnosticDetail = containsParserError
? withoutPaths.replace(/\binvalid[ _-]token\b/giu, "")
: withoutPaths;
@@ -11595,9 +11705,7 @@ export function skillCommandFailure(
let advice: string | undefined;
if (
classification === "unauthorized" ||
/\b(?:authorizationrequired|invalid[._ -]api[._ -]key|token[._ -]expired)\b/iu.test(
classificationDetail,
)
/\bauthorizationrequired\b/iu.test(classificationDetail)
) {
advice = authenticationFailureMessage(authentication);
} else if (
@@ -11605,14 +11713,14 @@ export function skillCommandFailure(
classificationDetail,
) ||
(!/\b(?:sqlite3?|database|workbench)\b/iu.test(classificationDetail) &&
/\bmodel[ \t]+(?:'[^'\r\n]+'|"[^"\r\n]+"|`[^`\r\n]+`)[ \t]+not[ \t]+found\b/iu.test(
/(?<![\w./\\-])model[ \t]+(?:'[^'\r\n]+'|"[^"\r\n]+"|`[^`\r\n]+`)[ \t]+not[ \t]+found(?!\.?[\w/\\-])/iu.test(
classificationDetail,
)) ||
/\b(?:model[._ -]not[._ -]found|model[._ -]?access[._ -]?denied|access[._ -]?(?:denied[._ -]?to[._ -]?model|to[._ -]?model[._ -]?denied))\b/iu.test(
/(?<![\w./\\-])(?:model[._ -]not[._ -]found|model[._ -]?access[._ -]?denied|access[._ -]?(?:denied[._ -]?to[._ -]?model|to[._ -]?model[._ -]?denied))(?!\.?[\w/\\-])/iu.test(
classificationDetail,
) ||
(classification === "forbidden" &&
/\b403\b|\bforbidden\b|\bmodel[ _-]?(?:not[ _-]?found|access)\b|\baccess.*model\b/iu.test(
/\b403\b|\bforbidden\b|\bmodel[ ._-]?(?:not[ ._-]?found|access)\b|\baccess.*model\b/iu.test(
classificationDetail,
))
) {
@@ -11635,7 +11743,7 @@ export function skillCommandFailure(
classification === "network_error" ||
classification === "timeout" ||
(!/\b(?:sqlite3?|database|workbench)\b/iu.test(classificationDetail) &&
/\b(?:ECONNABORTED|timed[._ -]out|network[._ -]?error|(?:(?:network|request)[._ -]?)?timeout(?:[._ -]?error)?)\b/iu.test(
/\b(?:ECONNABORTED|network[._ -]?error|(?:(?:network|request)[._ -]?)?timeout(?:[._ -]?error)?)\b/iu.test(
classificationDetail,
))
) {
@@ -13181,8 +13289,7 @@ function scanFailureMessage(
return error instanceof IncompleteScanError
? diagnosticValue(error)
: nativeRefreshRecovery;
const detail =
error instanceof IncompleteScanError ? `${diagnosticValue(error)}\n` : "";
const detail = `${diagnosticValue(error)}\n`;
const refreshFailure = message.match(
/\byour access token could not be refreshed(?: because your refresh token (has expired|was already used|was revoked))?\. Please log out and sign in again\./iu,
);
@@ -2,6 +2,36 @@ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import { delimiter, dirname, join } from "node:path";
import { PluginBootstrapError } from "./errors.js";
import { campaignExecutable } from "./trusted-executable.js";
export function definedEnvironment(
environment: Readonly<NodeJS.ProcessEnv>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(environment).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
}
/** Bind the native launch after the packaged SDK tools have been added to PATH. */
export async function nativeCodexLaunch(
command: string,
inherited?: Record<string, string>,
) {
const environment =
inherited && bundledCodexSdkEnvironment(command, inherited);
const campaign = campaignExecutable(command, environment ?? process.env);
if (!campaign) return { command, environment };
const selected = await campaign;
return {
command: selected.executable,
environment: definedEnvironment({
...selected.environment,
CODEX_CLI_PATH: selected.executable,
}),
};
}
export function bundledCodexSdkEnvironment(
command: string,
+260
View File
@@ -0,0 +1,260 @@
import { readdir, realpath, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
import { environmentEntry } from "./auth.js";
import { CodexSecurityError } from "./errors.js";
import { commandGitProtectionRoots } from "./local-git-metadata.js";
import {
isWithin,
resolveTrustedExecutable,
trustedHostPathResolver,
} from "./trusted-executable.js";
const windows = process.platform === "win32";
const accountDirectories = [
"APPDATA",
"HOME",
"LOCALAPPDATA",
"USERPROFILE",
"XDG_CONFIG_HOME",
];
const hostSettings = new Set([
...accountDirectories,
"ALL_PROXY",
"CURL_CA_BUNDLE",
"HOMEDRIVE",
"HOMEPATH",
"HTTPS_PROXY",
"HTTP_PROXY",
"LANG",
"LANGUAGE",
"LOGNAME",
"NO_PROXY",
"REQUESTS_CA_BUNDLE",
"SSH_AUTH_SOCK",
"SSL_CERT_DIR",
"SSL_CERT_FILE",
"SYSTEMROOT",
"TEMP",
"TMP",
"TMPDIR",
"TZ",
"USER",
"USERNAME",
"WINDIR",
]);
function expandVariables(path: string, environment: NodeJS.ProcessEnv): string {
// AWS uses Python's platform-specific expandvars for configuration paths.
const variables = windows
? /'[^']*'?|%(%|[^%]*%?)|\$(\$|[-\w]+|\{[^}]*\}?)/gu
: /\$(\w+|\{[^}]*\}?)/gu;
return path.replace(variables, (match) => {
if (match.startsWith("'")) return match;
const token = match.slice(1);
if (token === "%" || token === "$") return token;
let name = token;
if (match.startsWith("%")) {
if (!token.endsWith("%")) return match;
name = token.slice(0, -1);
} else if (token.startsWith("{")) {
if (!token.endsWith("}")) return match;
name = token.slice(1, -1);
}
return environmentEntry(environment, name) ?? match;
});
}
function expandedSetting(
name: string,
value: string,
home: string,
environment: NodeJS.ProcessEnv,
): string {
const path = expandVariables(value, environment);
if (
path === "~" ||
path.startsWith("~/") ||
(windows && path.startsWith("~\\"))
)
return home + path.slice(1);
if (path.startsWith("~"))
throw new CodexSecurityError(`Use a fully expanded file path for ${name}.`);
return path;
}
function pinSetting(
name: string,
path: string,
environment: NodeJS.ProcessEnv,
): string {
if (
expandVariables(path, environment) !== path ||
(name === "AWS_DATA_PATH" && path.includes(delimiter))
)
throw new CodexSecurityError(`Use a fully expanded file path for ${name}.`);
return path;
}
function missingPath(error: NodeJS.ErrnoException) {
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
}
async function checkModelPath(
path: string,
resolvePath: (path: string) => string | null,
roots: readonly string[],
signal: AbortSignal | undefined,
levels = 3,
): Promise<string> {
signal?.throwIfAborted();
const safe = resolvePath(path);
if (safe === null || roots.some((root) => isWithin(safe, root)))
throw new CodexSecurityError(
`Use an AWS model path separate from the selected checkout: ${path}`,
);
if (levels === 0) return safe;
const entries = await readdir(safe).catch(missingPath);
// AWS loads global models and service/version/*.json[.gz].
for (const entry of entries ?? []) {
const child = join(safe, entry);
if (
/\.json(?:\.gz)?$/iu.test(entry) ||
(levels > 1 && (await stat(child).catch(missingPath))?.isDirectory())
)
await checkModelPath(child, resolvePath, roots, signal, levels - 1);
}
return safe;
}
export async function prepareContinuumAws(
cwd: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
sourceRoot?: string,
) {
const caller = await realpath(cwd);
const source = sourceRoot ?? cwd;
if (
sourceRoot !== undefined &&
(!isAbsolute(sourceRoot) ||
!(await stat(sourceRoot).catch(missingPath))?.isDirectory())
)
throw new CodexSecurityError(
"Select an existing absolute directory with --source-root.",
);
const roots = [
...new Set([
resolve(source),
source === cwd ? caller : await realpath(source),
...(await commandGitProtectionRoots(source, environment, signal, {
cwd,
})),
]),
];
const resolvePath = await trustedHostPathResolver(caller, roots);
const name = windows ? "aws.exe" : "aws";
const directories: string[] = [];
for (let entry of (environmentEntry(environment, "PATH") ?? "").split(
delimiter,
)) {
if (windows && entry.startsWith('"') && entry.endsWith('"'))
entry = entry.slice(1, -1);
if (!isAbsolute(entry)) continue;
const path = resolvePath(entry);
if (path === null || path.includes(delimiter)) continue;
const candidate = resolvePath(join(path, name));
if (candidate !== null && (!windows || /\.exe$/iu.test(candidate)))
directories.push(path);
}
const aws = await resolveTrustedExecutable(
name,
{ PATH: directories.join(delimiter) },
roots,
);
const executable = aws ? resolvePath(aws.executable) : null;
if (!aws || executable === null)
throw new CodexSecurityError(
"Could not find an installed AWS CLI outside the selected checkout.",
);
// Credential helpers can use any interpreter. Only forward AWS and host settings.
const child: NodeJS.ProcessEnv = {};
for (const [name, value] of Object.entries(environment)) {
const key = windows ? name.toUpperCase() : name;
if (
value !== undefined &&
(key.startsWith("AWS_") ||
key.startsWith("LC_") ||
hostSettings.has(key.toUpperCase()))
)
child[key] = value;
}
child["PATH"] = aws.environment["PATH"];
function trustedSetting(path: string, label: string) {
const safe = resolvePath(path);
if (safe === null)
throw new CodexSecurityError(
`Use ${label} outside the selected checkout.`,
);
return safe;
}
for (const name of accountDirectories) {
const path = child[name];
if (path)
child[name] = trustedSetting(path, `an account ${name} directory`);
}
const configuredHome = windows
? (child["USERPROFILE"] ??
(child["HOMEPATH"]
? (child["HOMEDRIVE"] ?? "") + child["HOMEPATH"]
: undefined))
: child["HOME"];
const home = trustedSetting(
configuredHome ?? homedir(),
"an account home directory",
);
child[windows ? "USERPROFILE" : "HOME"] = home;
// AWS can run credential helpers from profiles and commands from aliases.
const awsDirectory = join(home, ".aws");
for (const [name, filename] of [
["AWS_CONFIG_FILE", "config"],
["AWS_SHARED_CREDENTIALS_FILE", "credentials"],
] as const) {
const value = child[name];
const path =
value === undefined
? join(awsDirectory, filename)
: expandedSetting(name, value, home, environment);
const safe = trustedSetting(path, `an ${name} file`);
if (value !== undefined) child[name] = pinSetting(name, safe, child);
}
trustedSetting(join(awsDirectory, "cli", "alias"), "an AWS CLI alias file");
await checkModelPath(
join(awsDirectory, "models"),
resolvePath,
roots,
signal,
);
if (child["AWS_DATA_PATH"] !== undefined) {
const paths: string[] = [];
for (const entry of child["AWS_DATA_PATH"].split(delimiter)) {
const path = expandedSetting("AWS_DATA_PATH", entry, home, environment);
if (!path) continue;
const safe = await checkModelPath(path, resolvePath, roots, signal);
paths.push(pinSetting("AWS_DATA_PATH", safe, child));
}
child["AWS_DATA_PATH"] = paths.join(delimiter);
}
// Windows may search the current directory for a bare credential helper name.
return {
executable,
cwd: dirname(executable),
environment: child,
};
}
+401
View File
@@ -0,0 +1,401 @@
import { execFile as execFileCallback } from "node:child_process";
import { promisify } from "node:util";
import { z } from "zod";
import { prepareContinuumAws } from "./continuum-aws.js";
import {
continuumIssueFormat,
findingIdentity,
issueIdentity,
readPatch,
} from "./continuum-findings.js";
import { CodexSecurityError } from "./errors.js";
import { array, record } from "./scanner-import.js";
import { declaredScannerRepositoryUrl } from "./scanner-repository-url.js";
const execFile = promisify(execFileCallback);
const continuumId = z
.string()
.regex(
/^[a-z0-9]{1,64}$/u,
"Use a short Continuum ID with lowercase letters and digits.",
);
export const continuumEnvironmentId = continuumId.describe(
"Short Continuum environment ID.",
);
export const continuumFindingId = continuumId.describe(
"Short Continuum finding ID.",
);
const nativeRecord = z.record(z.string(), z.unknown());
const continuumIssueExport = z.object({
format: z.literal(continuumIssueFormat),
environmentId: continuumEnvironmentId,
sourceRepositoryUrl: z.string(),
issues: z.array(
z.object({
issue: z.looseObject({ artifacts: z.array(nativeRecord) }),
findings: z.array(nativeRecord),
}),
),
});
export const continuumImportOutput = z.union([
continuumIssueExport,
nativeRecord,
]);
interface ContinuumCollectionOptions {
environmentId: string;
profile?: string;
region?: string;
cwd: string;
sourceRoot?: string;
environment: NodeJS.ProcessEnv;
signal?: AbortSignal;
}
type AwsCommand = (args: string[]) => Promise<Record<string, unknown>>;
const environmentSources = z.object({
configuration: z
.object({
codeConfiguration: z
.object({
sourceConfiguration: z
.object({
repositorySources: z.array(z.unknown()).optional(),
s3Sources: z.array(z.unknown()).optional(),
})
.optional(),
})
.optional(),
})
.optional(),
});
const repositorySource = z.object({
integrationId: continuumId,
repository: z.string().regex(/^[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)+$/iu),
});
const gitLabIntegration = z.object({
providerDetails: z.object({
gitlab: z.object({ instanceUrl: z.string().startsWith("https://") }),
}),
});
function configuredSources(environment: Record<string, unknown>) {
const { configuration } = environmentSources.parse(environment);
const sources = configuration?.codeConfiguration?.sourceConfiguration;
return {
repositories: sources?.repositorySources ?? [],
s3Sources: sources?.s3Sources ?? [],
};
}
async function singleRepositorySource(
environment: Record<string, unknown>,
getIntegration: (id: string) => Promise<Record<string, unknown>>,
) {
const { repositories, s3Sources } = configuredSources(environment);
if (repositories.length !== 1)
throw new CodexSecurityError(
`Continuum collection requires exactly one configured Git repository. This environment has ${repositories.length}.`,
);
const { integrationId, repository } = repositorySource.parse(repositories[0]);
const integration = await getIntegration(integrationId);
const type = integration["integrationType"];
if (type !== "GITHUB" && type !== "GITLAB")
throw new CodexSecurityError(
"Expected a GitHub or GitLab integration for the Continuum repository.",
);
const base =
type === "GITHUB"
? "https://github.com"
: gitLabIntegration.parse(integration).providerDetails.gitlab.instanceUrl;
return {
url: declaredScannerRepositoryUrl(
`${base.replace(/\/$/u, "")}/${repository}`,
"Continuum",
),
// Mixed environments do not identify the Git source by the patch's AWS source name.
includePatches: s3Sources.length === 0,
};
}
async function awsCommand({
cwd,
environment,
signal,
sourceRoot,
}: ContinuumCollectionOptions): Promise<AwsCommand> {
const aws = await prepareContinuumAws(cwd, environment, signal, sourceRoot);
return async (args) => {
const command = execFile(aws.executable, args, {
cwd: aws.cwd,
env: aws.environment,
signal,
maxBuffer: Infinity,
windowsHide: true,
});
command.child.stdin?.end();
const { stdout } = await command;
return record(JSON.parse(stdout), `AWS Continuum ${args[1]} response`);
};
}
async function continuumRequests(
options: ContinuumCollectionOptions,
runAws?: AwsCommand,
) {
const { profile, region, signal } = options;
signal?.throwIfAborted();
const run = runAws ?? (await awsCommand(options));
const awsArgs = [
"--output",
"json",
"--no-cli-pager",
...(profile === undefined ? [] : ["--profile", profile]),
...(region === undefined ? [] : ["--region", region]),
];
return (operation: string, scope: string[], ...args: string[]) => {
signal?.throwIfAborted();
return run(["continuum", operation, ...scope, ...awsArgs, ...args]);
};
}
type ContinuumRequest = Awaited<ReturnType<typeof continuumRequests>>;
async function getIssueArtifact(
request: ContinuumRequest,
scope: string[],
issueId: string,
artifactId: string,
artifactType: string,
) {
const artifact = await request(
"get-code-issue-artifact",
scope,
"--issue-id",
issueId,
"--artifact-id",
artifactId,
);
if (
artifact["artifactId"] !== artifactId ||
artifact["artifactType"] !== artifactType
)
throw new CodexSecurityError(
`Unexpected Continuum artifact ${artifactId} for issue ${issueId}.`,
);
return artifact;
}
function requireCompleteList(response: Record<string, unknown>, name: string) {
if (
Object.hasOwn(response, "nextToken") ||
Object.hasOwn(response, "NextToken")
)
throw new CodexSecurityError(`Expected a complete Continuum ${name} list.`);
}
export async function collectContinuumFinding(
options: ContinuumCollectionOptions & {
findingId: string;
sourceRoot: string;
repositoryName?: string;
warn?: (message: string) => void;
},
runAws?: AwsCommand,
): Promise<Record<string, unknown>> {
const { environmentId, findingId, repositoryName, warn, signal } = options;
const request = await continuumRequests(options, runAws);
const scope = ["--environment-id", environmentId];
if (repositoryName === undefined) {
const { repositories, s3Sources } = configuredSources(
await request("get-environment", scope),
);
if (
repositories.length !== 1 ||
s3Sources.length !== 0 ||
!repositorySource.safeParse(repositories[0]).success
)
throw new CodexSecurityError(
"Pass --repository-name with the exact AWS source name. Omitting it requires exactly one configured Git repository and no S3 sources.",
);
}
const finding = await request(
"get-code-finding",
scope,
"--finding-id",
findingId,
);
const identity = findingIdentity(finding);
if (finding["environmentId"] !== environmentId || identity.id !== findingId)
throw new CodexSecurityError(
`Unexpected detail for Continuum finding ${findingId}.`,
);
const linkedIssue =
finding["createdIssueId"] || finding["duplicateOfIssueId"];
if (!linkedIssue) return finding;
const issueId = continuumId.parse(linkedIssue);
const list = await request(
"list-code-issue-artifacts",
scope,
"--issue-id",
issueId,
"--artifact-type",
"PATCH",
);
requireCompleteList(list, "issue artifact");
const artifactIds = array(list["items"], "Continuum issue artifacts")
.map((item) =>
continuumId.parse(
record(item, "Continuum issue artifact summary")["artifactId"],
),
)
.sort();
const patches = [];
for (const artifactId of artifactIds) {
const artifact = await getIssueArtifact(
request,
scope,
issueId,
artifactId,
"PATCH",
);
const body = record(artifact["body"], "Continuum artifact body");
const patch = record(
body["patch"],
`Continuum artifact ${artifactId} patch body`,
);
if (
repositoryName !== undefined &&
patch["repositoryName"] !== repositoryName
) {
if (!patch["repositoryName"])
warn?.(
`Skipped Continuum patch ${artifactId}: AWS did not identify its repository.`,
);
continue;
}
patches.push(readPatch({ ...patch, artifactId }));
}
signal?.throwIfAborted();
return patches.length ? { finding, patches } : finding;
}
export async function collectContinuumIssues(
options: ContinuumCollectionOptions,
runAws?: AwsCommand,
): Promise<z.infer<typeof continuumIssueExport>> {
const { environmentId, signal } = options;
const request = await continuumRequests(options, runAws);
const environmentArgs = ["--environment-id", environmentId];
const { url: sourceRepositoryUrl, includePatches } =
await singleRepositorySource(
await request("get-environment", environmentArgs),
(id) => request("get-integration", ["--integration-id", id]),
);
// Let the AWS CLI assemble every page. A continuation token means the
// capture is incomplete and cannot be published as the environment's report.
const list = await request("list-code-issues", environmentArgs);
requireCompleteList(list, "issue");
const issues: z.infer<typeof continuumIssueExport>["issues"] = [];
const seenIssues = new Set<string>();
const fetchedFindings = new Map<string, Record<string, unknown>>();
let environmentScope: string | undefined;
for (const summary of array(list["items"], "Continuum issue list")) {
const selected = issueIdentity(summary);
if (
selected.environmentId !== environmentId ||
(environmentScope !== undefined && environmentScope !== selected.scope) ||
seenIssues.has(selected.id)
)
throw new CodexSecurityError(
"The Continuum issue list contains a duplicate issue or an issue from another environment.",
);
environmentScope = selected.scope;
seenIssues.add(selected.id);
const issue = await request(
"get-code-issue",
environmentArgs,
"--issue-id",
selected.id,
);
if (issueIdentity(issue).arn !== selected.arn)
throw new CodexSecurityError(
`Unexpected detail for Continuum issue ${selected.id}.`,
);
const ids = z.array(continuumId).nonempty().parse(issue["findingIds"]);
if (new Set(ids).size !== ids.length)
throw new CodexSecurityError(
`Duplicate finding IDs on Continuum issue ${selected.id}.`,
);
const findings: Record<string, unknown>[] = [];
for (const id of ids) {
let finding = fetchedFindings.get(id);
if (!finding) {
finding = await request(
"get-code-finding",
environmentArgs,
"--finding-id",
id,
);
const identity = findingIdentity(finding);
if (identity.id !== id || identity.scope !== selected.scope)
throw new CodexSecurityError(
`Unexpected detail for Continuum finding ${id}.`,
);
fetchedFindings.set(id, finding);
}
findings.push(finding);
}
const issueArtifacts: Record<string, unknown>[] = [];
if (issue["evidenceAvailability"] !== "NONE") {
const issueArgs = ["--issue-id", selected.id];
const artifacts = await request(
"list-code-issue-artifacts",
environmentArgs,
...issueArgs,
);
requireCompleteList(artifacts, "issue artifact");
for (const item of array(
artifacts["items"],
"Continuum issue artifacts",
)) {
const summary = record(item, "Continuum issue artifact summary");
const type = summary["artifactType"];
if (
type !== "EVIDENCE" &&
type !== "VALIDATION_EVIDENCE" &&
!(includePatches && type === "PATCH")
)
continue;
const artifactId = continuumId.parse(summary["artifactId"]);
issueArtifacts.push(
await getIssueArtifact(
request,
environmentArgs,
selected.id,
artifactId,
type,
),
);
}
}
issues.push({
issue: { ...issue, artifacts: issueArtifacts },
findings,
});
}
signal?.throwIfAborted();
return {
format: continuumIssueFormat,
environmentId,
sourceRepositoryUrl,
issues,
};
}
+528 -67
View File
@@ -1,9 +1,14 @@
import { hash } from "node:crypto";
import { CodexSecurityError } from "./errors.js";
import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
import {
CLOUD_EVIDENCE_BYTES,
DEFAULT_CLOUD_STRING_BYTES,
type ExternalImportTarget,
repositoryUrlKey,
validateEnrichedExternalEvidence,
validateExternalEvidence,
validateExternalEvidenceJson,
} from "./external-import-contract.js";
import type { ImportedPackage, Provider } from "./external-import-models.js";
import { isRecord } from "./record.js";
@@ -25,10 +30,13 @@ import {
} from "./scanner-repository-url.js";
const format = "aws-continuum-code-findings/v1";
export const continuumIssueFormat = "aws-continuum-code-issues/v1";
const findingArn =
/^(arn:[a-z0-9-]+:continuum:[a-z0-9-]+:\d{12}:environments\/([a-z0-9]+))\/code-findings\/([a-z0-9]+)$/u;
const issueArn =
/^(arn:[a-z0-9-]+:continuum:[a-z0-9-]+:\d{12}:environments\/([a-z0-9]+))\/code-issues\/([a-z0-9]+)$/u;
function identity(value: unknown) {
export function findingIdentity(value: unknown) {
const row = record(value, "Continuum finding");
const arn = requiredText(row["findingArn"], "Continuum finding ARN");
const match = findingArn.exec(arn);
@@ -40,7 +48,16 @@ function identity(value: unknown) {
throw new Error(
"Expected a Continuum finding ARN matching its environmentId and findingId.",
);
return { arn, scope: match[1]! };
return { arn, scope: match[1]!, id: match[3]! };
}
export function issueIdentity(value: unknown) {
const issue = record(value, "Continuum issue");
const arn = requiredText(issue["issueArn"], "Continuum issue ARN");
const match = issueArn.exec(arn);
if (!match || issue["issueId"] !== match[3])
throw new Error("Expected a Continuum issue ARN matching its issueId.");
return { arn, scope: match[1]!, environmentId: match[2]!, id: match[3]! };
}
function retainedRepository(
@@ -52,8 +69,10 @@ function retainedRepository(
source_finding_id: id,
evidence: { source_data: data },
} = finding;
const native = data?.["finding"];
const marked = data?.["format"] === format;
const isIssue =
data?.["format"] === continuumIssueFormat || issueArn.test(id);
const native = data?.[isIssue ? "issue" : "finding"];
const marked = isIssue || data?.["format"] === format;
const nativeArn =
isRecord(native) && findingArn.test(text(native["findingArn"]) ?? "");
if (provider !== "continuum") {
@@ -69,10 +88,12 @@ function retainedRepository(
return;
}
if (!marked && !nativeArn && !findingArn.test(id)) return;
const { arn, scope } = identity(native);
const { arn, scope } = isIssue
? issueIdentity(native)
: findingIdentity(native);
if (arn !== id)
throw new Error(
"Continuum source finding ID does not match the retained finding ARN.",
`Continuum source finding ID does not match the retained ${isIssue ? "issue" : "finding"} ARN.`,
);
return {
url: declaredScannerRepositoryUrl(
@@ -89,26 +110,61 @@ export const continuumReportRepositories = repositoryScopeValidator(
retainedRepository,
);
function codeLocations(
function findingVulnerabilities(row: Record<string, unknown>) {
return array(row["vulnerabilities"] ?? [], "Continuum vulnerabilities").map(
(item) => record(item, "Continuum vulnerability"),
);
}
function* findingCodeLocations(
row: Record<string, unknown>,
vulnerabilities: Record<string, unknown>[],
) {
yield {
filePath: row["filePath"],
startLine: row["lineNumber"],
endLine: row["endLine"],
code: row["vulnerableCode"],
};
for (const vulnerability of vulnerabilities) {
for (const value of array(
vulnerability["locations"] ?? [],
"Continuum vulnerability locations",
)) {
const location = record(value, "Continuum vulnerability location");
yield {
filePath: location["filePath"],
startLine: location["startLine"],
endLine: location["endLine"],
code: vulnerability["code"],
};
}
}
}
function locationLine(value: unknown): number | null {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
? value
: null;
}
function codeLocations(
ranges: Iterable<{
filePath: unknown;
startLine: unknown;
endLine: unknown;
code?: unknown;
}>,
) {
const locations: { path: string; line: number | null }[] = [];
const seen = new Set<string>();
let endLine: number | null = null;
let snippet: string | null = null;
function add(
value: unknown,
start: unknown,
end: unknown,
fragment: unknown,
) {
const path = repositoryFilePath(value);
if (!path) return;
const line =
typeof start === "number" && Number.isSafeInteger(start) && start > 0
? start
: null;
for (const range of ranges) {
const path = repositoryFilePath(range.filePath);
if (!path) continue;
const line = locationLine(range.startLine);
const end = locationLine(range.endLine);
const key = JSON.stringify([path, line]);
if (!seen.has(key)) {
seen.add(key);
@@ -116,34 +172,8 @@ function codeLocations(
}
// The flat location and first nested location can describe the same range.
if (locations[0]!.path === path && locations[0]!.line === line) {
if (
line !== null &&
typeof end === "number" &&
Number.isSafeInteger(end) &&
end >= line
)
endLine ??= end;
snippet ??= text(fragment);
}
}
add(
row["filePath"],
row["lineNumber"],
row["endLine"],
row["vulnerableCode"],
);
for (const vulnerability of vulnerabilities) {
for (const value of array(
vulnerability["locations"] ?? [],
"Continuum vulnerability locations",
)) {
const location = record(value, "Continuum vulnerability location");
add(
location["filePath"],
location["startLine"],
location["endLine"],
vulnerability["code"],
);
if (line !== null && end !== null && end >= line) endLine ??= end;
snippet ??= text(range.code);
}
}
return { locations, code: { end_line: endLine, snippet } };
@@ -159,9 +189,13 @@ function reportRows(input: unknown) {
throw new Error(
"Continuum export has a continuation token; supply the complete paginated CLI output.",
);
if (!("items" in document || "findingArn" in document))
if (!(
"items" in document ||
"findingArn" in document ||
"finding" in document
))
throw new Error(
"Expected a Continuum ListCodeFindings or GetCodeFinding response.",
"Expected a Continuum ListCodeFindings, GetCodeFinding, or finding with patch artifacts.",
);
const summary = "items" in document;
return {
@@ -170,6 +204,76 @@ function reportRows(input: unknown) {
};
}
function isPatchCapture(value: unknown): value is Record<string, unknown> {
return isRecord(value) && !("findingArn" in value) && "finding" in value;
}
export function readPatch(value: unknown) {
const artifact = record(value, "Continuum patch artifact");
const patch = requiredText(artifact["patch"], "Continuum patch content");
const sizeBytes = Buffer.byteLength(patch);
const patchSha256 = hash("sha256", patch);
if (
artifact["sizeBytes"] !== sizeBytes ||
artifact["patchSha256"] !== patchSha256
)
throw new Error(
"Continuum patch content does not match its sizeBytes or patchSha256.",
);
return {
artifactId: requiredText(
artifact["artifactId"],
"Continuum patch artifact ID",
),
patch,
patchSha256,
sizeBytes,
...(artifact["format"] !== undefined && {
format: requiredText(artifact["format"], "Continuum patch format"),
}),
...(artifact["repositoryName"] !== undefined && {
repositoryName: requiredText(
artifact["repositoryName"],
"Continuum patch repository",
),
}),
};
}
function projectPatches(
patches: ReturnType<typeof readPatch>[],
target: ExternalImportTarget,
project: (artifacts: object[]) => ExternalFinding["evidence"],
) {
if (!patches.length || target === "local") return project(patches);
try {
return project(patches);
} catch {
// Complete patches can exceed the Cloud evidence budget.
}
// Reserve each artifact's lookup information, then include whole patches that fit.
const marker = { contentOmitted: "cloud_evidence_limit" };
const markerBytes = Buffer.byteLength(JSON.stringify(marker));
const sizes = patches.map(
({ patch }) => Buffer.byteLength(JSON.stringify({ patch })) - markerBytes,
);
const projected = patches.map(({ patch, ...descriptor }, index) =>
sizes[index]! > 0 ? { ...descriptor, ...marker } : patches[index]!,
);
const result = project(projected);
let remaining =
CLOUD_EVIDENCE_BYTES - validateExternalEvidenceJson(result, target);
for (const [index, bytes] of sizes.entries()) {
if (bytes > 0 && bytes <= remaining) {
projected[index] = patches[index]!;
remaining -= bytes;
}
}
result.source_data!["patches"] = projected;
return result;
}
function subcategoryCwe(row: Record<string, unknown>) {
return /^(CWE-[1-9]\d*):/u.exec(text(row["subCategory"]) ?? "")?.[1];
}
@@ -222,22 +326,371 @@ function affectedPackages(
return [...unique.values()];
}
function linkedIssueFindings(
value: unknown,
issue: Record<string, unknown>,
scope: string,
) {
const ids = array(issue["findingIds"], "Continuum issue findingIds").map(
(id) => requiredText(id, "Continuum issue finding ID"),
);
const missing = new Set(ids);
const findings = new Map<string, Record<string, unknown>>();
const invalidLinks =
"Supply exactly one detail response per Continuum issue finding ID.";
if (ids.length === 0 || missing.size !== ids.length)
throw new Error(invalidLinks);
for (const item of array(value, "Continuum issue findings")) {
const { id, scope: findingScope } = findingIdentity(item);
if (findingScope !== scope)
throw new Error(
"Continuum issue and linked finding must share an environment.",
);
if (!missing.delete(id)) throw new Error(invalidLinks);
findings.set(id, record(item, "Continuum finding"));
}
if (missing.size) throw new Error(invalidLinks);
return ids.map((id) => findings.get(id)!);
}
function issueFindingEvidence(
finding: Record<string, unknown>,
includeReviewEvidence: boolean,
) {
const dependencyFields = (row: Record<string, unknown>) => ({
cveId: text(row["cveId"]),
affectedPackages: Array.isArray(row["affectedPackages"])
? row["affectedPackages"]
: [],
});
const vulnerableCode =
includeReviewEvidence && text(finding["vulnerableCode"]);
const mitigation = includeReviewEvidence && text(finding["mitigation"]);
const validation = finding["validation"];
// Retain the inputs needed to replay the stored issue. The export on disk
// retains the full finding details.
return {
findingArn: finding["findingArn"],
findingId: finding["findingId"],
environmentId: finding["environmentId"],
ocsfClass:
finding["posture"] != null
? "APPLICATION_SECURITY_POSTURE_FINDING"
: text(finding["ocsfClass"]),
...dependencyFields(finding),
filePath: text(finding["filePath"]),
lineNumber: locationLine(finding["lineNumber"]),
endLine: locationLine(finding["endLine"]),
...(vulnerableCode && { vulnerableCode }),
...(mitigation && { mitigation }),
...(includeReviewEvidence && isRecord(validation) && { validation }),
vulnerabilities: findingVulnerabilities(finding).map((vulnerability) => {
const code = includeReviewEvidence && text(vulnerability["code"]);
return {
...dependencyFields(vulnerability),
locations: vulnerability["locations"] ?? [],
...(code && { code }),
};
}),
};
}
function issueEvidenceBody(artifact: Record<string, unknown>) {
const body = artifact["body"];
if (!isRecord(body)) return;
if (artifact["artifactType"] === "VALIDATION_EVIDENCE") {
if (isRecord(body["validationEvidence"]))
return { validationEvidence: body["validationEvidence"] };
if (typeof body["raw"] === "string") return { raw: body["raw"] };
}
const projection = body["prevalidationSignals"];
if (artifact["artifactType"] !== "EVIDENCE" || !isRecord(projection)) return;
const signals = array(
projection["signals"] ?? [],
"Continuum evidence signals",
).map((signal) => record(signal, "Continuum evidence signal"));
return { prevalidationSignals: { ...projection, signals } };
}
function issueEvidenceArtifacts(artifacts: Record<string, unknown>[]) {
return artifacts.flatMap((artifact) => {
const body = issueEvidenceBody(artifact);
if (!body) return [];
return [
{
artifactId: requiredText(
artifact["artifactId"],
"Continuum evidence artifact ID",
),
artifactType: artifact["artifactType"],
...(artifact["createdAt"] != null && {
createdAt: artifact["createdAt"],
}),
...(artifact["mediaType"] != null && {
mediaType: artifact["mediaType"],
}),
...(artifact["producer"] != null && {
producer: artifact["producer"],
}),
body,
},
];
});
}
function normalizeContinuumIssues(
document: Record<string, unknown>,
repository: string,
target: ExternalImportTarget,
): ExternalFindings {
const environmentId = requiredText(
document["environmentId"],
"Continuum environment ID",
);
const rows = array(document["issues"], "Continuum issues");
const scopes = new Set<string>();
const result = normalizeRecords(
rows,
(value) => {
const row = record(value, "Continuum issue record");
const { artifacts, ...issue } = record(row["issue"], "Continuum issue");
const { arn, id, scope } = issueIdentity(issue);
const issueArtifacts = array(
artifacts ?? row["evidenceArtifacts"] ?? [],
"Continuum issue artifacts",
).map((artifact) => record(artifact, "Continuum issue artifact"));
const evidenceArtifacts = issueEvidenceArtifacts(issueArtifacts);
const patches = issueArtifacts
.filter((artifact) => artifact["artifactType"] === "PATCH")
.map((artifact) => {
const body = record(artifact["body"], "Continuum patch body");
return readPatch({
...record(body["patch"], "Continuum patch"),
artifactId: artifact["artifactId"],
});
});
const verdicts = new Set<string>();
for (const artifact of evidenceArtifacts) {
for (const signal of artifact.body.prevalidationSignals?.signals ??
[]) {
const subject = signal["subjectRef"];
const exploitability = signal["exploitability"];
if (
signal["dimension"] !== "EXPLOITABILITY" ||
(subject !== id && subject !== arn) ||
!isRecord(exploitability)
)
continue;
const verdict = text(exploitability["verdict"]);
if (verdict) verdicts.add(verdict);
}
}
const scannerVerdict = verdicts.size > 1 ? "MIXED" : [...verdicts][0];
const linked = linkedIssueFindings(row["findings"], issue, scope);
const findings = linked.map((finding) =>
issueFindingEvidence(finding, true),
);
const ranges = findings.flatMap((finding) =>
Array.from(findingCodeLocations(finding, finding.vulnerabilities)),
);
const { locations, code } = codeLocations([
...ranges.filter(({ startLine }) => locationLine(startLine) !== null),
...ranges.filter(({ startLine }) => locationLine(startLine) === null),
]);
const all = findings.flatMap((finding) => [
finding,
...finding.vulnerabilities,
]);
const advisories = [...new Set(strings(all.map((row) => row.cveId)))];
const packages = all.flatMap((row) => row.affectedPackages);
const dependency = advisories.length > 0 || packages.length > 0;
const posture = findings.some(
(finding) =>
finding.ocsfClass === "APPLICATION_SECURITY_POSTURE_FINDING",
);
const status = requiredText(issue["status"], "Continuum issue status");
const synopsis = requiredText(
issue["synopsis"],
"Continuum issue synopsis",
);
const details =
posture || (!scannerVerdict && locations[0]?.line == null)
? undefined
: {
details: {
kind: dependency ? "advisory" : "sast",
...(dependency && { advisory: { source: "repository" } }),
repository: { url: repository },
source_status: status,
...(scannerVerdict && { scanner_verdict: scannerVerdict }),
remediation_instructions: text(issue["summary"]),
code: { ...code, snippet: null },
},
};
const reviewDetails = details && {
details: {
...details.details,
remediation_instructions:
details.details.remediation_instructions ??
findings.find(({ mitigation }) => mitigation)?.mitigation ??
null,
code,
},
};
const dependencyEvidence = dependency
? {
advisory_ids:
target === "cloud" ? advisories.slice(0, 100) : advisories,
packages: affectedPackages(packages, target),
}
: undefined;
const source = {
format: continuumIssueFormat,
sourceRepositoryUrl: repository,
environmentId,
issue,
...(evidenceArtifacts.length && {
evidence_artifacts: evidenceArtifacts,
}),
};
const compactSource = structuredClone({
...source,
findings: linked.map((finding) => issueFindingEvidence(finding, false)),
});
const findingsWithVerdicts = compactSource.findings.map(
(finding, index) => {
const verdict = text(findings[index]?.validation?.["verdict"]);
return verdict ? { ...finding, validation: { verdict } } : finding;
},
);
const evidence = validateEnrichedExternalEvidence(
{
title: requiredText(issue["name"], "Continuum issue name"),
severity: text(issue["severity"])?.toLowerCase() ?? "unknown",
description: [synopsis, text(issue["severityReasoning"])]
.filter(Boolean)
.join("\n\n"),
// Keep every reported range in source_data, including ranges beyond
// the Cloud limit for navigable locations.
locations: target === "cloud" ? locations.slice(0, 100) : locations,
source_updated_at:
statusUpdatedAt(issue["updatedAt"]) ??
statusUpdatedAt(issue["statusUpdatedAt"]),
source_data: compactSource,
...(scannerVerdict &&
details && {
details: {
...details.details,
remediation_instructions: null,
code: null,
},
}),
},
target,
{
...reviewDetails,
...dependencyEvidence,
source_data: structuredClone({ ...source, findings }),
},
// Bulky linked validation evidence can exceed the Cloud record limit.
// Keep the per-finding verdicts with the structured review fields if they fit.
{
...reviewDetails,
...dependencyEvidence,
source_data: { ...compactSource, findings: findingsWithVerdicts },
},
dependencyEvidence
? { ...reviewDetails, ...dependencyEvidence }
: undefined,
reviewDetails,
dependencyEvidence ? { ...details, ...dependencyEvidence } : undefined,
details,
dependencyEvidence,
);
if (!patches.length) return evidence;
// Fit optional patch bodies after selecting the scanner evidence to retain.
return projectPatches(patches, target, (patches) =>
validateExternalEvidence(
{ ...evidence, source_data: { ...evidence.source_data, patches } },
target,
),
);
},
(value) => {
const issue = issueIdentity(
record(value, "Continuum issue record")["issue"],
);
if (issue.environmentId !== environmentId)
throw new Error(
"Continuum issue ARN does not match the export environment.",
);
scopes.add(issue.scope);
return issue.arn;
},
target,
);
if (scopes.size > 1)
throw new Error("Continuum issues must belong to the same environment.");
return result;
}
export function normalizeContinuumFindings(
input: unknown,
sourceRepositoryUrl: string,
sourceRepositoryUrl?: string,
target: ExternalImportTarget = "cloud",
): ExternalFindings {
const issueReport =
isRecord(input) && input["format"] === continuumIssueFormat;
const capturedSource =
issueReport && input["sourceRepositoryUrl"] !== undefined
? declaredScannerRepositoryUrl(
input["sourceRepositoryUrl"],
"Continuum",
target,
)
: undefined;
const repository = declaredScannerRepositoryUrl(
sourceRepositoryUrl,
sourceRepositoryUrl || capturedSource,
"Continuum",
target,
);
if (issueReport) {
if (
capturedSource &&
repositoryUrlKey(capturedSource) !== repositoryUrlKey(repository)
)
throw new Error(
"The Continuum export repository does not match the declared source repository.",
);
const findings = normalizeContinuumIssues(
input,
capturedSource ?? repository,
target,
);
return capturedSource
? { ...findings, report: { sourceRepositoryUrl: capturedSource } }
: findings;
}
const { rows, summary } = reportRows(input);
const scopes = new Set<string>();
const output = normalizeRecords(
rows,
(value) => {
const row = record(value, "Continuum finding");
const capture = !summary && isPatchCapture(value) ? value : undefined;
const row = record(
capture ? capture["finding"] : value,
"Continuum finding",
);
const patches = capture
? array(capture["patches"], "Continuum patches").map(readPatch)
: [];
if (
patches.length &&
!(text(row["createdIssueId"]) || text(row["duplicateOfIssueId"]))
)
throw new Error(
"Continuum patches require a finding linked to an issue.",
);
if (
row["type"] !== "CONTINUUM_CODE_VULN" &&
row["type"] !== "CUSTOMER_CODE_VULN"
@@ -249,11 +702,10 @@ export function normalizeContinuumFindings(
row["severity"],
"Continuum severity",
).toLowerCase();
const vulnerabilities = array(
row["vulnerabilities"] ?? [],
"Continuum vulnerabilities",
).map((item) => record(item, "Continuum vulnerability"));
const { locations, code } = codeLocations(row, vulnerabilities);
const vulnerabilities = findingVulnerabilities(row);
const { locations, code } = codeLocations(
findingCodeLocations(row, vulnerabilities),
);
const source = requiredText(row["source"], "Continuum source");
const status = requiredText(row["status"], "Continuum status");
const validation = record(
@@ -321,19 +773,28 @@ export function normalizeContinuumFindings(
? { details: { ...evidence.details, weakness_ids: [namedCwe] } }
: undefined;
// Keep previously admissible evidence if an optional projection exceeds the Cloud budget.
return validateEnrichedExternalEvidence(
evidence,
target,
inferred ? { ...enrichment, ...inferred } : undefined,
enrichment,
packages.length && updatedAt !== null
? { source_updated_at: updatedAt }
: undefined,
inferred,
return projectPatches(patches, target, (artifacts) =>
validateEnrichedExternalEvidence(
artifacts.length
? {
...evidence,
source_data: { ...evidence.source_data, patches: artifacts },
}
: evidence,
target,
inferred ? { ...enrichment, ...inferred } : undefined,
enrichment,
packages.length && updatedAt !== null
? { source_updated_at: updatedAt }
: undefined,
inferred,
),
);
},
(value) => {
const { arn, scope } = identity(value);
const { arn, scope } = findingIdentity(
!summary && isPatchCapture(value) ? value["finding"] : value,
);
scopes.add(scope);
return arn;
},
+308
View File
@@ -0,0 +1,308 @@
import { createHash } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { CodexSecurityError } from "./errors.js";
import type {
ExternalFindings,
ExternalSourceRepository,
} from "./external-findings.js";
import {
repositoryUrlKey,
validateExternalEvidence,
} from "./external-import-contract.js";
import { isGitHubCloudHost } from "./git-remote.js";
import {
array,
normalizeRecords,
readScannerJson,
record,
repositoryFilePath,
requiredText,
scannerSeverity,
stableId,
text,
} from "./scanner-import.js";
import {
declaredScannerRepositoryUrl,
validScannerRepositoryUrl,
} from "./scanner-repository-url.js";
export const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";
type NativeRecord = Record<string, unknown>;
interface Entry {
rule: NativeRecord;
detection: NativeRecord;
}
function joined(...values: (string | null)[]): string | null {
return values.filter((value) => value !== null).join("\n\n") || null;
}
function positive(value: unknown): number | null {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
? value
: null;
}
// A git:: scan path without its ?ref= query. When the scanned URL has a user
// name, FCS writes each detection path after this prefix.
function gitScan(path: unknown): string | undefined {
const value = text(path);
return value?.startsWith("git::") ? value.split("?", 1)[0] : undefined;
}
// The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts
// fetch over HTTPS or SSH, which do not match an http:// URL.
function gitScanRepository(scan: string): string | undefined {
const source = scan.slice("git::".length);
const scheme = /^https:\/\//iu.exec(source)?.[0];
if (!scheme) return undefined;
const subdirectory = source.indexOf("//", scheme.length);
const url = subdirectory === -1 ? source : source.slice(0, subdirectory);
return validScannerRepositoryUrl(url, "local") ? url : undefined;
}
// FCS writes paths relative to its working directory. A git:: scan writes them
// from the scan root, after a slash or after the scan path.
function detectionPath(detection: NativeRecord, scan: string | undefined) {
const raw = text(detection["file"]);
const relative =
scan === undefined || !raw
? raw
: raw.startsWith(`${scan}/`)
? raw.slice(scan.length + 1)
: raw.replace(/^\//u, "");
const path = repositoryFilePath(relative);
if (!path)
throw new CodexSecurityError(
"CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.",
);
return path;
}
// A detection in a registry or Git module names the calling file, but its line
// is inside the module. FCS states the call line only in module_remediation.
// FCS writes the file, module source and calling file in one form, so compare them as written.
function detectionLine(detection: NativeRecord): number | null {
const line = positive(detection["line"]);
const file = text(detection["file"]);
const source = text(detection["module_source"]);
if (
detection["is_from_module"] !== true ||
!file ||
!source ||
file.startsWith(`${source}/`)
)
return line;
// Search for this file's exact phrase; the remediation text comes from the report.
const remediation = text(detection["module_remediation"]) ?? "";
const marker = `called by ${file} at line `;
const start = remediation.indexOf(marker);
const call =
start === -1
? null
: /^\d+\b/u.exec(remediation.slice(start + marker.length));
return call ? positive(Number(call[0])) : null;
}
/** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */
export async function crowdstrikeCheckout(
input: ExternalFindings,
declared: string | undefined,
references: readonly ExternalSourceRepository[],
repository: string,
): Promise<ExternalSourceRepository | undefined> {
if (input.report?.["format"] !== crowdstrikeReportFormat)
throw new CodexSecurityError(
"CrowdStrike imports require a report from the crowdstrike reader.",
);
// Only a declared URL binds the checkout to its fetch remotes. A git:: report's
// own repository is recorded and must agree with it.
const declarations: unknown[] = [
declared,
input.report["repositoryUrl"],
...references.map(({ url }) => url),
];
const reportScan = gitScan(input.report["git_scan"]);
const claims = [...declarations, reportScan && gitScanRepository(reportScan)];
const files = new Map<string, Set<unknown>>();
for (const { evidence } of input.findings) {
validateExternalEvidence(evidence, "local");
const data = evidence.source_data;
if (data?.["format"] !== crowdstrikeReportFormat)
throw new CodexSecurityError(
"CrowdStrike findings must retain their native detection.",
);
const scan = gitScan(data["git_scan"]);
claims.push(
data["repository_url"],
evidence.details?.repository?.url,
scan && gitScanRepository(scan),
);
// Check the retained detection's file, and that the shown location is the same.
const detection = record(data["detection"], "CrowdStrike detection");
const file = detectionPath(detection, scan);
const [location, ...others] = evidence.locations ?? [];
if (
!location ||
others.length > 0 ||
location.path !== file ||
(location.line ?? null) !== detectionLine(detection)
)
throw new CodexSecurityError(
"CrowdStrike finding locations must match the native detection file and line.",
);
files.set(
file,
(files.get(file) ?? new Set()).add(detection["file_sha256"]),
);
}
const urls = claims
.filter((claim) => claim != null)
.map((claim) =>
declaredScannerRepositoryUrl(claim, "CrowdStrike", "local"),
);
if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)
throw new CodexSecurityError(
"CrowdStrike findings name a different repository than --source-repository-url.",
);
// Paths are relative to where FCS ran, so a missing file means a different root or checkout.
// FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.
for (const [file, hashes] of files) {
const path = join(repository, ...file.split("/"));
if (!(await stat(path).catch(() => null))?.isFile())
throw new CodexSecurityError(
`${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`,
);
const hash = createHash("sha256")
.update(await readFile(path))
.digest("hex");
if ([...hashes].some((expected) => expected !== hash))
throw new CodexSecurityError(
`${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`,
);
}
const url = urls[0];
if (url === undefined || declarations.every((claim) => claim == null))
return undefined;
const { hostname } = new URL(url);
return {
url,
platform: isGitHubCloudHost(hostname)
? "github"
: hostname === "gitlab.com"
? "gitlab"
: undefined,
};
}
/** Read a saved FCS CLI 4.x IaC JSON report. */
export async function readCrowdStrikeFindings(
path: string,
sourceRepositoryUrl?: string,
): Promise<ExternalFindings> {
const document = record(await readScannerJson(path), "CrowdStrike report");
if (!Array.isArray(document["rule_detections"]))
throw new CodexSecurityError(
"Expected an FCS CLI 4.x IaC JSON report with rule_detections.",
);
const version = text(document["fcs_version"]);
const scan = gitScan(document["path"]);
const declared =
sourceRepositoryUrl === undefined
? undefined
: declaredScannerRepositoryUrl(
sourceRepositoryUrl,
"CrowdStrike",
"local",
);
// A git:: report names the repository that FCS cloned.
const repositoryUrl = declared ?? (scan && gitScanRepository(scan));
const entries: Entry[] = array(
document["rule_detections"],
"CrowdStrike rule_detections",
).flatMap((value) => {
const { detections, ...rule } = record(value, "CrowdStrike rule");
return array(detections ?? [], "CrowdStrike detections").map(
(detection) => ({
rule,
detection: record(detection, "CrowdStrike detection"),
}),
);
});
return normalizeRecords(
entries,
({ rule, detection }) => {
const kind =
rule["rule_category"] === "Secret Management" ? "secret" : "iac";
const reason = text(detection["reason"]);
const recommendation = text(detection["recommendation"]);
const file = detectionPath(detection, scan);
return validateExternalEvidence(
{
title: requiredText(rule["rule_name"], "CrowdStrike rule_name"),
severity: scannerSeverity(text(rule["severity"])?.toLowerCase()),
description: joined(text(rule["description"]), reason),
locations: [{ path: file, line: detectionLine(detection) }],
source_scan_id: text(document["scan_uuid"]),
// Typed IaC and secret details must name their source repository.
details: repositoryUrl && {
kind,
repository: { url: repositoryUrl },
rule: {
id: text(rule["rule_uuid"]),
name: text(rule["rule_name"]),
},
configuration:
kind === "iac"
? {
platform: text(rule["platform"]),
cloud_platform: text(rule["cloud_provider"]),
expected: recommendation,
actual: reason,
}
: null,
remediation_instructions: joined(
recommendation,
text(detection["module_remediation"]),
),
scanner_origin: version
? `CrowdStrike FCS CLI ${version}`
: "CrowdStrike FCS CLI",
},
source_data: structuredClone({
format: crowdstrikeReportFormat,
fcs_version: version,
...(repositoryUrl && { repository_url: repositoryUrl }),
...(scan !== undefined && { git_scan: scan }),
rule,
detection,
}),
},
"local",
);
},
({ rule, detection }) =>
stableId("crowdstrike", [
requiredText(rule["rule_uuid"], "CrowdStrike rule_uuid"),
detectionPath(detection, scan),
positive(detection["line"]),
detection["resource_type"] ?? null,
detection["resource_name"] ?? null,
detection["reason"] ?? null,
detection["module_path"] ?? null,
]),
"local",
{
report: {
format: crowdstrikeReportFormat,
...(declared && { repositoryUrl: declared }),
...(scan !== undefined && { git_scan: scan }),
fcs_version: version,
scan_uuid: text(document["scan_uuid"]),
},
},
);
}
+2 -1
View File
@@ -37,10 +37,11 @@ export function isReviewRefusal(
/\bflagged for potentially high-risk cyber activity\b/iu,
/\bcyber[_\s-]?policy\b/iu,
/\b(?:cybersecurity|cyber)[ _-]*policy[ _-]*(?:violation|refusal|refused)\b/iu,
/^(?:content|safety) policy (?:violation|refusal)[.!]?$/iu,
/(?:^(?:refusal|refused)|\b(?:request|review)\s+(?:refusal|(?:(?:is|was|has been)\s+)?(?:refused|blocked)))\s+(?:under|by|due to|because of|because (?:it|this request) violates|for violating|in accordance with)\s+(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy\b/iu,
/^(?:(?:this|the|your)\s+)?(?:request|review)(?:\s+(?:is|was|has been))?\s+(?:refusal|refused|blocked)\s*:\s*(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy(?:[.!](?:\s+(?:I can offer|Please ask)\b[^\n]*)?)?$/iu,
/^(?:cybersecurity|cyber|content|safety)[ _-]*policy\s*:\s*(?:(?:(?:this|the|your)\s+)?request\s+)?(?:(?:is|was|has been)\s+)?(?:violation|refusal|refused|blocked)[.!]?$/iu,
/\b(?:cybersecurity|cyber|content|safety)[ _-]*policy\s+requires\s+(?:a\s+)?refusal\s+of\s+(?:(?:this|the|your)\s+)?(?:request|review)\b/iu,
/^(?:cybersecurity|cyber|content|safety)[ _-]*policy\s*:\s*(?:(?:(?:this|the|your)\s+)?(?:request|review)\s+)?(?:(?:is|was|has been)\s+)?(?:violation|refusal|refused|blocked)(?:[.!](?:\s+(?:I can offer|Please ask)\b[^\n]*)?)?$/iu,
/\bunder\s+(?:(?:the|a)\s+)?(?:cybersecurity|cyber|content|safety)[ _-]*policy[, :]\s*(?:this|the|your) request (?:is|was|has been) (?:refused|blocked)\b/iu,
/^(?:I(?:['’]m| am) sorry[,.:]?\s*(?:but\s+)?|Sorry[,.:]?\s*)?I(?:\s+(?:cannot|can['’]t|won['’]t|am (?:unable|not able) to)|['’]m (?:unable|not able) to)\s+(?:help|assist|comply)\b/iu,
].some((pattern) => pattern.test(text));
+20 -15
View File
@@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url";
import type { CodexOptions } from "@openai/codex-sdk";
import { parse } from "smol-toml";
import {
bundledCodexSdkEnvironment,
nativeCodexLaunch,
resolveBundledCodexExecutable,
} from "./codex-sdk-environment.js";
import { CodexSecurityError } from "./errors.js";
@@ -105,6 +105,22 @@ function codeModeTable(value: JsonValue | undefined): JsonObject | undefined {
return isRecord(value) ? value : undefined;
}
async function deepScanLaunch({
codexOptions,
preflightCommand: command,
}: Pick<DirectDeepScanOptions, "codexOptions" | "preflightCommand">) {
const launch = await nativeCodexLaunch(command.command, {
...codexOptions.env,
...(codexOptions.apiKey === undefined
? {}
: { CODEX_API_KEY: codexOptions.apiKey }),
});
return {
command: { ...command, command: launch.command },
environment: launch.environment!,
};
}
/** Read the same native layers and CLI overrides as the parent before adding its tool. */
export async function readDeepScanParentConfig(
options: Pick<
@@ -115,19 +131,14 @@ export async function readDeepScanParentConfig(
pluginServers?: Record<string, unknown>;
},
): Promise<JsonObject | undefined> {
const { codexOptions, preflightCommand: command } = options;
const { codexOptions } = options;
const config = codexOptions.config ?? {};
// The provider-profile launcher emits whole top-level tables instead.
const overrides =
codexOptions.nativeProfile === undefined
? sdkConfigFlags(config)
: (await nativeProfileClient()).profileConfigOverrides(config);
const environment = bundledCodexSdkEnvironment(command.command, {
...codexOptions.env,
...(codexOptions.apiKey === undefined
? {}
: { CODEX_API_KEY: codexOptions.apiKey }),
});
const { command, environment } = await deepScanLaunch(options);
const configOverrides = [
...overrides,
...(codexOptions.configOverrides ?? []),
@@ -367,13 +378,7 @@ export async function* runDeepScan(
pathToFileURL(join(options.pluginRoot, "scripts", "codex_profile.mjs")).href
);
const configured = options.codexOptions;
const command = options.preflightCommand;
const environment = bundledCodexSdkEnvironment(command.command, {
...configured.env,
...(configured.apiKey === undefined
? {}
: { CODEX_API_KEY: configured.apiKey }),
});
const { command, environment } = await deepScanLaunch(options);
const session = (await withCodexPreflightLock(
environment,
options.signal,
+1
View File
@@ -43,6 +43,7 @@ export class DeduplicationReviewError extends CodexSecurityError {
}
}
export class CodexConnectionError extends CodexSecurityError {}
export class ConfigurationError extends CodexSecurityError {}
export class AuthenticationRequiredError extends CodexSecurityError {}
export class PluginBootstrapError extends CodexSecurityError {}

Some files were not shown because too many files have changed in this diff Show More