Merge remote-tracking branch 'origin/main' into maintain/pr-2607

This commit is contained in:
Michael D'Angelo
2026-11-13 01:01:28 -08:00
228 changed files with 15322 additions and 14531 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
+32 -25
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 --csv FILE` or `--json FILE` saves a completed scan in local history. Use `--format json` to select 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. |
| 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 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.
+14 -20
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. |
@@ -143,26 +145,18 @@ With the SDK, repeat the preparation call that created the submission, using
the same options. For `prepareExternalPublication()`, supply the original
export file. For `prepareNormalizedExternalPublication()`, supply the original
`ExternalFindings`. Check `preview.resumed` before calling `publish()`.
Use the same SDK version throughout a submission when possible.
For stored findings, reprepare the interrupted source group with its saved selection
and review ID. Its checkpoint belongs to the selected checkout and finding versions.
After a repository reset, the workbench records any acknowledged receipts before
retiring the old request. Review the new destination before publishing again.
For hosted Semgrep or Snyk imports, finish any pending request before sending
updated evidence for the same finding IDs. Selections with distinct
scanner-issued IDs can proceed independently. If the checkpoint records
only the source, finish that request before starting another for the same
source and destination.
**Resuming across SDK versions.** Keep the SDK input that produced the
checkpoint, including report context and caller-added fields. Serializing it
as JSON can change the values used to identify the approved request. Retry on
the original deployment. If the SDK can verify the saved selection, it reuses
the request IDs and skips batches with receipts. Otherwise it preserves the
checkpoint and stops before uploading. If it cannot identify the approved
findings, a new submission for the same source and destination can also be blocked.
After a repository rename, a checkpoint that records only the repository ID
can still be retried with the original normalized findings and report metadata.
Omit supplemental repository declarations for that retry. A new declaration
requires a matching catalog entry or a URL recorded in the approval.
**Upgrading from an earlier import client.** Finish pending Cloud submissions with
the CLI or SDK build that created their checkpoints. Keep the original input and
state directory. If the outcome is uncertain, check the private inbox job or
read back the repository’s source reports to identify the accepted findings
before preparing a fresh submission. The current client starts a new approval
for a submission made with the retired checkpoint format.
[Verify an import](README.md#verify-the-import)
See [results and exit codes](../../sdk/typescript/docs/cli.md#results-and-exit-codes)
for cumulative counts and interrupted readback.
+10 -20
View File
@@ -423,8 +423,8 @@ leaves earlier exports available for replay.
```sh
report=$(mktemp ./semgrep-backlog.XXXXXX) &&
codex-security import semgrep example/project --semgrep-deployment example \
--semgrep-ref refs/heads/topic --semgrep-product sast --format json > "$report" &&
codex-security import semgrep example/project --deployment example \
--ref refs/heads/topic --semgrep-product sast --format json > "$report" &&
codex-security publish findings "$report" --to local --repository /path/to/project \
--provider semgrep --source-key example/project/topic --dry-run --format json
```
@@ -446,7 +446,7 @@ when the project has no repository URL. The report records that mapping in
For SSH projects, the report stores the original address in `nativeProjectUrl` and the resolved HTTP(S) address in `project.url`.
It records any supplied mapping separately. Save the complete output from a successful
command. The importer checks the recorded finding count and repository/ref
claims. It retains each original finding as JSON text so large IDs survive replay. The reader also accepts saved v1 project exports with native object rows and decimal type witnesses.
claims. It retains each original finding as JSON text so large IDs survive replay.
A finding that identifies its repository only by name can use the project name,
the Git URL path, or the final path component of either. For any other name,
@@ -483,18 +483,14 @@ and advisory IDs when Semgrep supplies them. With the same source key, importing
selection reports them as unchanged when switching between a selection and a full collection.
See the [Semgrep Findings API](https://docs.semgrep.dev/api-reference/v1/findingsservice/list-code-supply-chain-or-ai-powered-detection-findings).
When replaying v1 exports whose findings were stored as objects, the first
replay converts the stored finding to JSON text and increments its version.
Its local and source IDs stay the same.
For an older `semgrep-platform-findings/v1` export, rerun `cs import semgrep`
with the selected deployment, project, product and ref to collect a current export.
Check its IDs and scope before saving or publishing it.
## Replay saved Platform findings
Semgrep's native signed 64-bit finding IDs match across file and SDK imports.
For synthetic IDs above that range, repeat the original workflow and preserve
the ID's spelling and JSON type. A saved selection keeps its literal ref,
including older short refs. For a row without a URL but with a matching
project ID and ref, saved files also accept the complete percent-encoded
repository path. New selections require the decoded path.
Keep the original spelling and JSON type of each selected ID and the full Git ref in the saved capture.
**Repository mapping.** Local preview compares the project URL with the checkout's
named fetch URLs. For an IP address, use its canonical spelling, such as
@@ -513,14 +509,8 @@ evidence unchanged. Use a separate source key for CLI scans.
**Normalized SDK records.** Keep each generated `source_finding_id` with its
native row and original deployment, project, ref and product. If you assign
your own opaque ID, retain that scope in a marked Platform batch. The SDK checks
the serialized native row when present. In legacy v1 `source_data.finding`,
repository fields, `ref` (even `null`), recognized `product` or `issue_type`,
and non-null `found_dependency` or `vulnerability_identifier` can establish
scope. Put unrelated metadata under a different key, such as
`source_data.ticket`, or submit it in a batch without a Platform marker.
the serialized native row. Keep unrelated metadata in a separate field.
**Cloud retries.** Cloud checks the original project's repository, including
for Supply Chain findings without a typed repository field. New approvals
retain the collection scope of caller-managed rows. Older approvals check
the repository and the scope retained in their evidence. Retry the original
input with the same account and destination. [Retry a Cloud submission](schema-guide.md#retry-a-cloud-submission).
for Supply Chain findings without a typed repository field. Retry the original
selection with the same account and destination. [Retry a Cloud submission](schema-guide.md#retry-a-cloud-submission).
+8 -17
View File
@@ -121,7 +121,7 @@ example saves a fresh report there and imports it into the checkout at `./projec
```sh
report=$(mktemp ./snyk-issues.XXXXXX) &&
codex-security import snyk PROJECT_ID --snyk-org ORG_ID \
codex-security import snyk PROJECT_ID --org ORG_ID \
--source-repository-url https://github.com/example/project \
--format json > "$report" &&
codex-security publish findings "$report" --to local --provider snyk \
@@ -152,17 +152,13 @@ The SDK's `collectSnykIssues` defaults to Open Source and returns the same repor
Passing the configured `SNYK_TOKEN` explicitly retains its configured regional
API origin. Pass independently verified `sourceRepositories` in its
dependencies when a private repository uses an SSH target. The offline reader
`readSnykFindings(path, "local")` accepts `snyk-rest-issues/v1` and
`snyk-rest-issues/v2` reports from Snyk REST API version `2026-03-25`.
The collector writes v2 and preserves the original project and issue evidence.
For open Snyk Code issues from an SCM integration, both versions import
repository-relative paths from open coordinates. V2 also imports each
coordinate's reported start line when available. V2 keeps URI and SSH addresses
in the original evidence and uses only repository file paths for code locations
and package manifests. For resolved issues, closed
coordinates, and projects monitored through the CLI or API, read the original
location from `evidence.source_data.issue` in v1 or from the JSON text in
`evidence.source_data.issueJson` in v2.
`readSnykFindings(path, "local")` accepts the collector's `snyk-rest-issues/v2`
report for Snyk REST API version `2026-03-25`. Run the collector again to replace
an archived v1 export. The report preserves the original project and issue
evidence. Open Snyk Code issues from an SCM integration import repository file
paths and reported start lines. For resolved issues, closed coordinates, and
CLI- or API-monitored projects, read the original location from
`evidence.source_data.issueJson`.
Use the same source key on later imports. The issue key within the API
origin, organization, project and product identifies the finding. Replaying the
@@ -179,11 +175,6 @@ the monitored project for a row that retains only its original issue. The Cloud
preview includes the verified project and any captured target in the evidence it
will publish.
For a v1 row, keep `source_data.issue` and the original `source_data.numericFields`
when present. If you trim the metadata, keep its matching entries for every
`issue`, `project`, and `target` object you retain. V1 uses those entries to
distinguish exact numbers from strings with the same spelling. For a v2 row,
keep `source_data.issueJson`.
The local workbench stores the verified project and target with that issue,
so the stored row can be imported again. All selected issues must share the
report’s API region, organization, project and product. Keep SCM-integrated
+1 -1
View File
@@ -1,7 +1,7 @@
# Import SonarQube Cloud findings
Use `import sonar` to collect security issues for one project and branch or
pull request. A live `--dry-run` writes a private capture and returns its path.
pull request. A `--dry-run` with either live issues or a saved capture writes a private evidence copy and returns its path. Pass that path to confirm the reviewed selection.
Replay it without signing in to Sonar. If you already have issue-search JSON,
[preview the native export](#use-a-native-json-export).
+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)
```
+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,32 @@
{
"isError": false,
"content": [],
"structuredContent": {
"findings": [
{
"id": "9007199254740992",
"repository": { "name": "example/project" },
"ref": "refs/heads/main",
"issueType": "sast",
"rulePath": "demo.other-rule",
"message": "Another finding in the tool response",
"severity": "LOW",
"status": "open",
"filePath": "src/other.ts",
"line": 3
},
{
"id": "9007199254740993",
"repository": { "name": "example/project" },
"ref": "refs/heads/main",
"issueType": "sast",
"rulePath": "demo.unchecked-path",
"message": "A user-supplied path reaches the file reader",
"severity": "HIGH",
"status": "open",
"filePath": "src/read.ts",
"line": 12
}
]
}
}
@@ -0,0 +1,13 @@
{
"sourceKey": "demo/guardian/example/project/main/sast",
"sourceRepositoryUrl": "https://github.com/example/project",
"request": {
"name": "get_semgrep_sast_findings",
"arguments": {
"deployment_name": "demo",
"repository_name": "example/project",
"ref": "refs/heads/main"
}
},
"findingIds": ["9007199254740993"]
}
@@ -0,0 +1,33 @@
{
"SchemaVersion": 2,
"Trivy": { "Version": "0.76.1" },
"ReportID": "00000000-0000-7000-8000-000000000001",
"CreatedAt": "2026-01-01T00:00:00Z",
"ArtifactType": "repository",
"ArtifactName": "https://github.com/example/project",
"Metadata": {
"RepoURL": "https://github.com/example/project",
"Branch": "main",
"Commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
},
"Results": [
{
"Target": "package-lock.json",
"Class": "lang-pkgs",
"Type": "npm",
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2099-0001",
"PkgName": "@example/parser",
"PkgID": "@example/parser@1.0.0",
"InstalledVersion": "1.0.0",
"FixedVersion": "1.0.1",
"Title": "Example parser accepts an invalid length",
"Description": "A crafted length can cause excessive allocation.",
"Severity": "HIGH",
"PrimaryURL": "https://advisories.example.invalid/CVE-2099-0001"
}
]
}
]
}
@@ -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",
+18 -5
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";
@@ -80,8 +85,14 @@ function runHelper(): void {
"Usage: list-stored-findings\nReads a JSON object from stdin with an absolute stateDirectory, positive payload.limit and non-negative payload.offset.",
"store-external-findings":
"Usage: store-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload containing repository, provider, sourceKey and findings with source_finding_id and evidence.",
"list-external-findings":
"Usage: list-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository; payload.id optionally selects one external finding.",
"read-external-findings":
"Usage: read-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository. Select an id, an importId, or a list of findings with id and version.",
"list-external-imports":
"Usage: list-external-imports\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository.",
"record-external-finding-publications":
"Usage: record-external-finding-publications\nReads a JSON object from stdin with an absolute stateDirectory and publication receipts for stored finding versions.",
"list-external-finding-publications":
"Usage: list-external-finding-publications\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository. Select an optional finding id.",
"find-potential-duplicates":
"Usage: find-potential-duplicates\nReads a JSON object from stdin with an absolute stateDirectory, payload.findingId and payload.scope containing either repositoryId or allRepositories: true.",
"store-dedupe-groups":
@@ -99,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(
@@ -13,9 +13,16 @@ import {
} from "./duplicates";
import {
listExternalFindings,
listExternalImports,
storeExternalFindings,
type ExternalFindingSelection,
type ExternalFindingsImport,
} from "./external-findings";
import {
listExternalFindingPublications,
recordExternalFindingPublications,
type ExternalPublicationLinks,
} from "./external-finding-publications";
import {
readSeverityClassification,
@@ -84,6 +91,7 @@ export async function workbenchCommand(
command !== "local-dedupe" &&
command !== "store-findings" &&
command !== "store-external-findings" &&
command !== "record-external-finding-publications" &&
command !== "store-dedupe-groups" &&
command !== "severity-classification",
},
@@ -101,8 +109,21 @@ export async function workbenchCommand(
payload as ExternalFindingsImport,
new Date().toISOString(),
);
if (command === "list-external-findings")
if (command === "read-external-findings")
return listExternalFindings(
database,
payload as ExternalFindingSelection,
);
if (command === "list-external-imports")
return listExternalImports(database, payload as { repository: string });
if (command === "record-external-finding-publications")
return recordExternalFindingPublications(
database,
payload as ExternalPublicationLinks,
new Date().toISOString(),
);
if (command === "list-external-finding-publications")
return listExternalFindingPublications(
database,
payload as { repository: string; id?: string },
);
@@ -0,0 +1,105 @@
import type { DatabaseSync } from "node:sqlite";
import { requireRepository, requireText } from "./external-findings";
import { transaction } from "./transaction";
export interface ExternalPublicationLinks {
repository: string;
cloudApiUrl: string;
accountId: string;
destinationId: string;
entries: {
id: string;
version: number;
receiptId: string;
outcome: "created" | "updated" | "unchanged" | "private_job";
cloudFindingId?: string;
}[];
}
export function recordExternalFindingPublications(
database: DatabaseSync,
input: ExternalPublicationLinks,
timestamp: string,
) {
requireRepository(input?.repository);
requireText(input.cloudApiUrl, "cloudApiUrl");
requireText(input.accountId, "accountId");
requireText(input.destinationId, "destinationId");
if (!Array.isArray(input.entries))
throw new TypeError("entries must be an array.");
return transaction(database, "BEGIN IMMEDIATE", () => {
// The reviewed version may have been superseded during upload. Every
// positive revision through the current version existed in this repository.
const lookup = database.prepare(
"SELECT 1 FROM external_source_reports WHERE id = ? AND repository = ? AND version >= ?",
);
const insert = database.prepare(
`INSERT INTO external_finding_publications
(finding_id, version, cloud_api_url, account_id, destination_id, receipt_id, outcome, cloud_finding_id, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`,
);
let recorded = 0;
for (const {
id,
version,
receiptId,
outcome,
cloudFindingId,
} of input.entries) {
requireText(id, "id");
requireText(receiptId, "receiptId");
if (cloudFindingId !== undefined)
requireText(cloudFindingId, "cloudFindingId");
if (
!Number.isSafeInteger(version) ||
version < 1 ||
!lookup.get(id, input.repository, version)
)
throw new Error(
`No finding ${id} at version ${version} in the selected repository.`,
);
if (!["created", "updated", "unchanged", "private_job"].includes(outcome))
throw new TypeError("Unknown external publication outcome.");
recorded += Number(
insert.run(
id,
version,
input.cloudApiUrl,
input.accountId,
input.destinationId,
receiptId,
outcome,
cloudFindingId ?? null,
timestamp,
).changes,
);
}
return { recorded };
});
}
export function listExternalFindingPublications(
database: DatabaseSync,
input: { repository: string; id?: string },
) {
requireRepository(input?.repository);
if (input.id !== undefined) requireText(input.id, "id");
const query = database.prepare(
`SELECT p.finding_id AS id, p.version, p.cloud_api_url AS cloudApiUrl, p.account_id AS accountId,
p.destination_id AS destinationId, p.receipt_id AS receiptId, p.outcome, p.cloud_finding_id AS cloudFindingId,
p.created_at AS createdAt FROM external_finding_publications p
JOIN external_source_reports f ON f.id = p.finding_id WHERE f.repository = ?
${input.id === undefined ? "" : "AND p.finding_id = ?"}
ORDER BY p.created_at DESC, p.receipt_id, p.finding_id`,
);
const rows =
input.id === undefined
? query.all(input.repository)
: query.all(input.repository, input.id);
return {
publications: rows.map(({ cloudFindingId, ...row }) => ({
...row,
...(cloudFindingId == null ? {} : { cloudFindingId }),
})),
};
}
@@ -1,8 +1,9 @@
import { hash } from "node:crypto";
import { hash, randomUUID } from "node:crypto";
import { isAbsolute } from "node:path";
import type { DatabaseSync, StatementSync } from "node:sqlite";
import type { DatabaseSync } from "node:sqlite";
import { isDeepStrictEqual } from "node:util";
import {
compareCodePoints,
object,
parseJson,
requireFiniteNumbers,
@@ -21,6 +22,21 @@ export interface ExternalFindingsImport {
provider: string;
sourceKey: string;
findings: ExternalFindingInput[];
provenance?: {
sourceRepositories?: { url: string; platform?: "github" | "gitlab" }[];
inspectorProjectMap?: [string, string][];
};
read?: number;
excluded?: unknown[];
report?: Record<string, unknown>;
}
export interface ExternalFindingSelection {
repository: string;
id?: string;
importId?: string;
ifCurrent?: boolean;
findings?: Pick<StoredExternalFinding, "id" | "version">[];
}
export interface StoredExternalFinding {
@@ -36,13 +52,18 @@ export interface StoredExternalFinding {
updatedAt: string;
}
function requireText(value: unknown, name: string): asserts value is string {
export function requireText(
value: unknown,
name: string,
): asserts value is string {
if (typeof value !== "string" || value.length === 0)
throw new TypeError(`${name} must be a non-empty string.`);
requireSqliteText([value]);
}
function requireRepository(repository: unknown): asserts repository is string {
export function requireRepository(
repository: unknown,
): asserts repository is string {
requireText(repository, "repository");
if (!isAbsolute(repository))
throw new TypeError("repository must be an absolute local path.");
@@ -67,11 +88,41 @@ function fromRow(row: Record<string, unknown>): StoredExternalFinding {
};
}
// A change to the publication context advances the local revision. All imports
// of one finding revision therefore have equivalent provenance.
const findingWithProvenance = `SELECT f.*, (
SELECT i.provenance_json FROM external_finding_import_members m
JOIN external_finding_imports i ON i.id = m.import_id
WHERE m.finding_id = f.id AND m.version = f.version LIMIT 1
) AS provenance_json FROM external_source_reports f`;
// A scanner can enumerate the same repository bindings in a different order.
function serializeProvenance(provenance: ExternalFindingsImport["provenance"]) {
const repositories = provenance?.sourceRepositories;
const projects = provenance?.inspectorProjectMap;
if (!repositories?.length && !projects?.length) return null;
return JSON.stringify({
sourceRepositories: repositories?.length
? repositories
.map(({ url, platform }) => ({ url, platform }))
.sort(
(a, b) =>
compareCodePoints(a.url, b.url) ||
compareCodePoints(a.platform ?? "", b.platform ?? ""),
)
: undefined,
inspectorProjectMap: projects?.length
? projects.toSorted(([a], [b]) => compareCodePoints(a, b))
: undefined,
});
}
export function storeExternalFindings(
database: DatabaseSync,
input: ExternalFindingsImport,
timestamp: string,
): {
importId?: string;
findings: StoredExternalFinding[];
counts: { created: number; updated: number; unchanged: number };
} {
@@ -83,6 +134,14 @@ export function storeExternalFindings(
throw new TypeError("findings must be an array.");
const counts = { created: 0, updated: 0, unchanged: 0 };
if (input.findings.length === 0) return { findings: [], counts };
const provenanceJson = serializeProvenance(input.provenance);
const selection = {
read: input.read ?? input.findings.length,
excluded: input.excluded ?? [],
report: input.report,
};
requireFiniteNumbers(selection);
const selectionJson = stringifyJson(selection, 0);
// Validate and serialize the complete batch before taking the write lock.
const sourceIds = new Set<string>();
@@ -111,74 +170,164 @@ export function storeExternalFindings(
});
return transaction(database, "BEGIN IMMEDIATE", () => {
const stored = database.prepare(
"SELECT * FROM external_source_reports WHERE id = ?",
const importId = randomUUID();
database
.prepare(
`INSERT INTO external_finding_imports
(id, repository, created_at, provider, source_key, provenance_json, selection_json)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
)
.run(
importId,
input.repository,
timestamp,
input.provider,
input.sourceKey,
provenanceJson,
selectionJson,
);
const stored = database.prepare(`${findingWithProvenance} WHERE f.id = ?`);
const write = database.prepare(
`INSERT INTO external_source_reports
(id, repository, provider, source_key, source_finding_id, evidence_json, version, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
ON CONFLICT(id) DO UPDATE SET evidence_json = excluded.evidence_json,
version = external_source_reports.version + 1, updated_at = excluded.updated_at
RETURNING *`,
);
let insert: StatementSync | undefined;
let update: StatementSync | undefined;
const findings = entries.map((entry) => {
const previous = stored.get(entry.id);
if (!previous) {
insert ??= database.prepare(
`INSERT INTO external_source_reports
(id, repository, provider, source_key, source_finding_id,
evidence_json, version, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
);
insert.run(
entry.id,
input.repository,
input.provider,
input.sourceKey,
entry.sourceFindingId,
entry.evidenceJson,
timestamp,
timestamp,
);
counts.created++;
return fromRow(stored.get(entry.id)!);
}
const finding = fromRow(previous);
if (previous.evidence_json !== entry.evidenceJson) {
const evidence = parseEvidence(entry.evidenceJson);
if (!isDeepStrictEqual(finding.evidence, evidence)) {
update ??= database.prepare(
`UPDATE external_source_reports
SET evidence_json = ?, version = version + 1, updated_at = ?
WHERE id = ? RETURNING version, updated_at`,
);
const row = update.get(entry.evidenceJson, timestamp, entry.id)!;
counts.updated++;
return {
...finding,
evidence,
version: Number(row.version),
updatedAt: String(row.updated_at),
};
if (previous && previous.provenance_json === provenanceJson) {
const finding = fromRow(previous);
if (
previous.evidence_json === entry.evidenceJson ||
isDeepStrictEqual(finding.evidence, parseEvidence(entry.evidenceJson))
) {
counts.unchanged++;
return finding;
}
}
counts.unchanged++;
return finding;
const row = write.get(
entry.id,
input.repository,
input.provider,
input.sourceKey,
entry.sourceFindingId,
entry.evidenceJson,
timestamp,
timestamp,
)!;
counts[previous ? "updated" : "created"]++;
return fromRow(row);
});
return { findings, counts };
const member = database.prepare(
"INSERT INTO external_finding_import_members (import_id, position, finding_id, version) VALUES (?, ?, ?, ?)",
);
findings.forEach(({ id, version }, position) =>
member.run(importId, position, id, version),
);
return { importId, findings, counts };
});
}
export function listExternalImports(
database: DatabaseSync,
selection: { repository: string },
) {
requireRepository(selection?.repository);
return {
imports: database
.prepare(
`SELECT i.id AS importId, i.created_at AS createdAt, i.provider, i.source_key AS sourceKey,
(SELECT count(*) FROM external_finding_import_members m WHERE m.import_id = i.id) AS count
FROM external_finding_imports i WHERE i.repository = ?
ORDER BY i.created_at DESC, i.rowid DESC`,
)
.all(selection.repository),
};
}
export function listExternalFindings(
database: DatabaseSync,
selection: { repository: string; id?: string },
): { findings: StoredExternalFinding[] } {
selection: ExternalFindingSelection,
) {
requireRepository(selection?.repository);
if (selection.id !== undefined) requireText(selection.id, "id");
const selectByRepository =
"SELECT * FROM external_source_reports WHERE repository = ?";
const rows =
selection.id === undefined
? database
.prepare(`${selectByRepository} ORDER BY created_at, id`)
.all(selection.repository)
: database
.prepare(`${selectByRepository} AND id = ?`)
.all(selection.repository, selection.id);
return { findings: rows.map(fromRow) };
const { repository, id, importId, findings: versions } = selection;
if (importId === undefined && versions === undefined) {
if (id !== undefined) requireText(id, "id");
const lookup = "SELECT * FROM external_source_reports WHERE repository = ?";
const rows =
id === undefined
? database.prepare(`${lookup} ORDER BY created_at, id`).all(repository)
: database.prepare(`${lookup} AND id = ?`).all(repository, id);
return { findings: rows.map(fromRow) };
}
if (id !== undefined || (importId !== undefined && versions !== undefined))
throw new TypeError(
"Select either an import or a list of finding versions.",
);
return transaction(database, "BEGIN", () => {
let summary: Record<string, unknown> = {};
let pins: string, input: string;
if (importId !== undefined) {
requireText(importId, "importId");
const batch = database
.prepare(
"SELECT selection_json FROM external_finding_imports WHERE repository = ? AND id = ?",
)
.get(repository, importId);
if (!batch) {
if (selection.ifCurrent) return { read: 0, excluded: [], findings: [] };
throw new Error("Import does not exist in the selected repository.");
}
summary = parseJson(String(batch.selection_json)) as Record<
string,
unknown
>;
pins =
"SELECT finding_id AS id, version, position FROM external_finding_import_members WHERE import_id = ?";
input = importId;
} else {
if (!Array.isArray(versions) || versions.length === 0)
throw new TypeError("Select at least one finding version.");
const seen = new Set<string>();
input = JSON.stringify(
versions.map(({ id, version }) => {
requireText(id, "finding id");
if (seen.has(id) || !Number.isSafeInteger(version) || version < 1)
throw new TypeError(
"Select each finding once with a positive integer version.",
);
seen.add(id);
return [id, version];
}),
);
pins =
"SELECT value ->> 0 AS id, value ->> 1 AS version, key AS position FROM json_each(?)";
}
// A left join retains missing and foreign pins so a partial selection can never be approved.
const rows = database
.prepare(
`SELECT p.id AS pinned_id, p.version AS pinned_version, f.* FROM (${pins}) p
LEFT JOIN (${findingWithProvenance}) f ON f.id = p.id AND f.repository = ?
ORDER BY p.position`,
)
.all(input, repository);
const stale = rows.find((row) => row.version !== row.pinned_version);
if (stale) {
if (selection.ifCurrent) return { read: 0, excluded: [], findings: [] };
throw new Error(
`Finding ${stale.pinned_id} version ${stale.pinned_version} is missing or has changed. Review the current selection.`,
);
}
const findings = rows.map((row) => {
return {
...fromRow(row),
...(row.provenance_json != null && {
provenance: parseJson(String(row.provenance_json)),
}),
};
});
return { read: findings.length, excluded: [], ...summary, findings };
});
}
@@ -14,9 +14,10 @@ export interface Migration {
statements: readonly string[];
}
// Repository-dependent migrations run in Python before semantic workbench operations.
// Python owns the repository-dependent migrations 67–71. Migration 72 only uses
// the external source tables that both workbench runtimes already maintain.
export const migrations: readonly Migration[] = history.filter(
(item) => item.version <= 66,
(item) => item.version <= 66 || item.version === 72,
);
const migration = (version: number) =>
migrations.find((item) => item.version === version)!;
@@ -1449,6 +1449,7 @@ async function testWorkerRuntimeSettings() {
"PYTHONIOENCODING",
"CODEX_SECURITY_PYTHON_COMMAND",
"PATH",
"_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"HOME",
"NODE_OPTIONS",
"NODE_DEBUG",
@@ -2056,6 +2057,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(
@@ -2110,7 +2120,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,
@@ -2193,6 +2207,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,
@@ -2505,13 +2523,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);
@@ -2621,7 +2639,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assert.deepEqual(
preflight.gitEnvironment,
expectedGitEnvironment(
gitEnvironment,
scanGitEnvironments[index],
nodePaths[index],
selectedProvider.environment,
),
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { hash } from "node:crypto";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { after, test, type TestContext } from "node:test";
@@ -8,14 +8,18 @@ import { fileURLToPath } from "node:url";
import { importSource } from "./import-module.ts";
import { createTemporaryDirectories } from "./support/temporary-directories.ts";
import type * as External from "../src/workbench/external-findings.ts";
import type * as Publications from "../src/workbench/external-finding-publications.ts";
import type * as Migrations from "../src/workbench/migrations.ts";
const { storeExternalFindings, listExternalFindings } = (await importSource(
"src/workbench/external-findings.ts",
)) as typeof External;
const { storeExternalFindings, listExternalFindings, listExternalImports } =
(await importSource("src/workbench/external-findings.ts")) as typeof External;
const { applyMigrations, migrations } = (await importSource(
"src/workbench/migrations.ts",
)) as typeof Migrations;
const { recordExternalFindingPublications, listExternalFindingPublications } =
(await importSource(
"src/workbench/external-finding-publications.ts",
)) as typeof Publications;
const temporary = createTemporaryDirectories(true);
after(() => temporary.cleanup());
const repository = join(process.cwd(), "synthetic-repository");
@@ -101,7 +105,7 @@ test("external imports preserve incomplete evidence without creating assessed fi
input.findings[index].source_finding_id,
];
assert.deepEqual(finding, {
id: `ext_${createHash("sha256").update(JSON.stringify(identity)).digest("hex")}`,
id: `ext_${hash("sha256", JSON.stringify(identity))}`,
repository,
provider: input.provider,
sourceKey: input.sourceKey,
@@ -144,7 +148,17 @@ test("repeat imports keep identities and unchanged timestamps; changed evidence
],
};
const replay = storeExternalFindings(database, reordered, updated);
assert.notEqual(replay.importId, first.importId);
assert.deepEqual(
listExternalFindings(database, { repository, importId: replay.importId }),
{
read: 1,
excluded: [],
findings: [first.findings[0]],
},
);
assert.deepEqual(replay, {
importId: replay.importId,
findings: [first.findings[0]],
counts: { created: 0, updated: 0, unchanged: 1 },
});
@@ -221,11 +235,87 @@ test("a large mixed import and its replay return every stored row in input order
});
const changes = database.prepare("SELECT total_changes() AS writes");
const beforeReplay = changes.get()!.writes;
assert.deepEqual(storeExternalFindings(database, mixed, created), {
const replay = storeExternalFindings(database, mixed, created);
assert.deepEqual(replay, {
importId: replay.importId,
findings: result.findings,
counts: { created: 0, updated: 0, unchanged: 513 },
});
assert.equal(changes.get()!.writes, beforeReplay);
for (const selection of [
{ importId: replay.importId },
{ findings: replay.findings },
])
assert.deepEqual(
listExternalFindings(database, { repository, ...selection }).findings,
result.findings,
);
// Only the import and its membership were written; finding evidence stays untouched.
assert.equal(
Number(changes.get()!.writes) - Number(beforeReplay),
result.findings.length + 1,
);
});
test("stored selections retain run context, isolate repositories and reject stale evidence or provenance", (t) => {
const database = open(t);
const input = batch();
input.provenance = {
sourceRepositories: [{ url: "https://example.com/team/repo" }],
};
input.read = 3;
input.excluded = [
{ position: 3, source_finding_id: null, reason: "missing ID" },
];
input.report = { run: "scanner/run/1" };
const first = storeExternalFindings(database, input, created);
const expected = first.findings.map((f) => ({
...f,
provenance: input.provenance,
}));
const select = (
choice: Omit<External.ExternalFindingSelection, "repository">,
checkout = repository,
) => listExternalFindings(database, { repository: checkout, ...choice });
const asImport = { importId: first.importId };
const refs = first.findings
.toReversed()
.map(({ id, version }) => ({ id, version }));
const asVersions = { findings: refs };
assert.deepEqual(select(asImport), {
read: 3,
excluded: input.excluded,
report: input.report,
findings: expected,
});
assert.deepEqual(select(asVersions).findings, expected.toReversed());
assert.throws(() => select({ findings: [refs[0], refs[0]] }), /once/u);
const foreign = join(repository, "other");
assert.throws(() => select(asImport, foreign), /selected repository/u);
assert.throws(() => select(asVersions, foreign), /missing/u);
assert.deepEqual(
listExternalImports(database, { repository: foreign }).imports,
[],
);
const latest = storeExternalFindings(
database,
{ ...input, provenance: undefined },
updated,
);
assert.equal(latest.counts.updated, 2);
assert.throws(() => select(asImport), /has changed/u);
assert.throws(() => select(asVersions), /has changed/u);
assert.deepEqual(
listExternalImports(database, { repository }).imports.map((row) => ({
...row,
})),
[latest, first].map((x) => ({
importId: x.importId,
createdAt: x.findings[0].updatedAt,
provider: input.provider,
sourceKey: input.sourceKey,
count: 2,
})),
);
});
test("repository, provider and source namespaces keep distinct finding identities", (t) => {
@@ -256,11 +346,39 @@ test("repository, provider and source namespaces keep distinct finding identitie
);
});
test("reordering a scope's repository bindings keeps the same revision", (t) => {
const database = open(t);
const input = batch();
const refs = [
{ url: "https://example.com/A" },
{ url: "https://example.com/B" },
];
const mappings: [string, string][] = [
["arn:A", refs[0].url],
["arn:B", refs[1].url],
];
input.provenance = {
sourceRepositories: refs,
inspectorProjectMap: mappings,
};
storeExternalFindings(database, input, created);
input.provenance = {
sourceRepositories: refs.toReversed(),
inspectorProjectMap: mappings.toReversed(),
};
assert.deepEqual(storeExternalFindings(database, input, updated).counts, {
created: 0,
updated: 0,
unchanged: 2,
});
});
test("invalid batches and failed writes preserve all previously stored evidence", (t) => {
const database = open(t);
const input = batch();
storeExternalFindings(database, input, created);
const before = listExternalFindings(database, { repository });
const beforeImports = listExternalImports(database, { repository });
const duplicate = {
...input,
findings: [
@@ -297,9 +415,57 @@ test("invalid batches and failed writes preserve all previously stored evidence"
/synthetic write failure/u,
);
assert.deepEqual(listExternalFindings(database, { repository }), before);
assert.deepEqual(
listExternalImports(database, { repository }),
beforeImports,
);
}
});
test("receipt links retain the actually published revision and replay idempotently", (t) => {
const database = open(t);
const imported = storeExternalFindings(database, batch(), created);
const { id, version } = imported.findings[0];
const destination = {
cloudApiUrl: "https://service.example",
accountId: "account",
destinationId: "repo-id",
};
const receipt: Publications.ExternalPublicationLinks["entries"][number] = {
id,
version,
receiptId: "receipt-1",
outcome: "created",
cloudFindingId: "remote-id",
};
const record = (
...entries: Publications.ExternalPublicationLinks["entries"]
) =>
recordExternalFindingPublications(
database,
{ repository, ...destination, entries },
updated,
).recorded;
const read = (checkout = repository) =>
listExternalFindingPublications(database, { repository: checkout })
.publications;
const replacement = batch();
replacement.findings[0].evidence = { title: "New revision while uploading" };
storeExternalFindings(database, replacement, updated);
assert.throws(
() => record(receipt, { ...receipt, version: 99 }),
/No finding/u,
);
assert.deepEqual(read(), []);
assert.equal(record(receipt), 1);
assert.equal(record(receipt), 0);
assert.deepEqual(read(), [
{ ...receipt, ...destination, createdAt: updated },
]);
assert.deepEqual(read(join(repository, "other")), []);
});
test("a Python database at the preceding schema upgrades in Node and remains readable in Python", async () => {
const directory = await temporary.create("external-migration-");
const path = join(directory, "workbench.sqlite3");
@@ -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);
},
);
@@ -79,7 +79,7 @@ function assertMigrationNames(database: DatabaseSync, ...versions: number[]) {
database
.prepare("SELECT name FROM schema_migrations WHERE version = ?")
.get(version)?.name,
migrations[version - 1].name,
workbenchMigrations[version - 1].name,
);
}
@@ -1051,7 +1051,7 @@ test("recorded additive migrations restore missing columns and configured error
for (const version of [27, 28, 31, 32, 47, 54, 55, 58, 59, 60, 61])
database
.prepare("INSERT INTO schema_migrations VALUES (?, ?, 'original')")
.run(version, migrations[version - 1].name);
.run(version, workbenchMigrations[version - 1].name);
applyMigrations(database);
const launch = database
.prepare(
@@ -1488,7 +1488,7 @@ test("Node initialization leaves repository migration semantics to the Python co
pythonMigrations(controlPath);
await databaseInfo(directory);
const initialized = new DatabaseSync(databasePath);
assertMigrationNames(initialized, 48, 49, 53, 54, 55, 56, 60);
assertMigrationNames(initialized, 48, 49, 53, 54, 55, 56, 60, 72);
assert.deepEqual(
initialized.prepare("SELECT * FROM external_source_reports").all(),
originalReports,
@@ -1688,6 +1688,9 @@ with sqlite3.connect(sys.argv[2]) as connection:
name !== "finding_issue_receipts" &&
name !== "deep_scan_worker_threads" &&
name !== "external_source_reports" &&
name !== "external_finding_imports" &&
name !== "external_finding_import_members" &&
name !== "external_finding_publications" &&
name !== "sqlite_sequence",
)
.map(([name, rows]) => {
@@ -149,7 +149,10 @@ test("finding helper help exits without reading stdin", async () => {
"store-findings",
"list-stored-findings",
"store-external-findings",
"list-external-findings",
"read-external-findings",
"list-external-imports",
"record-external-finding-publications",
"list-external-finding-publications",
"find-potential-duplicates",
"store-dedupe-groups",
"list-dedupe-groups",
+2
View File
@@ -69,6 +69,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",
@@ -146,6 +147,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
@@ -2977,7 +2977,14 @@ def _is_sealed_artifact(scan_dir: Path, relative_output: str, artifact_paths: li
return False
def write_export_output(scan_dir: Path, output: Path, export_format: str, contents: bytes) -> None:
def write_export_output(
scan_dir: Path,
output: Path,
export_format: str,
contents: bytes,
*,
replace_existing: bool = True,
) -> None:
output_paths = {**EXPORT_PATHS, "md": THREAT_MODEL_EXPORT_PATH}
if export_format not in output_paths:
raise ContractError(f"unsupported export format: {export_format}")
@@ -3008,6 +3015,7 @@ def write_export_output(scan_dir: Path, output: Path, export_format: str, conten
output.name,
contents,
external_name=True,
replace_existing=replace_existing,
owner_read_write=export_format == "md",
)
return
@@ -3032,7 +3040,11 @@ def write_export_output(scan_dir: Path, output: Path, export_format: str, conten
f"{export_format.upper()} output path cannot overwrite a sealed scan artifact"
)
write_scan_local_bytes(
scan_dir, relative_output, contents, owner_read_write=export_format == "md"
scan_dir,
relative_output,
contents,
owner_read_write=export_format == "md",
replace_existing=replace_existing,
)
@@ -3365,6 +3377,7 @@ def main() -> int:
parser.add_argument("--export-format", choices=[*sorted(EXPORT_PATHS), "md"])
parser.add_argument("--avit-template", type=Path)
parser.add_argument("--export-output", type=Path)
parser.add_argument("--no-clobber", action="store_true")
parser.add_argument("--export-metadata", action="store_true")
parser.add_argument("--describe-threat-model", action="store_true")
parser.add_argument("--write-threat-model", action="store_true")
@@ -3426,7 +3439,20 @@ def main() -> int:
if args.export_output is None:
sys.stdout.buffer.write(contents)
else:
write_export_output(args.scan_dir, args.export_output, args.export_format, contents)
try:
write_export_output(
args.scan_dir,
args.export_output,
args.export_format,
contents,
replace_existing=not args.no_clobber,
)
except FileExistsError:
if not args.no_clobber:
raise
raise ContractError(
f"{args.export_output} already exists. Use --output FILE to choose or replace a file."
) from None
if args.export_metadata:
sys.stdout.buffer.write(
_json_bytes({**description, "path": str(args.export_output.absolute())})
@@ -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
@@ -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
@@ -577,5 +577,16 @@
"statements": [
"ALTER TABLE workspaces ADD COLUMN rejected_checkout_roots_json TEXT;"
]
},
{
"version": 72,
"name": "retain external finding import selections and provenance",
"statements": [
"CREATE TABLE external_finding_imports (\n id TEXT PRIMARY KEY,\n repository TEXT NOT NULL,\n created_at TEXT NOT NULL,\n provider TEXT NOT NULL,\n source_key TEXT NOT NULL,\n provenance_json TEXT,\n selection_json TEXT NOT NULL\n);",
"CREATE INDEX external_finding_imports_by_repository ON external_finding_imports (repository, created_at);",
"CREATE TABLE external_finding_import_members (\n import_id TEXT NOT NULL REFERENCES external_finding_imports(id),\n position INTEGER NOT NULL,\n finding_id TEXT NOT NULL REFERENCES external_source_reports(id),\n version INTEGER NOT NULL,\n PRIMARY KEY (import_id, position)\n) WITHOUT ROWID;",
"CREATE INDEX external_finding_members_by_version\nON external_finding_import_members (finding_id, version);",
"CREATE TABLE external_finding_publications (\n finding_id TEXT NOT NULL REFERENCES external_source_reports(id),\n version INTEGER NOT NULL,\n cloud_api_url TEXT NOT NULL,\n account_id TEXT NOT NULL,\n destination_id TEXT NOT NULL,\n receipt_id TEXT NOT NULL,\n outcome TEXT NOT NULL,\n cloud_finding_id TEXT,\n created_at TEXT NOT NULL,\n PRIMARY KEY (finding_id, version, cloud_api_url, account_id, destination_id, receipt_id)\n) WITHOUT ROWID;"
]
}
]
@@ -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 --snyk-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)
@@ -73,6 +73,9 @@ EXPECTED_TABLES = {
"deep_scan_runs",
"deep_scan_worker_threads",
"deep_scan_workers",
"external_finding_import_members",
"external_finding_imports",
"external_finding_publications",
"external_source_reports",
"finding_decisions",
"finding_dedupe_group_members",
@@ -142,6 +142,9 @@ def restore_v53_schema(state_dir: Path) -> None:
connection.execute("ALTER TABLE scans DROP COLUMN launch_package_version")
connection.execute("ALTER TABLE scans DROP COLUMN launch_surface")
connection.executescript("""
DROP TABLE external_finding_publications;
DROP TABLE external_finding_import_members;
DROP TABLE external_finding_imports;
DROP TRIGGER scans_assign_inserted_completion_sequence;
DROP TRIGGER scans_assign_updated_completion_sequence;
DROP INDEX scans_completion_sequence;
@@ -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"}
)
@@ -119,6 +119,7 @@ EXPECTED_MIGRATIONS = [
(69, "distinguish unvalidated workspace targets"),
(70, "retain checkout roots for Git discovery"),
(71, "retain rejected workspace checkout boundaries"),
(72, "retain external finding import selections and provenance"),
]
@@ -257,7 +258,8 @@ def test_repository_preview_history_keeps_original_application_times_after_budge
assert [
tuple(row)
for row in connection.execute(
"SELECT version, applied_at FROM schema_migrations WHERE version >= 67 ORDER BY version"
"SELECT version, applied_at FROM schema_migrations "
"WHERE version BETWEEN 67 AND 71 ORDER BY version"
)
] == [(version, f"preview-{version - 4}") for version in range(67, 72)]
assert (
@@ -3279,7 +3281,10 @@ def test_identity_migrations_skip_unavailable_historical_git(
(workspace_id, target_id, historical, timestamp, timestamp, timestamp),
)
apply_migrations(connection)
assert connection.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] == 71
assert (
connection.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0]
== EXPECTED_MIGRATIONS[-1][0]
)
assert tuple(
connection.execute(
"SELECT id, current_path, repository_identity FROM security_targets"
+101 -34
View File
@@ -629,7 +629,7 @@ available) or `SCAN_RESUME_UNAVAILABLE` for `scans resume`. Rerunning an importe
scan uses `SCAN_IMPORT_FAILED` if the import fails. YAML and TOON failures remain
on stderr without `--full-output`, or when retained results are unavailable.
Scan argument errors with `--full-output` and JSON or JSONL use an `ok: false`
Argument and execution errors with `--full-output` and JSON or JSONL use an `ok: false`
envelope with `error.code` and `error.message`. Command schema validation errors
with JSON or JSONL retain their field details and name missing or invalid
options by their CLI flags. Diagnostics stay on stderr.
@@ -724,8 +724,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:
@@ -770,16 +770,18 @@ from the config directory; scope paths resolve from the repository.
### Import findings as a saved scan
```bash
codex-security scan import --csv /path/to/findings.csv
codex-security scan import --json /path/to/findings.json --format json
codex-security scan import --csv /path/to/findings.csv --dry-run
codex-security scan import /path/to/findings.csv
codex-security scan import /path/to/findings.json --json
codex-security scan import /path/to/report --input-format csv --dry-run
```
Supply exactly one input. CSV follows the
[findings template](https://github.com/openai/codex-security/blob/main/examples/findings.csv).
JSON accepts a complete `codex-security.findings` document or
`{ "findings": [...] }` matching the findings schema. For this command, `--json`
selects the input file; use `--format json` for JSON output. The input must be a
`{ "findings": [...] }` matching the findings schema. The CLI infers the format from a `.csv` or `.json` suffix.
Use `--input-format csv|json` to override it. Put `--json` after the filename
to request JSON output. Existing scripts using `--csv FILE` or `--json FILE`
can continue to select the input that way. The input must be a
regular file with no symlinks or directory junctions in its path.
Each import creates a completed scan in local history, retains the input under
@@ -954,7 +956,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.
@@ -1406,6 +1408,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
@@ -1538,13 +1556,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`.
@@ -1561,8 +1579,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
@@ -1593,9 +1616,34 @@ 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 capture and returns its path. Preview
`import sonar --dry-run` writes a private evidence copy for both live and saved inputs and returns its path. Preview
that capture for the intended destination before confirming. A Cloud confirmation
saves the issues locally and publishes them. Use `--full-output` with
`--format json` or `--format jsonl` for a structured result.
@@ -1662,11 +1710,10 @@ Run the command with `--dry-run --format json`. Check `accountId`,
- **Private findings inbox.** If the preview includes `privateImport`, the
report goes to your inbox. The repository and connector identify the
suggested assessment target. Check `format`, `bytes` and `sha256` in
`privateImport` to identify the upload. For an Endor Finding, an Endor
`list.objects` response or a Wiz vulnerability JSON export, the CLI can
send the original bytes when Cloud accepts the format and every record
matches your selection. Other inputs, including arrays of selected Endor
Findings, use `security.findings.v1`.
`privateImport` to identify the upload. The CLI and SDK encode the reviewed
occurrences as `security.findings.v1` when it fits. For Wiz and Endor, an
inbox that requires native records or has a smaller upload limit can receive
native records that reproduce the reviewed evidence.
- **Repository publisher.** Check `repository.environment_id` in each entry
of `requests`. The publisher checks the current source versions. Existing
records keep their environment. New records use the repository's authorized
@@ -1695,10 +1742,10 @@ instructions. API requests always use the API root. The older
### Resume interrupted imports
If the result includes `savedSubmission`, keep that checkpoint. Rerun the
original command with `--dry-run --format json` using the same input, account,
original command with `--dry-run --format json` using the same build, input, account,
destination, API endpoint and state directory. Check `cloudApiUrl`. If
`resumed` is true, confirm to continue the saved submission. If it's false,
review the new submission before confirming.
review the new submission before confirming. Finish older-format pending submissions with the client that created them. If a response was lost, check the inbox job or repository records before starting a fresh upload.
- **Private inbox.** The CLI checks the report digest and reuses its saved
request IDs. It can read an accepted job even if the deployment has since
@@ -1808,8 +1855,8 @@ A dedicated login using automatic storage can publish if Codex Security
recorded the native file fallback. An unverified file can belong to another
account, so Cloud publication requires an explicit file store for an ambient login.
Use a positional scan directory or repeated `--scan-dir PATH` for artifacts
outside history. Each must contain one completed sealed scan, not a bulk-run
Use `publish scan DIR --to cloud` for one directory outside history. For
multiple directories, repeat `--scan-dir PATH`. Each must contain one completed sealed scan, not a bulk-run
directory or `results.jsonl`. Do not mix directories with `--scan`.
Cloud also accepts exported CSV:
@@ -1857,7 +1904,7 @@ codex-security publish check /path/to/completed-scan \
--linear-team TEAM_ID --json
```
`publish check` defaults to `--to linear`. It verifies artifacts and recorded publications. With an API key,
`publish check` verifies scan artifacts and recorded Linear publications. With an API key,
it also checks authentication and destination access. It does not test issue
creation; connected-app access is reported as `not-checked`.
@@ -2134,7 +2181,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. |
@@ -2230,7 +2277,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
@@ -2238,7 +2285,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,
@@ -2250,15 +2297,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
@@ -2346,6 +2400,10 @@ must already exist.
SARIF is the default format, and `./results.sarif` is the default output path.
Use `--export-format json` or `--export-format csv` to choose another format.
An existing default output file is preserved. Pass `--output FILE` to choose
a filename or explicitly replace it. Use `--output -` to pipe the complete
artifact. Response filters, token controls, and `--full-output` require a
command that returns a formatted response.
To select a saved scan by its ID and export JSON, run:
```bash
@@ -2804,11 +2862,20 @@ retain exit codes `130` and `143` without a result.
Start with `codex-security --help` for the task groups and shared output and agent options. Each command’s help shows its inputs and supported output formats. Use `import --help` to choose between a live collector, a saved scanner report, and a Codex Security CSV or JSON export.
Use `--llms` for the command manifest, `--llms-full` for argument details, and `scan --schema --format json` for the scan schema. The manifests and shell completion include `scan import` alongside the ordinary `scan [repository]` command. Generate completions with `completions bash|fish|nushell|zsh`. Scan output supports
Use `--llms` for the command manifest, `--llms-full` for argument details, and `scan --schema --format json` for the scan schema. The manifests and shell completion include `scan import` alongside the ordinary `scan [repository]` command. Generate completions with `completions bash|fish|nushell|zsh`. Add `--json` to return the generated script as a JSON string. The same option returns the menu text when an omitted command or subcommand displays help. With `--full-output`, the text is in `data`. Scan output supports
`--format toon|json|yaml|jsonl` and `--full-output`. The existing `--format`,
`--filter-output`, `--token-limit`, and `--token-offset` options accept either
`--option value` or `--option=value`.
`--token-limit` and `--token-offset` take nonnegative integers and select a
text view of the formatted result. Truncated JSON and JSONL views are returned
as a JSON string containing the excerpt and its token range. With
`--full-output`, the excerpt is in `data` and `meta.nextOffset` identifies
the next page when more tokens are available. `--token-count` returns the
estimated size instead. A failed full-output JSON or JSONL response always
retains its error code and message. If the failure carries result data,
`--token-count` reports its size in `meta.tokenCount`.
`skills add` syncs generated CLI command guidance; it does not install the full
Codex Security plugin. `mcp add` registers the CLI as an MCP server, exposing
only read-only `info` because the transport cannot cancel scans. For the plugin's
+77 -4
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
@@ -685,6 +689,68 @@ For issue tracking, see [Linear publication](cli.md#publish-completed-scans-to-l
### Import external findings
For an agent-written parser, use the normalized import API. Pass an absolute
checkout path, a stable source namespace and the repository URL when known.
Count each input occurrence in `read` and supply its evidence or a numbered
exclusion. Keep the upstream occurrence ID as a string.
```ts
import { prepareNormalizedLocalImport } from "@openai/codex-security";
const local = await prepareNormalizedLocalImport(
{
read: 1,
findings: [
{
source_finding_id: "17",
evidence: { title: "Unsafe eval", severity: "high" },
},
],
excluded: [],
},
{
repository: checkout,
provider: "example-scanner",
sourceKey: "payments/main",
sourceRepositoryUrl: scmUrl,
},
);
console.log(local.preview);
const { importId } = await local.import(); // After reviewing the preview.
```
A nonempty import returns an `importId`, including when every finding was
unchanged. Use `listLocalExternalImports({ repository })` to find an import.
`selectLocalExternalFindings({ repository, importId })` reads its members and
fails if a finding has since changed. To select individual findings across
imports, pass `{ repository, findings: [{ id, version }] }`.
```ts
import { prepareStoredFindingsPublication } from "@openai/codex-security";
const { groups, excluded } = await prepareStoredFindingsPublication(
{ repository: checkout, importId },
{ repository: cloudRepository },
);
console.log(
groups.map(({ preview }) => preview),
excluded,
);
```
Show the user all destinations, findings and exclusions together. For each
approved group, retain its selection and review ID, then call
`group.publish(approvedReviewId)`. Check the returned status, receipts and
per-item errors before proceeding. If a submission is interrupted, reprepare
that group and subsequent unstarted groups from their saved selections and use
the original review IDs. Report a terminal partial result with its exclusions
and errors. If the approved ID was lost or the preview changed, show the new
preview for review.
`listLocalFindingPublications({ repository, id })` returns receipts for a
stored version, including completed private inbox job IDs. Custom provider
names and Tenable can be used locally. Cloud eligibility follows its provider
contract and the selected destination.
For a saved scanner report, call `prepareLocalExternalImport` for a checkout
or `prepareExternalPublication` for a connected Cloud repository. Review the
returned `preview`, then call `import()` to save locally or `publish()` to
@@ -695,7 +761,7 @@ For normalized evidence, use `prepareNormalizedLocalImport(findings, options)`
or `prepareNormalizedExternalPublication(findings, options)` and review the
preview in the same way. Cloud file imports use `ExternalPublicationOptions`,
and normalized Cloud imports use `NormalizedExternalPublicationOptions`. Keep
Cloud receipts and saved requests when retrying an interrupted submission.
Cloud receipts and saved requests when retrying an interrupted submission. Use the SDK build that created a pending submission to finish it before upgrading.
Use `listLocalExternalFindings({ repository })` to read saved scanner evidence.
It starts unassessed. Reimporting the same repository, provider, source key
@@ -723,11 +789,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
+3 -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"
]
},
@@ -104,6 +105,7 @@
"smol-toml": "1.9.1",
"string-width": "8.3.0",
"strip-ansi": "7.2.0",
"tokenx": "1.6.0",
"yaml": "2.9.1",
"yauzl": "3.4.0",
"zod": "4.6.7"
+3
View File
@@ -71,6 +71,9 @@ importers:
strip-ansi:
specifier: 7.2.0
version: 7.2.0
tokenx:
specifier: 1.6.0
version: 1.6.0
yaml:
specifier: 2.9.1
version: 2.9.1
@@ -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 =

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