mirror of
https://github.com/openai/codex-security.git
synced 2026-11-23 09:59:21 +08:00
Merge main and reconcile saved findings with repository history
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -8,7 +8,7 @@ runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install Trivy
|
||||
uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0
|
||||
uses: taiki-e/install-action@c509219cf42fba86913069efd0ade2458c59337b # v2.90.1
|
||||
with:
|
||||
tool: trivy@0.76.1
|
||||
- name: Check for high and critical vulnerabilities
|
||||
|
||||
+13
-10
@@ -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 -->
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install ShellCheck and zizmor
|
||||
uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0
|
||||
uses: taiki-e/install-action@c509219cf42fba86913069efd0ade2458c59337b # v2.90.1
|
||||
with:
|
||||
tool: shellcheck@0.11.0,zizmor@1.30.1
|
||||
- name: Install actionlint
|
||||
|
||||
@@ -129,7 +129,9 @@ validation, severity classification, owner suggestions, and result handling.
|
||||
|
||||
Use `findings list` to browse saved findings across scans, `findings list --scan SCAN_ID`
|
||||
to inspect a previous scan, or `findings show OCCURRENCE_ID` for its details and history.
|
||||
See the [scan history guide](sdk/typescript/docs/cli.md#scan-history-and-reruns) for filters and pagination.
|
||||
Linked Git worktrees share scan history and saved findings when they use the same
|
||||
Codex Security state directory. Keep `CODEX_SECURITY_STATE_DIR` stable to retain
|
||||
that shared history and sign-in scope. See the [scan history guide](sdk/typescript/docs/cli.md#scan-history-and-reruns).
|
||||
|
||||
## Read existing Cloud findings
|
||||
|
||||
|
||||
@@ -5,5 +5,6 @@
|
||||
"@napi-rs/canvas-linux-x64-gnu@1.0.13": "https://github.com/Brooooooklyn/canvas/tree/00a115d9903647f116daf86eccd2c6ba36128371",
|
||||
"@napi-rs/canvas-linux-x64-gnu@1.1.0": "https://github.com/Brooooooklyn/canvas/tree/5246bbf5573fdf53b5672a4d096d4d8fa660a406",
|
||||
"@openai/codex@0.166.0-linux-x64": "https://github.com/openai/codex/tree/6ff1e1ca3b30fc8b914720681fcf5fe62e95f856",
|
||||
"@openai/codex@0.167.0-linux-x64": "https://github.com/openai/codex/tree/086ccc833bc9cf01024ad2dd6af7dbd421b6bf9a"
|
||||
"@openai/codex@0.167.0-linux-x64": "https://github.com/openai/codex/tree/086ccc833bc9cf01024ad2dd6af7dbd421b6bf9a",
|
||||
"@openai/codex@0.167.1-linux-x64": "https://github.com/openai/codex/tree/0a94398fa60c4fac0e7659e4213a0a36e613dd46"
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -36,6 +36,8 @@ codex-security info -c codex-security.yaml --json
|
||||
codex-security scan . -c codex-security.yaml --dry-run --json
|
||||
```
|
||||
|
||||
The init command prints a preview command using the file it created. On Windows the displayed command uses PowerShell syntax. It includes an editor schema hint when the package is installed in the project. With a global installation the starter contains an empty mapping, which you can replace with your settings. The CLI always validates the file with its bundled schema.
|
||||
|
||||
Check that the preview shows your intended repository and scope. To start the
|
||||
scan with those settings, keep the same file selection:
|
||||
|
||||
@@ -184,8 +186,8 @@ The resolver maps file keys to the existing SDK options:
|
||||
| `scan.deep.stop_after_no_new` | `stopAfterNoNew` | `--stop-after-no-new` |
|
||||
| `scan.deep.stop_after_consecutive_errors` | `stopAfterConsecutiveErrors` | No flag |
|
||||
| `scan.deep.max_discovery_runs` | `maxDiscoveryRuns` | `--max-discovery-runs` |
|
||||
| `scan.deep.max_time_hours` | `maxTimeHours` | `--max-time-hours` |
|
||||
| `scan.max_time_minutes` | `maxTimeMinutes` | `--max-time` |
|
||||
| `scan.deep.max_time_hours` | `maxTimeHours` | Legacy `--max-time-hours` (hours) |
|
||||
| `scan.max_time_minutes` | `maxTimeMinutes` | `--max-time` (minutes, preferred) |
|
||||
| `limits.max_cost_usd_per_scan` | `maxCostUsd` | `--max-cost` |
|
||||
| `policy.fail_on_severity` | `failureSeverity` | `--fail-on-severity` |
|
||||
| `output.directory` | `outputDir` | `--output-dir` |
|
||||
@@ -333,7 +335,8 @@ aliases there are errors, while equivalent durations are accepted.
|
||||
`max_cost_usd_per_scan` has the same meaning as `--max-cost`: an estimated limit for one
|
||||
scan attempt. In-flight work may exceed it. It is not a total budget for a batch or
|
||||
follow-up actions. `fail_on_severity` changes the exit status without filtering the
|
||||
retained findings.
|
||||
retained findings. A bounded scan cannot run `--patch` or `--validate`. Select a
|
||||
finding from the saved scan to patch or validate separately.
|
||||
|
||||
## Batch and component scans
|
||||
|
||||
@@ -349,6 +352,12 @@ context, prompts, per-attempt cost and investigation limits, and severity policy
|
||||
as `scan`. The investigation allowance applies independently to each scan, not
|
||||
planning, result matching, or total campaign time.
|
||||
|
||||
Use `--max-total-cost USD` for a whole invocation. It divides the estimate among
|
||||
explicit components or pending repository attempts, including retries. A tighter
|
||||
configured per-scan limit still applies. The total limit skips model-based matching
|
||||
and owner suggestions, including when `scan.owner_suggestions` is enabled. See the [component scan](../sdk/typescript/docs/cli.md#scan-project-components)
|
||||
and [bulk scan](../sdk/typescript/docs/cli.md#bulk-scans) guides for planning and recovery behavior.
|
||||
|
||||
A bulk CSV row's mode and scope override the file's defaults for that repository.
|
||||
Bulk checkouts are clean, shallow snapshots, so bulk scans accept repository or
|
||||
path scopes. A configured diff or working-tree scope is rejected before work
|
||||
@@ -410,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
```
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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,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).
|
||||
|
||||
|
||||
@@ -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)
|
||||
```
|
||||
@@ -30,7 +30,7 @@
|
||||
"pf:view": "PROMPTFOO_CONFIG_DIR=.promptfoo PROMPTFOO_DISABLE_WAL_MODE=true node --experimental-strip-types scripts/run-promptfoo.mts view"
|
||||
},
|
||||
"dependencies": {
|
||||
"@openai/codex-sdk": "0.167.0",
|
||||
"@openai/codex-sdk": "0.167.1",
|
||||
"promptfoo": "0.124.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+56
-56
@@ -9,8 +9,8 @@ overrides:
|
||||
minimatch@10: 11.0.2
|
||||
'@azure/identity@>=4.13.2 <=4.13.3>@azure/msal-node': 7.1.0
|
||||
promptfoo@0.124.1>@hono/node-server: 2.1.5
|
||||
'@openai/codex': 0.167.0
|
||||
'@openai/codex-sdk': 0.167.0
|
||||
'@openai/codex': 0.167.1
|
||||
'@openai/codex-sdk': 0.167.1
|
||||
ibm-cloud-sdk-core@5.6.0>axios: 1.20.0
|
||||
get-uri@8.0.1>basic-ftp: 6.2.1
|
||||
|
||||
@@ -19,8 +19,8 @@ importers:
|
||||
.:
|
||||
dependencies:
|
||||
'@openai/codex-sdk':
|
||||
specifier: 0.167.0
|
||||
version: 0.167.0
|
||||
specifier: 0.167.1
|
||||
version: 0.167.1
|
||||
promptfoo:
|
||||
specifier: 0.124.1
|
||||
version: 0.124.1(@types/json-schema@7.0.15)(@types/node@25.9.1)
|
||||
@@ -456,50 +456,50 @@ packages:
|
||||
'@neon-rs/load@0.0.4':
|
||||
resolution: {integrity: sha512-kTPhdZyTQxB+2wpiRcFWrDcejc4JI6tkPuS7UZCG4l6Zvc5kU/gGQ/ozvHTh1XR5tS+UlfAfGuPajjzQjCiHCw==}
|
||||
|
||||
'@nodable/entities@3.0.0':
|
||||
resolution: {integrity: sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw==}
|
||||
'@nodable/entities@3.1.0':
|
||||
resolution: {integrity: sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==}
|
||||
|
||||
'@openai/codex-sdk@0.167.0':
|
||||
resolution: {integrity: sha512-dps+zHZeB1MJIL9AO8Azasw5vvS8A5AyI/xmvnTObX8868/8uUeB/UHhuM9SJ4BcX0E6q46PnxuOPbJ2bqD+dA==}
|
||||
'@openai/codex-sdk@0.167.1':
|
||||
resolution: {integrity: sha512-EJHNG/bZ+/rptIIZMigTgnqrukDAgc/rmUBXLeDrFwOeunno7tQ4sWt/VPzeRXnKGq6yd4jprpgRlzgpYvayzQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@openai/codex@0.167.0':
|
||||
resolution: {integrity: sha512-1FSQgbTIKAdTub5Ln6z36NT4eXDmBRkinfigzycbgn9yLZdJ3UdkQZqr0N7jnl8/D1xxT/Pz3Fl2l7S2dmRaFA==}
|
||||
'@openai/codex@0.167.1':
|
||||
resolution: {integrity: sha512-39uApTRT9bkhE8tMXTIfZxaZ27oi7hPqWoF2Coyp+iQFAD3NVHgH838IYVUfJaX85leMSP2s4JOmVw0mMSCN5Q==}
|
||||
engines: {node: '>=16'}
|
||||
hasBin: true
|
||||
|
||||
'@openai/codex@0.167.0-darwin-arm64':
|
||||
resolution: {integrity: sha512-7YtMDZX/jbWH9+fCVQg7BVsov8WvBzu4iuedXJEDlUdZxaTrYX2bEQwHIn3p0gxgSMfm30HGK9+bZm1aGSZaHw==}
|
||||
'@openai/codex@0.167.1-darwin-arm64':
|
||||
resolution: {integrity: sha512-IMUByWGPhdbJFZzuk18iIdF/mfd21cPwalRTp5vGYIsOCyv3SJGRY5snbzZd0zO37WGuNjfUvH/62LvQHqNT2A==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@openai/codex@0.167.0-darwin-x64':
|
||||
resolution: {integrity: sha512-wKoBiI6SBSg8fqiEYEOJs/NM/ZzKaCgy1cseX9LJbuDq3GCCKkeW9BUGe1ZEkyhhZ5Yfj+HzdUfp698abP2tDA==}
|
||||
'@openai/codex@0.167.1-darwin-x64':
|
||||
resolution: {integrity: sha512-SwJf87Qtuktk8qHSDsbNkjVjOerqQRCBgdrqw6gvAlF3tO8UizEp/Vs8qQVznNI1aJfFc6GoJLvcgBGVWVylDg==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@openai/codex@0.167.0-linux-arm64':
|
||||
resolution: {integrity: sha512-5cv+sybRWqpRJL6KCv3YSnIx1GHRmjek997C38n1Zfno4HomKDLkNSjWLDOOc2+ISlVNSRRnySWq4zKmzlY12g==}
|
||||
'@openai/codex@0.167.1-linux-arm64':
|
||||
resolution: {integrity: sha512-z13jj4X4GDk7CTd1kXHkhXC8Gj8zomd1jYsU2//0KjevbLelPxowWLSTqIcR1rarJCtzveBHsS8gR7B9pAWB0g==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@openai/codex@0.167.0-linux-x64':
|
||||
resolution: {integrity: sha512-FNc7danfUng9Sp6w+Fh7kofNHHZpA6VMyNKWsWrS3OwHly69gywTWeiuwrUPXpJSho8Df4xqRsHfHRPzj7zYQg==}
|
||||
'@openai/codex@0.167.1-linux-x64':
|
||||
resolution: {integrity: sha512-qZteglyvMCj1QVymMyPyKdtw38HaXCv5gvw8WN+N0+JJstu3k/d8xiYj9ciL7OwFLhcujgP8bCGJgaREeqrHkw==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@openai/codex@0.167.0-win32-arm64':
|
||||
resolution: {integrity: sha512-dYeYQZ66LCNnFXyF5vHRsbJQLyfbY3G8vDyn6XG3NxcwMFz4stkgSdC94UPc1NhCxkhpufHlkAm1oe+Z28Pw5Q==}
|
||||
'@openai/codex@0.167.1-win32-arm64':
|
||||
resolution: {integrity: sha512-KFUMwSMBlQmabCSbpfv7AgouF+kNJE8iNw/nYv+IgHbHCY0v1pAzLFdt3BscYRUD+KNOeJqnp6n4xwCteA5OcQ==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@openai/codex@0.167.0-win32-x64':
|
||||
resolution: {integrity: sha512-duPCBwflc8qhQdLekbL8fDYF646tW4gj0/l9BDnsVhEzoqm6OwxMAJXDFwSOLUUJPCmjBeM+eHYAx4fP/hwfjg==}
|
||||
'@openai/codex@0.167.1-win32-x64':
|
||||
resolution: {integrity: sha512-yvUA7s46paDIT5I3Phz8KcoGpSGlWR3pOS0npqQ3LQMpjtTOBWoLPRdjuoKVreuKIuOLDMxwWCID4nwojbbrSA==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -1158,8 +1158,8 @@ packages:
|
||||
fast-xml-builder@1.3.1:
|
||||
resolution: {integrity: sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==}
|
||||
|
||||
fast-xml-parser@5.11.1:
|
||||
resolution: {integrity: sha512-TBw6K/fxoQGGjCmZDw9w/ZwP3uDcnTM4YH/g+PFRWr8sbe5idXtxNN6vITh4+1ruCZaho6uBFurElsA7F0zzgw==}
|
||||
fast-xml-parser@5.12.0:
|
||||
resolution: {integrity: sha512-/pXxRBtwxY9w8z7YbgsvIPPcPvFDsTbIkWwTQJhzNJPokj+TbN6ftmcv4j/pEQDvOCNnKGDzuk5Bo2oogIOiFg==}
|
||||
hasBin: true
|
||||
|
||||
fastest-levenshtein@1.0.16:
|
||||
@@ -1327,8 +1327,8 @@ packages:
|
||||
resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
is-unsafe@2.0.2:
|
||||
resolution: {integrity: sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==}
|
||||
is-unsafe@2.0.3:
|
||||
resolution: {integrity: sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==}
|
||||
|
||||
isexe@2.0.0:
|
||||
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
|
||||
@@ -1500,8 +1500,8 @@ packages:
|
||||
resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}
|
||||
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
|
||||
|
||||
node-forge@1.4.2:
|
||||
resolution: {integrity: sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==}
|
||||
node-forge@1.4.3:
|
||||
resolution: {integrity: sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==}
|
||||
engines: {node: '>= 6.13.0'}
|
||||
|
||||
node-int64@0.4.0:
|
||||
@@ -1864,8 +1864,8 @@ packages:
|
||||
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
strnum@2.4.2:
|
||||
resolution: {integrity: sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==}
|
||||
strnum@2.5.1:
|
||||
resolution: {integrity: sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==}
|
||||
|
||||
text-extensions@3.1.0:
|
||||
resolution: {integrity: sha512-anOjtXr8OT5w4vc/2mP4AYTCE0GWc/21icGmaHtBHnI7pN7o01a/oqG9m06/rGzoAsDm/WNzggBpqptuCmRlZQ==}
|
||||
@@ -2369,37 +2369,37 @@ snapshots:
|
||||
|
||||
'@neon-rs/load@0.0.4': {}
|
||||
|
||||
'@nodable/entities@3.0.0': {}
|
||||
'@nodable/entities@3.1.0': {}
|
||||
|
||||
'@openai/codex-sdk@0.167.0':
|
||||
'@openai/codex-sdk@0.167.1':
|
||||
dependencies:
|
||||
'@openai/codex': 0.167.0
|
||||
'@openai/codex': 0.167.1
|
||||
|
||||
'@openai/codex@0.167.0':
|
||||
'@openai/codex@0.167.1':
|
||||
optionalDependencies:
|
||||
'@openai/codex-darwin-arm64': '@openai/codex@0.167.0-darwin-arm64'
|
||||
'@openai/codex-darwin-x64': '@openai/codex@0.167.0-darwin-x64'
|
||||
'@openai/codex-linux-arm64': '@openai/codex@0.167.0-linux-arm64'
|
||||
'@openai/codex-linux-x64': '@openai/codex@0.167.0-linux-x64'
|
||||
'@openai/codex-win32-arm64': '@openai/codex@0.167.0-win32-arm64'
|
||||
'@openai/codex-win32-x64': '@openai/codex@0.167.0-win32-x64'
|
||||
'@openai/codex-darwin-arm64': '@openai/codex@0.167.1-darwin-arm64'
|
||||
'@openai/codex-darwin-x64': '@openai/codex@0.167.1-darwin-x64'
|
||||
'@openai/codex-linux-arm64': '@openai/codex@0.167.1-linux-arm64'
|
||||
'@openai/codex-linux-x64': '@openai/codex@0.167.1-linux-x64'
|
||||
'@openai/codex-win32-arm64': '@openai/codex@0.167.1-win32-arm64'
|
||||
'@openai/codex-win32-x64': '@openai/codex@0.167.1-win32-x64'
|
||||
|
||||
'@openai/codex@0.167.0-darwin-arm64':
|
||||
'@openai/codex@0.167.1-darwin-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-darwin-x64':
|
||||
'@openai/codex@0.167.1-darwin-x64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-linux-arm64':
|
||||
'@openai/codex@0.167.1-linux-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-linux-x64':
|
||||
'@openai/codex@0.167.1-linux-x64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-win32-arm64':
|
||||
'@openai/codex@0.167.1-win32-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-win32-x64':
|
||||
'@openai/codex@0.167.1-win32-x64':
|
||||
optional: true
|
||||
|
||||
'@opentelemetry/api-logs@0.222.0':
|
||||
@@ -2980,13 +2980,13 @@ snapshots:
|
||||
path-expression-matcher: 1.6.2
|
||||
xml-naming: 0.3.0
|
||||
|
||||
fast-xml-parser@5.11.1:
|
||||
fast-xml-parser@5.12.0:
|
||||
dependencies:
|
||||
'@nodable/entities': 3.0.0
|
||||
'@nodable/entities': 3.1.0
|
||||
fast-xml-builder: 1.3.1
|
||||
is-unsafe: 2.0.2
|
||||
is-unsafe: 2.0.3
|
||||
path-expression-matcher: 1.6.2
|
||||
strnum: 2.4.2
|
||||
strnum: 2.5.1
|
||||
xml-naming: 0.3.0
|
||||
|
||||
fastest-levenshtein@1.0.16: {}
|
||||
@@ -3188,7 +3188,7 @@ snapshots:
|
||||
|
||||
is-unicode-supported@2.1.0: {}
|
||||
|
||||
is-unsafe@2.0.2: {}
|
||||
is-unsafe@2.0.3: {}
|
||||
|
||||
isexe@2.0.0: {}
|
||||
|
||||
@@ -3202,7 +3202,7 @@ snapshots:
|
||||
|
||||
jks-js@1.1.7:
|
||||
dependencies:
|
||||
node-forge: 1.4.2
|
||||
node-forge: 1.4.3
|
||||
node-int64: 0.4.0
|
||||
node-rsa: 1.1.1
|
||||
optional: true
|
||||
@@ -3365,7 +3365,7 @@ snapshots:
|
||||
fetch-blob: 3.2.0
|
||||
formdata-polyfill: 4.0.10
|
||||
|
||||
node-forge@1.4.2:
|
||||
node-forge@1.4.3:
|
||||
optional: true
|
||||
|
||||
node-int64@0.4.0:
|
||||
@@ -3523,7 +3523,7 @@ snapshots:
|
||||
exsolve: 1.1.1
|
||||
fast-deep-equal: 3.1.3
|
||||
fast-safe-stringify: 2.1.1
|
||||
fast-xml-parser: 5.11.1
|
||||
fast-xml-parser: 5.12.0
|
||||
fastest-levenshtein: 1.0.16
|
||||
gcp-metadata: 9.0.3
|
||||
glob: 14.0.3
|
||||
@@ -3565,7 +3565,7 @@ snapshots:
|
||||
'@googleapis/sheets': 18.1.1
|
||||
'@modelcontextprotocol/sdk': 1.32.2(zod@4.6.7)
|
||||
'@modelcontextprotocol/server-filesystem': 2026.8.31(zod@4.6.7)
|
||||
'@openai/codex-sdk': 0.167.0
|
||||
'@openai/codex-sdk': 0.167.1
|
||||
'@smithy/node-http-handler': 4.12.1
|
||||
google-auth-library: 11.2.0
|
||||
hono: 4.13.13
|
||||
@@ -3866,7 +3866,7 @@ snapshots:
|
||||
dependencies:
|
||||
ansi-regex: 6.3.0
|
||||
|
||||
strnum@2.4.2:
|
||||
strnum@2.5.1:
|
||||
dependencies:
|
||||
anynum: 1.0.1
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -31,7 +31,14 @@ export async function prepareRoutingEval(root: string) {
|
||||
});
|
||||
}
|
||||
const skills: Skill[] = [];
|
||||
for (const name of (await readdir(join(runtime, "skills"))).sort()) {
|
||||
const entries = await readdir(join(runtime, "skills"), {
|
||||
withFileTypes: true,
|
||||
});
|
||||
const skillNames = entries
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
for (const name of skillNames) {
|
||||
const source = await readFile(
|
||||
join(runtime, "skills", name, "SKILL.md"),
|
||||
"utf8",
|
||||
|
||||
@@ -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. |
|
||||
|
||||
@@ -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()
|
||||
@@ -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
@@ -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);
|
||||
|
||||
Generated
+2
-2
@@ -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,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",
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.32.2",
|
||||
"@openai/codex-sdk": "0.167.0",
|
||||
"@openai/codex-sdk": "0.167.1",
|
||||
"ajv": "8.20.0",
|
||||
"fzstd": "0.1.1",
|
||||
"smol-toml": "1.9.1",
|
||||
|
||||
+33
-33
@@ -12,8 +12,8 @@ importers:
|
||||
specifier: ^1.32.2
|
||||
version: 1.32.2(zod@4.6.7)
|
||||
'@openai/codex-sdk':
|
||||
specifier: 0.167.0
|
||||
version: 0.167.0
|
||||
specifier: 0.167.1
|
||||
version: 0.167.1
|
||||
ajv:
|
||||
specifier: 8.20.0
|
||||
version: 8.20.0
|
||||
@@ -217,47 +217,47 @@ packages:
|
||||
'@cfworker/json-schema':
|
||||
optional: true
|
||||
|
||||
'@openai/codex-sdk@0.167.0':
|
||||
resolution: {integrity: sha512-dps+zHZeB1MJIL9AO8Azasw5vvS8A5AyI/xmvnTObX8868/8uUeB/UHhuM9SJ4BcX0E6q46PnxuOPbJ2bqD+dA==}
|
||||
'@openai/codex-sdk@0.167.1':
|
||||
resolution: {integrity: sha512-EJHNG/bZ+/rptIIZMigTgnqrukDAgc/rmUBXLeDrFwOeunno7tQ4sWt/VPzeRXnKGq6yd4jprpgRlzgpYvayzQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@openai/codex@0.167.0':
|
||||
resolution: {integrity: sha512-1FSQgbTIKAdTub5Ln6z36NT4eXDmBRkinfigzycbgn9yLZdJ3UdkQZqr0N7jnl8/D1xxT/Pz3Fl2l7S2dmRaFA==}
|
||||
'@openai/codex@0.167.1':
|
||||
resolution: {integrity: sha512-39uApTRT9bkhE8tMXTIfZxaZ27oi7hPqWoF2Coyp+iQFAD3NVHgH838IYVUfJaX85leMSP2s4JOmVw0mMSCN5Q==}
|
||||
engines: {node: '>=16'}
|
||||
hasBin: true
|
||||
|
||||
'@openai/codex@0.167.0-darwin-arm64':
|
||||
resolution: {integrity: sha512-7YtMDZX/jbWH9+fCVQg7BVsov8WvBzu4iuedXJEDlUdZxaTrYX2bEQwHIn3p0gxgSMfm30HGK9+bZm1aGSZaHw==}
|
||||
'@openai/codex@0.167.1-darwin-arm64':
|
||||
resolution: {integrity: sha512-IMUByWGPhdbJFZzuk18iIdF/mfd21cPwalRTp5vGYIsOCyv3SJGRY5snbzZd0zO37WGuNjfUvH/62LvQHqNT2A==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@openai/codex@0.167.0-darwin-x64':
|
||||
resolution: {integrity: sha512-wKoBiI6SBSg8fqiEYEOJs/NM/ZzKaCgy1cseX9LJbuDq3GCCKkeW9BUGe1ZEkyhhZ5Yfj+HzdUfp698abP2tDA==}
|
||||
'@openai/codex@0.167.1-darwin-x64':
|
||||
resolution: {integrity: sha512-SwJf87Qtuktk8qHSDsbNkjVjOerqQRCBgdrqw6gvAlF3tO8UizEp/Vs8qQVznNI1aJfFc6GoJLvcgBGVWVylDg==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@openai/codex@0.167.0-linux-arm64':
|
||||
resolution: {integrity: sha512-5cv+sybRWqpRJL6KCv3YSnIx1GHRmjek997C38n1Zfno4HomKDLkNSjWLDOOc2+ISlVNSRRnySWq4zKmzlY12g==}
|
||||
'@openai/codex@0.167.1-linux-arm64':
|
||||
resolution: {integrity: sha512-z13jj4X4GDk7CTd1kXHkhXC8Gj8zomd1jYsU2//0KjevbLelPxowWLSTqIcR1rarJCtzveBHsS8gR7B9pAWB0g==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@openai/codex@0.167.0-linux-x64':
|
||||
resolution: {integrity: sha512-FNc7danfUng9Sp6w+Fh7kofNHHZpA6VMyNKWsWrS3OwHly69gywTWeiuwrUPXpJSho8Df4xqRsHfHRPzj7zYQg==}
|
||||
'@openai/codex@0.167.1-linux-x64':
|
||||
resolution: {integrity: sha512-qZteglyvMCj1QVymMyPyKdtw38HaXCv5gvw8WN+N0+JJstu3k/d8xiYj9ciL7OwFLhcujgP8bCGJgaREeqrHkw==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@openai/codex@0.167.0-win32-arm64':
|
||||
resolution: {integrity: sha512-dYeYQZ66LCNnFXyF5vHRsbJQLyfbY3G8vDyn6XG3NxcwMFz4stkgSdC94UPc1NhCxkhpufHlkAm1oe+Z28Pw5Q==}
|
||||
'@openai/codex@0.167.1-win32-arm64':
|
||||
resolution: {integrity: sha512-KFUMwSMBlQmabCSbpfv7AgouF+kNJE8iNw/nYv+IgHbHCY0v1pAzLFdt3BscYRUD+KNOeJqnp6n4xwCteA5OcQ==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@openai/codex@0.167.0-win32-x64':
|
||||
resolution: {integrity: sha512-duPCBwflc8qhQdLekbL8fDYF646tW4gj0/l9BDnsVhEzoqm6OwxMAJXDFwSOLUUJPCmjBeM+eHYAx4fP/hwfjg==}
|
||||
'@openai/codex@0.167.1-win32-x64':
|
||||
resolution: {integrity: sha512-yvUA7s46paDIT5I3Phz8KcoGpSGlWR3pOS0npqQ3LQMpjtTOBWoLPRdjuoKVreuKIuOLDMxwWCID4nwojbbrSA==}
|
||||
engines: {node: '>=16'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -875,35 +875,35 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@openai/codex-sdk@0.167.0':
|
||||
'@openai/codex-sdk@0.167.1':
|
||||
dependencies:
|
||||
'@openai/codex': 0.167.0
|
||||
'@openai/codex': 0.167.1
|
||||
|
||||
'@openai/codex@0.167.0':
|
||||
'@openai/codex@0.167.1':
|
||||
optionalDependencies:
|
||||
'@openai/codex-darwin-arm64': '@openai/codex@0.167.0-darwin-arm64'
|
||||
'@openai/codex-darwin-x64': '@openai/codex@0.167.0-darwin-x64'
|
||||
'@openai/codex-linux-arm64': '@openai/codex@0.167.0-linux-arm64'
|
||||
'@openai/codex-linux-x64': '@openai/codex@0.167.0-linux-x64'
|
||||
'@openai/codex-win32-arm64': '@openai/codex@0.167.0-win32-arm64'
|
||||
'@openai/codex-win32-x64': '@openai/codex@0.167.0-win32-x64'
|
||||
'@openai/codex-darwin-arm64': '@openai/codex@0.167.1-darwin-arm64'
|
||||
'@openai/codex-darwin-x64': '@openai/codex@0.167.1-darwin-x64'
|
||||
'@openai/codex-linux-arm64': '@openai/codex@0.167.1-linux-arm64'
|
||||
'@openai/codex-linux-x64': '@openai/codex@0.167.1-linux-x64'
|
||||
'@openai/codex-win32-arm64': '@openai/codex@0.167.1-win32-arm64'
|
||||
'@openai/codex-win32-x64': '@openai/codex@0.167.1-win32-x64'
|
||||
|
||||
'@openai/codex@0.167.0-darwin-arm64':
|
||||
'@openai/codex@0.167.1-darwin-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-darwin-x64':
|
||||
'@openai/codex@0.167.1-darwin-x64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-linux-arm64':
|
||||
'@openai/codex@0.167.1-linux-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-linux-x64':
|
||||
'@openai/codex@0.167.1-linux-x64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-win32-arm64':
|
||||
'@openai/codex@0.167.1-win32-arm64':
|
||||
optional: true
|
||||
|
||||
'@openai/codex@0.167.0-win32-x64':
|
||||
'@openai/codex@0.167.1-win32-x64':
|
||||
optional: true
|
||||
|
||||
'@types/node@26.6.6':
|
||||
|
||||
@@ -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,7 +14,11 @@ export interface Migration {
|
||||
statements: readonly string[];
|
||||
}
|
||||
|
||||
export const migrations: readonly Migration[] = history;
|
||||
// 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.version === 72,
|
||||
);
|
||||
const migration = (version: number) =>
|
||||
migrations.find((item) => item.version === version)!;
|
||||
|
||||
@@ -130,9 +134,16 @@ export function stableTargetId(path: string): string {
|
||||
}
|
||||
|
||||
function backfillTargets(database: DatabaseSync): void {
|
||||
const validatedWorkspace = columns(database, "workspaces").has(
|
||||
"target_path_unvalidated",
|
||||
)
|
||||
? " AND target_path_unvalidated = 0"
|
||||
: "";
|
||||
const targets = database
|
||||
.prepare(
|
||||
"SELECT target_path FROM workspaces WHERE target_path IS NOT NULL UNION SELECT target_path FROM scans",
|
||||
"SELECT target_path FROM workspaces WHERE target_path IS NOT NULL" +
|
||||
validatedWorkspace +
|
||||
" UNION SELECT target_path FROM scans",
|
||||
)
|
||||
.all();
|
||||
const lookup = database.prepare(
|
||||
@@ -152,7 +163,8 @@ function backfillTargets(database: DatabaseSync): void {
|
||||
for (const table of ["workspaces", "scans"]) {
|
||||
database
|
||||
.prepare(
|
||||
`UPDATE ${table} SET target_id = ? WHERE target_path = ? AND target_id IS NULL`,
|
||||
`UPDATE ${table} SET target_id = ? WHERE target_path = ? AND target_id IS NULL` +
|
||||
(table === "workspaces" ? validatedWorkspace : ""),
|
||||
)
|
||||
.run(id, path);
|
||||
}
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
[
|
||||
{
|
||||
"version": 43,
|
||||
"name": "persist repository identities",
|
||||
"statements": [
|
||||
"ALTER TABLE security_targets\n ADD COLUMN repository_identity TEXT;",
|
||||
"CREATE INDEX security_targets_by_repository_identity\n ON security_targets(repository_identity);",
|
||||
"ALTER TABLE scans\n ADD COLUMN repository_generation TEXT;",
|
||||
"CREATE INDEX scans_by_repository_generation\n ON scans(repository_generation);",
|
||||
"CREATE INDEX scans_by_target_path\n ON scans(target_path);",
|
||||
"ALTER TABLE scans\n ADD COLUMN completion_sequence INTEGER CHECK (completion_sequence >= 1);",
|
||||
"CREATE UNIQUE INDEX scans_completion_sequence\n ON scans(completion_sequence);",
|
||||
"CREATE TRIGGER scans_assign_inserted_completion_sequence\n AFTER INSERT ON scans\n WHEN NEW.status = 'complete' AND NEW.completion_sequence IS NULL\n BEGIN\n UPDATE scans\n SET completion_sequence = (\n SELECT COALESCE(MAX(completion_sequence), 0) + 1 FROM scans\n )\n WHERE id = NEW.id AND completion_sequence IS NULL;\n END;",
|
||||
"CREATE TRIGGER scans_assign_updated_completion_sequence\n AFTER UPDATE OF status ON scans\n WHEN NEW.status = 'complete' AND NEW.completion_sequence IS NULL\n BEGIN\n UPDATE scans\n SET completion_sequence = (\n SELECT COALESCE(MAX(completion_sequence), 0) + 1 FROM scans\n )\n WHERE id = NEW.id AND completion_sequence IS NULL;\n END;"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": 44,
|
||||
"name": "stabilize Linux repository generations",
|
||||
"statements": []
|
||||
}
|
||||
]
|
||||
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
||||
export function createTemporaryDirectories(
|
||||
canonicalize = false,
|
||||
removeDirectory = (root: string) =>
|
||||
rm(root, { recursive: true, force: true }),
|
||||
rm(root, { recursive: true, force: true, maxRetries: 10 }),
|
||||
) {
|
||||
const roots: string[] = [];
|
||||
return {
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createHash } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { mkdir, stat, symlink } from "node:fs/promises";
|
||||
import { copyFile, mkdir, readFile, stat, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { after, test, type TestContext } from "node:test";
|
||||
import { Worker } from "node:worker_threads";
|
||||
import { importSource } from "./import-module.ts";
|
||||
import { createTemporaryDirectories } from "./support/temporary-directories.ts";
|
||||
import workbenchMigrations from "../../shared/workbench-migrations.json" with { type: "json" };
|
||||
import type * as Database from "../src/workbench/database.ts";
|
||||
import type * as Migrations from "../src/workbench/migrations.ts";
|
||||
|
||||
@@ -28,6 +31,17 @@ const { openWorkbenchDatabase, databaseInfo } = (await importSource(
|
||||
const { applyMigrations, migrations } = (await importSource(
|
||||
"src/workbench/migrations.ts",
|
||||
)) as typeof Migrations;
|
||||
// Frozen from 7fa0980411d89d7d1f2aafd5b2cbae941f539724, before severity migration 43.
|
||||
const historicalRepositoryMigrations: readonly Migrations.Migration[] =
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
"./fixtures/pre-severity-repository-migrations.json",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const temporary = createTemporaryDirectories(true);
|
||||
after(() => temporary.cleanup());
|
||||
|
||||
@@ -65,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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -718,7 +732,7 @@ test("database-info retains scan names from installed migration 42", async () =>
|
||||
await databaseInfo(directory);
|
||||
const upgraded = new DatabaseSync(databasePath);
|
||||
try {
|
||||
assertMigrationNames(upgraded, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51);
|
||||
assertMigrationNames(upgraded, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52);
|
||||
assert.equal(storedValue(upgraded, "scans", "name"), "Original scan");
|
||||
assert.equal(storedValue(upgraded, "scans", "source_scopes_json"), null);
|
||||
assert.equal(
|
||||
@@ -1012,6 +1026,57 @@ test("repairs recorded Deep Scan and target migrations and backfills stable iden
|
||||
assert.equal(storedValue(database, "scans", "target_id"), null);
|
||||
});
|
||||
|
||||
test("stable target repairs leave unvalidated setup paths unbound", (t) => {
|
||||
const database = memory(t, 53);
|
||||
insertScan(database);
|
||||
database.exec(`
|
||||
ALTER TABLE workspaces ADD COLUMN target_path_unvalidated INTEGER NOT NULL
|
||||
DEFAULT 0 CHECK (target_path_unvalidated IN (0, 1));
|
||||
INSERT INTO workspaces (
|
||||
id, target_path, target_path_unvalidated, created_at, updated_at
|
||||
) VALUES
|
||||
('unvalidated', '/synthetic/missing', 1, 'created', 'updated'),
|
||||
('unvalidated-shared', '/synthetic/repository', 1, 'created', 'updated');
|
||||
`);
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
database.exec("DROP INDEX scans_by_target");
|
||||
applyMigrations(database);
|
||||
const targetId = database
|
||||
.prepare(
|
||||
"SELECT id FROM security_targets WHERE current_path = '/synthetic/repository'",
|
||||
)
|
||||
.get()?.id;
|
||||
assert.equal(typeof targetId, "string");
|
||||
assert.equal(
|
||||
database.prepare("SELECT target_id FROM scans").get()?.target_id,
|
||||
targetId,
|
||||
);
|
||||
assert.deepEqual(
|
||||
database
|
||||
.prepare(
|
||||
"SELECT id, target_id, target_path_unvalidated FROM workspaces ORDER BY id",
|
||||
)
|
||||
.all()
|
||||
.map((row) => ({ ...row })),
|
||||
[
|
||||
{ id: "unvalidated", target_id: null, target_path_unvalidated: 1 },
|
||||
{
|
||||
id: "unvalidated-shared",
|
||||
target_id: null,
|
||||
target_path_unvalidated: 1,
|
||||
},
|
||||
{ id: "workspace", target_id: targetId, target_path_unvalidated: 0 },
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
database.prepare("SELECT COUNT(*) AS count FROM security_targets").get()
|
||||
?.count,
|
||||
1,
|
||||
);
|
||||
assert.deepEqual(database.prepare("PRAGMA foreign_key_check").all(), []);
|
||||
}
|
||||
});
|
||||
|
||||
test("recorded additive migrations restore missing columns and configured error thresholds", (t) => {
|
||||
const database = memory(t, 26);
|
||||
insertScan(database);
|
||||
@@ -1021,7 +1086,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(
|
||||
@@ -1299,3 +1364,481 @@ test("retries an upgrade when another process holds the write lock beyond the bu
|
||||
await writer.terminate();
|
||||
}
|
||||
});
|
||||
|
||||
function pythonMigrations(databasePath: string, through?: number): void {
|
||||
const result = spawnSync(
|
||||
process.env.PYTHON?.trim() || "python3",
|
||||
[
|
||||
"-I",
|
||||
"-B",
|
||||
"-c",
|
||||
`import sqlite3, sys
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import workbench_db, workbench_schema
|
||||
with sqlite3.connect(sys.argv[2]) as database:
|
||||
database.row_factory = sqlite3.Row
|
||||
database.execute("PRAGMA foreign_keys = ON")
|
||||
workbench_schema.apply_migrations(database,
|
||||
tuple(item for item in workbench_db.MIGRATIONS if item[0] <= int(sys.argv[3])),
|
||||
workbench_db.now, workbench_db.backfill_security_targets)
|
||||
`,
|
||||
fileURLToPath(new URL("../../scripts", import.meta.url)),
|
||||
databasePath,
|
||||
String(through ?? workbenchMigrations.at(-1)!.version),
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
assert.equal(result.status, 0, result.stderr || String(result.error));
|
||||
}
|
||||
|
||||
function storedRows(database: DatabaseSync) {
|
||||
return database
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",
|
||||
)
|
||||
.all()
|
||||
.map(({ name }) => {
|
||||
const rows = database.prepare(`SELECT * FROM "${name}"`);
|
||||
rows.setReadBigInts(true);
|
||||
return [
|
||||
name,
|
||||
rows.all().map((row) => {
|
||||
// Independently run initializers use different migration application times.
|
||||
if (name === "schema_migrations") delete row.applied_at;
|
||||
return row;
|
||||
}),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
test("Node initialization leaves repository migration semantics to the Python consumer", async (t) => {
|
||||
// Published schema version, followed by the historical identity migration range if installed.
|
||||
const fixtures: [string, number, number?, number?][] = [
|
||||
["main42", 42],
|
||||
["main43", 43],
|
||||
["main53", 53],
|
||||
["main60", 60],
|
||||
["main62", 62],
|
||||
["preview62", 60, 61, 62],
|
||||
["preview64MainReader", 60, 61, 64],
|
||||
["legacy30", 29],
|
||||
["legacy31", 30],
|
||||
["partial43", 42],
|
||||
["current43", 42, 43, 43],
|
||||
["current44", 42, 43, 44],
|
||||
["current48", 47, 48, 48],
|
||||
["current49", 47, 48, 49],
|
||||
["current50", 49, 50, 50],
|
||||
["current51", 49, 50, 51],
|
||||
["preview52and53", 51, 52, 53],
|
||||
["current53", 52, 53, 53],
|
||||
["current54", 52, 53, 54],
|
||||
["current56", 53, 54, 56],
|
||||
];
|
||||
for (const [
|
||||
fixture,
|
||||
publishedVersion,
|
||||
identityVersion,
|
||||
currentVersion,
|
||||
] of fixtures) {
|
||||
await t.test(fixture, async () => {
|
||||
const directory = await temporary.create("workbench-repository-upgrade-");
|
||||
const databasePath = join(directory, "workbench.sqlite3");
|
||||
const database = new DatabaseSync(databasePath);
|
||||
applyMigrations(
|
||||
database,
|
||||
migrations.filter((item) => item.version <= publishedVersion),
|
||||
);
|
||||
insertScan(database);
|
||||
database.exec(`INSERT INTO security_targets (id,current_path,display_name,created_at,updated_at)
|
||||
VALUES ('target','/synthetic/repository','Synthetic repository','created','updated');
|
||||
UPDATE workspaces SET target_id='target'; UPDATE scans SET target_id='target';
|
||||
UPDATE scans SET status='complete', started_at='2026-01-01T00:00:00Z',
|
||||
completed_at='2026-01-01T00:00:01.123456789123z';`);
|
||||
if (fixture === "main53")
|
||||
database.exec(`INSERT INTO external_source_reports
|
||||
(id,repository,provider,source_key,source_finding_id,evidence_json,version,created_at,updated_at)
|
||||
VALUES ('report','/synthetic/repository','synthetic','source','finding','{"title":"Saved report"}',1,'created','updated')`);
|
||||
if (["legacy30", "legacy31", "partial43"].includes(fixture)) {
|
||||
database.exec(
|
||||
"ALTER TABLE security_targets ADD COLUMN repository_identity TEXT",
|
||||
);
|
||||
database.exec(
|
||||
"UPDATE security_targets SET repository_identity='unestablished-legacy-identity'",
|
||||
);
|
||||
}
|
||||
if (fixture === "legacy30" || fixture === "legacy31")
|
||||
database
|
||||
.prepare(
|
||||
"INSERT INTO schema_migrations VALUES(?,'persist repository identities','original')",
|
||||
)
|
||||
.run(fixture === "legacy30" ? 30 : 31);
|
||||
database.close();
|
||||
if (identityVersion !== undefined && currentVersion !== undefined) {
|
||||
const current = new DatabaseSync(databasePath);
|
||||
applyMigrations(
|
||||
current,
|
||||
historicalRepositoryMigrations
|
||||
.map((item) => ({
|
||||
...item,
|
||||
version: item.version - 43 + identityVersion,
|
||||
}))
|
||||
.filter((item) => item.version <= currentVersion),
|
||||
);
|
||||
if (currentVersion === 56)
|
||||
current.exec(`ALTER TABLE workspaces ADD COLUMN target_path_unvalidated INTEGER
|
||||
NOT NULL DEFAULT 0 CHECK (target_path_unvalidated IN (0, 1));
|
||||
INSERT INTO schema_migrations VALUES (56, 'distinguish unvalidated workspace targets', 'original');`);
|
||||
if (fixture === "preview64MainReader")
|
||||
current.exec(`ALTER TABLE workspaces ADD COLUMN target_path_unvalidated INTEGER
|
||||
NOT NULL DEFAULT 0 CHECK (target_path_unvalidated IN (0, 1));
|
||||
ALTER TABLE security_targets ADD COLUMN git_checkout_root TEXT;
|
||||
INSERT INTO schema_migrations VALUES (63, 'distinguish unvalidated workspace targets', 'original');
|
||||
INSERT INTO schema_migrations VALUES (64, 'retain checkout roots for Git discovery', 'original');
|
||||
ALTER TABLE scans ADD COLUMN launch_surface TEXT;`);
|
||||
assert.equal(
|
||||
current
|
||||
.prepare("SELECT MAX(version) AS version FROM schema_migrations")
|
||||
.get()?.version,
|
||||
currentVersion,
|
||||
);
|
||||
current.exec(
|
||||
"UPDATE scans SET completion_sequence=77,repository_generation='synthetic-generation'; UPDATE security_targets SET repository_identity='synthetic-generation'",
|
||||
);
|
||||
current.close();
|
||||
}
|
||||
const saved = new DatabaseSync(databasePath);
|
||||
const originalReports =
|
||||
fixture === "main53"
|
||||
? saved.prepare("SELECT * FROM external_source_reports").all()
|
||||
: [];
|
||||
const originalHistory = saved
|
||||
.prepare(
|
||||
"SELECT name, applied_at FROM schema_migrations WHERE name IN ('persist repository identities', 'stabilize Linux repository generations', 'distinguish unvalidated workspace targets') ORDER BY name",
|
||||
)
|
||||
.all();
|
||||
saved.close();
|
||||
const controlPath = join(directory, "python.sqlite3");
|
||||
await copyFile(databasePath, controlPath);
|
||||
pythonMigrations(controlPath);
|
||||
await databaseInfo(directory);
|
||||
const initialized = new DatabaseSync(databasePath);
|
||||
assertMigrationNames(initialized, 48, 49, 53, 54, 55, 56, 60, 72);
|
||||
assert.deepEqual(
|
||||
initialized.prepare("SELECT * FROM external_source_reports").all(),
|
||||
originalReports,
|
||||
);
|
||||
const identity = initialized
|
||||
.prepare("SELECT * FROM security_targets")
|
||||
.get()?.repository_identity;
|
||||
assert.equal(
|
||||
identity,
|
||||
currentVersion !== undefined
|
||||
? "synthetic-generation"
|
||||
: fixture.startsWith("main")
|
||||
? undefined
|
||||
: "unestablished-legacy-identity",
|
||||
);
|
||||
assert.equal(
|
||||
initialized
|
||||
.prepare("PRAGMA table_info(scans)")
|
||||
.all()
|
||||
.some((row) => row.name === "repository_generation"),
|
||||
currentVersion !== undefined,
|
||||
);
|
||||
const beforeRepeat = storedRows(initialized);
|
||||
initialized.close();
|
||||
await databaseInfo(directory);
|
||||
const repeated = new DatabaseSync(databasePath);
|
||||
assert.deepEqual(storedRows(repeated), beforeRepeat);
|
||||
repeated.close();
|
||||
pythonMigrations(databasePath);
|
||||
const actual = new DatabaseSync(databasePath);
|
||||
const expected = new DatabaseSync(controlPath);
|
||||
try {
|
||||
assert.deepEqual(storedRows(actual), storedRows(expected));
|
||||
assert.deepEqual(
|
||||
actual.prepare("SELECT * FROM external_source_reports").all(),
|
||||
originalReports,
|
||||
);
|
||||
for (const row of originalHistory)
|
||||
assert.equal(
|
||||
actual
|
||||
.prepare("SELECT applied_at FROM schema_migrations WHERE name=?")
|
||||
.get(row.name!)?.applied_at,
|
||||
row.applied_at,
|
||||
);
|
||||
assert.equal(
|
||||
actual
|
||||
.prepare("SELECT MAX(version) AS version FROM schema_migrations")
|
||||
.get()?.version,
|
||||
workbenchMigrations.at(-1)!.version,
|
||||
);
|
||||
assert.equal(
|
||||
actual.prepare("SELECT completion_sequence FROM scans").get()
|
||||
?.completion_sequence,
|
||||
currentVersion !== undefined ? 77 : 1,
|
||||
);
|
||||
assert.deepEqual(actual.prepare("PRAGMA foreign_key_check").all(), []);
|
||||
} finally {
|
||||
actual.close();
|
||||
expected.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("Node repository migration-label collisions roll back without changing stored rows", async (t) => {
|
||||
for (const [name, setup] of [
|
||||
[
|
||||
"identity destination",
|
||||
"UPDATE schema_migrations SET name='persist repository identities' WHERE version=31; INSERT INTO schema_migrations VALUES(67,'persist repository identities','original')",
|
||||
],
|
||||
[
|
||||
"generation destination",
|
||||
"UPDATE schema_migrations SET name='stabilize Linux repository generations' WHERE version=44; INSERT INTO schema_migrations VALUES(68,'occupied destination','retained')",
|
||||
],
|
||||
[
|
||||
"identity collision after generation relocation",
|
||||
"UPDATE schema_migrations SET name='persist repository identities' WHERE version IN (31,43); UPDATE schema_migrations SET name='stabilize Linux repository generations' WHERE version=44",
|
||||
],
|
||||
] as const)
|
||||
await t.test(name, async () => {
|
||||
const directory = await temporary.create(
|
||||
"workbench-repository-collision-",
|
||||
);
|
||||
const databasePath = join(directory, "workbench.sqlite3");
|
||||
const database = new DatabaseSync(databasePath);
|
||||
applyMigrations(database);
|
||||
database.exec(setup);
|
||||
const beforeSchema = schema(database);
|
||||
const beforeRows = storedRows(database);
|
||||
const beforeHistory = database
|
||||
.prepare("SELECT * FROM schema_migrations ORDER BY version")
|
||||
.all();
|
||||
database.close();
|
||||
await assert.rejects(
|
||||
databaseInfo(directory),
|
||||
/UNIQUE constraint failed/u,
|
||||
);
|
||||
const after = new DatabaseSync(databasePath);
|
||||
try {
|
||||
assert.deepEqual(schema(after), beforeSchema);
|
||||
assert.deepEqual(storedRows(after), beforeRows);
|
||||
assert.deepEqual(
|
||||
after
|
||||
.prepare("SELECT * FROM schema_migrations ORDER BY version")
|
||||
.all(),
|
||||
beforeHistory,
|
||||
);
|
||||
} finally {
|
||||
after.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("Node database-info preserves a linked repository's stored43 history for Python", async () => {
|
||||
const directory = await temporary.create("workbench-linked-upgrade-");
|
||||
const databasePath = join(directory, "workbench.sqlite3");
|
||||
const repository = join(directory, "repository");
|
||||
const linked = join(directory, "linked");
|
||||
const database = new DatabaseSync(databasePath);
|
||||
applyMigrations(
|
||||
database,
|
||||
migrations.filter((item) => item.version <= 42),
|
||||
);
|
||||
insertScan(database, repository);
|
||||
database.exec(
|
||||
"INSERT INTO scan_progress (scan_id,updated_at) VALUES ('scan','updated')",
|
||||
);
|
||||
database.close();
|
||||
const scripts = fileURLToPath(new URL("../../scripts", import.meta.url));
|
||||
const seeded = spawnSync(
|
||||
process.env.PYTHON?.trim() || "python3",
|
||||
[
|
||||
"-I",
|
||||
"-B",
|
||||
"-c",
|
||||
`
|
||||
import json, pathlib, sqlite3, subprocess, sys
|
||||
from datetime import datetime, timezone
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import workbench_db as workbench, workbench_schema as schema, workbench_target_state as state
|
||||
repository, linked = map(pathlib.Path, sys.argv[3:5])
|
||||
subprocess.run(['git', 'init', '-q', str(repository)], check=True)
|
||||
subprocess.run(['git', '-C', str(repository), '-c', 'user.name=Fixture', '-c',
|
||||
'user.email=fixture@example.invalid', 'commit', '-q', '--allow-empty', '-m', 'fixture'], check=True)
|
||||
subprocess.run(['git', '-C', str(repository), 'worktree', 'add', '-q', '--detach', str(linked)], check=True)
|
||||
with sqlite3.connect(sys.argv[2]) as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
timestamp = datetime.now(timezone.utc).isoformat()
|
||||
connection.execute('UPDATE scans SET started_at=?, created_at=?, updated_at=?', (timestamp, timestamp, timestamp))
|
||||
connection.execute('UPDATE scan_progress SET updated_at=?', (timestamp,))
|
||||
metadata = repository.stat()
|
||||
connection.execute('UPDATE scans SET target_device=?, target_inode=?', (str(metadata.st_dev), str(metadata.st_ino)))
|
||||
migration = json.loads(pathlib.Path(sys.argv[5]).read_text())[0]
|
||||
assert migration['version'] == 43 and migration['name'] == 'persist repository identities'
|
||||
for statement in migration['statements']:
|
||||
connection.execute(statement)
|
||||
connection.execute('INSERT INTO schema_migrations VALUES (?, ?, ?)',
|
||||
(migration['version'], migration['name'], 'original'))
|
||||
workbench.backfill_security_targets(connection)
|
||||
identity = state._repository_identity_details(repository)
|
||||
generation = identity.previous_value or identity.value
|
||||
connection.execute('UPDATE security_targets SET repository_identity=?', (generation,))
|
||||
connection.execute('UPDATE scans SET repository_generation=?', (generation,))
|
||||
`,
|
||||
scripts,
|
||||
databasePath,
|
||||
repository,
|
||||
linked,
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"./fixtures/pre-severity-repository-migrations.json",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
assert.equal(seeded.status, 0, seeded.stderr || String(seeded.error));
|
||||
const before = new DatabaseSync(databasePath);
|
||||
const savedRows = storedRows(before);
|
||||
assert.equal(
|
||||
before
|
||||
.prepare("SELECT MAX(version) AS version FROM schema_migrations")
|
||||
.get()?.version,
|
||||
43,
|
||||
);
|
||||
before.close();
|
||||
assert.equal((await databaseInfo(directory)).databasePath, databasePath);
|
||||
const initialized = new DatabaseSync(databasePath);
|
||||
assert.deepEqual(
|
||||
storedRows(initialized)
|
||||
.filter(
|
||||
([name]) =>
|
||||
name !== "schema_migrations" &&
|
||||
name !== "scan_severity_assessments" &&
|
||||
name !== "local_finding_embeddings" &&
|
||||
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]) => {
|
||||
if (name === "scans")
|
||||
for (const row of rows as Record<string, unknown>[]) {
|
||||
for (const column of [
|
||||
"source_scopes_json",
|
||||
"retained_checkpoint_heads_json",
|
||||
"launch_surface",
|
||||
"launch_package_version",
|
||||
"launch_plugin_version",
|
||||
"launch_kind",
|
||||
"log_completed_at",
|
||||
"windows_resume_output_identity",
|
||||
"windows_resume_target_identity",
|
||||
]) {
|
||||
assert.equal(row[column], null);
|
||||
delete row[column];
|
||||
}
|
||||
}
|
||||
if (name === "workspaces")
|
||||
for (const row of rows as Record<string, unknown>[]) {
|
||||
assert.equal(row.deep_scan_config_json, null);
|
||||
delete row.deep_scan_config_json;
|
||||
}
|
||||
return [name, rows];
|
||||
}),
|
||||
savedRows.filter(
|
||||
([name]) =>
|
||||
name !== "schema_migrations" &&
|
||||
name !== "finding_publications" &&
|
||||
name !== "sqlite_sequence",
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
initialized.prepare("SELECT * FROM deep_scan_worker_threads").all(),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
savedRows.find(([name]) => name === "finding_publications")?.[1],
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
savedRows.find(([name]) => name === "sqlite_sequence")?.[1],
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
initialized.prepare("SELECT * FROM finding_issue_receipts").all(),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
initialized
|
||||
.prepare("SELECT name, seq FROM sqlite_sequence")
|
||||
.all()
|
||||
.map((row) => ({ ...row })),
|
||||
[{ name: "finding_issue_receipts", seq: 0 }],
|
||||
);
|
||||
assert.equal(
|
||||
initialized
|
||||
.prepare("SELECT COUNT(*) AS count FROM local_finding_embeddings")
|
||||
.get()?.count,
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
initialized
|
||||
.prepare("SELECT COUNT(*) AS count FROM scan_severity_assessments")
|
||||
.get()?.count,
|
||||
0,
|
||||
);
|
||||
assert.deepEqual(
|
||||
initialized.prepare("SELECT * FROM external_source_reports").all(),
|
||||
[],
|
||||
);
|
||||
assertMigrationNames(initialized, 53);
|
||||
assert.equal(
|
||||
initialized
|
||||
.prepare("SELECT name FROM schema_migrations WHERE version=67")
|
||||
.get()?.name,
|
||||
"persist repository identities",
|
||||
);
|
||||
assert.equal(
|
||||
initialized
|
||||
.prepare("SELECT name FROM schema_migrations WHERE version=68")
|
||||
.get(),
|
||||
undefined,
|
||||
);
|
||||
initialized.close();
|
||||
const queried = spawnSync(
|
||||
process.env.PYTHON?.trim() || "python3",
|
||||
[
|
||||
"-I",
|
||||
"-B",
|
||||
"-c",
|
||||
`
|
||||
import argparse, sqlite3, sys
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import workbench_db as workbench, workbench_scan_history as history
|
||||
with sqlite3.connect(sys.argv[2]) as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
workbench.apply_migrations(connection)
|
||||
for repository in sys.argv[3:5]:
|
||||
args = argparse.Namespace(repository=repository, scan_root=None, target_id=None,
|
||||
mode=None, status=None, query=None, limit=None, offset=0)
|
||||
scans = history.list_scans(connection, args)['scans']
|
||||
assert [scan['scanId'] for scan in scans] == ['scan'], (repository, scans)
|
||||
assert connection.execute('SELECT MAX(version) FROM schema_migrations').fetchone()[0] == workbench.MIGRATIONS[-1][0]
|
||||
`,
|
||||
scripts,
|
||||
databasePath,
|
||||
repository,
|
||||
linked,
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
assert.equal(queried.status, 0, queried.stderr || String(queried.error));
|
||||
});
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
@@ -147,6 +148,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",
|
||||
|
||||
@@ -25,6 +25,7 @@ from workbench.storage import (
|
||||
from workbench_constants import PHASES
|
||||
from workbench_source_scopes import capture_source_scopes
|
||||
from workbench_target import directory_snapshot_regular_file_count
|
||||
from workbench_target_state import require_scan_checkout_owner
|
||||
from workbench_validation import optional_text, require_uuid, user_context_argument
|
||||
|
||||
DEEP_SCAN_COORDINATOR_LEASE_SECONDS = 30
|
||||
@@ -611,6 +612,7 @@ def begin_deep_scan_for_scan(
|
||||
) -> dict[str, Any]:
|
||||
scan_id = require_uuid(scan_id, "scan-id")
|
||||
candidate = dependencies().require_scan(connection, scan_id)
|
||||
require_scan_checkout_owner(connection, candidate)
|
||||
model_thread_id = getattr(args, "model_thread_id", None)
|
||||
require_tokenless_scan_owner(connection, candidate, model_thread_id)
|
||||
workspace = dependencies().require_workspace(connection, candidate["workspace_id"])
|
||||
@@ -695,6 +697,7 @@ def begin_deep_scan_for_scan(
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
with connection:
|
||||
scan, _ = require_owned_scan(connection, scan_id, thread_id)
|
||||
require_scan_checkout_owner(connection, scan)
|
||||
require_current_continuation(
|
||||
scan,
|
||||
args.claim_token,
|
||||
@@ -761,6 +764,7 @@ def begin_deep_scan_for_target(
|
||||
with connection:
|
||||
existing = existing_deep_scan_for_target(connection, thread_id, target_path, scope)
|
||||
if existing is not None:
|
||||
require_scan_checkout_owner(connection, existing)
|
||||
connection.commit()
|
||||
return begin_deep_scan_for_scan(connection, existing["id"], thread_id, args)
|
||||
current_target = dependencies().require_remediation_target(target_path)
|
||||
@@ -785,6 +789,7 @@ def begin_deep_scan_for_target(
|
||||
target_inode,
|
||||
)
|
||||
if terminal is not None:
|
||||
require_scan_checkout_owner(connection, terminal)
|
||||
connection.commit()
|
||||
return deep_scan_result(
|
||||
connection,
|
||||
@@ -810,7 +815,8 @@ def begin_deep_scan_for_target(
|
||||
workspace_id = str(uuid.uuid4())
|
||||
scan_id = str(uuid.uuid4())
|
||||
timestamp = dependencies().now()
|
||||
target_id = dependencies().ensure_security_target(connection, target_path)
|
||||
registration = dependencies().register_security_target(connection, target_path)
|
||||
target_id = registration.target_id
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO workspaces (
|
||||
@@ -842,6 +848,7 @@ def begin_deep_scan_for_target(
|
||||
scope=scope,
|
||||
diff_target=None,
|
||||
target_identity=target_identity,
|
||||
repository_generation=registration.repository_generation,
|
||||
source_scopes=source_scopes,
|
||||
target_root=target_root,
|
||||
target_summary=None,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,6 +3,8 @@ setlocal DisableDelayedExpansion
|
||||
|
||||
set "CODEX_SECURITY_MCP_SCRIPT=%~dp0..\mcp\server.mjs"
|
||||
if "%~1"=="--helper" (
|
||||
rem An inherited ERRORLEVEL would shadow the helper exit code.
|
||||
set "ERRORLEVEL="
|
||||
set "CODEX_SECURITY_MCP_SCRIPT=%~dp0..\mcp\helpers.mjs"
|
||||
goto launch
|
||||
)
|
||||
|
||||
@@ -226,11 +226,15 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
|
||||
list_scans.add_argument("--status", choices=("running", "complete", "failed", "canceled"))
|
||||
list_scans.add_argument("--mode", choices=MODES)
|
||||
list_scans.add_argument("--repository")
|
||||
list_scans.add_argument(
|
||||
"--prefer-worktree", action="store_true", help="List scans from this checkout first."
|
||||
)
|
||||
list_scans.add_argument("--scan-root")
|
||||
list_scans.add_argument("--offset", type=non_negative_int, default=0)
|
||||
list_scans.add_argument("--limit", type=positive_int)
|
||||
|
||||
list_unmatched_scan_pairs = add_command("list-unmatched-scan-pairs", "--repository")
|
||||
list_unmatched_scan_pairs.add_argument("--after-scan-id")
|
||||
list_unmatched_scan_pairs.add_argument("--force", action="store_true")
|
||||
|
||||
register_cli_scan = add_command("register-cli-scan", "--scan-dir", "--repository")
|
||||
@@ -246,7 +250,17 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
|
||||
)
|
||||
register_cli_scan.add_argument("--archived-scan-dir")
|
||||
|
||||
add_command("set-scan-thread", "--scan-id", "--thread-id")
|
||||
restore_cli_scan_archive = subparsers.add_parser("restore-cli-scan-archive")
|
||||
restore_cli_scan_archive.add_argument("--scan-dir", required=True)
|
||||
restore_cli_scan_archive.add_argument("--archived-scan-dir", required=True)
|
||||
previous_scan = restore_cli_scan_archive.add_mutually_exclusive_group(required=True)
|
||||
previous_scan.add_argument("--previous-scan-id")
|
||||
previous_scan.add_argument("--previous-scan-absent", action="store_true")
|
||||
|
||||
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)
|
||||
@@ -274,8 +288,9 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
|
||||
list_global_findings.add_argument("--query")
|
||||
list_global_findings.add_argument("--severity", choices=FINDING_SEVERITIES)
|
||||
list_global_findings.add_argument("--status", choices=FINDING_STATUSES)
|
||||
list_global_findings.add_argument("--repository")
|
||||
list_global_findings.add_argument("--target-id", action="append")
|
||||
finding_repository = list_global_findings.add_mutually_exclusive_group()
|
||||
finding_repository.add_argument("--target-id", action="append")
|
||||
finding_repository.add_argument("--repository")
|
||||
list_global_findings.add_argument("--target-path", action="append")
|
||||
list_global_findings.add_argument("--include-resolved", action="store_true")
|
||||
list_global_findings.add_argument("--offset", type=non_negative_int, default=0)
|
||||
|
||||
@@ -79,6 +79,7 @@ from workbench_scan_start import (
|
||||
loaded_plugin_version,
|
||||
prepare_cli_scan_target,
|
||||
register_windows_resume_output,
|
||||
restore_cli_scan_archive,
|
||||
safe_segment,
|
||||
scan_diff_identity,
|
||||
scan_target_identity,
|
||||
@@ -86,6 +87,8 @@ from workbench_scan_start import (
|
||||
)
|
||||
from workbench_schema import (
|
||||
MIGRATIONS,
|
||||
migration_target_paths,
|
||||
recorded_git_checkout_roots,
|
||||
)
|
||||
from workbench_schema import (
|
||||
apply_migrations as apply_schema_migrations,
|
||||
@@ -122,17 +125,25 @@ from workbench_target import (
|
||||
git_submodule_entries,
|
||||
git_target_metadata,
|
||||
git_worktree_context,
|
||||
rejected_checkout_roots,
|
||||
remediation_checkout_snapshot,
|
||||
require_remediation_target,
|
||||
require_scan_target_identity,
|
||||
require_scan_target_unchanged,
|
||||
restore_directory_junctions,
|
||||
scan_target_warning,
|
||||
scoped_git_discovery,
|
||||
scoped_regular_file_count,
|
||||
worktree_content_digest,
|
||||
worktree_content_digest_for_context,
|
||||
)
|
||||
from workbench_target_state import backfill_security_targets, ensure_security_target
|
||||
from workbench_target_state import (
|
||||
RepositoryScanScope,
|
||||
backfill_security_targets,
|
||||
ensure_security_target,
|
||||
register_security_target,
|
||||
require_scan_checkout_owner,
|
||||
)
|
||||
from workbench_validation import (
|
||||
optional_text,
|
||||
parse_scan_cost,
|
||||
@@ -226,13 +237,21 @@ def release_completion_file_lock(descriptor: int) -> None:
|
||||
windows_file_lock.locking(descriptor, windows_file_lock.LK_UNLCK, 1)
|
||||
|
||||
|
||||
def connect(*, deferred: bool = False) -> sqlite3.Connection:
|
||||
def connect(
|
||||
*,
|
||||
deferred: bool = False,
|
||||
discovery_roots: tuple[Path, ...] = (),
|
||||
in_memory: bool = False,
|
||||
) -> sqlite3.Connection:
|
||||
"""Open the workbench SQLite database and bring its schema up to date.
|
||||
|
||||
Args:
|
||||
deferred (bool): Let the first migration attempt defer its write lock.
|
||||
Retries after lock contention use an immediate transaction.
|
||||
|
||||
discovery_roots: Additional local paths for bounded target discovery.
|
||||
in_memory: Keep a fresh profile read entirely in memory.
|
||||
|
||||
Returns:
|
||||
sqlite3.Connection: A caller-owned connection with named rows, foreign
|
||||
keys enabled, and write-ahead logging.
|
||||
@@ -248,13 +267,14 @@ def connect(*, deferred: bool = False) -> sqlite3.Connection:
|
||||
"the scanned repository."
|
||||
)
|
||||
try:
|
||||
create_private_directory(path.parent)
|
||||
if not in_memory:
|
||||
create_private_directory(path.parent)
|
||||
except OSError:
|
||||
print(guidance, file=sys.stderr)
|
||||
raise
|
||||
for attempt in range(SQLITE_RETRY_ATTEMPTS):
|
||||
try:
|
||||
connection = sqlite3.connect(path, timeout=5)
|
||||
connection = sqlite3.connect(":memory:" if in_memory else path, timeout=5)
|
||||
except sqlite3.OperationalError:
|
||||
print(guidance, file=sys.stderr)
|
||||
raise
|
||||
@@ -263,9 +283,12 @@ def connect(*, deferred: bool = False) -> sqlite3.Connection:
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.execute("PRAGMA busy_timeout = 5000")
|
||||
# Keep writer admission retries; readers only wait when a repair needs to write.
|
||||
apply_migrations(connection, immediate=not deferred or attempt > 0)
|
||||
apply_migrations(
|
||||
connection, immediate=not deferred or attempt > 0, discovery_roots=discovery_roots
|
||||
)
|
||||
connection.execute("PRAGMA journal_mode = WAL")
|
||||
path.chmod(0o600)
|
||||
if not in_memory:
|
||||
path.chmod(0o600)
|
||||
return connection
|
||||
except sqlite3.OperationalError as exc:
|
||||
connection.close()
|
||||
@@ -287,9 +310,19 @@ def begin_immediate_with_retry(connection: sqlite3.Connection) -> None:
|
||||
time.sleep(0.05 * (2**attempt))
|
||||
|
||||
|
||||
def apply_migrations(connection: sqlite3.Connection, *, immediate: bool = False) -> None:
|
||||
def apply_migrations(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
immediate: bool = False,
|
||||
discovery_roots: tuple[Path, ...] = (),
|
||||
) -> None:
|
||||
apply_schema_migrations(
|
||||
connection, MIGRATIONS, now, backfill_security_targets, immediate=immediate
|
||||
connection,
|
||||
MIGRATIONS,
|
||||
now,
|
||||
backfill_security_targets,
|
||||
immediate=immediate,
|
||||
discovery_roots=discovery_roots,
|
||||
)
|
||||
|
||||
|
||||
@@ -512,6 +545,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
|
||||
diff_content_digest = (
|
||||
optional_text(args.diff_content_digest, maximum=128) if args.mode == "diff" else None
|
||||
)
|
||||
target_path_unvalidated = False
|
||||
rejected_roots = None
|
||||
if target_path:
|
||||
try:
|
||||
inspected = inspect_setup_values(
|
||||
@@ -531,11 +566,17 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
|
||||
diff_head_revision = inspected["diffTarget"]["headRevision"]
|
||||
diff_content_digest = inspected["diffTarget"].get("contentDigest")
|
||||
except SystemExit:
|
||||
# Preserve an incomplete setup so workspace_state can report its validation error.
|
||||
pass
|
||||
# Setup may fail on scope even when the target itself is valid.
|
||||
try:
|
||||
require_target(target_path)
|
||||
except SystemExit:
|
||||
target_path_unvalidated = True
|
||||
rejected_roots = rejected_checkout_roots(target_path)
|
||||
with connection:
|
||||
target_id = (
|
||||
ensure_security_target(connection, target_path) if target_path is not None else None
|
||||
ensure_security_target(connection, target_path)
|
||||
if target_path is not None and not target_path_unvalidated
|
||||
else None
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
@@ -543,8 +584,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
|
||||
id, thread_id, target_id, target_path, target_title, target_summary,
|
||||
default_scope, default_mode,
|
||||
user_context, diff_target_kind, diff_base_revision, diff_head_revision,
|
||||
diff_content_digest, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
diff_content_digest, created_at, updated_at, target_path_unvalidated, rejected_checkout_roots_json
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
workspace_id,
|
||||
@@ -562,6 +603,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
|
||||
diff_content_digest,
|
||||
timestamp,
|
||||
timestamp,
|
||||
target_path_unvalidated,
|
||||
json.dumps(rejected_roots) if rejected_roots is not None else None,
|
||||
),
|
||||
)
|
||||
return workspace_state(connection, workspace_id)
|
||||
@@ -596,7 +639,10 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->
|
||||
SET target_id = ?, target_path = ?, target_title = ?, target_summary = ?, default_scope = ?,
|
||||
default_mode = ?, user_context = ?, diff_target_kind = ?,
|
||||
diff_base_revision = ?, diff_head_revision = ?, diff_content_digest = ?,
|
||||
deep_scan_config_json = ?, submitted = 1, updated_at = ?
|
||||
deep_scan_config_json = ?, submitted = 1, updated_at = ?, target_path_unvalidated = 0,
|
||||
-- JSON null keeps PATH discovery disabled after a legacy rejection.
|
||||
rejected_checkout_roots_json = COALESCE(rejected_checkout_roots_json,
|
||||
CASE WHEN target_path_unvalidated = 1 AND target_id IS NULL THEN 'null' END)
|
||||
WHERE id = ? AND active_scan_id IS NULL
|
||||
""",
|
||||
(
|
||||
@@ -670,6 +716,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
|
||||
(workspace["id"],),
|
||||
).fetchone()
|
||||
if active is not None:
|
||||
require_scan_checkout_owner(connection, active)
|
||||
return workspace_state(connection, workspace["id"], result_scan_id=active["id"])
|
||||
workspace_version = workspace["updated_at"]
|
||||
scan_id = str(uuid.uuid4())
|
||||
@@ -719,6 +766,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
|
||||
(workspace["id"],),
|
||||
).fetchone()
|
||||
if active is not None:
|
||||
require_scan_checkout_owner(connection, active)
|
||||
if manages_transaction:
|
||||
connection.commit()
|
||||
return workspace_state(connection, workspace["id"], result_scan_id=active["id"])
|
||||
@@ -745,6 +793,11 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
|
||||
"This Codex thread already has an active Deep Scan for the selected "
|
||||
"target and scope. Rejoin that scan instead of starting another one."
|
||||
)
|
||||
registration = register_security_target(connection, str(current_target))
|
||||
if registration.target_id != workspace["target_id"]:
|
||||
raise SystemExit(
|
||||
"The saved workspace no longer matches the selected repository target."
|
||||
)
|
||||
insert_running_scan(
|
||||
connection,
|
||||
scan_id=scan_id,
|
||||
@@ -753,6 +806,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
|
||||
scope=scope,
|
||||
diff_target=diff_target,
|
||||
target_identity=target_identity,
|
||||
repository_generation=registration.repository_generation,
|
||||
source_scopes=source_scopes,
|
||||
target_root=target_root,
|
||||
target_summary=target_summary,
|
||||
@@ -872,6 +926,7 @@ def _start_prompt_driven_scan(
|
||||
),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
require_scan_checkout_owner(connection, existing)
|
||||
connection.commit()
|
||||
return {
|
||||
**scan_context(connection, existing["id"], model_thread_id=thread_id),
|
||||
@@ -881,7 +936,8 @@ def _start_prompt_driven_scan(
|
||||
workspace_id = str(uuid.uuid4())
|
||||
scan_id = str(uuid.uuid4())
|
||||
timestamp = now()
|
||||
target_id = ensure_security_target(connection, target_path)
|
||||
registration = register_security_target(connection, target_path)
|
||||
target_id = registration.target_id
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO workspaces (
|
||||
@@ -914,6 +970,7 @@ def _start_prompt_driven_scan(
|
||||
scope=scope,
|
||||
diff_target=diff_target,
|
||||
target_identity=target_identity,
|
||||
repository_generation=registration.repository_generation,
|
||||
source_scopes=source_scopes,
|
||||
target_root=target_root,
|
||||
target_summary=target_summary,
|
||||
@@ -1507,12 +1564,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
|
||||
@@ -1526,10 +1578,9 @@ def register_cli_scan(
|
||||
|
||||
repository = require_target(args.repository)
|
||||
require_scannable_target(repository)
|
||||
scan_dir = None
|
||||
if not args.archive_existing or args.archived_scan_dir is not None:
|
||||
# Preserve early output rejection when this call will not move the directory.
|
||||
scan_dir = require_cli_scan_directory(repository, args)
|
||||
require_cli_scan_directory(repository, args)
|
||||
user_context = None
|
||||
workflow_id = None
|
||||
hosted = False
|
||||
@@ -1605,9 +1656,19 @@ def register_cli_scan(
|
||||
with ExitStack() as archive:
|
||||
deadline = None
|
||||
while True:
|
||||
if scan_dir is None:
|
||||
# Wait for any previous archive to finish before inspecting its replacement.
|
||||
scan_dir = require_cli_scan_directory(repository, args)
|
||||
registration = register_security_target(connection, str(repository))
|
||||
target_id = registration.target_id
|
||||
if parent_scan_id is not None:
|
||||
parent = require_scan(connection, parent_scan_id)
|
||||
parent_scope = RepositoryScanScope(
|
||||
registration.repository_generation, target_id
|
||||
)
|
||||
if not parent_scope.contains(parent):
|
||||
raise SystemExit(
|
||||
"A rerun must belong to the same repository as its parent scan."
|
||||
)
|
||||
# Revalidate the output and its owner under the current write lock.
|
||||
scan_dir = require_cli_scan_directory(repository, args)
|
||||
try:
|
||||
archived_scan_dir = archive.enter_context(
|
||||
archive_scan(
|
||||
@@ -1638,14 +1699,6 @@ def register_cli_scan(
|
||||
scan_dir = None # Revalidate the directory and its owner under the next lock.
|
||||
time.sleep(min(0.05, remaining))
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
target_id = ensure_security_target(connection, str(repository))
|
||||
if parent_scan_id is not None:
|
||||
parent = require_scan(connection, parent_scan_id)
|
||||
if parent["target_id"] != target_id:
|
||||
raise SystemExit(
|
||||
"A rerun must belong to the same repository as its parent scan."
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO workspaces (
|
||||
@@ -1675,6 +1728,7 @@ def register_cli_scan(
|
||||
scope=scope,
|
||||
diff_target=diff_target,
|
||||
target_identity=target_identity,
|
||||
repository_generation=registration.repository_generation,
|
||||
source_scopes=source_scopes,
|
||||
target_root=scan_dir.parent,
|
||||
target_summary=None,
|
||||
@@ -1718,6 +1772,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,
|
||||
@@ -1730,8 +1789,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}
|
||||
|
||||
@@ -1839,7 +1901,7 @@ def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace)
|
||||
timestamp = now()
|
||||
occurrence = require_occurrence(connection, args.occurrence_id)
|
||||
scan = require_scan(connection, occurrence["scan_id"])
|
||||
_require_finding_checkout_owner(connection, scan)
|
||||
scan_history.require_finding_checkout_owner(connection, scan)
|
||||
indexed_finding = _indexed_scan_findings(connection, scan).get(occurrence["id"])
|
||||
triaged_occurrences = [occurrence]
|
||||
verification_ids = {occurrence["id"]}
|
||||
@@ -1958,7 +2020,7 @@ def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace)
|
||||
def require_finding_open(connection: sqlite3.Connection, occurrence_id: str) -> None:
|
||||
occurrence = require_occurrence(connection, occurrence_id)
|
||||
scan = require_scan(connection, occurrence["scan_id"])
|
||||
_require_finding_checkout_owner(connection, scan)
|
||||
scan_history.require_finding_checkout_owner(connection, scan)
|
||||
triage = _indexed_scan_findings(connection, scan).get(occurrence_id)
|
||||
if triage is None:
|
||||
triage = connection.execute(
|
||||
@@ -2693,59 +2755,6 @@ def scan_context(
|
||||
return context
|
||||
|
||||
|
||||
def _require_finding_checkout_owner(
|
||||
connection: sqlite3.Connection, scan: sqlite3.Row
|
||||
) -> sqlite3.Row | None:
|
||||
target = connection.execute(
|
||||
"SELECT current_path FROM security_targets WHERE id = ?", (scan["target_id"],)
|
||||
).fetchone()
|
||||
if scan["target_id"] is None:
|
||||
scan_path = Path(scan["target_path"]).expanduser().resolve()
|
||||
for candidate in (scan_path, *scan_path.parents):
|
||||
target = connection.execute(
|
||||
"SELECT current_path FROM security_targets WHERE current_path = ?",
|
||||
(str(candidate),),
|
||||
).fetchone()
|
||||
if target is not None:
|
||||
break
|
||||
if target is None:
|
||||
return None
|
||||
elif target is not None and not Path(target["current_path"]).exists():
|
||||
ownership = scan_history._recorded_target_ownership(connection, scan["target_id"])
|
||||
if ownership is None:
|
||||
return target
|
||||
recorded, epoch_start = ownership
|
||||
sequence = connection.execute(
|
||||
"SELECT rowid AS ownership_sequence FROM scans WHERE id = ?", (scan["id"],)
|
||||
).fetchone()
|
||||
same_owner = (
|
||||
scan["target_device"] == recorded["target_device"]
|
||||
and scan["target_inode"] == recorded["target_inode"]
|
||||
) or (
|
||||
epoch_start is None and scan["target_device"] is None and scan["target_inode"] is None
|
||||
)
|
||||
if same_owner and (
|
||||
epoch_start is None
|
||||
or (sequence is not None and sequence["ownership_sequence"] > epoch_start)
|
||||
):
|
||||
return target
|
||||
raise SystemExit("Codex Security finding is unavailable for the current checkout owner.")
|
||||
if target is not None and scan["target_id"] is not None:
|
||||
if scan_history._same_registered_repository(connection, scan, scan):
|
||||
return target
|
||||
elif target is not None:
|
||||
clauses, values, _, _ = scan_history.repository_scan_scope(
|
||||
connection, target["current_path"]
|
||||
)
|
||||
allowed = connection.execute(
|
||||
f"SELECT 1 FROM scans WHERE scans.id = ? AND {' AND '.join(clauses)}",
|
||||
(scan["id"], *values),
|
||||
).fetchone()
|
||||
if allowed is not None:
|
||||
return target
|
||||
raise SystemExit("Codex Security finding is unavailable for the current checkout owner.")
|
||||
|
||||
|
||||
def _indexed_scan_findings(
|
||||
connection: sqlite3.Connection,
|
||||
scan: sqlite3.Row,
|
||||
@@ -2780,7 +2789,7 @@ def get_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[s
|
||||
if args.occurrence_id is not None or not scan_history.is_unbound_standard_handoff(
|
||||
connection, scan, context_claim
|
||||
):
|
||||
_require_finding_checkout_owner(connection, scan)
|
||||
scan_history.require_finding_checkout_owner(connection, scan)
|
||||
if getattr(args, "progress_only", False):
|
||||
scan = connection.execute(
|
||||
"""
|
||||
@@ -2861,7 +2870,7 @@ def get_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[s
|
||||
|
||||
def list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
|
||||
scan = require_scan(connection, args.scan_id)
|
||||
_require_finding_checkout_owner(connection, scan)
|
||||
scan_history.require_finding_checkout_owner(connection, scan)
|
||||
backfill_legacy_finding_details(connection, scan)
|
||||
indexed = _indexed_scan_findings(connection, scan)
|
||||
connection.create_function(
|
||||
@@ -3166,48 +3175,9 @@ def finding_result(
|
||||
)
|
||||
|
||||
|
||||
def finding_remediation_result(
|
||||
connection: sqlite3.Connection, occurrence_id: str
|
||||
) -> dict[str, Any]:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT remediation.request_id, remediation.state, remediation.version,
|
||||
remediation.base_revision, remediation.pending_action,
|
||||
remediation.pending_action_claimed_at, remediation.pending_action_claim_token,
|
||||
remediation.pending_action_delivered_at,
|
||||
remediation.patch_path, remediation.patch_digest, remediation.summary,
|
||||
remediation.verification_summary, remediation.updated_at, scans.scan_dir
|
||||
FROM finding_remediation_attempts AS remediation
|
||||
JOIN finding_occurrences AS occurrences ON occurrences.id = remediation.occurrence_id
|
||||
JOIN scans ON scans.id = occurrences.scan_id
|
||||
WHERE remediation.occurrence_id = ?
|
||||
ORDER BY remediation.created_at DESC, remediation.rowid DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(occurrence_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {"state": "idle"}
|
||||
patch, patch_stats = patch_artifact_preview(
|
||||
Path(row["scan_dir"]), row["patch_path"], row["patch_digest"]
|
||||
)
|
||||
return {
|
||||
"baseRevision": row["base_revision"],
|
||||
"actionClaimedAt": row["pending_action_claimed_at"],
|
||||
"actionClaimToken": row["pending_action_claim_token"],
|
||||
"actionDeliveredAt": row["pending_action_delivered_at"],
|
||||
"pendingAction": row["pending_action"],
|
||||
"patchDigest": row["patch_digest"],
|
||||
"patchPath": row["patch_path"],
|
||||
"patch": patch,
|
||||
"patchStats": patch_stats,
|
||||
"requestId": row["request_id"],
|
||||
"state": row["state"],
|
||||
"summary": row["summary"],
|
||||
"updatedAt": row["updated_at"],
|
||||
"verificationSummary": row["verification_summary"],
|
||||
"version": row["version"],
|
||||
}
|
||||
finding_remediation_result = partial(
|
||||
remediation_state.finding_remediation_result, open_scan_file=open_scan_local_file
|
||||
)
|
||||
|
||||
|
||||
def patch_artifact_preview(
|
||||
@@ -3331,19 +3301,34 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
|
||||
raise SystemExit(73) from None
|
||||
print(json.dumps(result, allow_nan=False, sort_keys=True))
|
||||
return
|
||||
with closing(
|
||||
connect(
|
||||
deferred=args.command
|
||||
in {
|
||||
"get-scan",
|
||||
"get-finding",
|
||||
"read-scan-usage",
|
||||
"list-scans",
|
||||
"database-info",
|
||||
"update-progress",
|
||||
}
|
||||
)
|
||||
) as connection:
|
||||
command_targets = tuple(
|
||||
Path(value).expanduser()
|
||||
for field in ("target_path", "repository")
|
||||
for raw in (getattr(args, field, None),)
|
||||
for value in (raw if isinstance(raw, list) else [raw])
|
||||
if value
|
||||
)
|
||||
with (
|
||||
closing(
|
||||
connect(
|
||||
deferred=args.command
|
||||
in {
|
||||
"get-scan",
|
||||
"get-finding",
|
||||
"read-scan-usage",
|
||||
"list-scans",
|
||||
"database-info",
|
||||
"update-progress",
|
||||
},
|
||||
discovery_roots=command_targets,
|
||||
in_memory=scan_history.reads_missing_history(args, database_path()),
|
||||
)
|
||||
) as connection,
|
||||
scoped_git_discovery(
|
||||
lambda: [*migration_target_paths(connection), *command_targets],
|
||||
recorded_git_roots=lambda: recorded_git_checkout_roots(connection),
|
||||
),
|
||||
):
|
||||
remediation_state.require_available(connection, args, require_scan)
|
||||
handlers = {
|
||||
"create-workspace": create_workspace,
|
||||
@@ -3360,6 +3345,9 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
|
||||
"record-deep-scan-publication-failure": deep_scan.record_deep_scan_publication_failure,
|
||||
"list-scans": scan_history.list_scans,
|
||||
"register-cli-scan": partial(register_cli_scan, before_archive=before_archive),
|
||||
"restore-cli-scan-archive": partial(
|
||||
restore_cli_scan_archive, canonical_directory=require_canonical_scan_directory
|
||||
),
|
||||
"set-scan-thread": set_scan_thread,
|
||||
"set-scan-cost-limit": set_scan_cost_limit,
|
||||
"read-scan-usage": read_scan_usage,
|
||||
@@ -3416,7 +3404,7 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
|
||||
elif args.command == "get-finding":
|
||||
occurrence = require_occurrence(connection, args.occurrence_id)
|
||||
scan = require_scan(connection, occurrence["scan_id"])
|
||||
current_target = _require_finding_checkout_owner(connection, scan)
|
||||
current_target = scan_history.require_finding_checkout_owner(connection, scan)
|
||||
backfill_legacy_finding_details(connection, scan)
|
||||
occurrence = require_occurrence(connection, occurrence["id"])
|
||||
result = {
|
||||
@@ -3426,9 +3414,9 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
|
||||
"scanId": scan["id"],
|
||||
"targetPath": scan["target_path"],
|
||||
**(
|
||||
{"currentTargetPath": current_target["current_path"]}
|
||||
{"currentTargetPath": current_target["target_path"]}
|
||||
if current_target is not None
|
||||
and current_target["current_path"] != scan["target_path"]
|
||||
and current_target["target_path"] != scan["target_path"]
|
||||
else {}
|
||||
),
|
||||
}
|
||||
|
||||
@@ -18,9 +18,8 @@ from workbench_constants import (
|
||||
FINDING_TITLE_BYTES,
|
||||
PRIMARY_FINDING_LOCATION_SQL,
|
||||
)
|
||||
from workbench_finding_results import finding_triage_result
|
||||
from workbench_native_indexes import _indexed_findings
|
||||
from workbench_scan_history import _same_registered_repository, saved_repository_target_ids
|
||||
from workbench_target_state import RepositoryIdentityCache
|
||||
from workbench_validation import bounded_output_text
|
||||
|
||||
|
||||
@@ -30,88 +29,40 @@ def get_scan_feedback(connection: sqlite3.Connection, scan: sqlite3.Row) -> dict
|
||||
For each finding, include the latest decision only if it closes the finding as a
|
||||
false positive with a nonblank reason. Prefer the root-control location in its preview.
|
||||
"""
|
||||
connection.create_function(
|
||||
"codex_security_finding_group",
|
||||
2,
|
||||
lambda occurrence_id, finding_id: f"finding:{finding_id}",
|
||||
deterministic=True,
|
||||
)
|
||||
checkout_relationships: dict[tuple[str, ...], bool] = {}
|
||||
source_ids = {
|
||||
row["id"]
|
||||
for row in connection.execute(
|
||||
"SELECT * FROM scans WHERE (status = 'complete' "
|
||||
"OR (status = 'failed' AND seal_manifest_digest IS NOT NULL)) AND id != ? "
|
||||
"AND target_id IN (SELECT value FROM json_each(?))",
|
||||
(scan["id"], json.dumps(sorted(saved_repository_target_ids(connection, scan)))),
|
||||
)
|
||||
if _same_registered_repository(
|
||||
connection, scan, row, checkout_relationships=checkout_relationships
|
||||
identities = RepositoryIdentityCache(connection)
|
||||
scope = identities.scope_for_scan(scan)
|
||||
if not scope.available:
|
||||
return {"scanId": scan["id"], "targetId": scan["target_id"], "falsePositives": []}
|
||||
|
||||
reviewed = {
|
||||
finding["decision_occurrence_id"]
|
||||
for finding in _indexed_findings(
|
||||
connection,
|
||||
identities=identities,
|
||||
scan_scope=scope,
|
||||
exclude_scan_id=scan["id"],
|
||||
)
|
||||
if finding["status"] == "closed" and finding["close_reason"] == "false_positive"
|
||||
}
|
||||
closed_decisions = {}
|
||||
for finding in _indexed_findings(connection, source_ids, allow_cross_target_matches=True):
|
||||
triage = finding_triage_result(connection, finding["occurrence_id"], finding)
|
||||
if triage["status"] == "closed" and triage.get("closeReason") == "false_positive":
|
||||
closed_decisions.update(
|
||||
(finding_id, triage) for finding_id in finding["matched_finding_ids"]
|
||||
)
|
||||
connection.create_function(
|
||||
"codex_security_feedback_note",
|
||||
1,
|
||||
lambda finding_id: closed_decisions.get(finding_id, {}).get("note"),
|
||||
deterministic=True,
|
||||
)
|
||||
connection.create_function(
|
||||
"codex_security_feedback_updated_at",
|
||||
1,
|
||||
lambda finding_id: closed_decisions.get(finding_id, {}).get("updatedAt"),
|
||||
deterministic=True,
|
||||
)
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
WITH ranked_decisions AS (
|
||||
SELECT findings.id AS finding_id, findings.fingerprint, findings.rule_id,
|
||||
findings.identity_anchor, findings.identity_instance, occurrences.title,
|
||||
occurrences.summary, codex_security_feedback_note(findings.id) AS note,
|
||||
COALESCE(codex_security_feedback_updated_at(findings.id),
|
||||
source_scans.completed_at) AS updated_at,
|
||||
source_scans.id AS source_scan_id,
|
||||
source_scans.completed_at AS source_completed_at,
|
||||
locations.relative_path, locations.start_line, locations.end_line, locations.role,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY findings.id
|
||||
ORDER BY julianday(upper(COALESCE(codex_security_feedback_updated_at(findings.id),
|
||||
source_scans.completed_at))) DESC,
|
||||
julianday(upper(source_scans.completed_at)) DESC,
|
||||
source_scans.id DESC, occurrences.id DESC
|
||||
) AS decision_rank
|
||||
FROM finding_occurrences AS occurrences
|
||||
JOIN findings ON findings.id = occurrences.finding_id
|
||||
JOIN scans AS source_scans ON source_scans.id = occurrences.scan_id
|
||||
JOIN finding_locations AS locations ON locations.id = (
|
||||
SELECT id {PRIMARY_FINDING_LOCATION_SQL}
|
||||
)
|
||||
WHERE source_scans.target_id = ?
|
||||
AND source_scans.id != ?
|
||||
AND source_scans.id IN (SELECT value FROM json_each(?))
|
||||
AND findings.id IN (SELECT value FROM json_each(?))
|
||||
)
|
||||
SELECT *
|
||||
FROM ranked_decisions
|
||||
WHERE decision_rank = 1
|
||||
AND note IS NOT NULL
|
||||
AND trim(note) != ''
|
||||
ORDER BY julianday(upper(updated_at)) DESC,
|
||||
julianday(upper(source_completed_at)) DESC,
|
||||
source_scan_id DESC, finding_id DESC
|
||||
SELECT findings.id AS finding_id, findings.fingerprint, findings.rule_id,
|
||||
findings.identity_anchor, findings.identity_instance, occurrences.title,
|
||||
occurrences.summary, triage.note, triage.updated_at,
|
||||
source_scans.id AS source_scan_id,
|
||||
locations.relative_path, locations.start_line, locations.end_line, locations.role
|
||||
FROM finding_occurrences AS occurrences
|
||||
JOIN findings ON findings.id = occurrences.finding_id
|
||||
JOIN scans AS source_scans ON source_scans.id = occurrences.scan_id
|
||||
JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id
|
||||
JOIN finding_locations AS locations ON locations.id = (SELECT id {PRIMARY_FINDING_LOCATION_SQL})
|
||||
WHERE occurrences.id IN (SELECT value FROM json_each(?)) AND source_scans.id != ?
|
||||
AND (source_scans.status = 'complete' OR (source_scans.status = 'failed' AND source_scans.seal_manifest_digest IS NOT NULL))
|
||||
AND trim(triage.note) != ''
|
||||
ORDER BY julianday(upper(triage.updated_at)) DESC,
|
||||
julianday(upper(source_scans.completed_at)) DESC, source_scans.id DESC, findings.id DESC
|
||||
""",
|
||||
(
|
||||
scan["target_id"],
|
||||
scan["id"],
|
||||
json.dumps(sorted(source_ids)),
|
||||
json.dumps(sorted(closed_decisions)),
|
||||
),
|
||||
(json.dumps(sorted(reviewed)), scan["id"]),
|
||||
)
|
||||
false_positives = []
|
||||
for row in rows:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -50,6 +50,53 @@ COMMANDS = {
|
||||
SCAN_STATUS_ERROR = "Remediation is available only for successfully completed scans."
|
||||
|
||||
|
||||
def finding_remediation_result(
|
||||
connection: sqlite3.Connection,
|
||||
occurrence_id: str,
|
||||
*,
|
||||
open_scan_file: Callable[[Path, str], AbstractContextManager[BinaryIO]],
|
||||
) -> dict[str, Any]:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT remediation.request_id, remediation.state, remediation.version,
|
||||
remediation.base_revision, remediation.pending_action,
|
||||
remediation.pending_action_claimed_at, remediation.pending_action_claim_token,
|
||||
remediation.pending_action_delivered_at,
|
||||
remediation.patch_path, remediation.patch_digest, remediation.summary,
|
||||
remediation.verification_summary, remediation.updated_at, scans.scan_dir
|
||||
FROM finding_remediation_attempts AS remediation
|
||||
JOIN finding_occurrences AS occurrences ON occurrences.id = remediation.occurrence_id
|
||||
JOIN scans ON scans.id = occurrences.scan_id
|
||||
WHERE remediation.occurrence_id = ?
|
||||
ORDER BY remediation.created_at DESC, remediation.rowid DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(occurrence_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {"state": "idle"}
|
||||
patch, patch_stats = patch_artifact_preview(
|
||||
Path(row["scan_dir"]), row["patch_path"], row["patch_digest"], open_scan_file
|
||||
)
|
||||
return {
|
||||
"baseRevision": row["base_revision"],
|
||||
"actionClaimedAt": row["pending_action_claimed_at"],
|
||||
"actionClaimToken": row["pending_action_claim_token"],
|
||||
"actionDeliveredAt": row["pending_action_delivered_at"],
|
||||
"pendingAction": row["pending_action"],
|
||||
"patchDigest": row["patch_digest"],
|
||||
"patchPath": row["patch_path"],
|
||||
"patch": patch,
|
||||
"patchStats": patch_stats,
|
||||
"requestId": row["request_id"],
|
||||
"state": row["state"],
|
||||
"summary": row["summary"],
|
||||
"updatedAt": row["updated_at"],
|
||||
"verificationSummary": row["verification_summary"],
|
||||
"version": row["version"],
|
||||
}
|
||||
|
||||
|
||||
def patch_artifact_preview(
|
||||
scan_dir: Path,
|
||||
relative_path: str | None,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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:
|
||||
@@ -304,6 +304,57 @@ def archive_scan(
|
||||
raise
|
||||
|
||||
|
||||
def restore_cli_scan_archive(
|
||||
connection: sqlite3.Connection,
|
||||
args: argparse.Namespace,
|
||||
canonical_directory: Callable[[Path], Path],
|
||||
) -> dict[str, str]:
|
||||
supplied_scan_dir = Path(args.scan_dir).expanduser().absolute()
|
||||
supplied_archive = Path(args.archived_scan_dir).expanduser().absolute()
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
scan_dir = supplied_scan_dir.resolve()
|
||||
archived_scan_dir = supplied_archive.resolve()
|
||||
archived_owner = connection.execute(
|
||||
"SELECT id FROM scans WHERE scan_dir = ?", (str(archived_scan_dir),)
|
||||
).fetchone()
|
||||
previous_scan = connection.execute(
|
||||
"SELECT id FROM scans WHERE scan_dir = ?", (str(scan_dir),)
|
||||
).fetchone()
|
||||
previous_scan_id = previous_scan["id"] if previous_scan is not None else None
|
||||
if archived_owner is not None:
|
||||
disposition = "already-recorded"
|
||||
elif previous_scan_id != args.previous_scan_id:
|
||||
disposition = "ownership-changed"
|
||||
else:
|
||||
archived_scan_dir = canonical_directory(supplied_archive)
|
||||
if (
|
||||
os.path.normcase(supplied_scan_dir) != os.path.normcase(scan_dir)
|
||||
or archived_scan_dir.parent != scan_dir.parent
|
||||
or not archived_scan_dir.name.startswith(f"{scan_dir.name}.previous-")
|
||||
):
|
||||
raise SystemExit(
|
||||
"The archived scan must be a previous sibling of the scan directory."
|
||||
)
|
||||
try:
|
||||
supplied_scan_dir.lstat()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
canonical_directory(supplied_scan_dir).rmdir()
|
||||
archived_scan_dir.rename(scan_dir)
|
||||
disposition = "restored"
|
||||
connection.commit()
|
||||
except BaseException:
|
||||
connection.rollback()
|
||||
raise
|
||||
return {
|
||||
"disposition": disposition,
|
||||
"scanDir": str(scan_dir),
|
||||
"archivedScanDir": str(archived_scan_dir),
|
||||
}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def register_windows_resume_output(
|
||||
connection: sqlite3.Connection,
|
||||
@@ -351,6 +402,7 @@ def insert_running_scan(
|
||||
scope: str,
|
||||
diff_target: dict[str, str] | None,
|
||||
target_identity: tuple[str, str | None, int | str, int | str],
|
||||
repository_generation: str | None,
|
||||
source_scopes: dict[str, Any],
|
||||
target_root: Path,
|
||||
target_summary: str | None,
|
||||
@@ -381,19 +433,21 @@ def insert_running_scan(
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO scans (
|
||||
id, workspace_id, target_id, target_path, target_revision, target_snapshot_digest,
|
||||
id, workspace_id, target_id, repository_generation, target_path,
|
||||
target_revision, target_snapshot_digest,
|
||||
target_device, target_inode, source_scopes_json, scope, mode, user_context,
|
||||
deep_scan_owner_thread_id, diff_target_kind, diff_base_revision,
|
||||
diff_head_revision, diff_content_digest, target_summary, scan_dir, model,
|
||||
reasoning_effort, status, phase, handoff_status, started_at, created_at, updated_at,
|
||||
launch_surface, launch_package_version, launch_plugin_version, launch_kind
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
'running', ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
scan_id,
|
||||
workspace["id"],
|
||||
workspace["target_id"],
|
||||
repository_generation,
|
||||
str(target),
|
||||
*target_identity,
|
||||
json.dumps(source_scopes, allow_nan=False, separators=(",", ":"), sort_keys=True),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -52,6 +52,7 @@ def apply_migrations(
|
||||
backfill_security_targets: Callable[[sqlite3.Connection], None],
|
||||
*,
|
||||
immediate: bool = False,
|
||||
discovery_roots: tuple[Path, ...] = (),
|
||||
) -> None:
|
||||
"""Apply missing schema versions and repair supported historical migrations.
|
||||
|
||||
@@ -59,9 +60,17 @@ def apply_migrations(
|
||||
Set immediate to acquire the SQLite write lock up front. The backfill callback
|
||||
links older scans and workspaces to stable targets when required.
|
||||
"""
|
||||
from workbench_target import scoped_git_discovery
|
||||
|
||||
connection.commit()
|
||||
connection.execute("BEGIN IMMEDIATE" if immediate else "BEGIN")
|
||||
with connection:
|
||||
with (
|
||||
connection,
|
||||
scoped_git_discovery(
|
||||
lambda: [*migration_target_paths(connection), *discovery_roots],
|
||||
recorded_git_roots=lambda: recorded_git_checkout_roots(connection),
|
||||
),
|
||||
):
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
@@ -83,8 +92,33 @@ def apply_migrations(
|
||||
apply_repair_statement(connection, statement.replace("\n", " "))
|
||||
elif version == 16:
|
||||
should_backfill_targets = repair_stable_targets_migration(connection)
|
||||
elif version == 67:
|
||||
should_backfill_targets = (
|
||||
repair_repository_identity_migration(connection)
|
||||
or version not in applied
|
||||
or should_backfill_targets
|
||||
)
|
||||
elif version in applied:
|
||||
if version in (2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55, 58, 59, 60, 61):
|
||||
if version in (
|
||||
2,
|
||||
12,
|
||||
13,
|
||||
26,
|
||||
28,
|
||||
31,
|
||||
32,
|
||||
42,
|
||||
47,
|
||||
50,
|
||||
54,
|
||||
55,
|
||||
58,
|
||||
59,
|
||||
60,
|
||||
61,
|
||||
69,
|
||||
70,
|
||||
):
|
||||
repair_schema(connection, version)
|
||||
elif version == 11:
|
||||
repair_deep_scan_migration(connection)
|
||||
@@ -96,6 +130,10 @@ def apply_migrations(
|
||||
connection.execute(statement)
|
||||
if version == 38:
|
||||
migrate_finding_workflow_results(connection)
|
||||
elif version == 68:
|
||||
from workbench_target_state import upgrade_linux_repository_generations
|
||||
|
||||
upgrade_linux_repository_generations(connection)
|
||||
if version not in applied:
|
||||
connection.execute(
|
||||
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
|
||||
@@ -107,6 +145,65 @@ def apply_migrations(
|
||||
backfill_security_targets(connection)
|
||||
|
||||
|
||||
def migration_target_paths(connection: sqlite3.Connection) -> list[Path]:
|
||||
paths: set[Path] = set()
|
||||
for table, column in (
|
||||
("security_targets", "current_path"),
|
||||
("workspaces", "target_path"),
|
||||
("scans", "target_path"),
|
||||
):
|
||||
columns = {row["name"] for row in connection.execute(f"PRAGMA table_info({table})")}
|
||||
if column in columns:
|
||||
condition = (
|
||||
" AND (target_path_unvalidated = 0 OR target_id IS NOT NULL)"
|
||||
if table == "workspaces" and "target_path_unvalidated" in columns
|
||||
else ""
|
||||
)
|
||||
paths.update(
|
||||
Path(row[0])
|
||||
for row in connection.execute(
|
||||
f"SELECT DISTINCT {column} FROM {table} WHERE {column} IS NOT NULL{condition}"
|
||||
)
|
||||
)
|
||||
return list(paths)
|
||||
|
||||
|
||||
def recorded_git_checkout_roots(connection: sqlite3.Connection) -> set[Path] | None:
|
||||
"""Return saved boundaries, or None if any historical target lacks one."""
|
||||
target_columns = {
|
||||
row["name"] for row in connection.execute("PRAGMA table_info(security_targets)")
|
||||
}
|
||||
boundaries = (
|
||||
{
|
||||
Path(target): Path(root)
|
||||
for target, root in connection.execute(
|
||||
"SELECT current_path, git_checkout_root FROM security_targets "
|
||||
"WHERE git_checkout_root IS NOT NULL"
|
||||
)
|
||||
}
|
||||
if "git_checkout_root" in target_columns
|
||||
else {}
|
||||
)
|
||||
# Even an unversioned scan may have come from an unborn Git checkout.
|
||||
if any(path not in boundaries for path in migration_target_paths(connection)):
|
||||
return None
|
||||
roots = set(boundaries.values())
|
||||
columns = {row["name"] for row in connection.execute("PRAGMA table_info(workspaces)")}
|
||||
if "target_path_unvalidated" in columns:
|
||||
saved = (
|
||||
"rejected_checkout_roots_json" if "rejected_checkout_roots_json" in columns else "NULL"
|
||||
)
|
||||
for (root,) in connection.execute(
|
||||
f"SELECT DISTINCT value FROM workspaces LEFT JOIN json_each({saved}) "
|
||||
f"WHERE {saved} IS NOT NULL OR "
|
||||
"(target_path IS NOT NULL AND target_path_unvalidated = 1 AND target_id IS NULL)"
|
||||
):
|
||||
if root is None:
|
||||
return None
|
||||
roots.add(Path(root))
|
||||
return roots
|
||||
|
||||
|
||||
def normalize_pre_release_migrations(connection: sqlite3.Connection, timestamp: str) -> None:
|
||||
for query in _REPAIR_PLAN:
|
||||
actions = connection.execute("\n".join(query), {"history": _REPAIR_HISTORY}).fetchall()
|
||||
@@ -181,22 +278,131 @@ def repair_stable_targets_migration(connection: sqlite3.Connection) -> bool:
|
||||
and "target_id" in scan_columns
|
||||
and existing_objects == {"security_targets", "scans_by_target"}
|
||||
):
|
||||
return False
|
||||
validated_workspace = (
|
||||
"workspace.target_path_unvalidated = 0 AND "
|
||||
if "target_path_unvalidated" in workspace_columns
|
||||
else ""
|
||||
)
|
||||
needs_backfill = bool(
|
||||
connection.execute(
|
||||
f"""
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM workspaces AS workspace
|
||||
WHERE ({validated_workspace}workspace.target_id IS NULL
|
||||
AND workspace.target_path IS NOT NULL)
|
||||
OR (
|
||||
workspace.target_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM security_targets
|
||||
WHERE security_targets.id = workspace.target_id
|
||||
)
|
||||
)
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM scans AS scan
|
||||
WHERE scan.target_id IS NULL
|
||||
OR NOT EXISTS (
|
||||
SELECT 1 FROM security_targets
|
||||
WHERE security_targets.id = scan.target_id
|
||||
)
|
||||
)
|
||||
"""
|
||||
).fetchone()[0]
|
||||
)
|
||||
if not needs_backfill:
|
||||
return False
|
||||
else:
|
||||
repair_schema(connection, 16)
|
||||
|
||||
repair_schema(connection, 16)
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE scans
|
||||
SET target_id = NULL
|
||||
WHERE target_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM security_targets WHERE security_targets.id = scans.target_id
|
||||
)
|
||||
"""
|
||||
)
|
||||
for table in ("workspaces", "scans"):
|
||||
connection.execute(
|
||||
f"""
|
||||
UPDATE {table}
|
||||
SET target_id = NULL
|
||||
WHERE target_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM security_targets
|
||||
WHERE security_targets.id = {table}.target_id
|
||||
)
|
||||
"""
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def repair_repository_identity_migration(connection: sqlite3.Connection) -> bool:
|
||||
columns = {row["name"] for row in connection.execute("PRAGMA table_info(security_targets)")}
|
||||
index_exists = connection.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'index' "
|
||||
"AND name = 'security_targets_by_repository_identity'"
|
||||
).fetchone()
|
||||
identity_changed = "repository_identity" not in columns or index_exists is None
|
||||
if (
|
||||
"repository_identity" in columns
|
||||
and connection.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = 67 AND name = ?",
|
||||
("persist repository identities",),
|
||||
).fetchone()
|
||||
is not None
|
||||
and not any(
|
||||
row["name"] == "repository_generation"
|
||||
for row in connection.execute("PRAGMA table_info(scans)")
|
||||
)
|
||||
):
|
||||
from workbench_target_state import normalize_pre_release_repository_identities
|
||||
|
||||
normalize_pre_release_repository_identities(connection)
|
||||
migration_sql = next(sql for version, _, sql in MIGRATIONS if version == 67)
|
||||
for statement in sql_statements(migration_sql):
|
||||
if statement.startswith(("ALTER TABLE security_targets", "ALTER TABLE scans")):
|
||||
add_migration_column(connection, statement)
|
||||
continue
|
||||
for prefix in ("CREATE UNIQUE INDEX ", "CREATE INDEX ", "CREATE TRIGGER "):
|
||||
if statement.startswith(prefix):
|
||||
statement = statement.replace(prefix, f"{prefix}IF NOT EXISTS ", 1)
|
||||
break
|
||||
connection.execute(statement)
|
||||
|
||||
from workbench_scan_history import _scan_completion_order
|
||||
|
||||
if connection.execute(
|
||||
"SELECT 1 FROM scans WHERE status = 'complete' AND completion_sequence IS NULL LIMIT 1"
|
||||
).fetchone():
|
||||
# SQL preserves the recorded sequence. Both projections omit it so the merge
|
||||
# compares each pending row with the timestamp of the next recorded completion.
|
||||
recorded = connection.execute(
|
||||
"SELECT id, started_at, completed_at FROM scans "
|
||||
"WHERE status = 'complete' AND completion_sequence IS NOT NULL "
|
||||
"ORDER BY completion_sequence"
|
||||
).fetchall()
|
||||
unsequenced = connection.execute(
|
||||
"SELECT id, started_at, completed_at FROM scans "
|
||||
"WHERE status = 'complete' AND completion_sequence IS NULL"
|
||||
).fetchall()
|
||||
pending = iter(sorted(unsequenced, key=_scan_completion_order))
|
||||
candidate = next(pending, None)
|
||||
completed = []
|
||||
for scan in recorded:
|
||||
while candidate is not None and _scan_completion_order(
|
||||
candidate
|
||||
) <= _scan_completion_order(scan):
|
||||
completed.append(candidate)
|
||||
candidate = next(pending, None)
|
||||
completed.append(scan)
|
||||
if candidate is not None:
|
||||
completed.append(candidate)
|
||||
completed.extend(pending)
|
||||
connection.execute("UPDATE scans SET completion_sequence = NULL WHERE status = 'complete'")
|
||||
sequence = connection.execute(
|
||||
"SELECT COALESCE(MAX(completion_sequence), 0) FROM scans"
|
||||
).fetchone()[0]
|
||||
for scan in completed:
|
||||
sequence += 1
|
||||
connection.execute(
|
||||
"UPDATE scans SET completion_sequence = ? WHERE id = ?",
|
||||
(sequence, scan["id"]),
|
||||
)
|
||||
return identity_changed
|
||||
|
||||
|
||||
def repair_schema(connection: sqlite3.Connection, version: int) -> None:
|
||||
for statement in _STATEMENTS[version]:
|
||||
apply_repair_statement(connection, statement)
|
||||
|
||||
@@ -15,9 +15,10 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from collections.abc import Iterator
|
||||
from collections.abc import Iterable, Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from contextvars import ContextVar
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any, BinaryIO, Callable, cast
|
||||
|
||||
@@ -29,6 +30,7 @@ from workbench_constants import GIT_REPOSITORY_ENVIRONMENT
|
||||
|
||||
SOURCE_METADATA_DIRECTORIES = {".git", ".svn"}
|
||||
_WINDOWS = os.name == "nt"
|
||||
_SCOPED_GIT: ContextVar[Callable[[Path], str] | None] = ContextVar("workbench_git", default=None)
|
||||
|
||||
|
||||
class UnreadableLocalFile(SystemExit):
|
||||
@@ -207,8 +209,10 @@ def _stream_is_binary(output: BinaryIO, size: int, *, drain: bool = False) -> bo
|
||||
|
||||
def _protected_repository_root(target: Path) -> Path:
|
||||
root = target.resolve()
|
||||
if root.is_file():
|
||||
root = root.parent
|
||||
return _outer_checkout_root(root.parent if root.is_file() else root)
|
||||
|
||||
|
||||
def _outer_checkout_root(root: Path) -> Path:
|
||||
protected = root
|
||||
for ancestor in (root, *root.parents):
|
||||
try:
|
||||
@@ -219,9 +223,67 @@ def _protected_repository_root(target: Path) -> Path:
|
||||
return protected
|
||||
|
||||
|
||||
def rejected_checkout_roots(value: str) -> list[str] | None:
|
||||
# Retain both spellings before a checkout marker or symlink can move.
|
||||
try:
|
||||
lexical = Path(value).expanduser().absolute()
|
||||
canonical = lexical.resolve()
|
||||
lexical_root = _outer_checkout_root(lexical)
|
||||
roots = {
|
||||
lexical,
|
||||
canonical,
|
||||
lexical_root,
|
||||
lexical_root.resolve(),
|
||||
_protected_repository_root(canonical),
|
||||
}
|
||||
return sorted(map(str, roots))
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
|
||||
|
||||
def pin_scoped_git(target: Path) -> str | None:
|
||||
scoped = _SCOPED_GIT.get()
|
||||
return scoped(target) if scoped is not None else None
|
||||
|
||||
|
||||
def trusted_git_executable(protected_root: Path) -> str | None:
|
||||
"""Validate host-selected Git, or discover Git for a direct plugin invocation."""
|
||||
configured = os.environ.get("CODEX_SECURITY_GIT")
|
||||
if configured is None:
|
||||
configured = pin_scoped_git(protected_root)
|
||||
return _resolve_git_executable(protected_root, configured)
|
||||
|
||||
|
||||
def _historical_repository_roots(target: Path) -> Iterator[Path]:
|
||||
try:
|
||||
yield _protected_repository_root(target)
|
||||
except (OSError, RuntimeError):
|
||||
# Keep checking lexical ancestry when the saved path cannot be resolved.
|
||||
pass
|
||||
# A moved or unavailable descendant still excludes its lexical checkout ancestry.
|
||||
root = Path(os.path.abspath(target))
|
||||
protected = root
|
||||
for ancestor in (root, *root.parents):
|
||||
try:
|
||||
(ancestor / ".git").lstat()
|
||||
except (OSError, RuntimeError):
|
||||
continue
|
||||
protected = ancestor
|
||||
yield protected
|
||||
try:
|
||||
yield protected.resolve()
|
||||
except (OSError, RuntimeError):
|
||||
# The lexical root above still excludes tools at an unavailable checkout.
|
||||
pass
|
||||
|
||||
|
||||
def _resolve_git_executable(
|
||||
protected_root: Path,
|
||||
configured: str | None,
|
||||
*,
|
||||
discovery_roots: Iterable[Path] = (),
|
||||
recorded_git_roots: Iterable[Path] | None = (),
|
||||
) -> str | None:
|
||||
windows = sys.platform == "win32"
|
||||
if configured is None:
|
||||
names = ("git.exe", "git.com") if windows else ("git",)
|
||||
@@ -239,7 +301,22 @@ def trusted_git_executable(protected_root: Path) -> str | None:
|
||||
candidates = iter((candidate,))
|
||||
|
||||
try:
|
||||
repository = _protected_repository_root(protected_root)
|
||||
repositories = [_protected_repository_root(protected_root)]
|
||||
if configured is None:
|
||||
# A legacy Git target has no trustworthy boundary to exclude from PATH.
|
||||
if recorded_git_roots is None:
|
||||
return None
|
||||
saved_boundaries = tuple(recorded_git_roots)
|
||||
for root in saved_boundaries:
|
||||
repositories.extend(_historical_repository_roots(root))
|
||||
for root in discovery_roots:
|
||||
for repository in _historical_repository_roots(root):
|
||||
if not repository.is_dir() and not any(
|
||||
repository.is_relative_to(boundary) for boundary in saved_boundaries
|
||||
):
|
||||
# Its former checkout is neither discoverable nor already excluded.
|
||||
return None
|
||||
repositories.append(repository)
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
|
||||
@@ -264,6 +341,7 @@ def trusted_git_executable(protected_root: Path) -> str | None:
|
||||
continue
|
||||
if any(
|
||||
path == repository or repository in path.parents
|
||||
for repository in repositories
|
||||
for path in (lexical, invocation, canonical)
|
||||
):
|
||||
if configured is not None:
|
||||
@@ -273,6 +351,39 @@ def trusted_git_executable(protected_root: Path) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def scoped_git_discovery(
|
||||
protected_roots: Callable[[], Iterable[Path]],
|
||||
*,
|
||||
recorded_git_roots: Callable[[], Iterable[Path] | None] = lambda: (),
|
||||
) -> Iterator[None]:
|
||||
"""Pin ambient Git when an operation first needs to inspect repository targets."""
|
||||
if os.environ.get("CODEX_SECURITY_GIT") is not None:
|
||||
yield
|
||||
return
|
||||
executable: str | None = None
|
||||
|
||||
def resolve_once(target: Path) -> str:
|
||||
nonlocal executable
|
||||
if executable is None:
|
||||
executable = (
|
||||
_resolve_git_executable(
|
||||
Path.cwd(),
|
||||
None,
|
||||
discovery_roots=(*protected_roots(), target),
|
||||
recorded_git_roots=recorded_git_roots(),
|
||||
)
|
||||
or ""
|
||||
)
|
||||
return executable
|
||||
|
||||
token = _SCOPED_GIT.set(resolve_once)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_SCOPED_GIT.reset(token)
|
||||
|
||||
|
||||
def git_command(
|
||||
target: Path,
|
||||
*args: str,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,9 +8,9 @@
|
||||
"SELECT 'sql' AS operation,",
|
||||
" 'UPDATE schema_migrations SET version = ' || destination || ' WHERE version = ' || version AS value",
|
||||
"FROM schema_migrations JOIN history USING (name)",
|
||||
"WHERE (destination = 67 AND version IN (42, 43, 48, 50, 53, 54, 61, 63, 64))",
|
||||
" OR (destination = 68 AND version IN (43, 44, 49, 51, 54, 55, 62, 64, 65))",
|
||||
" OR (destination = 69 AND version IN (56, 63, 65, 66)) ORDER BY version DESC;"
|
||||
"WHERE (destination = 73 AND version IN (67, 42, 43, 48, 50, 53, 54, 61, 63, 64))",
|
||||
" OR (destination = 74 AND version IN (68, 43, 44, 49, 51, 54, 55, 62, 64, 65))",
|
||||
" OR (destination = 75 AND version IN (69, 56, 63, 65, 66)) ORDER BY version DESC;"
|
||||
],
|
||||
[
|
||||
"-- A released reader can add its columns while a finding history preview still owns the version.",
|
||||
@@ -34,6 +34,23 @@
|
||||
"WITH input AS (SELECT :history AS history),",
|
||||
"previews AS (",
|
||||
" SELECT version, CASE",
|
||||
" -- Prefer the original timestamp when a reader reopened the 52/53 repository preview.",
|
||||
" WHEN version IN (64, 67) AND name = 'persist repository identities'",
|
||||
" AND EXISTS (SELECT 1 FROM schema_migrations WHERE version = 52 AND name = receipt.name)",
|
||||
" THEN 'DELETE FROM schema_migrations'",
|
||||
" WHEN version IN (65, 68) AND name = 'stabilize Linux repository generations'",
|
||||
" AND EXISTS (SELECT 1 FROM schema_migrations WHERE version = 53 AND name = receipt.name)",
|
||||
" THEN 'DELETE FROM schema_migrations'",
|
||||
" WHEN version IN (50, 52, 53, 54, 61, 63, 64) AND name = 'persist repository identities'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 67'",
|
||||
" WHEN version IN (51, 53, 54, 55, 62, 64, 65) AND name = 'stabilize Linux repository generations'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 68'",
|
||||
" WHEN version IN (56, 63, 65, 66) AND name = 'distinguish unvalidated workspace targets'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 69'",
|
||||
" WHEN version IN (64, 66, 67) AND name = 'retain checkout roots for Git discovery'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 70'",
|
||||
" WHEN version IN (67, 68) AND name = 'retain rejected workspace checkout boundaries'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 71'",
|
||||
" WHEN version IN (48, 50, 63) AND name = 'persist scan log completion boundaries'",
|
||||
" THEN 'UPDATE schema_migrations SET version = 64'",
|
||||
" WHEN version IN (58, 59) AND name = 'record classification rubric provenance'",
|
||||
@@ -44,23 +61,13 @@
|
||||
" THEN 'UPDATE schema_migrations SET version = 50'",
|
||||
" WHEN version = 63 AND name = 'retain native investigation time allowances'",
|
||||
" THEN 'DELETE FROM schema_migrations'",
|
||||
" END AS repair FROM schema_migrations",
|
||||
" END AS repair FROM schema_migrations AS receipt",
|
||||
")",
|
||||
"SELECT 'sql' AS operation, repair || ' WHERE version = ' || version AS value",
|
||||
"FROM previews WHERE repair IS NOT NULL",
|
||||
"-- Vacate checkpoint preview 50 before moving a lower source-scope receipt into it.",
|
||||
"ORDER BY version DESC;"
|
||||
],
|
||||
[
|
||||
"WITH history AS (",
|
||||
" SELECT json_extract(value, '$.version') AS version,",
|
||||
" json_extract(value, '$.name') AS name FROM json_each(:history)",
|
||||
")",
|
||||
"SELECT 'error' AS operation,",
|
||||
" 'The Codex Security database has an unsupported source-scope migration history.' AS value",
|
||||
"FROM schema_migrations JOIN history USING (version)",
|
||||
"WHERE version IN (43, 50) AND schema_migrations.name != history.name;"
|
||||
],
|
||||
[
|
||||
"-- mirror and early-moves: relocate numbers before checking profiles.",
|
||||
"WITH",
|
||||
@@ -81,9 +88,20 @@
|
||||
"),",
|
||||
"moves(position, version, destination, name) AS (",
|
||||
" VALUES",
|
||||
" (0, 33, 40, 'index finding identity and comparison history'),",
|
||||
" (1, 25, 26, 'persist scan completion warnings'),",
|
||||
" (2, 12, 20, 'phase-specific scan progress')",
|
||||
" (-2, 48, 67, 'persist repository identities'),",
|
||||
" (-1, 49, 68, 'stabilize Linux repository generations'),",
|
||||
" (0, 44, 68, 'stabilize Linux repository generations'),",
|
||||
" (1, 45, 68, 'stabilize Linux repository generations'),",
|
||||
" (2, 30, 67, 'persist repository identities'),",
|
||||
" (3, 31, 67, 'persist repository identities'),",
|
||||
" (4, 33, 67, 'persist repository identities'),",
|
||||
" (5, 40, 67, 'persist repository identities'),",
|
||||
" (6, 42, 67, 'persist repository identities'),",
|
||||
" (7, 43, 67, 'persist repository identities'),",
|
||||
" (8, 44, 67, 'persist repository identities'),",
|
||||
" (9, 33, 40, 'index finding identity and comparison history'),",
|
||||
" (10, 25, 26, 'persist scan completion warnings'),",
|
||||
" (11, 12, 20, 'phase-specific scan progress')",
|
||||
")",
|
||||
"SELECT 0 AS position, 'error' AS operation,",
|
||||
" 'The Codex Security database has an unsupported mirror migration history.' AS value",
|
||||
@@ -100,6 +118,34 @@
|
||||
" FROM moves JOIN schema_migrations USING (version, name)",
|
||||
"ORDER BY position;"
|
||||
],
|
||||
[
|
||||
"WITH history AS (",
|
||||
" SELECT json_extract(value, '$.version') AS version,",
|
||||
" json_extract(value, '$.name') AS name FROM json_each(:history)",
|
||||
")",
|
||||
"SELECT 'error' AS operation,",
|
||||
" 'The Codex Security database has an unsupported source-scope migration history.' AS value",
|
||||
"FROM schema_migrations JOIN history USING (version)",
|
||||
"WHERE version IN (43, 50) AND schema_migrations.name != history.name;"
|
||||
],
|
||||
[
|
||||
"-- A released reader can add its columns while a repository preview still owns the version.",
|
||||
"WITH released(version, table_name, column_name) AS (",
|
||||
" VALUES (54, 'workspaces', 'deep_scan_config_json'),",
|
||||
" (55, 'deep_scan_runs', 'pending_target_project_path'),",
|
||||
" (58, 'deep_scan_runs', 'terminal_reviewed_surface_count'),",
|
||||
" (59, 'deep_scan_runs', 'service_tier'),",
|
||||
" (61, 'scans', 'launch_surface')",
|
||||
")",
|
||||
"SELECT 'timestamp' AS operation,",
|
||||
" 'INSERT INTO schema_migrations (version, name, applied_at) VALUES (' ||",
|
||||
" released.version || ', ' || quote(json_extract(history.value, '$.name')) || ', ?)' AS value",
|
||||
"FROM released JOIN json_each(:history) AS history",
|
||||
" ON json_extract(history.value, '$.version') = released.version",
|
||||
"WHERE EXISTS (SELECT 1 FROM schema_migrations WHERE name = 'persist repository identities')",
|
||||
" AND NOT EXISTS (SELECT 1 FROM schema_migrations WHERE version = released.version)",
|
||||
" AND EXISTS (SELECT 1 FROM pragma_table_info(released.table_name) WHERE name = released.column_name);"
|
||||
],
|
||||
[
|
||||
"-- A main-branch reader may have added discovery context under the old checkpoint number.",
|
||||
"SELECT 'timestamp' AS operation,",
|
||||
@@ -295,6 +341,6 @@
|
||||
" json_extract(value, '$.name') AS name FROM json_each(:history))",
|
||||
"SELECT 'error' AS operation, 'Unsupported finding history migration receipt.' AS value",
|
||||
"FROM schema_migrations AS receipt JOIN history USING (version)",
|
||||
"WHERE receipt.version BETWEEN 63 AND 69 AND receipt.name != history.name LIMIT 1;"
|
||||
"WHERE receipt.version BETWEEN 63 AND 75 AND receipt.name != history.name LIMIT 1;"
|
||||
]
|
||||
]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user