Skip to content

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

feat(action)!: prepare hosted runners and require completed PR checks (#1580)

Michael D'Angelof601cd659bbb
diff --git a/.github/workflows/action-ci.yml b/.github/workflows/action-ci.yml
index f33cd0fea..31524c9e9 100644
--- a/.github/workflows/action-ci.yml
+++ b/.github/workflows/action-ci.yml
@@ -59,9 +59,6 @@ jobs:
with:
node-version: "24"
package-manager-cache: false
- - &set-up-the-ubuntu-sandbox
- name: Set up the Ubuntu sandbox
- run: bash scripts/setup-ubuntu-sandbox.sh
- run: npm ci --ignore-scripts --no-audit --no-fund
- run: npm run validate
- name: Set up Bun for Action release contracts
@@ -74,12 +71,12 @@ jobs:
if: inputs.sdk-contracts
working-directory: sdk/typescript
run: bun test --timeout 30000 tests-ts/action-release-workflow.test.ts tests-ts/codex-dependency-pins.test.ts
+ - name: Packaged Linux sandbox and configuration smoke test (no model calls)
+ run: node scripts/linux-smoke.mjs
- name: Install the pinned CLI for integration tests
run: npm ci --prefix runtime --ignore-scripts --no-audit --no-fund
- name: Published CLI result and SARIF compatibility (no model calls)
run: npm run test:cli
- - name: Packaged Linux configuration smoke test (no model calls)
- run: node scripts/linux-smoke.mjs
- name: Save generated release metadata
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -102,11 +99,10 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # Run setup from the merge commit, then test the Action at its PR head.
+ # Test the Action at its PR head.
fetch-depth: 2
persist-credentials: false
- *actions-setup-node
- - *set-up-the-ubuntu-sandbox
- name: Check out the PR head for the Action smoke tests
if: github.event_name == 'pull_request'
env:
diff --git a/.github/workflows/workflow-quality.yml b/.github/workflows/workflow-quality.yml
index 36658a6a5..25412c825 100644
--- a/.github/workflows/workflow-quality.yml
+++ b/.github/workflows/workflow-quality.yml
@@ -38,6 +38,7 @@ jobs:
SHELLCHECK_OPTS: --severity=warning
run: |
actionlint -color
+ actionlint -color github-action/examples/*.yml
shellcheck .github/scripts/*.sh docker/verify-container-compose.sh github-action/scripts/setup-ubuntu-sandbox.sh
- name: Test release progress reporting
run: node --test .github/scripts/test_release_progress.mjs
diff --git a/README.md b/README.md
index 6f4114a6c..a0a9eaca1 100644
--- a/README.md
+++ b/README.md
@@ -197,7 +197,8 @@ Run scheduled, manual, or pull request scans with the GitHub Action. For a weekl
repository scan, add an OpenAI API key as the repository secret
`CODEX_SECURITY_API_KEY`, then save this workflow in
`.github/workflows/codex-security.yml`. Replace `REPLACE_WITH_REVIEWED_COMMIT`
-with the full SHA of an Action commit.
+with the full SHA of an Action release that includes automatic Ubuntu sandbox setup.
+For older pins, including `action-v0.6.0`, keep the [manual sandbox setup](https://github.com/openai/codex-security/blob/action-v0.6.0/github-action/README.md#ubuntu-sandbox-setup).
This workflow requests Daybreak Blue. Use an API key from a project with Blue
enabled; without Daybreak access, omit `cyber-access-program` or set it to
@@ -217,12 +218,6 @@ jobs:
security:
runs-on: ubuntu-24.04
steps:
- # Configure Bubblewrap and AppArmor so Codex Security can run safely in its sandbox.
- - name: Set up the Ubuntu sandbox
- run: |
- sudo apt-get update
- sudo apt-get install --yes bubblewrap apparmor-profiles
- sudo apparmor_parser -r /usr/share/apparmor/extra-profiles/bwrap-userns-restrict
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -235,6 +230,9 @@ jobs:
OPENAI_API_KEY: ${{ secrets.CODEX_SECURITY_API_KEY }}
```
+The Action sets up and verifies the sandbox on GitHub-hosted Ubuntu 24.04 VMs.
+Self-hosted runners and job containers must provide a working Codex sandbox.
+
Findings are report-only by default. Set a severity threshold to fail on reported
findings at or above it. Scanner and required reporting errors fail the job;
intentional file exclusions and investigation notes do not.
diff --git a/action.yml b/action.yml
index 1fc4c627e..a794f4680 100644
--- a/action.yml
+++ b/action.yml
@@ -38,7 +38,7 @@ inputs:
description: Stream CLI diagnostics to the job log. Set false for lifecycle and elapsed-time messages only.
default: 'true'
dry-run:
- description: Validate local configuration without a scan or API key. Does not verify authentication or model access. Use a separate non-required job.
+ description: 'Validate local configuration without a scan or API key. Does not verify authentication or model access. Requires fail-on-severity: none; use a separate non-required job.'
default: 'false'
summary:
description: Write a human-readable job summary.
@@ -47,7 +47,7 @@ inputs:
description: Emit up to 50 source finding annotations; complete findings remain in reports.
default: 'true'
upload-artifacts:
- description: Upload an allowlist of validated reports. Reports may contain source and vulnerability details.
+ description: Upload an allowlist of validated reports and link the artifact in the job summary. Reports may contain source and vulnerability details.
default: 'false'
artifact-name:
description: Report artifact name; choose distinct names for matrix jobs and multiple invocations.
diff --git a/github-action/README.md b/github-action/README.md
index b8dceeec4..37c347c77 100644
--- a/github-action/README.md
+++ b/github-action/README.md
@@ -12,14 +12,17 @@ with access to the selected model. OpenAI is the default provider. See
Add your API key as a repository secret named `CODEX_SECURITY_API_KEY`, then
save this workflow in `.github/workflows/codex-security.yml`.
-Replace `REPLACE_WITH_REVIEWED_COMMIT` with the full SHA of an Action commit.
-The matching `action-vX.Y.Z` release lists the full distribution commit SHA
-and links to the product changelog after the Action has passed release checks.
+Replace `REPLACE_WITH_REVIEWED_COMMIT` with the full distribution SHA from an
+`action-vX.Y.Z` release that includes automatic Ubuntu sandbox setup.
+For older pins, including `action-v0.6.0`, keep the [manual sandbox setup](https://github.com/openai/codex-security/blob/action-v0.6.0/github-action/README.md#ubuntu-sandbox-setup).
When using a fork, replace `openai` with the fork owner.
-This example requests Daybreak Blue. Use an API key from a project with Blue
-enabled; without Daybreak access, omit `cyber-access-program` or set it to
-`standard`. See [Daybreak access and refusals](#daybreak-access-and-refusals).
+The [repository workflow](examples/repository.yml) below uses `gpt-5.6-sol` and
+an estimated $5 cost limit. Change `max-cost` to adjust the budget, or remove it
+for no estimated cost limit. Requests already in progress can exceed the limit.
+Daybreak is optional; see [Daybreak access and refusals](#daybreak-access-and-refusals).
+
+<!-- action-workflow:repository:start -->
```yaml
name: Codex Security repository
@@ -34,25 +37,26 @@ permissions:
jobs:
security:
runs-on: ubuntu-24.04
+ timeout-minutes: 120
steps:
- # Configure Bubblewrap and AppArmor so Codex Security can run safely in its sandbox.
- - name: Set up the Ubuntu sandbox
- run: |
- sudo apt-get update
- sudo apt-get install --yes bubblewrap apparmor-profiles
- sudo apparmor_parser -r /usr/share/apparmor/extra-profiles/bwrap-userns-restrict
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT
+ - name: Scan the repository
+ id: security
+ uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT
with:
+ scope: repository
model: gpt-5.6-sol
effort: high
- cyber-access-program: daybreak_blue
+ max-cost: "5"
+ fail-on-severity: none
env:
OPENAI_API_KEY: ${{ secrets.CODEX_SECURITY_API_KEY }}
```
+<!-- action-workflow:repository:end -->
+
The workflow runs weekly on Mondays at 07:23 UTC. To run it manually, use
**Actions → Codex Security repository → Run workflow**.
Findings are report-only by default. Set `fail-on-severity` to fail on reported
@@ -61,21 +65,15 @@ also fail the job. Intentional exclusions and investigation notes do not.
### Ubuntu sandbox setup
-Codex Security runs commands inside a sandbox to limit their filesystem and
-network access. On the Ubuntu 24.04 runner used above, that sandbox uses
-Bubblewrap (`bwrap`), and Ubuntu's AppArmor policy must allow it to create the
-required isolated environment.
-
-The setup step installs `bubblewrap` and `apparmor-profiles`, then uses
-`apparmor_parser -r` to load the supplied `bwrap-userns-restrict` profile. The
-profile permits Bubblewrap's sandbox setup while retaining Ubuntu's broader
-AppArmor restrictions. Keep this step before the Action: the CLI checks that
-its sandbox works before scanning and fails if it cannot start, for example
-with `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`.
+The Action checks that Codex can start its sandbox before using the scan
+credential. If sandbox startup fails on a GitHub-hosted Ubuntu 24.04 VM and Codex
+can load its configuration, the Action installs `bubblewrap` and
+`apparmor-profiles`, loads the supplied
+`bwrap-userns-restrict` AppArmor profile, and checks startup again.
-This setup is specific to the Linux runner. Local macOS scans use the built-in
-Seatbelt sandbox and do not need Bubblewrap. See the
-[sandbox documentation](https://learn.chatgpt.com/docs/sandboxing) for details.
+Self-hosted runners and job containers must provide a working Codex sandbox.
+The Action checks sandbox startup in both, but does not install system packages
+or change AppArmor there. See the [sandbox documentation](https://learn.chatgpt.com/docs/sandboxing).
## Supported GitHub hosts and checkout URLs
@@ -175,11 +173,6 @@ jobs:
contents: read
id-token: write
steps:
- - name: Set up the Ubuntu sandbox
- run: |
- sudo apt-get update
- sudo apt-get install --yes bubblewrap apparmor-profiles
- sudo apparmor_parser -r /usr/share/apparmor/extra-profiles/bwrap-userns-restrict
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -207,7 +200,9 @@ jobs:
```
Replace the Action placeholder with a reviewed commit that includes Bedrock
-support. This example is report-only; the usual severity thresholds, summaries,
+support and [automatic Ubuntu sandbox setup](#ubuntu-sandbox-setup). For older
+pins, keep the [manual setup step](https://github.com/openai/codex-security/blob/action-v0.6.0/github-action/README.md#ubuntu-sandbox-setup).
+This example is report-only; the usual severity thresholds, summaries,
annotations, artifacts, and SARIF outputs also work with Bedrock.
Both `mode: standard` and `mode: deep` use the selected AWS credentials. Allow
@@ -230,8 +225,7 @@ Daybreak is optional. You can use the Action with a general-purpose model your
credentials can access under standard safeguards. Some security tasks may trigger
model refusals or API cybersecurity safety blocks. **If a refusal or safety
block aborts the scan, the Action fails**, even with `fail-on-severity: none`.
-That setting controls failures caused by findings; it does not suppress scanner
-errors. Check the job summary and logs for the reason. A failed scan does not
+The findings setting does not suppress scanner errors. Check the job summary and logs for the reason. A failed scan does not
mean the repository has no vulnerabilities.
For authorized security work that needs reduced refusals,
@@ -254,35 +248,100 @@ use an approved model ID and AWS provisioning as described in
## Scan pull requests
-Use the same API-key secret and Action commit as above. Check out the PR head
-with full history so the Action can resolve the diff.
+Use the same API-key secret and Action commit as above. The
+[pull-request workflow](examples/pull-request.yml) checks out the PR head with
+full history and requires a completed scan of the event's snapshot. For each protected target branch,
+require its matching **Codex Security / <target-branch>** check (for example,
+**Codex Security / main** on `main`) from the GitHub Actions app as part of the
+branch's merge policy. An independent merge-time gate must require fresh scan
+qualification whenever the live base changes, including after this check passes.
+GitHub can reuse a successful head check after a base-only update, even with
+strict up-to-date checks when the new base is already an ancestor of the head.
+This example does not implement that merge-time gate: the named check alone
+cannot establish that the current merge diff was scanned. Require this check
+only for branches that do not use a merge queue. The Action
+does not support `merge_group` events, so this workflow cannot provide the required
+check for a merge queue.
+
+When migrating from the previous example, let the new target-specific check run,
+then replace the old **Codex Security** required check with the matching
+**Codex Security / <target-branch>** check. Keeping the old requirement leaves a
+check pending that this workflow no longer produces.
+
+The check name includes the target branch because GitHub can evaluate checks on
+the shared head commit when a test merge commit has no status. The workflow uses
+read-only pull request and Git-ref access on the triggering GitHub host to verify
+the event's head, target branch, and live base SHA before the scan and before
+accepting its result. The pull record's base SHA alone can lag the branch tip.
+Retargeted PRs get a new review. During a run, a changed snapshot fails verification;
+a stale rerun cannot cancel another event's scan.
+The concurrency group also includes the run ID because GitHub compares group
+names without case sensitivity. Separate workflow events can run concurrently.
+Run the workflow from the current PR event after retargeting. If the target has
+advanced since that event, update the PR branch to trigger a fresh review.
+See GitHub's [required-check evaluation](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks)
+and [rerun semantics](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/re-run-workflows-and-jobs).
+
+When the required check must establish which workflow ran, use an
+[organization ruleset that requires a workflow](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-workflows-to-pass-before-merging)
+from a protected ref. Selecting the GitHub Actions app identifies the app, not a
+particular workflow or ref. Code owner approval for `.github/workflows/` and
+`CODEOWNERS`, together with dismissing stale approvals, protects edits in the PR
+being reviewed. It does not stop a workflow on another writable branch from
+creating a check with the same name and app on that PR's head, so it cannot
+substitute for the protected-ref workflow requirement.
+
+<!-- action-workflow:pull-request:start -->
```yaml
+# Required-check policy prerequisites, including merge-time freshness, are in the README.
name: Codex Security PR
on:
pull_request:
- types: [opened, synchronize, reopened, ready_for_review]
+ types: [opened, synchronize, reopened, ready_for_review, edited]
permissions:
contents: read
+ pull-requests: read
concurrency:
- group: codex-security-pr-${{ github.event.pull_request.number }}
+ # Group names are case-insensitive; the run ID also separates case-only retargets.
+ group: codex-security-pr-${{ github.event.pull_request.number }}-${{ github.run_id }}
cancel-in-progress: true
jobs:
security:
- if: github.event.pull_request.head.repo.full_name == github.repository
- name: Codex Security
+ if: >-
+ github.event.pull_request.head.repo.full_name == github.repository &&
+ (github.event.action != 'edited' || github.event.changes.base != null)
+ name: Scan changes
runs-on: ubuntu-24.04
timeout-minutes: 60
+ outputs:
+ scan-status: ${{ steps.security.outputs.scan-status }}
+ skip-reason: ${{ steps.security.outputs.skip-reason }}
steps:
- # Configure Bubblewrap and AppArmor so Codex Security can run safely in its sandbox.
- - name: Set up the Ubuntu sandbox
+ - &verify-current-pr
+ name: Verify the PR still matches this scan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
+ PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
- sudo apt-get update
- sudo apt-get install --yes bubblewrap apparmor-profiles
- sudo apparmor_parser -r /usr/share/apparmor/extra-profiles/bwrap-userns-restrict
+ current=$(gh api --hostname "${GITHUB_SERVER_URL#https://}" "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '[.head.sha, .base.ref, .base.sha] | @tsv')
+ expected=$(printf '%s\t%s\t%s' "$PR_HEAD_SHA" "$PR_BASE_REF" "$PR_BASE_SHA")
+ if [ "$current" != "$expected" ]; then
+ echo 'The PR head or target changed. Run the workflow for the current PR snapshot.' >&2
+ exit 1
+ fi
+ base_ref=$(printf '%s' "$PR_BASE_REF" | jq -sRr @uri)
+ live_base=$(gh api --hostname "${GITHUB_SERVER_URL#https://}" "repos/$GITHUB_REPOSITORY/git/ref/heads/$base_ref" --jq '.object.sha')
+ if [ "$live_base" != "$PR_BASE_SHA" ]; then
+ echo 'The PR head or target changed. Run the workflow for the current PR snapshot.' >&2
+ exit 1
+ fi
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
@@ -293,15 +352,56 @@ jobs:
uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT
with:
scope: diff
- model: gpt-5.6-luna
- effort: medium
+ model: gpt-5.6-sol
+ effort: high
+ max-cost: "5"
fail-on-severity: high
env:
OPENAI_API_KEY: ${{ secrets.CODEX_SECURITY_API_KEY }}
+
+ required-review:
+ name: ${{ github.event.action == 'edited' && github.event.changes.base == null && 'metadata / ' || '' }}Codex Security / ${{ github.event.pull_request.base.ref }}
+ needs: security
+ if: always() && (github.event.action != 'edited' || github.event.changes.base != null)
+ runs-on: ubuntu-24.04
+ steps:
+ - *verify-current-pr
+ - name: Require a completed review or an empty diff
+ env:
+ SCAN_JOB_RESULT: ${{ needs.security.result }}
+ SCAN_STATUS: ${{ needs.security.outputs.scan-status }}
+ SKIP_REASON: ${{ needs.security.outputs.skip-reason }}
+ run: |
+ test "$SCAN_JOB_RESULT" = success
+ if [ "$SCAN_STATUS" = completed ]; then
+ exit 0
+ fi
+ test "$SCAN_STATUS" = skipped
+ test "$SKIP_REASON" = empty-diff
```
-This job fails on reported high or critical findings, or on scanner and required
-reporting errors. File and line annotations are enabled by default.
+<!-- action-workflow:pull-request:end -->
+
+The scan job fails on high or critical findings, scanner errors, or required
+reporting errors. After a failure, a later step with `if: failure()` in the same
+job can read any validated reports through the Action outputs. Set
+`upload-artifacts: 'true'` to make those reports downloadable after the job ends.
+File and line annotations are enabled by default.
+
+The repository workflow above reruns when a PR's base branch changes, even when
+the head commit is unchanged. Title and body edits skip the scan and use a
+separate concurrency group and check name, preserving the active scan and its
+required **Codex Security** result.
+
+For `pull_request`, GitHub runs required ruleset workflows on `opened`,
+`synchronize`, and `reopened`. After retargeting a PR covered by that rule, push
+a new commit or close and reopen the PR to scan the new base.
+See [GitHub's supported ruleset triggers](https://docs.github.com/en/enterprise-cloud@latest/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#supported-event-triggers).
+
+For scan-triggering events, the separate **Codex Security** job runs even if the
+scan job is skipped. It passes only after a successful scan job that reports a completed scan or a
+verified empty diff. A dry run, cancellation, or skipped scan job fails this
+required check.
Use PR scanning for trusted contributors with branches in the calling repository.
To scan Dependabot PRs, also configure `CODEX_SECURITY_API_KEY` as a
@@ -309,9 +409,10 @@ To scan Dependabot PRs, also configure `CODEX_SECURITY_API_KEY` as a
The same workflow uses that secret for Dependabot runs and the Actions secret for
other runs. Missing credentials fail with setup guidance.
-Fork PRs are skipped by this example. GitHub treats skipped jobs as successful
-for required checks; skipped does not mean scanned. `pull_request_target` and
-`workflow_run` are not supported.
+The scan job skips fork PRs, so the required check fails for those PRs. Repositories
+accepting fork contributions need an approved review process for them before
+using this check as a merge requirement. `pull_request_target` and `workflow_run`
+are not supported.
The scanner uses applicable `SECURITY.md` guidance from the checked-out revision,
including policy changes in the PR. Review those changes alongside the code.
@@ -325,28 +426,33 @@ Keep unrelated credentials and deployment steps in separate jobs.
Names such as `src/[slug]/page.tsx` are literal paths; glob characters are not expanded.
This requires repository scope.
- For diff scans outside PR events, set `diff-base`.
-- Set `dry-run: 'true'` to check configuration without an API key or model calls.
- Use a separate setup job; dry-run does not assess code or verify model access.
+- Set `dry-run: 'true'` with `fail-on-severity: none` to check configuration and
+ sandbox startup without an API key or model calls. Use a separate setup job;
+ dry-run does not assess code or verify model access.
For a Deep scan of a repository or selected paths, add these inputs to the scan step:
```yaml
with:
mode: deep
- max-time-hours: "2"
+ max-time-hours: "1"
```
Deep mode does not support diff scans. `max-time-hours` limits Deep discovery;
finalization can take additional time. It is unset by default, which uses the
CLI's default of 96 hours. Set an explicit budget for Deep scans that leaves
-room for finalization within your job timeout.
+room for finalization within your job timeout. The one-hour discovery budget
+above leaves time for setup and finalization within the repository workflow's
+two-hour job timeout.
## Reports
The Action lists the highest-severity findings first in the job summary and
source annotations, preserving scan order within each severity level. Set
-`upload-artifacts: 'true'` for downloadable reports, retained for seven days by
-default. Reports can contain source code and vulnerability details.
+`upload-artifacts: 'true'` to upload full reports and link them from the summary.
+Anyone signed in to GitHub with read access to the repository can download the
+reports, which can contain source code and vulnerability details. Set
+`retention-days` to change the default of seven days.
The job summary includes the configured provider, reported input/cached/output
token usage, and estimated USD cost, including a range when supplied by the CLI.
@@ -371,8 +477,14 @@ The Action follows the CLI outcome consistently:
| `1` | `scan-status: completed`, `policy-status: failed`; the step fails on findings. |
| `2` or an interrupted process | `scan-status: failed`, `policy-status: not-evaluated`; the step fails. |
-Usable reports retained after an execution failure remain available, but are not
-eligible for SARIF upload. Invalid or missing required reports, a changed
+A verified empty diff succeeds with `scan-status: skipped` and
+`skip-reason: empty-diff`, including when a severity threshold is configured.
+A dry run checks local setup and requires `fail-on-severity: none`.
+Use the [required PR check](#scan-pull-requests) to handle skipped scan jobs as
+well as the Action's own results.
+
+After an execution failure, the Action returns paths to usable reports and sets
+`sarif-upload-ready: false`. Invalid or missing required reports, a changed
checkout, and requested artifact-upload or runtime-cleanup failures also fail
the step. Empty diffs and dry runs use `scan-status: skipped`.
@@ -385,8 +497,10 @@ artifact upload that fails still fails the job.
### GitHub code scanning
Grant the job `security-events: write` and, for private repositories,
-`actions: read`, alongside `contents: read`. Set `id: security` on the scan step,
-then add this step after it:
+`actions: read`, alongside `contents: read`. When extending the pull-request
+workflow, retain `pull-requests: read` in the job's permissions map for its
+snapshot checks; a job-level map replaces the workflow-level permissions.
+Set `id: security` on the scan step, then add this step after it:
```yaml
- name: Upload security findings
@@ -410,12 +524,10 @@ for code scanning availability and permissions.
## Runtime
The Action installs a pinned CLI release from npm using a committed dependency
-lock. It runs on Linux x64 with Node 24 and Python 3.11 or later; the Ubuntu 24.04
-runner supplies Node and Python. The setup step above installs Bubblewrap and
-loads Ubuntu's `bwrap-userns-restrict` AppArmor profile. This profile lets
-Bubblewrap create the sandbox's user namespace and denies capabilities to its
-child processes. It is loaded into the running kernel for the job's runner.
-Codex uses the system Bubblewrap from `PATH`.
+lock. It runs on Linux x64 with Node 24 and Python 3.11 or later.
+GitHub-hosted Ubuntu 24.04 VMs supply Node and Python. Codex uses the system
+Bubblewrap from `PATH`; see [Ubuntu sandbox setup](#ubuntu-sandbox-setup) for VM
+setup and requirements for self-hosted runners and job containers.
npm and Python are found on the runner's `PATH`; `actions/setup-node` and `actions/setup-python` can select installations.
Python helpers preserve the selected virtual environment and library settings.
@@ -451,11 +563,10 @@ and artifact uploads retain their existing controls.
- **Authentication errors:** for OpenAI, check the repository secret and model access.
For Bedrock, check the AWS identity, session expiry, region, and permission to
invoke the exact model ID.
-- **Sandbox startup errors:** on Ubuntu 24.04, include the sandbox setup step
- shown above. Installing Bubblewrap alone does not load the AppArmor profile.
- A `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted` error means
- the sandbox could not configure its network namespace. Check that the profile
- loaded successfully before running the Action.
+- **Sandbox startup errors:** for jobs running directly on GitHub-hosted Ubuntu
+ 24.04 VMs, inspect the package-install and AppArmor diagnostics. On self-hosted
+ runners and in job containers, configure the sandbox before running the Action.
+ Installing Bubblewrap alone does not load Ubuntu's required AppArmor profile.
- **Missing SARIF uploads:** inspect `scan-status`, `report-status`, and
`sarif-upload-ready`.
- **Failed scans:** inspect the CLI diagnostics for execution errors. Scope
@@ -465,6 +576,18 @@ and artifact uploads retain their existing controls.
CLI diagnostics stream by default. Set `verbose: 'false'` for lifecycle and
elapsed-time messages only.
+## Upgrading from Action 0.2.0
+
+`dry-run: 'true'` now requires `fail-on-severity: none`; put configuration checks
+in a separate job. A dry run does not perform the security review required
+by a severity-enforcing job.
+
+Once your Action pin includes automatic sandbox setup, remove the manual
+Bubblewrap/AppArmor step from jobs running directly on GitHub-hosted Ubuntu
+24.04 VMs. Self-hosted runners and job containers still require a preconfigured sandbox.
+
+The workflow examples use a model and cost limit supported by the pinned CLI.
+
## Development
From the repository root, use Node.js 24 to check the committed files and audit
@@ -477,10 +600,11 @@ npm --prefix github-action audit --audit-level=high
npm --prefix github-action/runtime audit --omit=dev --audit-level=high
```
-After changing Action inputs or outputs, run `npm --prefix github-action run docs`
-to regenerate the README reference. After changing bundled source or the runtime
-lock, run `npm --prefix github-action run build`. Review the generated README and
-`dist/*.cjs` changes, rerun validation, and commit them with their source changes.
+After editing Action inputs, outputs, or the workflows in `examples/*.yml`, run
+`npm --prefix github-action run docs` to regenerate the README. After changing
+bundled source or the runtime lock, run `npm --prefix github-action run build`.
+Review the generated README and `dist/*.cjs` changes, rerun validation, and
+commit them with their source changes.
On Linux x64 with a working sandbox, run the published CLI integration and
packaged smoke tests.
@@ -532,10 +656,10 @@ Inputs are strings. Quote booleans and use newline-separated literal paths for l
| `max-time-hours` | Unset | Positive Deep discovery duration in hours, up to 96. Unset uses the CLI default. Finalization and job timeout are separate. |
| `fail-on-severity` | `none` | none, low, medium, high, or critical. Fails on reported findings at or above the selected severity. Scanner and required reporting errors also fail. |
| `verbose` | `true` | Stream CLI diagnostics to the job log. Set false for lifecycle and elapsed-time messages only. |
-| `dry-run` | `false` | Validate local configuration without a scan or API key. Does not verify authentication or model access. Use a separate non-required job. |
+| `dry-run` | `false` | Validate local configuration without a scan or API key. Does not verify authentication or model access. Requires fail-on-severity: none; use a separate non-required job. |
| `summary` | `true` | Write a human-readable job summary. |
| `annotations` | `true` | Emit up to 50 source finding annotations; complete findings remain in reports. |
-| `upload-artifacts` | `false` | Upload an allowlist of validated reports. Reports may contain source and vulnerability details. |
+| `upload-artifacts` | `false` | Upload an allowlist of validated reports and link the artifact in the job summary. Reports may contain source and vulnerability details. |
| `artifact-name` | `codex-security` | Report artifact name; choose distinct names for matrix jobs and multiple invocations. |
| `retention-days` | `7` | Artifact retention, 1–90 days (subject to repository limits). |
diff --git a/github-action/dist/index.cjs b/github-action/dist/index.cjs
index 971618588..71eb91216 100644
--- a/github-action/dist/index.cjs
+++ b/github-action/dist/index.cjs
@@ -25703,13 +25703,13 @@ var require_minimatch = __commonJS({
var require_readdir_glob = __commonJS({
"node_modules/readdir-glob/index.js"(exports2, module2) {
module2.exports = readdirGlob;
- var fs8 = require("fs");
+ var fs9 = require("fs");
var { EventEmitter: EventEmitter3 } = require("events");
var { Minimatch } = require_minimatch();
var { resolve: resolve7 } = require("path");
function readdir2(dir, strict) {
return new Promise((resolve8, reject) => {
- fs8.readdir(dir, { withFileTypes: true }, (err, files) => {
+ fs9.readdir(dir, { withFileTypes: true }, (err, files) => {
if (err) {
switch (err.code) {
case "ENOTDIR":
@@ -25742,7 +25742,7 @@ var require_readdir_glob = __commonJS({
}
function stat2(file, followSymlinks) {
return new Promise((resolve8, reject) => {
- const statFunc = followSymlinks ? fs8.stat : fs8.lstat;
+ const statFunc = followSymlinks ? fs9.stat : fs9.lstat;
statFunc(file, (err, stats) => {
if (err) {
switch (err.code) {
@@ -27807,54 +27807,54 @@ var require_polyfills = __commonJS({
}
var chdir;
module2.exports = patch;
- function patch(fs8) {
+ function patch(fs9) {
if (constants4.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
- patchLchmod(fs8);
- }
- if (!fs8.lutimes) {
- patchLutimes(fs8);
- }
- fs8.chown = chownFix(fs8.chown);
- fs8.fchown = chownFix(fs8.fchown);
- fs8.lchown = chownFix(fs8.lchown);
- fs8.chmod = chmodFix(fs8.chmod);
- fs8.fchmod = chmodFix(fs8.fchmod);
- fs8.lchmod = chmodFix(fs8.lchmod);
- fs8.chownSync = chownFixSync(fs8.chownSync);
- fs8.fchownSync = chownFixSync(fs8.fchownSync);
- fs8.lchownSync = chownFixSync(fs8.lchownSync);
- fs8.chmodSync = chmodFixSync(fs8.chmodSync);
- fs8.fchmodSync = chmodFixSync(fs8.fchmodSync);
- fs8.lchmodSync = chmodFixSync(fs8.lchmodSync);
- fs8.stat = statFix(fs8.stat);
- fs8.fstat = statFix(fs8.fstat);
- fs8.lstat = statFix(fs8.lstat);
- fs8.statSync = statFixSync(fs8.statSync);
- fs8.fstatSync = statFixSync(fs8.fstatSync);
- fs8.lstatSync = statFixSync(fs8.lstatSync);
- if (fs8.chmod && !fs8.lchmod) {
- fs8.lchmod = function(path6, mode, cb) {
+ patchLchmod(fs9);
+ }
+ if (!fs9.lutimes) {
+ patchLutimes(fs9);
+ }
+ fs9.chown = chownFix(fs9.chown);
+ fs9.fchown = chownFix(fs9.fchown);
+ fs9.lchown = chownFix(fs9.lchown);
+ fs9.chmod = chmodFix(fs9.chmod);
+ fs9.fchmod = chmodFix(fs9.fchmod);
+ fs9.lchmod = chmodFix(fs9.lchmod);
+ fs9.chownSync = chownFixSync(fs9.chownSync);
+ fs9.fchownSync = chownFixSync(fs9.fchownSync);
+ fs9.lchownSync = chownFixSync(fs9.lchownSync);
+ fs9.chmodSync = chmodFixSync(fs9.chmodSync);
+ fs9.fchmodSync = chmodFixSync(fs9.fchmodSync);
+ fs9.lchmodSync = chmodFixSync(fs9.lchmodSync);
+ fs9.stat = statFix(fs9.stat);
+ fs9.fstat = statFix(fs9.fstat);
+ fs9.lstat = statFix(fs9.lstat);
+ fs9.statSync = statFixSync(fs9.statSync);
+ fs9.fstatSync = statFixSync(fs9.fstatSync);
+ fs9.lstatSync = statFixSync(fs9.lstatSync);
+ if (fs9.chmod && !fs9.lchmod) {
+ fs9.lchmod = function(path6, mode, cb) {
if (cb) process.nextTick(cb);
};
- fs8.lchmodSync = function() {
+ fs9.lchmodSync = function() {
};
}
- if (fs8.chown && !fs8.lchown) {
- fs8.lchown = function(path6, uid, gid, cb) {
+ if (fs9.chown && !fs9.lchown) {
+ fs9.lchown = function(path6, uid, gid, cb) {
if (cb) process.nextTick(cb);
};
- fs8.lchownSync = function() {
+ fs9.lchownSync = function() {
};
}
if (platform2 === "win32") {
- fs8.rename = typeof fs8.rename !== "function" ? fs8.rename : (function(fs$rename) {
+ fs9.rename = typeof fs9.rename !== "function" ? fs9.rename : (function(fs$rename) {
function rename2(from, to, cb) {
var start = Date.now();
var backoff = 0;
fs$rename(from, to, function CB(er) {
if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
setTimeout(function() {
- fs8.stat(to, function(stater, st) {
+ fs9.stat(to, function(stater, st) {
if (stater && stater.code === "ENOENT")
fs$rename(from, to, CB);
else
@@ -27870,9 +27870,9 @@ var require_polyfills = __commonJS({
}
if (Object.setPrototypeOf) Object.setPrototypeOf(rename2, fs$rename);
return rename2;
- })(fs8.rename);
+ })(fs9.rename);
}
- fs8.read = typeof fs8.read !== "function" ? fs8.read : (function(fs$read) {
+ fs9.read = typeof fs9.read !== "function" ? fs9.read : (function(fs$read) {
function read(fd, buffer2, offset, length, position, callback_) {
var callback;
if (callback_ && typeof callback_ === "function") {
@@ -27880,22 +27880,22 @@ var require_polyfills = __commonJS({
callback = function(er, _2, __) {
if (er && er.code === "EAGAIN" && eagCounter < 10) {
eagCounter++;
- return fs$read.call(fs8, fd, buffer2, offset, length, position, callback);
+ return fs$read.call(fs9, fd, buffer2, offset, length, position, callback);
}
callback_.apply(this, arguments);
};
}
- return fs$read.call(fs8, fd, buffer2, offset, length, position, callback);
+ return fs$read.call(fs9, fd, buffer2, offset, length, position, callback);
}
if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
return read;
- })(fs8.read);
- fs8.readSync = typeof fs8.readSync !== "function" ? fs8.readSync : /* @__PURE__ */ (function(fs$readSync) {
+ })(fs9.read);
+ fs9.readSync = typeof fs9.readSync !== "function" ? fs9.readSync : /* @__PURE__ */ (function(fs$readSync) {
return function(fd, buffer2, offset, length, position) {
var eagCounter = 0;
while (true) {
try {
- return fs$readSync.call(fs8, fd, buffer2, offset, length, position);
+ return fs$readSync.call(fs9, fd, buffer2, offset, length, position);
} catch (er) {
if (er.code === "EAGAIN" && eagCounter < 10) {
eagCounter++;
@@ -27905,10 +27905,10 @@ var require_polyfills = __commonJS({
}
}
};
- })(fs8.readSync);
- function patchLchmod(fs9) {
- fs9.lchmod = function(path6, mode, callback) {
- fs9.open(
+ })(fs9.readSync);
+ function patchLchmod(fs10) {
+ fs10.lchmod = function(path6, mode, callback) {
+ fs10.open(
path6,
constants4.O_WRONLY | constants4.O_SYMLINK,
mode,
@@ -27917,80 +27917,80 @@ var require_polyfills = __commonJS({
if (callback) callback(err);
return;
}
- fs9.fchmod(fd, mode, function(err2) {
- fs9.close(fd, function(err22) {
+ fs10.fchmod(fd, mode, function(err2) {
+ fs10.close(fd, function(err22) {
if (callback) callback(err2 || err22);
});
});
}
);
};
- fs9.lchmodSync = function(path6, mode) {
- var fd = fs9.openSync(path6, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
+ fs10.lchmodSync = function(path6, mode) {
+ var fd = fs10.openSync(path6, constants4.O_WRONLY | constants4.O_SYMLINK, mode);
var threw = true;
var ret;
try {
- ret = fs9.fchmodSync(fd, mode);
+ ret = fs10.fchmodSync(fd, mode);
threw = false;
} finally {
if (threw) {
try {
- fs9.closeSync(fd);
+ fs10.closeSync(fd);
} catch (er) {
}
} else {
- fs9.closeSync(fd);
+ fs10.closeSync(fd);
}
}
return ret;
};
}
- function patchLutimes(fs9) {
- if (constants4.hasOwnProperty("O_SYMLINK") && fs9.futimes) {
- fs9.lutimes = function(path6, at, mt, cb) {
- fs9.open(path6, constants4.O_SYMLINK, function(er, fd) {
+ function patchLutimes(fs10) {
+ if (constants4.hasOwnProperty("O_SYMLINK") && fs10.futimes) {
+ fs10.lutimes = function(path6, at, mt, cb) {
+ fs10.open(path6, constants4.O_SYMLINK, function(er, fd) {
if (er) {
if (cb) cb(er);
return;
}
- fs9.futimes(fd, at, mt, function(er2) {
- fs9.close(fd, function(er22) {
+ fs10.futimes(fd, at, mt, function(er2) {
+ fs10.close(fd, function(er22) {
if (cb) cb(er2 || er22);
});
});
});
};
- fs9.lutimesSync = function(path6, at, mt) {
- var fd = fs9.openSync(path6, constants4.O_SYMLINK);
+ fs10.lutimesSync = function(path6, at, mt) {
+ var fd = fs10.openSync(path6, constants4.O_SYMLINK);
var ret;
var threw = true;
try {
- ret = fs9.futimesSync(fd, at, mt);
+ ret = fs10.futimesSync(fd, at, mt);
threw = false;
} finally {
if (threw) {
try {
- fs9.closeSync(fd);
+ fs10.closeSync(fd);
} catch (er) {
}
} else {
- fs9.closeSync(fd);
+ fs10.closeSync(fd);
}
}
return ret;
};
- } else if (fs9.futimes) {
- fs9.lutimes = function(_a, _b, _c, cb) {
+ } else if (fs10.futimes) {
+ fs10.lutimes = function(_a, _b, _c, cb) {
if (cb) process.nextTick(cb);
};
- fs9.lutimesSync = function() {
+ fs10.lutimesSync = function() {
};
}
}
function chmodFix(orig) {
if (!orig) return orig;
return function(target, mode, cb) {
- return orig.call(fs8, target, mode, function(er) {
+ return orig.call(fs9, target, mode, function(er) {
if (chownErOk(er)) er = null;
if (cb) cb.apply(this, arguments);
});
@@ -28000,7 +28000,7 @@ var require_polyfills = __commonJS({
if (!orig) return orig;
return function(target, mode) {
try {
- return orig.call(fs8, target, mode);
+ return orig.call(fs9, target, mode);
} catch (er) {
if (!chownErOk(er)) throw er;
}
@@ -28009,7 +28009,7 @@ var require_polyfills = __commonJS({
function chownFix(orig) {
if (!orig) return orig;
return function(target, uid, gid, cb) {
- return orig.call(fs8, target, uid, gid, function(er) {
+ return orig.call(fs9, target, uid, gid, function(er) {
if (chownErOk(er)) er = null;
if (cb) cb.apply(this, arguments);
});
@@ -28019,7 +28019,7 @@ var require_polyfills = __commonJS({
if (!orig) return orig;
return function(target, uid, gid) {
try {
- return orig.call(fs8, target, uid, gid);
+ return orig.call(fs9, target, uid, gid);
} catch (er) {
if (!chownErOk(er)) throw er;
}
@@ -28039,13 +28039,13 @@ var require_polyfills = __commonJS({
}
if (cb) cb.apply(this, arguments);
}
- return options ? orig.call(fs8, target, options, callback) : orig.call(fs8, target, callback);
+ return options ? orig.call(fs9, target, options, callback) : orig.call(fs9, target, callback);
};
}
function statFixSync(orig) {
if (!orig) return orig;
return function(target, options) {
- var stats = options ? orig.call(fs8, target, options) : orig.call(fs8, target);
+ var stats = options ? orig.call(fs9, target, options) : orig.call(fs9, target);
if (stats) {
if (stats.uid < 0) stats.uid += 4294967296;
if (stats.gid < 0) stats.gid += 4294967296;
@@ -28074,7 +28074,7 @@ var require_legacy_streams = __commonJS({
"node_modules/graceful-fs/legacy-streams.js"(exports2, module2) {
var Stream2 = require("stream").Stream;
module2.exports = legacy;
- function legacy(fs8) {
+ function legacy(fs9) {
return {
ReadStream,
WriteStream
@@ -28117,7 +28117,7 @@ var require_legacy_streams = __commonJS({
});
return;
}
- fs8.open(this.path, this.flags, this.mode, function(err, fd) {
+ fs9.open(this.path, this.flags, this.mode, function(err, fd) {
if (err) {
self2.emit("error", err);
self2.readable = false;
@@ -28156,7 +28156,7 @@ var require_legacy_streams = __commonJS({
this.busy = false;
this._queue = [];
if (this.fd === null) {
- this._open = fs8.open;
+ this._open = fs9.open;
this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
this.flush();
}
@@ -28191,7 +28191,7 @@ var require_clone = __commonJS({
// node_modules/graceful-fs/graceful-fs.js
var require_graceful_fs = __commonJS({
"node_modules/graceful-fs/graceful-fs.js"(exports2, module2) {
- var fs8 = require("fs");
+ var fs9 = require("fs");
var polyfills = require_polyfills();
var legacy = require_legacy_streams();
var clone = require_clone();
@@ -28223,12 +28223,12 @@ var require_graceful_fs = __commonJS({
m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
console.error(m);
};
- if (!fs8[gracefulQueue]) {
+ if (!fs9[gracefulQueue]) {
queue = global[gracefulQueue] || [];
- publishQueue(fs8, queue);
- fs8.close = (function(fs$close) {
+ publishQueue(fs9, queue);
+ fs9.close = (function(fs$close) {
function close(fd, cb) {
- return fs$close.call(fs8, fd, function(err) {
+ return fs$close.call(fs9, fd, function(err) {
if (!err) {
resetQueue();
}
@@ -28240,40 +28240,40 @@ var require_graceful_fs = __commonJS({
value: fs$close
});
return close;
- })(fs8.close);
- fs8.closeSync = (function(fs$closeSync) {
+ })(fs9.close);
+ fs9.closeSync = (function(fs$closeSync) {
function closeSync(fd) {
- fs$closeSync.apply(fs8, arguments);
+ fs$closeSync.apply(fs9, arguments);
resetQueue();
}
Object.defineProperty(closeSync, previousSymbol, {
value: fs$closeSync
});
return closeSync;
- })(fs8.closeSync);
+ })(fs9.closeSync);
if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
process.on("exit", function() {
- debug2(fs8[gracefulQueue]);
- require("assert").equal(fs8[gracefulQueue].length, 0);
+ debug2(fs9[gracefulQueue]);
+ require("assert").equal(fs9[gracefulQueue].length, 0);
});
}
}
var queue;
if (!global[gracefulQueue]) {
- publishQueue(global, fs8[gracefulQueue]);
- }
- module2.exports = patch(clone(fs8));
- if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs8.__patched) {
- module2.exports = patch(fs8);
- fs8.__patched = true;
- }
- function patch(fs9) {
- polyfills(fs9);
- fs9.gracefulify = patch;
- fs9.createReadStream = createReadStream2;
- fs9.createWriteStream = createWriteStream2;
- var fs$readFile = fs9.readFile;
- fs9.readFile = readFile4;
+ publishQueue(global, fs9[gracefulQueue]);
+ }
+ module2.exports = patch(clone(fs9));
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs9.__patched) {
+ module2.exports = patch(fs9);
+ fs9.__patched = true;
+ }
+ function patch(fs10) {
+ polyfills(fs10);
+ fs10.gracefulify = patch;
+ fs10.createReadStream = createReadStream2;
+ fs10.createWriteStream = createWriteStream2;
+ var fs$readFile = fs10.readFile;
+ fs10.readFile = readFile4;
function readFile4(path6, options, cb) {
if (typeof options === "function")
cb = options, options = null;
@@ -28289,8 +28289,8 @@ var require_graceful_fs = __commonJS({
});
}
}
- var fs$writeFile = fs9.writeFile;
- fs9.writeFile = writeFile4;
+ var fs$writeFile = fs10.writeFile;
+ fs10.writeFile = writeFile4;
function writeFile4(path6, data, options, cb) {
if (typeof options === "function")
cb = options, options = null;
@@ -28306,9 +28306,9 @@ var require_graceful_fs = __commonJS({
});
}
}
- var fs$appendFile = fs9.appendFile;
+ var fs$appendFile = fs10.appendFile;
if (fs$appendFile)
- fs9.appendFile = appendFile2;
+ fs10.appendFile = appendFile2;
function appendFile2(path6, data, options, cb) {
if (typeof options === "function")
cb = options, options = null;
@@ -28324,9 +28324,9 @@ var require_graceful_fs = __commonJS({
});
}
}
- var fs$copyFile = fs9.copyFile;
+ var fs$copyFile = fs10.copyFile;
if (fs$copyFile)
- fs9.copyFile = copyFile3;
+ fs10.copyFile = copyFile3;
function copyFile3(src, dest, flags, cb) {
if (typeof flags === "function") {
cb = flags;
@@ -28344,8 +28344,8 @@ var require_graceful_fs = __commonJS({
});
}
}
- var fs$readdir = fs9.readdir;
- fs9.readdir = readdir2;
+ var fs$readdir = fs10.readdir;
+ fs10.readdir = readdir2;
var noReaddirOptionVersions = /^v[0-5]\./;
function readdir2(path6, options, cb) {
if (typeof options === "function")
@@ -28386,21 +28386,21 @@ var require_graceful_fs = __commonJS({
}
}
if (process.version.substr(0, 4) === "v0.8") {
- var legStreams = legacy(fs9);
+ var legStreams = legacy(fs10);
ReadStream = legStreams.ReadStream;
WriteStream = legStreams.WriteStream;
}
- var fs$ReadStream = fs9.ReadStream;
+ var fs$ReadStream = fs10.ReadStream;
if (fs$ReadStream) {
ReadStream.prototype = Object.create(fs$ReadStream.prototype);
ReadStream.prototype.open = ReadStream$open;
}
- var fs$WriteStream = fs9.WriteStream;
+ var fs$WriteStream = fs10.WriteStream;
if (fs$WriteStream) {
WriteStream.prototype = Object.create(fs$WriteStream.prototype);
WriteStream.prototype.open = WriteStream$open;
}
- Object.defineProperty(fs9, "ReadStream", {
+ Object.defineProperty(fs10, "ReadStream", {
get: function() {
return ReadStream;
},
@@ -28410,7 +28410,7 @@ var require_graceful_fs = __commonJS({
enumerable: true,
configurable: true
});
- Object.defineProperty(fs9, "WriteStream", {
+ Object.defineProperty(fs10, "WriteStream", {
get: function() {
return WriteStream;
},
@@ -28421,7 +28421,7 @@ var require_graceful_fs = __commonJS({
configurable: true
});
var FileReadStream = ReadStream;
- Object.defineProperty(fs9, "FileReadStream", {
+ Object.defineProperty(fs10, "FileReadStream", {
get: function() {
return FileReadStream;
},
@@ -28432,7 +28432,7 @@ var require_graceful_fs = __commonJS({
configurable: true
});
var FileWriteStream = WriteStream;
- Object.defineProperty(fs9, "FileWriteStream", {
+ Object.defineProperty(fs10, "FileWriteStream", {
get: function() {
return FileWriteStream;
},
@@ -28481,13 +28481,13 @@ var require_graceful_fs = __commonJS({
});
}
function createReadStream2(path6, options) {
- return new fs9.ReadStream(path6, options);
+ return new fs10.ReadStream(path6, options);
}
function createWriteStream2(path6, options) {
- return new fs9.WriteStream(path6, options);
+ return new fs10.WriteStream(path6, options);
}
- var fs$open = fs9.open;
- fs9.open = open3;
+ var fs$open = fs10.open;
+ fs10.open = open3;
function open3(path6, flags, mode, cb) {
if (typeof mode === "function")
cb = mode, mode = null;
@@ -28503,20 +28503,20 @@ var require_graceful_fs = __commonJS({
});
}
}
- return fs9;
+ return fs10;
}
function enqueue(elem) {
debug2("ENQUEUE", elem[0].name, elem[1]);
- fs8[gracefulQueue].push(elem);
+ fs9[gracefulQueue].push(elem);
retry2();
}
var retryTimer;
function resetQueue() {
var now = Date.now();
- for (var i = 0; i < fs8[gracefulQueue].length; ++i) {
- if (fs8[gracefulQueue][i].length > 2) {
- fs8[gracefulQueue][i][3] = now;
- fs8[gracefulQueue][i][4] = now;
+ for (var i = 0; i < fs9[gracefulQueue].length; ++i) {
+ if (fs9[gracefulQueue][i].length > 2) {
+ fs9[gracefulQueue][i][3] = now;
+ fs9[gracefulQueue][i][4] = now;
}
}
retry2();
@@ -28524,9 +28524,9 @@ var require_graceful_fs = __commonJS({
function retry2() {
clearTimeout(retryTimer);
retryTimer = void 0;
- if (fs8[gracefulQueue].length === 0)
+ if (fs9[gracefulQueue].length === 0)
return;
- var elem = fs8[gracefulQueue].shift();
+ var elem = fs9[gracefulQueue].shift();
var fn = elem[0];
var args = elem[1];
var err = elem[2];
@@ -28548,7 +28548,7 @@ var require_graceful_fs = __commonJS({
debug2("RETRY", fn.name, args);
fn.apply(null, args.concat([startTime]));
} else {
- fs8[gracefulQueue].push(elem);
+ fs9[gracefulQueue].push(elem);
}
}
if (retryTimer === void 0) {
@@ -43631,8 +43631,8 @@ var require_commonjs6 = __commonJS({
*
* @internal
*/
- constructor(cwd = process.cwd(), pathImpl, sep7, { nocase, childrenCacheSize = 16 * 1024, fs: fs8 = defaultFS } = {}) {
- this.#fs = fsFromOption(fs8);
+ constructor(cwd = process.cwd(), pathImpl, sep7, { nocase, childrenCacheSize = 16 * 1024, fs: fs9 = defaultFS } = {}) {
+ this.#fs = fsFromOption(fs9);
if (cwd instanceof URL || cwd.startsWith("file://")) {
cwd = (0, node_url_1.fileURLToPath)(cwd);
}
@@ -44191,8 +44191,8 @@ var require_commonjs6 = __commonJS({
/**
* @internal
*/
- newRoot(fs8) {
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
+ newRoot(fs9) {
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs9 });
}
/**
* Return true if the provided path string is an absolute path
@@ -44221,8 +44221,8 @@ var require_commonjs6 = __commonJS({
/**
* @internal
*/
- newRoot(fs8) {
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
+ newRoot(fs9) {
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs9 });
}
/**
* Return true if the provided path string is an absolute path
@@ -45407,7 +45407,7 @@ var require_commonjs7 = __commonJS({
// node_modules/archiver-utils/file.js
var require_file2 = __commonJS({
"node_modules/archiver-utils/file.js"(exports2, module2) {
- var fs8 = require_graceful_fs();
+ var fs9 = require_graceful_fs();
var path6 = require("path");
var flatten = require_flatten();
var difference = require_difference();
@@ -45434,7 +45434,7 @@ var require_file2 = __commonJS({
};
file.exists = function() {
var filepath = path6.join.apply(path6, arguments);
- return fs8.existsSync(filepath);
+ return fs9.existsSync(filepath);
};
file.expand = function(...args) {
var options = isPlainObject3(args[0]) ? args.shift() : {};
@@ -45452,7 +45452,7 @@ var require_file2 = __commonJS({
if (typeof options.filter === "function") {
return options.filter(filepath);
} else {
- return fs8.statSync(filepath)[options.filter]();
+ return fs9.statSync(filepath)[options.filter]();
}
} catch (e) {
return false;
@@ -45560,7 +45560,7 @@ var require_file2 = __commonJS({
// node_modules/archiver-utils/index.js
var require_archiver_utils = __commonJS({
"node_modules/archiver-utils/index.js"(exports2, module2) {
- var fs8 = require_graceful_fs();
+ var fs9 = require_graceful_fs();
var path6 = require("path");
var isStream = require_is_stream();
var lazystream = require_lazystream();
@@ -45609,7 +45609,7 @@ var require_archiver_utils = __commonJS({
};
utils.lazyReadStream = function(filepath) {
return new lazystream.Readable(function() {
- return fs8.createReadStream(filepath);
+ return fs9.createReadStream(filepath);
});
};
utils.normalizeInputSource = function(source) {
@@ -45637,7 +45637,7 @@ var require_archiver_utils = __commonJS({
callback = base;
base = dirpath;
}
- fs8.readdir(dirpath, function(err, list) {
+ fs9.readdir(dirpath, function(err, list) {
var i = 0;
var file;
var filepath;
@@ -45650,7 +45650,7 @@ var require_archiver_utils = __commonJS({
return callback(null, results);
}
filepath = path6.join(dirpath, file);
- fs8.stat(filepath, function(err2, stats) {
+ fs9.stat(filepath, function(err2, stats) {
results.push({
path: filepath,
relative: path6.relative(base, filepath).replace(/\\/g, "/"),
@@ -45712,7 +45712,7 @@ var require_error = __commonJS({
// node_modules/archiver/lib/core.js
var require_core = __commonJS({
"node_modules/archiver/lib/core.js"(exports2, module2) {
- var fs8 = require("fs");
+ var fs9 = require("fs");
var glob = require_readdir_glob();
var async = require_async();
var path6 = require("path");
@@ -45776,7 +45776,7 @@ var require_core = __commonJS({
data.sourcePath = filepath;
task.data = data;
this._entriesCount++;
- if (data.stats && data.stats instanceof fs8.Stats) {
+ if (data.stats && data.stats instanceof fs9.Stats) {
task = this._updateQueueTaskWithStats(task, data.stats);
if (task) {
if (data.stats.size) {
@@ -45947,7 +45947,7 @@ var require_core = __commonJS({
callback();
return;
}
- fs8.lstat(task.filepath, function(err, stats) {
+ fs9.lstat(task.filepath, function(err, stats) {
if (this._state.aborted) {
setImmediate(callback);
return;
@@ -45990,7 +45990,7 @@ var require_core = __commonJS({
task.data.sourceType = "buffer";
task.source = Buffer.concat([]);
} else if (stats.isSymbolicLink() && this._moduleSupports("symlink")) {
- var linkPath = fs8.readlinkSync(task.filepath);
+ var linkPath = fs9.readlinkSync(task.filepath);
var dirName = path6.dirname(task.filepath);
task.data.type = "symlink";
task.data.linkname = path6.relative(dirName, path6.resolve(dirName, linkPath));
@@ -52814,7 +52814,7 @@ var require_parser_stream = __commonJS({
var require_mkdirp = __commonJS({
"node_modules/mkdirp/index.js"(exports2, module2) {
var path6 = require("path");
- var fs8 = require("fs");
+ var fs9 = require("fs");
var _0777 = parseInt("0777", 8);
module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
function mkdirP(p, opts, f, made) {
@@ -52825,7 +52825,7 @@ var require_mkdirp = __commonJS({
opts = { mode: opts };
}
var mode = opts.mode;
- var xfs = opts.fs || fs8;
+ var xfs = opts.fs || fs9;
if (mode === void 0) {
mode = _0777;
}
@@ -52864,7 +52864,7 @@ var require_mkdirp = __commonJS({
opts = { mode: opts };
}
var mode = opts.mode;
- var xfs = opts.fs || fs8;
+ var xfs = opts.fs || fs9;
if (mode === void 0) {
mode = _0777;
}
@@ -52901,7 +52901,7 @@ var require_mkdirp = __commonJS({
// node_modules/unzip-stream/lib/extract.js
var require_extract2 = __commonJS({
"node_modules/unzip-stream/lib/extract.js"(exports2, module2) {
- var fs8 = require("fs");
+ var fs9 = require("fs");
var path6 = require("path");
var util3 = require("util");
var mkdirp = require_mkdirp();
@@ -52948,7 +52948,7 @@ var require_extract2 = __commonJS({
var directory = entry.isDirectory ? destPath : path6.dirname(destPath);
this.unfinishedEntries++;
var writeFileFn = function() {
- var pipedStream = fs8.createWriteStream(destPath);
+ var pipedStream = fs9.createWriteStream(destPath);
pipedStream.on("close", function() {
self2.unfinishedEntries--;
self2._notifyAwaiter();
@@ -55771,6 +55771,9 @@ function parseInputs(read, workspace) {
const maxTimeHours = num("max-time-hours", false, Number.MIN_VALUE, 96);
if (maxTimeHours !== void 0 && mode !== "deep") throw new Error("max-time-hours requires mode: deep.");
const dryRun = bool("dry-run", false);
+ const failOnSeverity = choice("fail-on-severity", ["none", "low", "medium", "high", "critical"], "none");
+ if (dryRun && failOnSeverity !== "none")
+ throw new Error("dry-run requires fail-on-severity: none. Configuration validation cannot satisfy a required security review.");
const provider = choice("provider", ["openai", "openrouter", "fireworks", "amazon-bedrock"], "openai");
const model = str("model", provider === "openai" ? "gpt-5.6-sol" : "");
const cyberAccessProgram = str("cyber-access-program") ? choice("cyber-access-program", ["standard", "daybreak_blue", "daybreak_red"], "standard") : void 0;
@@ -55786,7 +55789,7 @@ function parseInputs(read, workspace) {
effort: str("effort", "xhigh"),
maxCost: num("max-cost", false, Number.MIN_VALUE),
maxTimeHours,
- failOnSeverity: choice("fail-on-severity", ["none", "low", "medium", "high", "critical"], "none"),
+ failOnSeverity,
verbose: bool("verbose", true),
dryRun,
summary: bool("summary", true),
@@ -56070,7 +56073,7 @@ async function resolveTarget(inputs, event) {
else if (pr) diffBase = (await git(repository, ["merge-base", pr.base.sha, diffHead])).trim();
else throw new Error("diff-base is required for diff scans outside pull_request events.");
if (!SHA.test(diffBase)) throw new Error("Could not resolve the diff base. Fetch full history.");
- emptyDiff = (await gitResult(repository, ["diff", "--no-ext-diff", "--no-textconv", "--quiet", diffBase, diffHead, "--"], [0, 1])).exitCode === 0;
+ emptyDiff = (await gitResult(repository, ["diff", "--no-ext-diff", "--no-textconv", "--ignore-submodules=none", "--quiet", diffBase, diffHead, "--"], [0, 1])).exitCode === 0;
}
const analysisRef = pr ? `refs/pull/${pr.number ?? event.payload.number}/head` : event.ref;
const publishable = /^refs\/(heads|tags|pull)\//.test(analysisRef);
@@ -56078,6 +56081,7 @@ async function resolveTarget(inputs, event) {
}
// src/runtime.ts
+var import_node_fs = __toESM(require("node:fs"), 1);
var import_promises3 = require("node:fs/promises");
var import_node_path4 = require("node:path");
@@ -56218,6 +56222,87 @@ async function checkPython(pythonPath, cwd, env) {
if (result.exitCode !== 0 || result.timedOut || result.interrupted || result.signal)
throw new Error("Python 3.11 or later with sqlite3 and tomllib is required. Use actions/setup-python to select a compatible interpreter.");
}
+var SANDBOX_UNAVAILABLE_EXIT = 75;
+var SandboxUnavailableError = class extends Error {
+};
+async function ensureSandbox(options, probe, execute = runProcess) {
+ let initialError;
+ try {
+ await probe();
+ return;
+ } catch (error2) {
+ if (!(error2 instanceof SandboxUnavailableError) || options.runnerEnvironment !== "github-hosted" || options.imageOS !== "ubuntu24" || import_node_fs.default.existsSync("/.dockerenv")) throw error2;
+ initialError = error2;
+ }
+ const sudo = "/usr/bin/sudo";
+ for (const args of [
+ ["-n", "/usr/bin/apt-get", "update"],
+ // Defer only the hosted image's problematic PHP restart during this install.
+ ["-n", "/bin/sh", "-eu", "-c", String.raw`
+ if [ -d /etc/needrestart/conf.d ]; then
+ override=$(/usr/bin/mktemp /etc/needrestart/conf.d/codex-security-XXXXXX.conf)
+ trap '/usr/bin/rm -f "$override"' EXIT
+ trap 'exit 1' HUP INT TERM
+ printf '%s\n' '$nrconf{override_rc}{qr(^php8\.3-fpm\.service$)} = 0;' > "$override"
+ fi
+ /usr/bin/apt-get install --yes bubblewrap apparmor-profiles
+ `],
+ ["-n", "/usr/sbin/apparmor_parser", "-r", "/usr/share/apparmor/extra-profiles/bwrap-userns-restrict"]
+ ]) {
+ const result = await execute(sudo, args, options);
+ for (const line of safeLogLines(result.stdout)) {
+ try {
+ options.log?.(line);
+ } catch {
+ }
+ }
+ if (result.exitCode !== 0 || result.signal || result.interrupted || result.timedOut) {
+ const details = safeLogLines([result.stderr, result.stdout].join("\n")).join("\n");
+ throw new Error(`Ubuntu sandbox setup failed: sudo ${args.join(" ")} (exit ${result.exitCode}).
+${details}
+Original sandbox preflight: ${initialError.message}`, { cause: initialError });
+ }
+ }
+ await probe();
+}
+async function checkSandbox(nodePath, cliPath, options, env) {
+ const result = await runProcess(nodePath, ["--input-type=module", "--eval", `
+ import { pathToFileURL } from 'node:url';
+ import { dirname, join } from 'node:path';
+ const [cli, provider, model] = process.argv.slice(1);
+ const fromCli = file => import(pathToFileURL(join(dirname(cli), '../dist', file)).href);
+ const { parseCodexOverrides } = await fromCli('cli.js');
+ const { scanRuntimeCodexConfig } = await fromCli('api.js');
+ const { writeCodexConfig } = await fromCli('config.js');
+ const runtime = await fromCli('runtime.js');
+ const config = parseCodexOverrides(['analytics.enabled=false'], model || undefined, undefined, provider);
+ await writeCodexConfig(join(process.env.CODEX_HOME, 'config.toml'), scanRuntimeCodexConfig(config, process.env.CODEX_HOME));
+ const command = runtime.resolveCodexCommand(process.env);
+ try { await runtime.probeCodexSandbox(command, process.env); }
+ catch (error) {
+ const { SandboxUnavailableError } = await fromCli('errors.js');
+ if (!(error instanceof SandboxUnavailableError)) throw error;
+ console.error(error);
+ // The feature list loads the native configuration without starting Bubblewrap.
+ const config = await runtime.runCodexCommand(command, ['features', 'list'], process.env,
+ undefined, AbortSignal.timeout(10_000));
+ if (!config.success) {
+ console.error('Codex configuration check failed (exit ' + config.exitCode + ').');
+ if (config.stdout) console.error(config.stdout);
+ if (config.stderr) console.error(config.stderr);
+ }
+ process.exitCode = config.success ? ${SANDBOX_UNAVAILABLE_EXIT} : 1;
+ }
+ `, cliPath, options.provider, options.model], { cwd: options.repository, env });
+ const detail = result.stderr || result.stdout;
+ if (result.interrupted || result.signal || result.timedOut)
+ throw new Error(`Codex Security sandbox preflight ${result.timedOut ? "timed out" : "was interrupted"}. ${detail}`);
+ if (result.exitCode !== 0) {
+ const message = `Codex Security sandbox preflight failed. ${detail}`;
+ if (result.exitCode === SANDBOX_UNAVAILABLE_EXIT) throw new SandboxUnavailableError(message);
+ throw new Error(message);
+ }
+}
async function writeRuntimeLauncher(path6, executable, name, value) {
const quote = (value2) => "'" + value2.replaceAll("'", "'\\''") + "'";
await (0, import_promises3.writeFile)(path6, `#!/bin/sh
@@ -56265,10 +56350,21 @@ async function setupRuntime(options) {
await (0, import_promises3.writeFile)(globalConfig, "", { mode: 384, flag: "wx" });
const install = await runProcess(npmPath, ["ci", "--ignore-scripts", "--include=optional", `--registry=${REGISTRY}`, `--userconfig=${userConfig}`, `--globalconfig=${globalConfig}`, `--cache=${(0, import_node_path4.join)(root, "npm-cache")}`, "--no-audit", "--no-fund", "--loglevel=error"], { cwd: destination, env, timeoutMs: 10 * 60 * 1e3, log: options.log });
if (install.exitCode !== 0 || install.timedOut || install.interrupted) {
- for (const line of safeLogLines(install.stdout)) options.log?.(line);
- throw new Error(`Integrity-locked CLI installation failed (exit ${install.exitCode}${install.timedOut ? ", timed out" : ""}${install.interrupted ? ", interrupted" : ""}). Check the prefixed npm diagnostics, registry access, and runner prerequisites.`);
+ const details = safeLogLines([install.stderr, install.stdout].join("\n")).join("\n");
+ throw new Error(`Integrity-locked CLI installation failed (exit ${install.exitCode}${install.timedOut ? ", timed out" : ""}${install.interrupted ? ", interrupted" : ""}).
+${details}`);
}
const cliPath = await regularFile((0, import_node_path4.join)(destination, "node_modules", "@openai", "codex-security", "bin", "codex-security.mjs"));
+ if (options.model) {
+ await ensureSandbox(
+ { cwd: root, env, runnerEnvironment: process.env.RUNNER_ENVIRONMENT, imageOS: process.env.ImageOS, log: options.log },
+ () => checkSandbox(nodePath, cliPath, options, { ...env, CODEX_HOME: (0, import_node_path4.join)(root, "probe-home") })
+ );
+ try {
+ options.log?.("Codex sandbox probe succeeded without model calls.");
+ } catch {
+ }
+ }
const resultsDirectory = await (0, import_promises3.mkdtemp)((0, import_node_path4.join)(tempRoot, "codex-security-reports-"));
await (0, import_promises3.chmod)(resultsDirectory, 448);
return { ...paths, nodePath, cliPath, resultsDirectory, env: (credentials) => runtimeEnvironment(paths, credentials) };
@@ -56279,7 +56375,7 @@ async function setupRuntime(options) {
}
// src/results.ts
-var import_node_fs = require("node:fs");
+var import_node_fs2 = require("node:fs");
var import_promises4 = require("node:fs/promises");
var import_node_path5 = require("node:path");
@@ -56327,7 +56423,7 @@ async function processReportFile(root, name, adapt) {
const path6 = (0, import_node_path5.join)(absoluteRoot, name);
const before = await (0, import_promises4.lstat)(path6);
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1) throw new Error("Report must be a regular file without links.");
- const file = await (0, import_promises4.open)(path6, (adapt ? import_node_fs.constants.O_RDWR : import_node_fs.constants.O_RDONLY) | import_node_fs.constants.O_NOFOLLOW | import_node_fs.constants.O_NONBLOCK);
+ const file = await (0, import_promises4.open)(path6, (adapt ? import_node_fs2.constants.O_RDWR : import_node_fs2.constants.O_RDONLY) | import_node_fs2.constants.O_NOFOLLOW | import_node_fs2.constants.O_NONBLOCK);
try {
const opened = await file.stat();
if (!opened.isFile() || opened.nlink !== 1 || opened.dev !== before.dev || opened.ino !== before.ino) throw new Error("Report changed while opening.");
@@ -56526,7 +56622,7 @@ function getMaxArtifactListCount() {
}
// node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js
-var fs6 = __toESM(require("fs"), 1);
+var fs7 = __toESM(require("fs"), 1);
var path4 = __toESM(require("path"), 1);
// node_modules/@actions/artifact/lib/generated/google/protobuf/timestamp.js
@@ -58586,13 +58682,13 @@ function internalArtifactTwirpClient(options) {
}
// node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js
-var fs3 = __toESM(require("fs"), 1);
+var fs4 = __toESM(require("fs"), 1);
var import_path = require("path");
function validateRootDirectory(rootDirectory) {
- if (!fs3.existsSync(rootDirectory)) {
+ if (!fs4.existsSync(rootDirectory)) {
throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`);
}
- if (!fs3.statSync(rootDirectory).isDirectory()) {
+ if (!fs4.statSync(rootDirectory).isDirectory()) {
throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`);
}
info(`Root directory input is valid!`);
@@ -58602,7 +58698,7 @@ function getUploadZipSpecification(filesToZip, rootDirectory) {
rootDirectory = (0, import_path.normalize)(rootDirectory);
rootDirectory = (0, import_path.resolve)(rootDirectory);
for (let file of filesToZip) {
- const stats = fs3.lstatSync(file, { throwIfNoEntry: false });
+ const stats = fs4.lstatSync(file, { throwIfNoEntry: false });
if (!stats) {
throw new Error(`File ${file} does not exist`);
}
@@ -91184,7 +91280,7 @@ var Batch = class {
};
// node_modules/@azure/storage-blob/dist/esm/utils/utils.js
-var import_node_fs2 = __toESM(require("node:fs"), 1);
+var import_node_fs3 = __toESM(require("node:fs"), 1);
var import_node_util3 = __toESM(require("node:util"), 1);
async function streamToBuffer(stream4, buffer2, offset, end, encoding) {
let pos = 0;
@@ -91227,7 +91323,7 @@ async function streamToBuffer(stream4, buffer2, offset, end, encoding) {
}
async function readStreamToLocalFile(rs, file) {
return new Promise((resolve7, reject) => {
- const ws = import_node_fs2.default.createWriteStream(file);
+ const ws = import_node_fs3.default.createWriteStream(file);
rs.on("error", (err) => {
reject(err);
});
@@ -91238,8 +91334,8 @@ async function readStreamToLocalFile(rs, file) {
rs.pipe(ws);
});
}
-var fsStat = import_node_util3.default.promisify(import_node_fs2.default.stat);
-var fsCreateReadStream = import_node_fs2.default.createReadStream;
+var fsStat = import_node_util3.default.promisify(import_node_fs3.default.stat);
+var fsCreateReadStream = import_node_fs3.default.createReadStream;
// node_modules/@azure/storage-blob/dist/esm/Clients.js
var BlobClient = class _BlobClient extends StorageClient2 {
@@ -94062,7 +94158,7 @@ var import_archiver = __toESM(require_archiver(), 1);
// node_modules/@actions/artifact/lib/internal/upload/stream.js
var stream2 = __toESM(require("stream"), 1);
-var fs5 = __toESM(require("fs"), 1);
+var fs6 = __toESM(require("fs"), 1);
var import_promises6 = require("fs/promises");
var __awaiter8 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
@@ -94108,11 +94204,11 @@ function createRawFileUploadStream(filePath) {
const bufferSize = getUploadChunkSize();
const uploadStream = new WaterMarkedUploadStream(bufferSize);
let sourcePath = filePath;
- const stats = yield fs5.promises.lstat(filePath);
+ const stats = yield fs6.promises.lstat(filePath);
if (stats.isSymbolicLink()) {
sourcePath = yield (0, import_promises6.realpath)(filePath);
}
- const fileStream = fs5.createReadStream(sourcePath, {
+ const fileStream = fs6.createReadStream(sourcePath, {
highWaterMark: bufferSize
});
fileStream.on("error", (error2) => {
@@ -94312,7 +94408,7 @@ function uploadArtifact(name, files, rootDirectory, options) {
if (files.length > 1) {
throw new Error("skipArchive option is only supported when uploading a single file");
}
- if (!fs6.existsSync(files[0])) {
+ if (!fs7.existsSync(files[0])) {
throw new FilesNotFoundError(files);
}
artifactFileName = path4.basename(files[0]);
@@ -99390,7 +99486,8 @@ async function uploadReports(reports, inputs, tempRoot) {
await (0, import_promises9.writeFile)(dest, bytes, { mode: 384, flag: "wx" });
files.push(dest);
}
- await new DefaultArtifactClient().uploadArtifact(inputs.artifactName, files, staging, { retentionDays: inputs.retentionDays, compressionLevel: 0 });
+ const artifact = await new DefaultArtifactClient().uploadArtifact(inputs.artifactName, files, staging, { retentionDays: inputs.retentionDays, compressionLevel: 0 });
+ return artifact.id;
} finally {
await (0, import_promises9.rm)(staging, { recursive: true, force: true });
}
@@ -99413,7 +99510,7 @@ function resultTitle(result, inputs) {
if (inputs.failOnSeverity === "none") return "Scan completed. Findings are reported without failing the job.";
return "Scan completed. No findings meet the failure threshold.";
}
-function resultSummary(result, inputs, target) {
+function resultSummary(result, inputs, target, artifactUrl) {
const esc = (value, limit = 4e3) => html(plain(value, limit));
const counts = result.counts ? Object.entries(result.counts).map(([level, count]) => `${level}: ${count}`).join(" \xB7 ") : "unavailable";
const usage = result.usage;
@@ -99422,6 +99519,7 @@ function resultSummary(result, inputs, target) {
const cost = range2 && range2.max !== range2.min ? range2.max === null ? `$${range2.min.toFixed(4)} (upper estimate unavailable)` : `$${range2.min.toFixed(4)}\u2013$${range2.max.toFixed(4)}` : result.estimatedCost === void 0 ? "unavailable" : `$${result.estimatedCost.toFixed(4)}`;
const parts = [
`**Scan:** ${result.scanStatus} \xB7 **Findings policy:** ${result.policyStatus} \xB7 **Report:** ${result.reportStatus}`,
+ ...artifactUrl ? [`**Reports:** <a href="${html(artifactUrl)}">${esc(inputs.artifactName)}</a> \xB7 Retention: up to ${inputs.retentionDays} days.`] : [],
`**Findings:** ${counts}`,
`**Scope:** ${inputs.scope}${inputs.paths.length ? ` <code>${esc(inputs.paths.join(", "))}</code>` : ""} \xB7 **Mode:** ${inputs.mode}`,
`**Commit:** <code>${target.scannedSha}</code>`,
@@ -99563,7 +99661,7 @@ async function runAction(actionRoot, overrides = {}) {
const preparationStarted = performance.now();
let timer = heartbeat("CLI preparation", preparationStarted);
try {
- runtime = await deps.setupRuntime({ actionRoot, tempRoot, log: info });
+ runtime = await deps.setupRuntime({ actionRoot, tempRoot, repository: target.repository, provider: inputs.provider, model: inputs.model, log: inputs.verbose ? info : void 0 });
} finally {
clearInterval(timer);
}
@@ -99628,12 +99726,15 @@ async function runAction(actionRoot, overrides = {}) {
if (checkoutError) result.errors.unshift(checkoutError);
if (interrupted) result.errors.unshift("Scan was interrupted or exceeded its execution limit.");
let reportsValidated = false;
+ let artifactUrl;
try {
const reports = await collectReports(result);
reportsValidated = true;
if (inputs.uploadArtifacts) {
info("Uploading validated report artifacts.");
- await uploadReports(reports, inputs, tempRoot);
+ const artifactId = await uploadReports(reports, inputs, tempRoot);
+ if (artifactId !== void 0 && process.env.GITHUB_RUN_ID)
+ artifactUrl = `${event.serverUrl}/${event.repository}/actions/runs/${process.env.GITHUB_RUN_ID}/artifacts/${artifactId}`;
}
} catch (error2) {
result.reportStatus = "failed";
@@ -99650,7 +99751,7 @@ async function runAction(actionRoot, overrides = {}) {
...result,
findings: [...result.findings].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])
};
- finalSummary = resultSummary(displayResult, inputs, target);
+ finalSummary = resultSummary(displayResult, inputs, target, artifactUrl);
if (inputs.annotations) emitAnnotations(displayResult);
success = result.reportStatus !== "failed" && result.scanStatus === "completed" && result.policyStatus === "passed";
finalTitle = resultTitle(result, inputs);
@@ -99673,7 +99774,7 @@ async function runAction(actionRoot, overrides = {}) {
setOutput("sarif-upload-ready", "false");
}
}
- if (inputs?.summary !== false) {
+ if (inputs?.summary ?? getInput("summary") !== "false") {
try {
await summary.addRaw(`## Codex Security
diff --git a/github-action/examples/pull-request.yml b/github-action/examples/pull-request.yml
new file mode 100644
index 000000000..9a1c4971f
--- /dev/null
+++ b/github-action/examples/pull-request.yml
@@ -0,0 +1,84 @@
+# Required-check policy prerequisites, including merge-time freshness, are in the README.
+name: Codex Security PR
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, ready_for_review, edited]
+
+permissions:
+ contents: read
+ pull-requests: read
+
+concurrency:
+ # Group names are case-insensitive; the run ID also separates case-only retargets.
+ group: codex-security-pr-${{ github.event.pull_request.number }}-${{ github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ security:
+ if: >-
+ github.event.pull_request.head.repo.full_name == github.repository &&
+ (github.event.action != 'edited' || github.event.changes.base != null)
+ name: Scan changes
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ outputs:
+ scan-status: ${{ steps.security.outputs.scan-status }}
+ skip-reason: ${{ steps.security.outputs.skip-reason }}
+ steps:
+ - &verify-current-pr
+ name: Verify the PR still matches this scan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
+ PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: |
+ current=$(gh api --hostname "${GITHUB_SERVER_URL#https://}" "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '[.head.sha, .base.ref, .base.sha] | @tsv')
+ expected=$(printf '%s\t%s\t%s' "$PR_HEAD_SHA" "$PR_BASE_REF" "$PR_BASE_SHA")
+ if [ "$current" != "$expected" ]; then
+ echo 'The PR head or target changed. Run the workflow for the current PR snapshot.' >&2
+ exit 1
+ fi
+ base_ref=$(printf '%s' "$PR_BASE_REF" | jq -sRr @uri)
+ live_base=$(gh api --hostname "${GITHUB_SERVER_URL#https://}" "repos/$GITHUB_REPOSITORY/git/ref/heads/$base_ref" --jq '.object.sha')
+ if [ "$live_base" != "$PR_BASE_SHA" ]; then
+ echo 'The PR head or target changed. Run the workflow for the current PR snapshot.' >&2
+ exit 1
+ fi
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - name: Scan PR changes
+ id: security
+ uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT
+ with:
+ scope: diff
+ model: gpt-5.6-sol
+ effort: high
+ max-cost: "5"
+ fail-on-severity: high
+ env:
+ OPENAI_API_KEY: ${{ secrets.CODEX_SECURITY_API_KEY }}
+
+ required-review:
+ name: ${{ github.event.action == 'edited' && github.event.changes.base == null && 'metadata / ' || '' }}Codex Security / ${{ github.event.pull_request.base.ref }}
+ needs: security
+ if: always() && (github.event.action != 'edited' || github.event.changes.base != null)
+ runs-on: ubuntu-24.04
+ steps:
+ - *verify-current-pr
+ - name: Require a completed review or an empty diff
+ env:
+ SCAN_JOB_RESULT: ${{ needs.security.result }}
+ SCAN_STATUS: ${{ needs.security.outputs.scan-status }}
+ SKIP_REASON: ${{ needs.security.outputs.skip-reason }}
+ run: |
+ test "$SCAN_JOB_RESULT" = success
+ if [ "$SCAN_STATUS" = completed ]; then
+ exit 0
+ fi
+ test "$SCAN_STATUS" = skipped
+ test "$SKIP_REASON" = empty-diff
diff --git a/github-action/examples/repository.yml b/github-action/examples/repository.yml
new file mode 100644
index 000000000..6624e4e47
--- /dev/null
+++ b/github-action/examples/repository.yml
@@ -0,0 +1,28 @@
+name: Codex Security repository
+on:
+ workflow_dispatch:
+ schedule:
+ - cron: "23 7 * * 1" # Mondays at 07:23 UTC
+
+permissions:
+ contents: read
+
+jobs:
+ security:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Scan the repository
+ id: security
+ uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT
+ with:
+ scope: repository
+ model: gpt-5.6-sol
+ effort: high
+ max-cost: "5"
+ fail-on-severity: none
+ env:
+ OPENAI_API_KEY: ${{ secrets.CODEX_SECURITY_API_KEY }}
diff --git a/github-action/scripts/cli-integration.ts b/github-action/scripts/cli-integration.ts
index 260bd3d78..7c6e0be93 100644
--- a/github-action/scripts/cli-integration.ts
+++ b/github-action/scripts/cli-integration.ts
@@ -7,9 +7,10 @@ import { createServer, type IncomingHttpHeaders } from 'node:http';
import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { promisify } from 'node:util';
+import { parse as parseYaml } from 'yaml';
import { parseInputs, scanArguments } from '../src/inputs.js';
import { analyzeResults } from '../src/results.js';
-import { captureRunnerPath, checkPython, resolveTool, runtimeEnvironment, writeRuntimeLauncher } from '../src/runtime.js';
+import { captureRunnerPath, checkPython, checkSandbox, resolveTool, runtimeEnvironment, SandboxUnavailableError, writeRuntimeLauncher } from '../src/runtime.js';
import runtimeManifest from '../runtime/package.json' with { type: 'json' };
const [candidatePackage, candidateVersion] = process.argv.slice(2);
@@ -101,6 +102,34 @@ try {
assert.equal(deepPreflight.maxTimeHours, 0.25);
assert.deepEqual(deepPreflight.target.paths, ['example.ts']);
+ // Validate workflow model and cost settings against both the published pin and release candidates.
+ const diffBase = git('rev-parse', 'HEAD').trim();
+ await writeFile(join(repository, 'added.ts'), 'export const added = true;\n');
+ git('add', 'added.ts'); git('commit', '-m', 'Synthetic pull request');
+ const diffHead = git('rev-parse', 'HEAD').trim();
+ for (const example of ['repository', 'pull-request']) {
+ const workflow = parseYaml(await readFile(resolve(import.meta.dirname, `../examples/${example}.yml`), 'utf8'));
+ const values: Record<string, string> = workflow.jobs.security.steps.find((step: {id?: string}) => step.id === 'security').with;
+ const production = parseInputs(name => values[name] ?? '', repository);
+ assert.equal(production.dryRun, false);
+ for (const mode of production.scope === 'repository' ? ['standard', 'deep'] : ['standard']) for (const program of [undefined, 'daybreak_blue']) {
+ // Test the example's program selection first, then the optional Blue variant.
+ // The production policy was already parsed; dry-run cannot enforce it.
+ const dryValues: Record<string, string> = {...values, mode,
+ ...(program === undefined ? {} : {'cyber-access-program':program}),
+ 'fail-on-severity':'none', 'dry-run':'true'};
+ const inputs = parseInputs(name => dryValues[name] ?? '', repository);
+ const target = production.scope === 'diff' ? {repository, diffBase, diffHead} : {repository};
+ const args = scanArguments(inputs, target, join(root, `budget-${example}-${mode}-${program ?? 'example'}`));
+ const result = JSON.parse(run(args, 0));
+ assert.equal(result.dryRun, true);
+ assert.equal(result.mode, mode);
+ assert.equal(result.model, production.model);
+ assert.equal(result.reasoningEffort, production.effort);
+ assert.equal(result.maxCostUsd, production.maxCost);
+ }
+ }
+
// Exercise each installed provider while covering both scan modes.
for (const [provider, mode] of [['amazon-bedrock', 'deep'], ['openrouter', 'standard'], ['fireworks', 'deep']]) {
const values: Record<string, string> = {provider, model:'synthetic/model', mode, 'dry-run':'true'};
@@ -240,6 +269,17 @@ try {
await writeRuntimeLauncher(nodeLauncher, process.execPath, 'RUNNER_TRACKING_ID', 'synthetic-cli-job');
const venvEnv = runtimeEnvironment({root, home, codexHome:env.CODEX_HOME, stateDirectory:env.CODEX_SECURITY_STATE_DIR,
runnerPath, runnerTrackingId:'synthetic-cli-job', runnerLibraryPath:libraryPath});
+ const shadowBin = join(repository, 'bin');
+ await mkdir(shadowBin);
+ await writeFile(join(shadowBin, 'bwrap'), '#!/bin/sh\n: > "$0.ran"\nexit 70\n', {mode:0o755});
+ const probeEnv = {...venvEnv, CODEX_HOME:join(root, 'probe-home')};
+ await checkSandbox(process.execPath, cli, {repository, provider:'openrouter', model:'example/model'}, {
+ ...probeEnv, PATH:shadowBin + delimiter + venvEnv.PATH,
+ });
+ await assert.rejects(checkSandbox(process.execPath, cli, {repository, provider:'openrouter', model:''}, probeEnv),
+ error => error instanceof Error && !(error instanceof SandboxUnavailableError) && /model/i.test(error.message));
+ await assert.rejects(readFile(join(shadowBin, 'bwrap.ran')), {code:'ENOENT'});
+ await rm(shadowBin, {recursive:true});
// Use the published MCP launcher and its actual allowlist without a model turn.
// The synthetic server reports its marker and one actual Node child's marker.
const mcpConfig = JSON.parse(await readFile(join(cliPackage, '_bundled_plugin/.mcp.json'), 'utf8')).mcpServers['codex-security'];
@@ -276,6 +316,40 @@ try {
assert.equal(selected.loader, libraryPath);
assert.equal(selected.tracking, 'synthetic-cli-job');
+ const nativeProbe = join(root, 'native-probe');
+ const nativeEnv = {...probeEnv, CODEX_CLI_PATH:nativeProbe, PROBE_CODEX:selected.codex};
+ const probe = (nodePath = process.execPath) => checkSandbox(nodePath, cli, {repository, provider:'openai', model:''}, nativeEnv);
+ await writeFile(nativeProbe, `#!/bin/sh\nexec "$PROBE_CODEX" -c 'model_provider="synthetic-undefined"' "$@"\n`, {mode:0o755});
+ await assert.rejects(probe, error => error instanceof Error && !(error instanceof SandboxUnavailableError) && error.message.includes('synthetic-undefined'));
+ await writeFile(nativeProbe, '#!/bin/sh\n[ "$1" != sandbox ] && exec "$PROBE_CODEX" "$@"\n');
+ await assert.rejects(probe, SandboxUnavailableError);
+ // Observe both real SDK child boundaries without invoking a sandbox or a model.
+ const probeInvocations = join(root, 'probe-invocations.jsonl');
+ for (const featuresExit of [0, 19]) {
+ await writeFile(probeInvocations, '');
+ await writeFile(nativeProbe, `#!${process.execPath}
+ const fs = require('node:fs'); const path = require('node:path');
+ fs.appendFileSync(${JSON.stringify(probeInvocations)}, JSON.stringify({args:process.argv.slice(2),
+ config:fs.readFileSync(path.join(process.env.CODEX_HOME, 'config.toml'), 'utf8')}) + '\\n');
+ if (process.argv[2] === 'sandbox') {
+ console.error('synthetic sandbox failure sk-example-original'); process.exitCode = 1;
+ } else {
+ console.log('synthetic configuration stdout'); console.error('synthetic configuration stderr');
+ process.exitCode = ${featuresExit};
+ }
+ `);
+ await assert.rejects(probe, error => error instanceof Error
+ && (error instanceof SandboxUnavailableError) === (featuresExit === 0)
+ && error.message.includes('synthetic sandbox failure sk-example-original')
+ && (featuresExit === 0 || (error.message.includes('synthetic configuration stdout')
+ && error.message.includes('synthetic configuration stderr') && error.message.includes('exit 19'))));
+ const invocations = (await readFile(probeInvocations, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
+ assert.deepEqual(invocations.map(call => call.args[0]), ['sandbox', 'features']);
+ for (const call of invocations) assert.match(call.config, /\[analytics\]\s+enabled = false/);
+ }
+ await writeFile(nativeProbe, `#!${process.execPath}\nprocess.on('SIGTERM', () => process.exit(0)); process.kill(process.ppid, 'SIGINT'); setInterval(() => {}, 1000);\n`);
+ await assert.rejects(probe(nativeProbe), /sandbox preflight was interrupted/);
+
// Exercise filesystem enforcement with the scan and network-disabled Deep
// worker profiles, using the same pinned Codex and child PATH as the Action.
const sandboxWorkspace = join(root, 'sandbox-workspace');
diff --git a/github-action/scripts/generate-input-docs.mjs b/github-action/scripts/generate-input-docs.mjs
index 7d6c94b7f..b08c14b83 100644
--- a/github-action/scripts/generate-input-docs.mjs
+++ b/github-action/scripts/generate-input-docs.mjs
@@ -22,14 +22,22 @@ reference = await format(reference, { parser: 'markdown' });
const path = new URL('../README.md', import.meta.url);
const current = await readFile(path, 'utf8');
-const start = '<!-- action-reference:start -->';
-const end = '<!-- action-reference:end -->';
-const startIndex = current.indexOf(start);
-const endIndex = current.indexOf(end);
-assert.ok(startIndex >= 0 && startIndex < endIndex, 'README must contain action reference markers in order');
-const updated = current.slice(0, startIndex) + start + '\n\n' + reference + '\n' + current.slice(endIndex);
+function replaceSection(text, section, content, label) {
+ const start = `<!-- ${section}:start -->`;
+ const end = `<!-- ${section}:end -->`;
+ const startIndex = text.indexOf(start);
+ const endIndex = text.indexOf(end);
+ assert.ok(startIndex >= 0 && startIndex < endIndex, `README must contain ${label} markers in order`);
+ return text.slice(0, startIndex) + start + '\n\n' + content + '\n' + text.slice(endIndex);
+}
+let updated = replaceSection(current, 'action-reference', reference, 'action reference');
+for (const name of ['repository', 'pull-request']) {
+ const workflow = await readFile(new URL(`../examples/${name}.yml`, import.meta.url), 'utf8');
+ const snippet = await format('```yaml\n' + workflow + '```\n', { parser: 'markdown' });
+ updated = replaceSection(updated, `action-workflow:${name}`, snippet, `${name} workflow`);
+}
if (process.argv.includes('--check')) {
- assert.equal(current, updated, 'Action reference differs from action.yml. Run npm run docs.');
+ assert.equal(current, updated, 'Action reference or workflow examples are out of date. Run npm run docs.');
} else {
await writeFile(path, updated);
}
diff --git a/github-action/scripts/linux-smoke.mjs b/github-action/scripts/linux-smoke.mjs
index d3ee2d884..302fa8298 100644
--- a/github-action/scripts/linux-smoke.mjs
+++ b/github-action/scripts/linux-smoke.mjs
@@ -1,4 +1,4 @@
-// Runs the SHIPPED action in a temporary checkout with dry-run and no secrets.
+// Runs the shipped Action and its real sandbox probe with dry-run and no secrets.
import { mkdir, mkdtemp, writeFile, readFile, rm, lstat } from 'node:fs/promises';
import { execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
@@ -21,16 +21,20 @@ try {
for (const name of ['output','state','summary']) await writeFile(join(commandRoot,name),'');
await writeFile(join(commandRoot,'event.json'),'{}');
const action = resolve(repositoryRoot, metadata.runs.main);
- const run = spawnSync(process.execPath,[action], {cwd:root, encoding:'utf8', timeout:600_000,maxBuffer:8*1024*1024,env:{...baseEnv,
+ const runAction = (inputs = {}) => spawnSync(process.execPath,[action], {cwd:root, encoding:'utf8', timeout:600_000,maxBuffer:8*1024*1024,env:{...baseEnv,
GITHUB_ACTIONS:'true',GITHUB_EVENT_NAME:'workflow_dispatch',GITHUB_EVENT_PATH:join(commandRoot,'event.json'),
GITHUB_REPOSITORY:'example/smoke',GITHUB_SHA:sha,GITHUB_REF:'refs/heads/main',GITHUB_ACTOR:'smoke',GITHUB_SERVER_URL:'https://github.com',
GITHUB_WORKSPACE:root,RUNNER_TEMP:commandRoot,RUNNER_TRACKING_ID:'synthetic-smoke-job',GITHUB_OUTPUT:join(commandRoot,'output'),GITHUB_STATE:join(commandRoot,'state'),GITHUB_STEP_SUMMARY:join(commandRoot,'summary'),
- 'INPUT_DRY-RUN':'true',INPUT_VERBOSE:'true',
+ RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT,ImageOS:process.env.ImageOS,
+ 'INPUT_DRY-RUN':'true',INPUT_VERBOSE:'true',...inputs,
}});
+ const run = runAction();
if (run.status !== 0) {
console.error(run.stdout); console.error(run.stderr);
throw run.error ?? new Error(`Packaged action exited ${run.status}`);
}
+ assert.match(run.stdout, /Codex sandbox probe succeeded without model calls\./,
+ 'The packaged Action must exercise the shipped SDK sandbox probe, not just CLI input validation');
const output=await readFile(join(commandRoot,'output'),'utf8');
assert.match(output,/scan-status<<[^\n]+\nskipped\n/);
assert.match(output,/skip-reason<<[^\n]+\ndry-run\n/);
@@ -55,6 +59,11 @@ try {
await writeFile(join(runtimeRoot, '.codex-security-action-owned'), 'codex-security-action-v1\n', {mode: 0o600});
await writeFile(join(runtimeRoot, 'home', 'auth.json'), '{"token":"synthetic-smoke-token"}\n', {mode: 0o600});
await runPost();
- console.log('Packaged Linux action installed the locked CLI, passed dry-run, and verified post cleanup for absent and leftover runtimes without credentials or model calls.');
+ await writeFile(join(commandRoot, 'output'), '');
+ const invalidProvider = runAction({INPUT_PROVIDER:'openrouter', INPUT_MODEL:''});
+ assert.equal(invalidProvider.status, 1, invalidProvider.stderr);
+ assert.match(invalidProvider.stdout, /--model is required when using --provider openrouter/);
+ assert.match(await readFile(join(commandRoot, 'output'), 'utf8'), /exit-code<<[^\n]+\n2\n/);
+ console.log('Packaged Linux action installed the locked CLI, passed the sandbox probe and dry-run, preserved the missing-model exit code, and verified post cleanup without credentials or model calls.');
} finally { await rm(commandRoot,{recursive:true,force:true}); }
} finally { await rm(root,{recursive:true,force:true}); }
diff --git a/github-action/src/artifacts.ts b/github-action/src/artifacts.ts
index b02b197fc..0a73a3844 100644
--- a/github-action/src/artifacts.ts
+++ b/github-action/src/artifacts.ts
@@ -16,7 +16,7 @@ export async function collectReports(result: ScanResults): Promise<Map<string, B
}
return reports;
}
-export async function uploadReports(reports: Map<string, Buffer>, inputs: Inputs, tempRoot: string): Promise<void> {
+export async function uploadReports(reports: Map<string, Buffer>, inputs: Inputs, tempRoot: string): Promise<number | undefined> {
if (!reports.size) throw new Error('Artifact upload requested, but no validated reports are available.');
const staging = await mkdtemp(join(tempRoot, 'codex-security-upload-'));
try {
@@ -27,6 +27,7 @@ export async function uploadReports(reports: Map<string, Buffer>, inputs: Inputs
await writeFile(dest, bytes, {mode: 0o600, flag: 'wx'});
files.push(dest);
}
- await new DefaultArtifactClient().uploadArtifact(inputs.artifactName, files, staging, {retentionDays: inputs.retentionDays, compressionLevel: 0});
+ const artifact = await new DefaultArtifactClient().uploadArtifact(inputs.artifactName, files, staging, {retentionDays: inputs.retentionDays, compressionLevel: 0});
+ return artifact.id;
} finally { await rm(staging, {recursive: true, force: true}); }
}
diff --git a/github-action/src/inputs.ts b/github-action/src/inputs.ts
index 4f4c0e466..af3753b7c 100644
--- a/github-action/src/inputs.ts
+++ b/github-action/src/inputs.ts
@@ -46,6 +46,9 @@ export function parseInputs(read: (name: string) => string, workspace: string) {
const maxTimeHours = num('max-time-hours', false, Number.MIN_VALUE, 96);
if (maxTimeHours !== undefined && mode !== 'deep') throw new Error('max-time-hours requires mode: deep.');
const dryRun = bool('dry-run', false);
+ const failOnSeverity = choice('fail-on-severity', ['none','low','medium','high','critical'], 'none');
+ if (dryRun && failOnSeverity !== 'none')
+ throw new Error('dry-run requires fail-on-severity: none. Configuration validation cannot satisfy a required security review.');
const provider = choice('provider', ['openai', 'openrouter', 'fireworks', 'amazon-bedrock'], 'openai');
const model = str('model', provider === 'openai' ? 'gpt-5.6-sol' : '');
const cyberAccessProgram = str('cyber-access-program')
@@ -54,7 +57,7 @@ export function parseInputs(read: (name: string) => string, workspace: string) {
return {
repository: str('repository', workspace), scope, paths, diffBase, mode, cyberAccessProgram,
provider, model, effort: str('effort', 'xhigh'),
- maxCost: num('max-cost', false, Number.MIN_VALUE), maxTimeHours, failOnSeverity: choice('fail-on-severity', ['none','low','medium','high','critical'], 'none'),
+ maxCost: num('max-cost', false, Number.MIN_VALUE), maxTimeHours, failOnSeverity,
verbose: bool('verbose', true), dryRun,
summary: bool('summary', true), annotations: bool('annotations', true),
uploadArtifacts: bool('upload-artifacts', false), artifactName: str('artifact-name', 'codex-security'), retentionDays: num('retention-days', true, 1, 90) ?? 7,
diff --git a/github-action/src/main.ts b/github-action/src/main.ts
index 4fcc5db6b..179b226ce 100644
--- a/github-action/src/main.ts
+++ b/github-action/src/main.ts
@@ -91,7 +91,9 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc
core.info(`Preparing Codex Security ${SUPPORTED_CLI_VERSION}. Scope: ${inputs.scope}; mode: ${inputs.mode}; effort: ${inputs.effort}.`);
const preparationStarted = performance.now();
let timer = heartbeat('CLI preparation', preparationStarted);
- try { runtime = await deps.setupRuntime({actionRoot, tempRoot, log: core.info}); }
+ try {
+ runtime = await deps.setupRuntime({actionRoot, tempRoot, repository: target.repository, provider: inputs.provider, model: inputs.model, log: inputs.verbose ? core.info : undefined});
+ }
finally { clearInterval(timer); }
core.info(`CLI preparation completed in ${elapsed(preparationStarted)}.`);
core.saveState('runtime-root', runtime.root);
@@ -143,12 +145,15 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc
if (checkoutError) result.errors.unshift(checkoutError);
if (interrupted) result.errors.unshift('Scan was interrupted or exceeded its execution limit.');
let reportsValidated = false;
+ let artifactUrl: string | undefined;
try {
const reports = await collectReports(result);
reportsValidated = true;
if (inputs.uploadArtifacts) {
core.info('Uploading validated report artifacts.');
- await uploadReports(reports, inputs, tempRoot);
+ const artifactId = await uploadReports(reports, inputs, tempRoot);
+ if (artifactId !== undefined && process.env.GITHUB_RUN_ID)
+ artifactUrl = `${event.serverUrl}/${event.repository}/actions/runs/${process.env.GITHUB_RUN_ID}/artifacts/${artifactId}`;
}
} catch (error) {
result.reportStatus = 'failed';
@@ -166,7 +171,7 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc
...result,
findings: [...result.findings].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]),
};
- finalSummary = resultSummary(displayResult, inputs, target);
+ finalSummary = resultSummary(displayResult, inputs, target, artifactUrl);
if (inputs.annotations) emitAnnotations(displayResult);
success = result.reportStatus !== 'failed' && result.scanStatus === 'completed' && result.policyStatus === 'passed';
finalTitle = resultTitle(result, inputs);
@@ -188,7 +193,7 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc
core.setOutput('sarif-upload-ready', 'false');
}
}
- if (inputs?.summary !== false) {
+ if (inputs?.summary ?? (core.getInput('summary') !== 'false')) {
try { await core.summary.addRaw(`## Codex Security\n\n**${finalTitle}**\n\n${finalSummary}`).write(); }
catch { core.warning('Could not write the job summary.'); }
}
diff --git a/github-action/src/reporting.ts b/github-action/src/reporting.ts
index 64bdddd18..0f4460c06 100644
--- a/github-action/src/reporting.ts
+++ b/github-action/src/reporting.ts
@@ -22,7 +22,7 @@ export function resultTitle(result: ScanResults, inputs: Inputs): string {
if (inputs.failOnSeverity === 'none') return 'Scan completed. Findings are reported without failing the job.';
return 'Scan completed. No findings meet the failure threshold.';
}
-export function resultSummary(result: ScanResults, inputs: Inputs, target: Target): string {
+export function resultSummary(result: ScanResults, inputs: Inputs, target: Target, artifactUrl?: string): string {
const esc = (value: string, limit = 4000) => html(plain(value, limit));
const counts = result.counts ? Object.entries(result.counts).map(([level, count]) => `${level}: ${count}`).join(' · ') : 'unavailable';
const usage = result.usage;
@@ -33,6 +33,7 @@ export function resultSummary(result: ScanResults, inputs: Inputs, target: Targe
: result.estimatedCost === undefined ? 'unavailable' : `$${result.estimatedCost.toFixed(4)}`;
const parts = [
`**Scan:** ${result.scanStatus} · **Findings policy:** ${result.policyStatus} · **Report:** ${result.reportStatus}`,
+ ...(artifactUrl ? [`**Reports:** <a href="${html(artifactUrl)}">${esc(inputs.artifactName)}</a> · Retention: up to ${inputs.retentionDays} days.`] : []),
`**Findings:** ${counts}`,
`**Scope:** ${inputs.scope}${inputs.paths.length ? ` <code>${esc(inputs.paths.join(', '))}</code>` : ''} · **Mode:** ${inputs.mode}`,
`**Commit:** <code>${target.scannedSha}</code>`,
diff --git a/github-action/src/runtime.ts b/github-action/src/runtime.ts
index aa5e0c782..18996288f 100644
--- a/github-action/src/runtime.ts
+++ b/github-action/src/runtime.ts
@@ -1,4 +1,5 @@
import { which } from '@actions/io';
+import fs from 'node:fs';
import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, realpath, symlink, writeFile } from 'node:fs/promises';
import { delimiter, isAbsolute, join, resolve, sep } from 'node:path';
import { runProcess, safeLogLines } from './process.js';
@@ -36,6 +37,9 @@ export function scanCredentials(provider: ScanCredentials['provider'], source: N
export interface RuntimeOptions {
actionRoot: string;
tempRoot: string;
+ repository: string;
+ provider: ScanCredentials['provider'];
+ model: string;
log?: (line: string) => void;
}
export interface Runtime {
@@ -114,6 +118,92 @@ export async function checkPython(pythonPath: string, cwd: string, env: NodeJS.P
throw new Error('Python 3.11 or later with sqlite3 and tomllib is required. Use actions/setup-python to select a compatible interpreter.');
}
+// Carry only the pinned SDK's SandboxUnavailableError across the probe process.
+const SANDBOX_UNAVAILABLE_EXIT = 75;
+export class SandboxUnavailableError extends Error {}
+
+export async function ensureSandbox(options: {
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ runnerEnvironment?: string;
+ imageOS?: string;
+ log?: (line: string) => void;
+}, probe: () => Promise<void>, execute = runProcess): Promise<void> {
+ let initialError: SandboxUnavailableError;
+ try { await probe(); return; }
+ catch (error) {
+ // Docker job containers inherit the host image labels but own their setup.
+ if (!(error instanceof SandboxUnavailableError) || options.runnerEnvironment !== 'github-hosted' || options.imageOS !== 'ubuntu24' || fs.existsSync('/.dockerenv')) throw error;
+ initialError = error;
+ }
+ const sudo = '/usr/bin/sudo';
+ for (const args of [
+ ['-n', '/usr/bin/apt-get', 'update'],
+ // Defer only the hosted image's problematic PHP restart during this install.
+ ['-n', '/bin/sh', '-eu', '-c', String.raw`
+ if [ -d /etc/needrestart/conf.d ]; then
+ override=$(/usr/bin/mktemp /etc/needrestart/conf.d/codex-security-XXXXXX.conf)
+ trap '/usr/bin/rm -f "$override"' EXIT
+ trap 'exit 1' HUP INT TERM
+ printf '%s\n' '$nrconf{override_rc}{qr(^php8\.3-fpm\.service$)} = 0;' > "$override"
+ fi
+ /usr/bin/apt-get install --yes bubblewrap apparmor-profiles
+ `],
+ ['-n', '/usr/sbin/apparmor_parser', '-r', '/usr/share/apparmor/extra-profiles/bwrap-userns-restrict'],
+ ]) {
+ const result = await execute(sudo, args, options);
+ for (const line of safeLogLines(result.stdout)) {
+ try { options.log?.(line); }
+ catch { /* Optional diagnostics must not interrupt sandbox preparation. */ }
+ }
+ if (result.exitCode !== 0 || result.signal || result.interrupted || result.timedOut) {
+ const details = safeLogLines([result.stderr, result.stdout].join('\n')).join('\n');
+ throw new Error(`Ubuntu sandbox setup failed: sudo ${args.join(' ')} (exit ${result.exitCode}).\n${details}\nOriginal sandbox preflight: ${initialError.message}`, {cause: initialError});
+ }
+ }
+ await probe();
+}
+
+export async function checkSandbox(nodePath: string, cliPath: string, options: Pick<RuntimeOptions, 'repository' | 'provider' | 'model'>, env: NodeJS.ProcessEnv): Promise<void> {
+ // Reuse the shipped SDK's executable selection and sandbox probe. No model calls.
+ const result = await runProcess(nodePath, ['--input-type=module', '--eval', `
+ import { pathToFileURL } from 'node:url';
+ import { dirname, join } from 'node:path';
+ const [cli, provider, model] = process.argv.slice(1);
+ const fromCli = file => import(pathToFileURL(join(dirname(cli), '../dist', file)).href);
+ const { parseCodexOverrides } = await fromCli('cli.js');
+ const { scanRuntimeCodexConfig } = await fromCli('api.js');
+ const { writeCodexConfig } = await fromCli('config.js');
+ const runtime = await fromCli('runtime.js');
+ const config = parseCodexOverrides(['analytics.enabled=false'], model || undefined, undefined, provider);
+ await writeCodexConfig(join(process.env.CODEX_HOME, 'config.toml'), scanRuntimeCodexConfig(config, process.env.CODEX_HOME));
+ const command = runtime.resolveCodexCommand(process.env);
+ try { await runtime.probeCodexSandbox(command, process.env); }
+ catch (error) {
+ const { SandboxUnavailableError } = await fromCli('errors.js');
+ if (!(error instanceof SandboxUnavailableError)) throw error;
+ console.error(error);
+ // The feature list loads the native configuration without starting Bubblewrap.
+ const config = await runtime.runCodexCommand(command, ['features', 'list'], process.env,
+ undefined, AbortSignal.timeout(10_000));
+ if (!config.success) {
+ console.error('Codex configuration check failed (exit ' + config.exitCode + ').');
+ if (config.stdout) console.error(config.stdout);
+ if (config.stderr) console.error(config.stderr);
+ }
+ process.exitCode = config.success ? ${SANDBOX_UNAVAILABLE_EXIT} : 1;
+ }
+ `, cliPath, options.provider, options.model], {cwd: options.repository, env});
+ const detail = result.stderr || result.stdout;
+ if (result.interrupted || result.signal || result.timedOut)
+ throw new Error(`Codex Security sandbox preflight ${result.timedOut ? 'timed out' : 'was interrupted'}. ${detail}`);
+ if (result.exitCode !== 0) {
+ const message = `Codex Security sandbox preflight failed. ${detail}`;
+ if (result.exitCode === SANDBOX_UNAVAILABLE_EXIT) throw new SandboxUnavailableError(message);
+ throw new Error(message);
+ }
+}
+
/** Restore a captured runner setting after Codex clears an MCP child's environment. */
export async function writeRuntimeLauncher(path: string, executable: string, name: 'LD_LIBRARY_PATH' | 'RUNNER_TRACKING_ID', value: string): Promise<void> {
const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
@@ -160,12 +250,19 @@ export async function setupRuntime(options: RuntimeOptions): Promise<Runtime> {
await writeFile(globalConfig, '', { mode: 0o600, flag: 'wx' });
const install = await runProcess(npmPath, ['ci', '--ignore-scripts', '--include=optional', `--registry=${REGISTRY}`, `--userconfig=${userConfig}`, `--globalconfig=${globalConfig}`, `--cache=${join(root, 'npm-cache')}`, '--no-audit', '--no-fund', '--loglevel=error'], { cwd: destination, env, timeoutMs: 10 * 60 * 1000, log: options.log });
if (install.exitCode !== 0 || install.timedOut || install.interrupted) {
- // npm sometimes writes lock/usage diagnostics to stdout. This process had
- // no credentials and every physical line is still treated as untrusted.
- for (const line of safeLogLines(install.stdout)) options.log?.(line);
- throw new Error(`Integrity-locked CLI installation failed (exit ${install.exitCode}${install.timedOut ? ', timed out' : ''}${install.interrupted ? ', interrupted' : ''}). Check the prefixed npm diagnostics, registry access, and runner prerequisites.`);
+ // npm can write lockfile diagnostics to stdout.
+ const details = safeLogLines([install.stderr, install.stdout].join('\n')).join('\n');
+ throw new Error(`Integrity-locked CLI installation failed (exit ${install.exitCode}${install.timedOut ? ', timed out' : ''}${install.interrupted ? ', interrupted' : ''}).\n${details}`);
}
const cliPath = await regularFile(join(destination, 'node_modules', '@openai', 'codex-security', 'bin', 'codex-security.mjs'));
+ // parseInputs supplies the OpenAI default. The CLI reports missing external-provider models.
+ if (options.model) {
+ // Codex excludes executables under its working directory during sandbox startup.
+ await ensureSandbox({cwd: root, env, runnerEnvironment: process.env.RUNNER_ENVIRONMENT, imageOS: process.env.ImageOS, log: options.log},
+ () => checkSandbox(nodePath, cliPath, options, {...env, CODEX_HOME: join(root, 'probe-home')}));
+ try { options.log?.('Codex sandbox probe succeeded without model calls.'); }
+ catch { /* Optional progress must not interrupt runtime preparation. */ }
+ }
// Private reports deliberately live outside the disposable credentials/runtime
// root so downstream upload-sarif remains usable after the post action.
const resultsDirectory = await mkdtemp(join(tempRoot, 'codex-security-reports-'));
diff --git a/github-action/src/targets.ts b/github-action/src/targets.ts
index c50b216c9..f40d02cf1 100644
--- a/github-action/src/targets.ts
+++ b/github-action/src/targets.ts
@@ -121,7 +121,7 @@ export async function resolveTarget(inputs: Inputs, event: EventContext): Promis
else if (pr) diffBase = (await git(repository, ['merge-base', pr.base.sha, diffHead])).trim();
else throw new Error('diff-base is required for diff scans outside pull_request events.');
if (!SHA.test(diffBase)) throw new Error('Could not resolve the diff base. Fetch full history.');
- emptyDiff = (await gitResult(repository, ['diff', '--no-ext-diff', '--no-textconv', '--quiet', diffBase, diffHead, '--'], [0, 1])).exitCode === 0;
+ emptyDiff = (await gitResult(repository, ['diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules=none', '--quiet', diffBase, diffHead, '--'], [0, 1])).exitCode === 0;
}
const analysisRef = pr ? `refs/pull/${pr.number ?? event.payload.number}/head` : event.ref;
const publishable = /^refs\/(heads|tags|pull)\//.test(analysisRef);
diff --git a/github-action/tests/ci-events.test.mjs b/github-action/tests/ci-events.test.mjs
index 8fe4ee16e..9faa8b31c 100644
--- a/github-action/tests/ci-events.test.mjs
+++ b/github-action/tests/ci-events.test.mjs
@@ -49,3 +49,12 @@ test('the called workflow requires every eligible job to finish successfully', (
}
}
});
+
+
+test('hosted smoke uses the shipped sandbox setup without a CI-only prerequisite', () => {
+ for (const job of [workflow.jobs.validate, workflow.jobs.smoke]) {
+ assert.ok(job.steps.every(step => !/needrestart|setup-ubuntu-sandbox/.test(step.run ?? '')));
+ }
+ assert.ok(workflow.jobs.validate.steps.some(step => step.run === 'node scripts/linux-smoke.mjs'));
+ assert.ok(workflow.jobs.smoke.steps.some(step => step.uses === './'));
+});
diff --git a/github-action/tests/examples.test.ts b/github-action/tests/examples.test.ts
new file mode 100644
index 000000000..e3d81b335
--- /dev/null
+++ b/github-action/tests/examples.test.ts
@@ -0,0 +1,226 @@
+import test, { type TestContext } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { parse } from 'yaml';
+
+const workflow = parse(readFileSync(new URL('../examples/pull-request.yml', import.meta.url), 'utf8'));
+const scan = workflow.jobs.security;
+const gate = workflow.jobs['required-review'];
+const step = gate.steps.find((value: {name: string}) => value.name === 'Require a completed review or an empty diff');
+
+function context(action: string, changes: Record<string, unknown> = {}, fork = false) {
+ return {run_id: 42, token: 'synthetic-read-only-token', repository: 'example/repo', server_url: 'https://github.com', event: {
+ action, changes, pull_request: {number: 7, head: {sha: 'a'.repeat(40), repo: {full_name: fork ? 'example/fork' : 'example/repo'}}, base: {ref: 'main', sha: 'b'.repeat(40)}},
+ }};
+}
+
+function evaluate(expression: string, github: ReturnType<typeof context>): unknown {
+ // These workflow expressions use the same boolean operators as JavaScript.
+ return new Function('github', 'always', `return (${expression});`)(github, () => true);
+}
+
+function render(value: string, github: ReturnType<typeof context>): string {
+ return value.replace(/\$\{\{([\s\S]*?)\}\}/g, (_, expression) => String(evaluate(expression, github)));
+}
+
+test('the required PR check runs even when the scan job is skipped', () => {
+ assert.ok(workflow.on.pull_request.types.includes('edited'), 'Retargeting a PR must rerun the scan against its new base.');
+ assert.equal(render(gate.name, context('synchronize')), 'Codex Security / main');
+ assert.equal(gate.needs, 'security');
+ assert.equal(evaluate(gate.if, context('synchronize', {}, true)), true);
+ assert.deepEqual(scan.outputs, {
+ 'scan-status': '${{ steps.security.outputs.scan-status }}',
+ 'skip-reason': '${{ steps.security.outputs.skip-reason }}',
+ });
+ assert.deepEqual(step.env, {
+ SCAN_JOB_RESULT: '${{ needs.security.result }}',
+ SCAN_STATUS: '${{ needs.security.outputs.scan-status }}',
+ SKIP_REASON: '${{ needs.security.outputs.skip-reason }}',
+ });
+ assert.equal(evaluate(scan.if, context('synchronize', {}, true)), false);
+ const checkout = scan.steps.find((entry: {uses?: string}) => entry.uses?.startsWith('actions/checkout@'));
+ assert.equal(checkout.with.ref, '${{ github.event.pull_request.head.sha }}');
+ assert.equal(checkout.with['fetch-depth'], 0);
+ assert.equal(checkout.with['persist-credentials'], false);
+ const action = scan.steps.find((entry: {id?: string}) => entry.id === 'security');
+ assert.equal(action.with['fail-on-severity'], 'high');
+});
+
+for (const [label, action, changes, review] of [
+ ['opened', 'opened', {}, true],
+ ['new commits', 'synchronize', {}, true],
+ ['reopened', 'reopened', {}, true],
+ ['ready for review', 'ready_for_review', {}, true],
+ ['base retarget without a new head', 'edited', {base: {ref: {from: 'previous-base'}}}, true],
+ ['title edit', 'edited', {title: {from: 'Previous title'}}, false],
+ ['body edit', 'edited', {body: {from: 'Previous body'}}, false],
+] as const) {
+ test(`PR workflow admission handles ${label}`, () => {
+ const github = context(action, changes);
+ assert.equal(evaluate(scan.if, github), review);
+ assert.equal(evaluate(gate.if, github), review);
+ if (review) {
+ assert.equal(render(gate.name, github), 'Codex Security / main');
+ }
+ });
+}
+
+for (const field of ['title', 'body']) {
+ test(`${field} edits cannot cancel a scan or replace its required result`, () => {
+ const github = context('edited', {[field]: {from: 'Previous value'}});
+ github.run_id = 43;
+ assert.equal(workflow.concurrency['cancel-in-progress'], true);
+ assert.notEqual(render(workflow.concurrency.group, github), render(workflow.concurrency.group, context('synchronize')));
+ assert.notEqual(render(gate.name, github), 'Codex Security / main');
+ });
+}
+
+for (const [jobResult, scanStatus, skipReason, accepted] of [
+ ['success', 'completed', '', true],
+ ['success', 'skipped', 'empty-diff', true],
+ ['success', 'failed', '', false],
+ ['success', 'skipped', 'dry-run', false],
+ ['success', '', '', false],
+ ['failure', 'completed', '', false],
+ ['failure', 'skipped', 'empty-diff', false],
+ ['cancelled', 'completed', '', false],
+ ['skipped', '', '', false],
+] as const) {
+ test(`required PR check handles ${jobResult}/${scanStatus || 'no scan'}/${skipReason || 'no skip reason'}`, () => {
+ const result = spawnSync('/bin/bash', ['--noprofile', '--norc', '-e', '-o', 'pipefail', '-c', step.run], {
+ encoding: 'utf8', env: {PATH: process.env.PATH, SCAN_JOB_RESULT: jobResult, SCAN_STATUS: scanStatus, SKIP_REASON: skipReason},
+ });
+ assert.ifError(result.error);
+ assert.equal(result.status, accepted ? 0 : 1, result.stderr);
+ });
+}
+
+
+async function prBindingFixture(t: TestContext) {
+ const directory = await mkdtemp(join(tmpdir(), 'action-pr-binding-'));
+ t.after(() => rm(directory, {recursive:true, force:true}));
+ const gh = join(directory, 'gh');
+ await writeFile(gh, `#!${process.execPath}
+ const assert = require('node:assert/strict');
+ const args = process.argv.slice(2);
+ assert.equal(args.shift(), 'api');
+ const hostIndex = args.indexOf('--hostname');
+ const host = hostIndex < 0 ? 'github.com' : args.splice(hostIndex, 2)[1];
+ assert.equal(host, new URL(process.env.GITHUB_SERVER_URL).hostname);
+ assert.equal(process.env.GH_TOKEN, 'synthetic-read-only-token');
+ if (args[0] === 'repos/example/repo/pulls/7') {
+ assert.deepEqual(args.slice(1), ['--jq', '[.head.sha, .base.ref, .base.sha] | @tsv']);
+ console.log(process.env.SYNTHETIC_CURRENT_PR);
+ process.exitCode = Number(process.env.SYNTHETIC_API_EXIT);
+ } else {
+ const ref = encodeURIComponent(process.env.PR_BASE_REF).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
+ assert.deepEqual(args, ['repos/example/repo/git/ref/heads/' + ref, '--jq', '.object.sha']);
+ console.log(process.env.SYNTHETIC_LIVE_BASE);
+ process.exitCode = Number(process.env.SYNTHETIC_REF_API_EXIT);
+ }
+ `, {mode:0o700});
+ const before = scan.steps[0];
+ const after = gate.steps[0];
+ assert.equal(workflow.permissions['pull-requests'], 'read');
+ assert.equal(before.name, 'Verify the PR still matches this scan');
+ assert.deepEqual(after, before);
+ return (github: ReturnType<typeof context>, current: ReturnType<typeof context>, accepting = false, apiExit = 0,
+ liveBase = current.event.pull_request.base.sha, refApiExit = 0) => {
+ const pr = current.event.pull_request;
+ const result = spawnSync('/bin/bash', ['--noprofile', '--norc', '-e', '-o', 'pipefail', '-c',
+ accepting ? gate.steps.map((value: {run: string}) => value.run).join('\n') : before.run], {
+ encoding:'utf8', env:{PATH:`${directory}:${process.env.PATH}`, GITHUB_REPOSITORY:github.repository,
+ GITHUB_SERVER_URL:github.server_url, GH_HOST:'unrelated.example.invalid',
+ ...Object.fromEntries(Object.entries(before.env).map(([key, value]) => [key, render(String(value), github)])),
+ SYNTHETIC_CURRENT_PR:[pr.head.sha, pr.base.ref, pr.base.sha].join('\t'), SYNTHETIC_API_EXIT:String(apiExit),
+ SYNTHETIC_LIVE_BASE:liveBase, SYNTHETIC_REF_API_EXIT:String(refApiExit),
+ SCAN_JOB_RESULT:'success', SCAN_STATUS:'completed', SKIP_REASON:''},
+ });
+ assert.ifError(result.error);
+ return result;
+ };
+}
+
+for (const [label, currentHead, currentRef, currentBase, apiExit, accepted] of [
+ ['current snapshot', 'a', 'main', 'b', 0, true],
+ ['stale head', 'c', 'main', 'b', 0, false],
+ ['retarget with the same base commit', 'a', 'release', 'b', 0, false],
+ ['target advanced', 'a', 'main', 'c', 0, false],
+ ['API failure', 'a', 'main', 'b', 7, false],
+] as const) {
+ test(`PR snapshot binding fails closed before scanning and accepting: ${label}`, async t => {
+ const run = await prBindingFixture(t);
+ const original = context('synchronize');
+ const current = context('synchronize');
+ current.event.pull_request.head.sha = currentHead.repeat(40);
+ current.event.pull_request.base = {ref:currentRef, sha:currentBase.repeat(40)};
+ for (const accepting of [false, true]) {
+ const result = run(original, current, accepting, apiExit);
+ assert.equal(result.status === 0, accepted, result.stderr);
+ if (apiExit === 0 && !accepted) assert.match(result.stderr, /PR head or target changed/);
+ }
+ });
+}
+
+for (const accepting of [false, true]) {
+ test(`a cached pull base cannot accept an advanced live branch (${accepting ? 'acceptance' : 'scan'})`, async t => {
+ const run = await prBindingFixture(t);
+ const original = context('opened');
+ assert.equal(run(original, original, accepting, 0, 'c'.repeat(40)).status, 1);
+ assert.notEqual(run(original, original, accepting, 0, original.event.pull_request.base.sha, 7).status, 0);
+ });
+
+ test(`PR verification uses the triggering enterprise host (${accepting ? 'acceptance' : 'scan'})`, async t => {
+ const run = await prBindingFixture(t);
+ const github = context('opened');
+ github.server_url = 'https://octocat.ghe.com';
+ const result = run(github, github, accepting);
+ assert.equal(result.status, 0, result.stderr);
+ });
+}
+
+test('live branch verification preserves slashes and URL-significant ref characters', async t => {
+ const run = await prBindingFixture(t);
+ const github = context('opened');
+ github.event.pull_request.base.ref = 'release/#canary%';
+ for (const accepting of [false, true]) {
+ const result = run(github, github, accepting);
+ assert.equal(result.status, 0, result.stderr);
+ }
+});
+
+test('case-only retargets isolate an old rerun and reject its completed result', async t => {
+ const run = await prBindingFixture(t);
+ const original = context('opened');
+ const current = context('edited', {base: {ref: {from: 'main'}}});
+ current.event.pull_request.base.ref = 'Main';
+ current.run_id = 43;
+ const oldRerun = {...original, run_attempt:2};
+ const group = (github: ReturnType<typeof context>) => render(workflow.concurrency.group, github).toLowerCase();
+ assert.notEqual(group(original), group(current));
+ assert.equal(group(original), group(oldRerun));
+ assert.notEqual(render(gate.name, original), render(gate.name, current));
+ assert.equal(run(original, original).status, 0);
+ // The target changes after the initial check, while the first scan is running.
+ assert.equal(run(original, current, true).status, 1);
+ assert.equal(run(current, current).status, 0);
+ assert.equal(run(current, current, true).status, 0);
+ assert.equal(run(oldRerun, current).status, 1);
+ assert.equal(run(oldRerun, current, true).status, 1);
+});
+
+test('same-head PRs targeting different branches require distinct check names', () => {
+ const first = context('opened');
+ const second = context('opened');
+ second.event.pull_request.number = 8;
+ second.event.pull_request.base.ref = 'release';
+ second.run_id = 43;
+ assert.equal(first.event.pull_request.head.sha, second.event.pull_request.head.sha);
+ assert.equal(first.event.pull_request.base.sha, second.event.pull_request.base.sha);
+ assert.notEqual(render(gate.name, first), render(gate.name, second));
+ assert.notEqual(render(workflow.concurrency.group, first), render(workflow.concurrency.group, second));
+});
diff --git a/github-action/tests/input-docs.test.ts b/github-action/tests/input-docs.test.ts
index 48281e2f1..3a4b239de 100644
--- a/github-action/tests/input-docs.test.ts
+++ b/github-action/tests/input-docs.test.ts
@@ -11,6 +11,7 @@ test('input docs preserve escaped table values and reject reversed reference mar
t.after(() => rm(root, { recursive: true, force: true }));
const action = join(root, 'github-action');
await mkdir(join(action, 'scripts'), { recursive: true });
+ await mkdir(join(action, 'examples'));
await symlink(fileURLToPath(new URL('../node_modules', import.meta.url)), join(action, 'node_modules'), 'junction');
const script = join(action, 'scripts', 'generate-input-docs.mjs');
await copyFile(new URL('../scripts/generate-input-docs.mjs', import.meta.url), script);
@@ -24,7 +25,12 @@ test('input docs preserve escaped table values and reject reversed reference mar
outputs: { example: { description: 'one|two' } },
}));
const readme = join(action, 'README.md');
- await writeFile(readme, '<!-- action-reference:start -->\n<!-- action-reference:end -->\n');
+ let markers = '<!-- action-reference:start -->\n<!-- action-reference:end -->\n';
+ for (const name of ['repository', 'pull-request']) {
+ await writeFile(join(action, 'examples', `${name}.yml`), `name: ${name}\njobs: {}\n`);
+ markers += `<!-- action-workflow:${name}:start -->\n<!-- action-workflow:${name}:end -->\n`;
+ }
+ await writeFile(readme, markers);
execFileSync(process.execPath, [script]);
const generated = await readFile(readme, 'utf8');
assert.ok(generated.includes(String.raw`Path C:\\temp\\\|value next line`), generated);
@@ -36,9 +42,18 @@ test('input docs preserve escaped table values and reject reversed reference mar
assert.ok(generated.includes('`C:\\temp`'), generated);
assert.ok(generated.includes('`one\\|two`'), generated);
execFileSync(process.execPath, [script, '--check']);
+ await writeFile(join(action, 'examples', 'repository.yml'), 'name: updated repository\njobs: {}\n');
+ assert.throws(() => execFileSync(process.execPath, [script, '--check'], {stdio: 'pipe'}));
+ execFileSync(process.execPath, [script]);
+ assert.match(await readFile(readme, 'utf8'), /name: updated repository/);
+ execFileSync(process.execPath, [script, '--check']);
- const reversed = '<!-- action-reference:end -->\nContributor notes\n<!-- action-reference:start -->\n';
- await writeFile(readme, reversed);
- assert.throws(() => execFileSync(process.execPath, [script], { stdio: 'pipe' }), /README must contain action reference markers in order/);
- assert.equal(await readFile(readme, 'utf8'), reversed);
+ for (const [section, label] of [['action-reference', 'action reference'], ['action-workflow:repository', 'repository workflow'], ['action-workflow:pull-request', 'pull-request workflow']]) {
+ const start = `<!-- ${section}:start -->`;
+ const end = `<!-- ${section}:end -->`;
+ const reversed = markers.replace(`${start}\n${end}`, `${end}\nContributor notes\n${start}`);
+ await writeFile(readme, reversed);
+ assert.throws(() => execFileSync(process.execPath, [script], { stdio: 'pipe' }), new RegExp(`README must contain ${label} markers in order`));
+ assert.equal(await readFile(readme, 'utf8'), reversed);
+ }
});
diff --git a/github-action/tests/inputs.test.ts b/github-action/tests/inputs.test.ts
index 7d4ef0414..9bbe71b01 100644
--- a/github-action/tests/inputs.test.ts
+++ b/github-action/tests/inputs.test.ts
@@ -116,6 +116,11 @@ test('dry-run allows keyless configuration validation', () => {
const dryArgs=scanArguments(parse({'dry-run':'true'}),{repository:'/checkout'},'/results');
assert.equal(dryArgs[dryArgs.indexOf('--auth')+1],'auto'); assert.ok(dryArgs.includes('--dry-run'));
});
+test('dry-run cannot be combined with findings enforcement', () => {
+ for (const threshold of ['low', 'medium', 'high', 'critical'])
+ assert.throws(() => parse({'dry-run':'true', 'fail-on-severity':threshold}), /dry-run requires fail-on-severity: none/);
+ assert.equal(parse({'dry-run':'true', 'fail-on-severity':'none'}).dryRun, true);
+});
test('CLI arguments preserve literal values and enforce CI policy', () => {
const input = parse({paths:'src/my folder',model:'model; echo never-execute', effort:'medium', 'max-cost':'5', 'fail-on-severity':'high'});
const args = scanArguments(input, {repository:'/checkout'}, '/private/results');
diff --git a/github-action/tests/main.test.ts b/github-action/tests/main.test.ts
index 508883343..1d130a24b 100644
--- a/github-action/tests/main.test.ts
+++ b/github-action/tests/main.test.ts
@@ -16,7 +16,7 @@ import { runtimeEnvironment, type Runtime } from '../src/runtime.js';
import type { ProcessResult } from '../src/process.js';
import { copyCompletedScan } from './fixtures.js';
-type Scenario = 'schedule' | 'pr' | 'policy-pr';
+type Scenario = 'schedule' | 'pr' | 'policy-pr' | 'empty-pr';
const inputKey = (name: string): string => `INPUT_${name.toUpperCase()}`;
function assertAttribution(args: readonly string[], provider: string): void {
@@ -56,7 +56,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule', serverUr
git('add', '.'); git('commit', '-qm', 'base');
const base = git('rev-parse', 'HEAD');
let sha = base;
- if (scenario !== 'schedule') {
+ if (scenario !== 'schedule' && scenario !== 'empty-pr') {
await writeFile(join(repository, scenario === 'policy-pr' ? 'SECURITY.md' : 'app.txt'), 'synthetic change\n');
git('add', '.'); git('commit', '-qm', 'PR change');
sha = git('rev-parse', 'HEAD');
@@ -81,7 +81,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule', serverUr
GITHUB_EVENT_PATH: eventPath, GITHUB_EVENT_NAME: scenario === 'schedule' ? 'schedule' : 'pull_request',
GITHUB_REPOSITORY: 'example/repo', GITHUB_WORKSPACE: repository, GITHUB_SHA: sha,
GITHUB_REF: scenario === 'schedule' ? 'refs/heads/main' : 'refs/pull/4/merge',
- GITHUB_ACTOR: 'trusted-maintainer', GITHUB_SERVER_URL: serverUrl,
+ GITHUB_ACTOR: 'trusted-maintainer', GITHUB_SERVER_URL: serverUrl, GITHUB_RUN_ID: '123456',
GITHUB_OUTPUT: outputPath, GITHUB_STATE: statePath, RUNNER_TEMP: root,
OPENAI_API_KEY: 'synthetic-offline-test-key', INPUT_SUMMARY: 'true', INPUT_ANNOTATIONS: 'false',
INPUT_SCOPE: scenario === 'schedule' ? 'repository' : 'diff',
@@ -152,7 +152,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule', serverUr
try {
process.exitCode = 0;
await runAction(root, {
- setupRuntime: async () => { setups++; await configuration.prepare?.(); await reports(); return runtime; },
+ setupRuntime: async (options) => { setups++; options.log?.('Synthetic provisioning output.'); await configuration.prepare?.(); await reports(); return runtime; },
cleanupRuntime: async () => { cleanups++; if (configuration.cleanupFails) throw new Error('Synthetic cleanup failure'); },
runProcess: async (_executable, args, options): Promise<ProcessResult> => {
processes++; capturedArgs = args; capturedEnvironment = options.env;
@@ -422,6 +422,8 @@ for (const threshold of ['none', 'high']) {
test(`summary write failure preserves the scan result with severity threshold ${threshold}`, async (t) => {
const app = await harness(t);
app.setInput('summary', 'true'); app.setInput('fail-on-severity', threshold);
+ app.setInput('upload-artifacts', 'true');
+ const upload = t.mock.method(DefaultArtifactClient.prototype, 'uploadArtifact', async () => ({id: 2468, size: 1}));
t.mock.method(core.summary, 'write', async () => { throw new Error('Synthetic summary write failure'); });
const result = await app.run();
assert.equal(result.exitCode, threshold === 'none' ? 0 : 1);
@@ -431,6 +433,7 @@ for (const threshold of ['none', 'high']) {
assert.equal(result.outputs['sarif-upload-ready'], 'true');
assert.ok(result.outputs['sarif-path']);
assert.equal(result.cleanups, 1);
+ assert.equal(upload.mock.callCount(), 1);
assert.match(result.logs, /::warning::Could not write the job summary\./);
});
}
@@ -458,7 +461,7 @@ test('scope exclusions and deferred notes do not fail completed scans or make fi
assert.equal(result.outputs['policy-status'], 'passed'); assert.equal(result.outputs['sarif-upload-ready'], 'true');
assert.equal(result.outputs['high-count'], '1'); assert.ok(result.outputs['json-path']);
assert.ok(!result.args.includes('--verbose'));
- assert.doesNotMatch(result.logs, /Synthetic live CLI progress/);
+ assert.doesNotMatch(result.logs, /Synthetic live CLI progress|Synthetic provisioning output/);
assert.match(result.logs, /Starting security scan/);
assert.match(result.logs, /Scan: completed/);
assert.match(result.logs, /Findings:.*high: 1/);
@@ -573,6 +576,64 @@ test('dry-run is explicitly skipped with no findings policy pass', async (t) =>
assert.equal(result.outputs['high-count'], ''); assert.ok(result.args.includes('--dry-run')); assert.equal(result.environment.OPENAI_API_KEY, undefined);
});
+for (const threshold of ['low', 'medium', 'high', 'critical']) {
+ test(`dry-run rejects ${threshold} enforcement before runtime setup`, async (t) => {
+ const app = await harness(t);
+ app.setInput('dry-run', 'true'); app.setInput('fail-on-severity', threshold);
+ app.setInput('summary', 'false');
+ const result = await app.run();
+ assert.equal(result.exitCode, 1); assert.equal(result.setups, 0); assert.equal(result.processes, 0);
+ assert.equal(result.outputs['policy-status'], 'not-evaluated');
+ assert.equal(result.outputs['scan-status'], 'failed');
+ assert.match(result.logs, /dry-run requires fail-on-severity: none/);
+ assert.equal(result.summary, '');
+ });
+}
+
+for (const threshold of ['none', 'high']) {
+ test(`verified empty PR diff succeeds without a scan for ${threshold} enforcement`, async (t) => {
+ const app = await harness(t, 'empty-pr');
+ app.setInput('fail-on-severity', threshold);
+ delete process.env.OPENAI_API_KEY;
+ const result = await app.run();
+ assert.equal(result.exitCode, 0); assert.equal(result.setups, 0); assert.equal(result.processes, 0);
+ assert.equal(result.outputs['scan-status'], 'skipped'); assert.equal(result.outputs['skip-reason'], 'empty-diff');
+ assert.equal(result.outputs['policy-status'], 'not-evaluated'); assert.equal(result.outputs['high-count'], '');
+ assert.equal(result.outputs['sarif-upload-ready'], 'false');
+ assert.match(result.summary, /No committed changes to scan/);
+ });
+}
+
+test('successful artifact uploads link named reports and retention in the job summary', async (t) => {
+ const app = await harness(t);
+ app.setInput('upload-artifacts', 'true'); app.setInput('artifact-name', 'review-reports'); app.setInput('retention-days', '14');
+ const upload = t.mock.method(DefaultArtifactClient.prototype, 'uploadArtifact', async (...[name, files, _root, options]: Parameters<DefaultArtifactClient['uploadArtifact']>) => {
+ assert.equal(name, 'review-reports'); assert.equal(options?.retentionDays, 14);
+ assert.ok(files.some(file => basename(file) === 'findings.json'));
+ return {id: 2468, size: 1};
+ });
+ const result = await app.run();
+ assert.equal(result.exitCode, 0); assert.equal(upload.mock.callCount(), 1);
+ assert.match(result.summary, /<a href="https:\/\/github.com\/example\/repo\/actions\/runs\/123456\/artifacts\/2468">review-reports<\/a> · Retention: up to 14 days/);
+});
+
+test('disabled artifact upload neither uploads reports nor adds a download link', async (t) => {
+ const app = await harness(t);
+ const upload = t.mock.method(DefaultArtifactClient.prototype, 'uploadArtifact', async () => ({id: 2468, size: 1}));
+ const result = await app.run();
+ assert.equal(result.exitCode, 0); assert.equal(upload.mock.callCount(), 0);
+ assert.doesNotMatch(result.summary, /\/artifacts\//);
+});
+
+test('disabled summary leaves requested artifact upload and scan outcome intact', async (t) => {
+ const app = await harness(t);
+ app.setInput('summary', 'false'); app.setInput('upload-artifacts', 'true');
+ const upload = t.mock.method(DefaultArtifactClient.prototype, 'uploadArtifact', async () => ({id: 2468, size: 1}));
+ const result = await app.run();
+ assert.equal(result.exitCode, 0); assert.equal(upload.mock.callCount(), 1); assert.equal(result.summary, '');
+ assert.equal(result.outputs['report-status'], 'ready');
+});
+
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);
@@ -626,6 +687,7 @@ test('requested artifact upload failure remains fatal without SARIF', async (t)
assert.ok(result.outputs['results-directory']); assert.equal(result.outputs['sarif-path'], '');
assert.match(result.logs, /::error::Scan completed, but required reporting failed\./);
assert.match(result.summary, /Synthetic artifact upload failure/);
+ assert.doesNotMatch(result.summary, /\/artifacts\//);
});
test('archive read failure preserves scan reports, summary and cleanup', {
@@ -677,7 +739,8 @@ test('archive read failure preserves scan reports, summary and cleanup', {
assert.ok((await readFile(result.outputs[name])).length);
}
assert.match(result.summary, /EACCES/);
- assert.ok(result.summary.includes(unreadable));
+ const displayedSummary = result.summary.replace(/&#(\d+);/g, (_entity, value: string) => String.fromCodePoint(Number(value)));
+ assert.ok(displayedSummary.includes(unreadable));
assert.match(result.logs, /::error::Scan completed, but required reporting failed\./);
assert.deepEqual(requests, ['/twirp/github.actions.results.api.v1.ArtifactService/CreateArtifact']);
assert.equal(signal?.aborted, true);
diff --git a/github-action/tests/runtime.test.ts b/github-action/tests/runtime.test.ts
index 7543d3317..ff5e4fd3b 100644
--- a/github-action/tests/runtime.test.ts
+++ b/github-action/tests/runtime.test.ts
@@ -1,11 +1,12 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
import { mkdtemp, mkdir, writeFile, readFile, realpath, symlink, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { captureRunnerPath, checkPython, cleanupRuntime, resolveTool, runtimeEnvironment, scanCredentials, setupRuntime, writeRuntimeLauncher } from '../src/runtime.js';
+import { captureRunnerPath, checkPython, checkSandbox, ensureSandbox, cleanupRuntime, resolveTool, runtimeEnvironment, SandboxUnavailableError, scanCredentials, setupRuntime, writeRuntimeLauncher } from '../src/runtime.js';
import { runProcess } from '../src/process.js';
test('tool discovery preserves the selected PATH launcher spelling', async (t) => {
@@ -49,6 +50,7 @@ test('runtime installation accepts npm shell shims and uses the Action Node exec
const previousPath = process.env.PATH;
const previousTrackingId = process.env.RUNNER_TRACKING_ID;
const previousLibraryPath = process.env.LD_LIBRARY_PATH;
+ const previousRunnerEnvironment = process.env.RUNNER_ENVIRONMENT;
t.after(async () => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
@@ -56,9 +58,13 @@ test('runtime installation accepts npm shell shims and uses the Action Node exec
else process.env.RUNNER_TRACKING_ID = previousTrackingId;
if (previousLibraryPath === undefined) delete process.env.LD_LIBRARY_PATH;
else process.env.LD_LIBRARY_PATH = previousLibraryPath;
+ if (previousRunnerEnvironment === undefined) delete process.env.RUNNER_ENVIRONMENT;
+ else process.env.RUNNER_ENVIRONMENT = previousRunnerEnvironment;
await rm(root, { recursive: true, force: true });
});
const bin = join(root, 'tools');
+ const repository = join(root, 'checkout');
+ await mkdir(repository);
await mkdir(bin);
await symlink(python, join(bin, 'python3'));
await writeFile(join(bin, 'node'), '#!/bin/sh\nexit 72\n', {mode:0o755});
@@ -72,14 +78,26 @@ fs.writeFileSync('npm-invocation.json', JSON.stringify({
const bin = path.join('node_modules', '@openai', 'codex-security', 'bin');
fs.mkdirSync(bin, {recursive:true});
fs.writeFileSync(path.join(bin, 'codex-security.mjs'), '// Synthetic installed CLI entrypoint.\n');
+const packageRoot = path.dirname(bin);
+fs.writeFileSync(path.join(packageRoot, 'package.json'), '{"type":"module"}');
+fs.mkdirSync(path.join(packageRoot, 'dist'));
+fs.writeFileSync(path.join(packageRoot, 'dist/cli.js'), 'export const parseCodexOverrides = (overrides, model, effort, provider) => ({overrides, model, provider});');
+fs.writeFileSync(path.join(packageRoot, 'dist/api.js'), 'export const scanRuntimeCodexConfig = config => config;');
+fs.writeFileSync(path.join(packageRoot, 'dist/config.js'), "export const writeCodexConfig = (file, config) => { process.env.PROBE_CONFIG = JSON.stringify(config); };");
+fs.writeFileSync(path.join(packageRoot, 'dist/runtime.js'), [
+ "import { writeFileSync } from 'node:fs';",
+ "export function resolveCodexCommand(env) { return {command: env.CODEX_HOME + '/synthetic-codex'}; }",
+ "export async function probeCodexSandbox(command, env) { writeFileSync('sandbox-invocation.json', JSON.stringify({command, env})); }",
+].join('\n'));
NODE
`, {mode:0o755});
+ process.env.RUNNER_ENVIRONMENT = 'self-hosted';
process.env.PATH = `${relative(process.cwd(), bin)}:`;
process.env.RUNNER_TRACKING_ID = 'synthetic-first-job';
const libraryPath = (previousLibraryPath === undefined ? '' : previousLibraryPath + ':') + '/synthetic-first-library';
process.env.LD_LIBRARY_PATH = libraryPath;
const captured = captureRunnerPath();
- const runtime = await setupRuntime({actionRoot:fileURLToPath(new URL('../', import.meta.url)), tempRoot:root});
+ const runtime = await setupRuntime({actionRoot:fileURLToPath(new URL('../', import.meta.url)), tempRoot:root, repository, provider:'openrouter', model:'example/model'});
const invocation = JSON.parse(await readFile(join(runtime.root, 'install', 'npm-invocation.json'), 'utf8'));
assert.equal(invocation.nodePath, process.execPath);
assert.equal(invocation.cwd, join(runtime.root, 'install'));
@@ -95,6 +113,13 @@ NODE
const credentials = scanCredentials('openai', {OPENAI_API_KEY:'synthetic-scan-key'});
assert.equal(runtime.env(credentials).PYTHON, 'python3');
assert.equal(runtime.env(credentials).CODEX_MCP_NODE_PATH, join(runtime.root, 'bin', 'node'));
+ const sandboxInvocation = JSON.parse(await readFile(join(repository, 'sandbox-invocation.json'), 'utf8'));
+ assert.equal(sandboxInvocation.command.command, join(runtime.root, 'probe-home', 'synthetic-codex'));
+ assert.equal(sandboxInvocation.env.CODEX_HOME, join(runtime.root, 'probe-home'));
+ assert.deepEqual(JSON.parse(sandboxInvocation.env.PROBE_CONFIG), {overrides:['analytics.enabled=false'], model:'example/model', provider:'openrouter'});
+ assert.equal(sandboxInvocation.env.PATH, invocation.env.PATH);
+ assert.equal(sandboxInvocation.env.OPENAI_API_KEY, undefined);
+ assert.equal(sandboxInvocation.env.ACTIONS_RUNTIME_TOKEN, undefined);
process.env.RUNNER_TRACKING_ID = 'synthetic-later-job';
process.env.LD_LIBRARY_PATH = '/synthetic-later-library';
assert.equal(runtime.env(credentials).RUNNER_TRACKING_ID, 'synthetic-first-job');
@@ -106,6 +131,83 @@ NODE
await cleanupRuntime(runtime.root, root);
});
+test('hosted Ubuntu sandbox setup uses system commands despite checkout PATH shadows', async t => {
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-hosted-sandbox-')));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const existsSync = fs.existsSync;
+ t.mock.method(fs, 'existsSync', (path: fs.PathLike) => path === '/.dockerenv' ? false : existsSync(path));
+ const checkout = join(root, 'checkout');
+ await mkdir(checkout);
+ for (const command of ['sudo', 'apt-get', 'apparmor_parser']) {
+ await writeFile(join(checkout, command), `#!${process.execPath}
+ require('node:fs').writeFileSync('checkout-command-ran', 'unexpected');
+ process.exit(70);
+ `, {mode:0o755});
+ }
+ const sudo = join(root, 'synthetic-system-sudo');
+ await writeFile(sudo, `#!${process.execPath}
+ require('node:fs').appendFileSync('setup.jsonl', JSON.stringify({args:process.argv.slice(2),env:process.env}) + '\\n');
+ console.log('Synthetic sandbox setup output.');
+ `, {mode:0o755});
+ const execute: typeof runProcess = async (executable, args, options) => {
+ assert.equal(executable, '/usr/bin/sudo');
+ return runProcess(sudo, args, options);
+ };
+ const env = runtimeEnvironment({root, home:root, codexHome:root, stateDirectory:root, runnerPath:`${checkout}:/usr/bin:/bin`});
+ let probes = 0;
+ const probe = async () => { if (++probes === 1) throw new SandboxUnavailableError('Synthetic unavailable sandbox'); };
+ await ensureSandbox({cwd:root, env, runnerEnvironment:'github-hosted', imageOS:'ubuntu24', log:() => {throw new Error('synthetic log failure');}}, probe, execute);
+ assert.equal(probes, 2);
+ await ensureSandbox({cwd:root, env, runnerEnvironment:'github-hosted', imageOS:'ubuntu24'}, probe, execute);
+ const calls = (await readFile(join(root, 'setup.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line));
+ assert.deepEqual(calls.map(call => call.args), [
+ ['-n','/usr/bin/apt-get','update'],
+ ['-n','/bin/sh','-eu','-c',calls[1].args[4]],
+ ['-n','/usr/sbin/apparmor_parser','-r','/usr/share/apparmor/extra-profiles/bwrap-userns-restrict'],
+ ]);
+ assert.match(calls[1].args[4], /php8\\\.3-fpm/);
+ assert.match(calls[1].args[4], /\/usr\/bin\/apt-get install --yes bubblewrap apparmor-profiles/);
+ for (const call of calls) {
+ assert.equal(call.env.OPENAI_API_KEY, undefined);
+ assert.equal(call.env.ACTIONS_RUNTIME_TOKEN, undefined);
+ assert.equal(call.env.CODEX_HOME, root);
+ assert.equal(call.env.PATH, env.PATH);
+ }
+ assert.equal(fs.existsSync(join(root, 'checkout-command-ran')), false);
+ await writeFile(sudo, `#!${process.execPath}\nconsole.error('synthetic apt diagnostic'); console.log('dpkg: synthetic package configuration failed'); process.exitCode = 17;\n`, {mode:0o755});
+ await assert.rejects(ensureSandbox({cwd:root,env,runnerEnvironment:'github-hosted',imageOS:'ubuntu24'}, async () => { throw new SandboxUnavailableError('Sandbox unavailable'); }, execute),
+ /Ubuntu sandbox setup failed: sudo -n \/usr\/bin\/apt-get update \(exit 17\)\.\n\[codex-security\] synthetic apt diagnostic\n\[codex-security\] dpkg: synthetic package configuration failed/);
+});
+
+test('sandbox setup leaves self-hosted runners and other images unchanged', async t => {
+ const execute = t.mock.fn<typeof runProcess>(async () => { throw new Error('Sandbox provisioning must not run.'); });
+ for (const [runnerEnvironment,imageOS] of [['self-hosted','ubuntu24'],['github-hosted','ubuntu22'],[undefined,undefined]])
+ await assert.rejects(ensureSandbox({cwd:'/unused',env:{PATH:'/no-sudo'},runnerEnvironment,imageOS}, async () => { throw new SandboxUnavailableError('Runner sandbox unavailable'); }, execute), /Runner sandbox unavailable/);
+ assert.equal(execute.mock.callCount(), 0);
+});
+
+test('sandbox setup skips Docker job containers with inherited hosted Ubuntu labels', async t => {
+ const existsSync = fs.existsSync;
+ t.mock.method(fs, 'existsSync', (path: fs.PathLike) => path === '/.dockerenv' ? true : existsSync(path));
+ const execute = t.mock.fn<typeof runProcess>(async () => { throw new Error('Container provisioning must not run.'); });
+ await assert.rejects(ensureSandbox({cwd:'/unused',env:{PATH:'/no-sudo'},runnerEnvironment:'github-hosted',imageOS:'ubuntu24'}, async () => { throw new SandboxUnavailableError('Container sandbox unavailable'); }, execute), /Container sandbox unavailable/);
+ assert.equal(execute.mock.callCount(), 0);
+});
+
+test('hosted setup propagates provider errors without provisioning', async t => {
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-sandbox-failure-')));
+ t.after(() => rm(root, {recursive:true,force:true}));
+ const existsSync = fs.existsSync;
+ t.mock.method(fs, 'existsSync', (path: fs.PathLike) => path === '/.dockerenv' ? false : existsSync(path));
+ const probe = join(root, 'probe');
+ const execute = t.mock.fn<typeof runProcess>(async () => { throw new Error('Unexpected host setup'); });
+ const check = () => checkSandbox(probe, join(root, 'cli.mjs'), {repository:root,provider:'openrouter',model:''}, {});
+ const host = {cwd:root, env:{}, runnerEnvironment:'github-hosted', imageOS:'ubuntu24'};
+ await writeFile(probe, `#!${process.execPath}\nconsole.error('synthetic provider diagnostic'); process.exitCode = 1;\n`, {mode:0o755});
+ await assert.rejects(ensureSandbox(host, check, execute), /Codex Security sandbox preflight failed.*synthetic provider diagnostic/s);
+ assert.equal(execute.mock.callCount(), 0);
+});
+
test('Python launcher selection and preflight preserve virtualenv context', async (t) => {
const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-venv-')));
t.after(() => rm(root, { recursive: true, force: true }));
@@ -338,3 +440,56 @@ test('cleanup preserves reports and rejects arbitrary or symlink roots', async (
await cleanupRuntime(owned, base);
} finally { await rm(base, { recursive: true, force: true }); }
});
+
+
+for (const hasNeedrestart of [true, false])
+for (const aptExit of [0, 17]) test(`hosted install with needrestart=${hasNeedrestart} cleans its PHP override after exit ${aptExit}`, async t => {
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-needrestart-')));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const existsSync = fs.existsSync;
+ t.mock.method(fs, 'existsSync', (path: fs.PathLike) => path === '/.dockerenv' ? false : existsSync(path));
+ const conf = join(root, 'conf.d');
+ if (hasNeedrestart) {
+ await mkdir(conf);
+ await writeFile(join(conf, 'existing.conf'), 'existing configuration');
+ }
+ const apt = join(root, 'apt');
+ await writeFile(apt, `#!${process.execPath}
+ const fs = require('node:fs'); const path = require('node:path'); const assert = require('node:assert/strict');
+ const directory = ${JSON.stringify(conf)};
+ let value = '';
+ if (${hasNeedrestart}) {
+ const overrides = fs.readdirSync(directory).filter(name => name.startsWith('codex-security-'));
+ assert.equal(overrides.length, 1);
+ value = fs.readFileSync(path.join(directory, overrides[0]), 'utf8');
+ assert.equal(value, ${JSON.stringify('$nrconf{override_rc}{qr(^php8\\.3-fpm\\.service$)} = 0;\n')});
+ } else assert.equal(fs.existsSync(directory), false);
+ assert.deepEqual(process.argv.slice(2), ['install', '--yes', 'bubblewrap', 'apparmor-profiles']);
+ fs.writeFileSync(${JSON.stringify(join(root, 'apt-ran'))}, value);
+ console.error('synthetic apt diagnostic'); process.exitCode = ${aptExit};
+ `, {mode:0o700});
+ const env = runtimeEnvironment({root,home:root,codexHome:root,stateDirectory:root});
+ const success = {exitCode:0,signal:null,stdout:'',stderr:'',timedOut:false,interrupted:false} as const;
+ const calls: readonly string[][] = [];
+ const execute: typeof runProcess = async (command, args, options) => {
+ assert.equal(command, '/usr/bin/sudo');
+ (calls as string[][]).push([...args]);
+ if (args[1] !== '/bin/sh') return success;
+ const script = args[4].replaceAll('/etc/needrestart/conf.d', conf).replaceAll('/usr/bin/apt-get', apt);
+ return runProcess('/bin/sh', ['-eu', '-c', script], options);
+ };
+ let probes = 0;
+ const original = new SandboxUnavailableError('original synthetic preflight detail sk-example-secret');
+ const result = ensureSandbox({cwd:root,env,runnerEnvironment:'github-hosted',imageOS:'ubuntu24'},
+ async () => { if (++probes === 1) throw original; }, execute);
+ if (aptExit === 0) await result;
+ else await assert.rejects(result, error => error instanceof Error && error.cause === original
+ && error.message.includes(original.message) && error.message.includes('synthetic apt diagnostic'));
+ assert.equal(fs.existsSync(join(root, 'apt-ran')), true);
+ if (hasNeedrestart) {
+ assert.deepEqual(fs.readdirSync(conf), ['existing.conf']);
+ assert.equal(await readFile(join(conf, 'existing.conf'), 'utf8'), 'existing configuration');
+ } else assert.equal(fs.existsSync(conf), false);
+ assert.equal(probes, aptExit === 0 ? 2 : 1);
+ assert.equal(calls.length, aptExit === 0 ? 3 : 2);
+});
diff --git a/github-action/tests/targets.test.ts b/github-action/tests/targets.test.ts
index 3203bcf23..0c8ed85be 100644
--- a/github-action/tests/targets.test.ts
+++ b/github-action/tests/targets.test.ts
@@ -134,6 +134,20 @@ test('large diffs are nonempty without collecting every changed pathname', async
assert.equal(target.emptyDiff, false);
}
});
+test('a changed submodule commit is nonempty even when Git ignores the submodule', async t => {
+ const f = await fixture(t);
+ await writeFile(join(f.path, '.gitmodules'), '[submodule "lib"]\n\tpath = lib\n\turl = ../lib.git\n\tignore = all\n');
+ await mkdir(join(f.path, 'lib'));
+ f.run('add', '.gitmodules');
+ f.run('update-index', '--add', '--cacheinfo', `160000,${f.base},lib`);
+ f.run('commit', '-m', 'Add submodule');
+ const base = f.run('rev-parse', 'HEAD');
+ f.run('update-index', '--cacheinfo', `160000,${base},lib`);
+ f.run('commit', '-m', 'Update submodule');
+ const event = f.event(f.run('rev-parse', 'HEAD'));
+ event.payload.pull_request.base.sha = base;
+ assert.equal((await resolveTarget(f.inputs(), event)).emptyDiff, false);
+});
test('empty diff is a verified no-op and schedule has no PR dependency', async t => {
const f=await fixture(t);
assert.equal((await resolveTarget(f.inputs(),f.event(f.base))).emptyDiff,true);
@@ -169,7 +183,7 @@ test('wrong checkout, local changes, missing diff base and option revisions are
test('forks and privileged events fail eligibility',()=>{
const event=eventContext();
event.payload.pull_request.head.repo.full_name='fork/repo'; assert.throws(()=>validateEvent(event),/Fork PR/);
- for(const eventName of ['pull_request_target','workflow_run']) assert.throws(()=>validateEvent({...event,eventName}),/Unsupported event/);
+ for(const eventName of ['pull_request_target','workflow_run','merge_group']) assert.throws(()=>validateEvent({...event,eventName}),/Unsupported event/);
});
test('persisted Git credentials and origin userinfo are refused without revealing secrets',async t=>{
const f=await fixture(t);