OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(action): support scan CLI inference providers (#1677)
Michael D'Angelo009228d09c87
diff --git a/.github/workflows/action-ci.yml b/.github/workflows/action-ci.ymlindex 25c924319..73659c89e 100644--- a/.github/workflows/action-ci.yml+++ b/.github/workflows/action-ci.yml@@ -57,11 +57,20 @@ jobs:if-no-files-found: errorsmoke:- name: Hosted Action smoke test+ name: Hosted Action smoke test (${{ matrix.name }})# Fork PRs are unsupported; their push workflows exercise the Action instead.if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repositoryruns-on: ubuntu-24.04timeout-minutes: 15+ strategy:+ matrix:+ include:+ - name: OpenAI default+ provider: ""+ model: ""+ - name: Bedrock+ provider: amazon-bedrock+ model: openai.gpt-5.6-lunasteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:@@ -73,6 +82,8 @@ jobs:id: smokeuses: ./with:+ provider: ${{ matrix.provider }}+ model: ${{ matrix.model }}dry-run: "true"- name: Verify dry-run outputsenv:diff --git a/action.yml b/action.ymlindex edf388f7d..94a605e93 100644--- a/action.yml+++ b/action.yml@@ -17,9 +17,11 @@ inputs:mode:description: 'standard or deep. Deep supports repository scans, including selected paths; not diff scans.'default: standard+ provider:+ description: "Inference provider, matching scan --provider: openai, openrouter, fireworks, or amazon-bedrock. Supply the selected provider's credentials to the step."+ default: openaimodel:- description: Model with access through your API key. Cost limits require CLI pricing support for the model.- default: gpt-5.6-sol+ description: Model to scan with, passed to scan --model. Defaults to gpt-5.6-sol for OpenAI; other providers require an explicit model ID. Cost limits require CLI pricing support for the model.cyber-access-program:description: 'Optional Cyber access program: standard, daybreak_blue, or daybreak_red. Unset preserves CLI defaults. Daybreak selections require approved organization and enabled API project access; model access is checked separately.'effort:diff --git a/github-action/README.md b/github-action/README.mdindex 3ca64e320..8586adccc 100644--- a/github-action/README.md+++ b/github-action/README.md@@ -7,8 +7,8 @@ SARIF reports.## Quick startUse a GitHub-hosted Ubuntu 24.04 x64 runner on GitHub.com and an OpenAI API key-with access to the selected model. For Amazon Bedrock, see the separate-[workflow example](../examples/github-actions/README.md).+with access to the selected model. OpenAI is the default provider. See+[Inference providers](#inference-providers) for Bedrock, OpenRouter, and Fireworks.Add your API key as a repository secret named `CODEX_SECURITY_API_KEY`, thensave this workflow in `.github/workflows/codex-security.yml`.@@ -77,10 +77,121 @@ This setup is specific to the Linux runner. Local macOS scans use the built-inSeatbelt sandbox and do not need Bubblewrap. See the[sandbox documentation](https://learn.chatgpt.com/docs/sandboxing) for details.+## Inference providers++`provider` and `model` map to `codex-security scan --provider` and `--model`.+The CLI configures the provider and validates its model requirements. The Action+uses the same provider names and forwards only the selected provider's credentials:++| `provider` | Step environment |+| --- | --- |+| `openai` (default) | `OPENAI_API_KEY`, or `CODEX_API_KEY` as a fallback |+| `amazon-bedrock` | AWS credentials and region; see the OIDC example below |+| `openrouter` | `OPENROUTER_API_KEY` |+| `fireworks` | `FIREWORKS_API_KEY` |++OpenAI retains the `gpt-5.6-sol` default. Other providers require an explicit+model ID your credentials can access. For example, replace the scan step in the+quick start with:++```yaml+- name: Scan with OpenRouter+ uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT+ with:+ provider: openrouter+ model: ${{ vars.INFERENCE_MODEL_ID }}+ env:+ OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}+```++Use `provider: fireworks` and `FIREWORKS_API_KEY` for Fireworks. These providers+require a reviewed Action revision containing the `provider` input;+`action-v0.3.0` supports OpenAI only. Installation and dry runs receive no provider+credentials. For CLI settings beyond the Action's named inputs, use the+[CLI workflow](../examples/github-actions/README.md).++## Scan with Amazon Bedrock++Set `provider: amazon-bedrock` and supply the exact Bedrock model ID your AWS+identity can invoke. No OpenAI API key or Codex login is needed.++This workflow uses GitHub OIDC to assume an AWS role and passes the temporary+credentials only to the scan step. Configure repository variables `AWS_REGION`,+`AWS_ROLE_ARN`, and `BEDROCK_MODEL_ID`. The role needs permission to invoke that+model, and its OIDC trust policy must restrict access to your repository and+approved branches or environments. See+[AWS credentials configuration](https://github.com/aws-actions/configure-aws-credentials#oidc-configuration-details)+for the role and identity-provider setup.++```yaml+name: Codex Security Bedrock+on:+ workflow_dispatch:++permissions:+ contents: read++jobs:+ security:+ runs-on: ubuntu-24.04+ timeout-minutes: 60+ permissions:+ 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+ - name: Assume the Bedrock role+ id: aws+ uses: aws-actions/configure-aws-credentials@cbe3b392738ccf3f987d68400dafcf4b0624a56c # v6.2.4+ with:+ aws-region: ${{ vars.AWS_REGION }}+ role-to-assume: ${{ vars.AWS_ROLE_ARN }}+ role-duration-seconds: 3600+ output-env-credentials: false+ output-credentials: true+ - name: Scan with Bedrock+ id: security+ uses: openai/codex-security@REPLACE_WITH_REVIEWED_COMMIT+ with:+ provider: amazon-bedrock+ model: ${{ vars.BEDROCK_MODEL_ID }}+ effort: high+ env:+ AWS_REGION: ${{ vars.AWS_REGION }}+ AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }}+ AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }}+ AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }}+```++Replace the Action placeholder with a reviewed commit that includes Bedrock+support. 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+enough time in the AWS role session and job timeout for the scan to finish;+the Action does not renew exported temporary credentials. For PR scans, apply+the same trusted-contributor restrictions as [Scan pull requests](#scan-pull-requests).++You can also supply `AWS_BEARER_TOKEN_BEDROCK` and a region directly to the step.+The Action forwards AWS region, profile, web-identity, and container-credential+settings used by the CLI. It keeps its private home directories, so profiles+must specify absolute `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` paths+instead of relying on the runner's `~/.aws` files. Installation and dry runs+receive no provider credentials; Bedrock scans receive no OpenAI API key.+See [Bedrock setup](../docs/bedrock.md) for model access and authentication, or+the [CLI workflow](../examples/github-actions/README.md) to run without the Action.+## Daybreak access and refusalsDaybreak is optional. You can use the Action with a general-purpose model your-API key can access under standard safeguards. Some security tasks may trigger+credentials can access under standard safeguards. Some security tasks may triggermodel refusals or API cybersecurity safety blocks. **If a refusal or safetyblock aborts the scan, the Action fails**, even with `fail-on-severity: none`.That setting controls failures caused by findings; it does not suppress scanner@@ -101,6 +212,10 @@ Selecting `standard` does not require Daybreak approval. Selecting a Daybreakprogram does not grant access; an unavailable program or incompatible modelcauses the scan to fail.+The API-project instructions above apply to `provider: openai`. For Bedrock,+use an approved model ID and AWS provisioning as described in+[Bedrock setup](../docs/bedrock.md#daybreak-blue-and-red).+## Scan pull requestsUse the same API-key secret and Action commit as above. Check out the PR head@@ -263,7 +378,8 @@ Codex uses the system Bubblewrap from `PATH`.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.The runner's process tracking marker is retained by the scan coordinator and Deep Scan workers.-Authentication uses `OPENAI_API_KEY`.+OpenAI authentication uses `OPENAI_API_KEY`. With `provider: amazon-bedrock`,+only the selected AWS credential and region settings are forwarded to the scan.Temporary runtime files are removed after the job; reports remain available todownstream steps.@@ -275,7 +391,9 @@ report paths empty; it does not recover unvalidated files from disk.- **Checkout or history errors:** use the triggering revision, `fetch-depth: 0`for PRs, and `persist-credentials: false`.-- **Authentication errors:** check the repository secret and model access.+- **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 stepshown above. Installing Bubblewrap alone does not load the AppArmor profile.A `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted` error means@@ -350,7 +468,8 @@ Inputs are strings. Quote booleans and use newline-separated literal paths for l| `paths` | Unset | Newline-delimited literal repository-relative files or folders. Only for repository scope; no glob expansion. || `diff-base` | Unset | Diff base revision. Defaults to the PR merge base; required outside PRs when scope is diff. || `mode` | `standard` | standard or deep. Deep supports repository scans, including selected paths; not diff scans. |-| `model` | `gpt-5.6-sol` | Model with access through your API key. Cost limits require CLI pricing support for the model. |+| `provider` | `openai` | Inference provider, matching scan --provider: openai, openrouter, fireworks, or amazon-bedrock. Supply the selected provider's credentials to the step. |+| `model` | Unset | Model to scan with, passed to scan --model. Defaults to gpt-5.6-sol for OpenAI; other providers require an explicit model ID. Cost limits require CLI pricing support for the model. || `cyber-access-program` | Unset | Optional Cyber access program: standard, daybreak_blue, or daybreak_red. Unset preserves CLI defaults. Daybreak selections require approved organization and enabled API project access; model access is checked separately. || `effort` | `xhigh` | Reasoning effort: minimal, low, medium, high, xhigh, or max (subject to model support). || `max-cost` | Unset | Positive estimated USD stop threshold per invocation. In-flight requests can exceed it; unset means no cost limit. |diff --git a/github-action/dist/index.cjs b/github-action/dist/index.cjsindex 1a745226e..2494315f4 100644--- a/github-action/dist/index.cjs+++ b/github-action/dist/index.cjs@@ -55586,6 +55586,8 @@ 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 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;return {repository: str("repository", workspace),@@ -55594,7 +55596,8 @@ function parseInputs(read, workspace) {diffBase,mode,cyberAccessProgram,- model: str("model", "gpt-5.6-sol"),+ provider,+ model,effort: choice("effort", ["minimal", "low", "medium", "high", "xhigh", "max"], "xhigh"),maxCost: num("max-cost", false, Number.MIN_VALUE),maxTimeHours,@@ -55609,16 +55612,17 @@ function parseInputs(read, workspace) {};}function scanArguments(inputs, target, resultsDirectory) {+ const auth2 = inputs.dryRun || inputs.provider === "amazon-bedrock" ? "auto" : "api-key";const args = ["scan",target.repository,"--auth",- inputs.dryRun ? "auto" : "api-key",+ auth2,"--provider",- "openai",+ inputs.provider,"--mode",inputs.mode,- `--model=${inputs.model}`,+ ...inputs.model ? [`--model=${inputs.model}`] : [],"--effort",inputs.effort,"--headless",@@ -55890,7 +55894,39 @@ var package_default = {// src/runtime.tsvar SUPPORTED_CLI_VERSION = package_default.dependencies["@openai/codex-security"];var REGISTRY = "https://registry.npmjs.org/";-function runtimeEnvironment(paths, apiKey) {+var AWS_ENVIRONMENT_VARIABLES = [+ "AWS_BEARER_TOKEN_BEDROCK",+ "AWS_ACCESS_KEY_ID",+ "AWS_SECRET_ACCESS_KEY",+ "AWS_SESSION_TOKEN",+ "AWS_REGION",+ "AWS_DEFAULT_REGION",+ "AWS_PROFILE",+ "AWS_CONFIG_FILE",+ "AWS_SHARED_CREDENTIALS_FILE",+ "AWS_ROLE_ARN",+ "AWS_ROLE_SESSION_NAME",+ "AWS_WEB_IDENTITY_TOKEN_FILE",+ "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",+ "AWS_CONTAINER_CREDENTIALS_FULL_URI",+ "AWS_CONTAINER_AUTHORIZATION_TOKEN",+ "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"+];+var API_KEY_ENVIRONMENT_VARIABLES = {+ openai: "OPENAI_API_KEY",+ openrouter: "OPENROUTER_API_KEY",+ fireworks: "FIREWORKS_API_KEY"+};+function scanCredentials(provider, source) {+ if (provider !== "amazon-bedrock") return {+ provider,+ apiKey: source[API_KEY_ENVIRONMENT_VARIABLES[provider]] || (provider === "openai" ? source.CODEX_API_KEY : void 0) || ""+ };+ const environment = {};+ for (const name of AWS_ENVIRONMENT_VARIABLES) if (source[name] !== void 0) environment[name] = source[name];+ return { provider, environment };+}+function runtimeEnvironment(paths, credentials) {const env = {PATH: `${(0, import_node_path4.join)(paths.root, "bin")}:${paths.runnerPath ?? "/usr/bin:/bin"}`,HOME: paths.home,@@ -55931,9 +55967,13 @@ function runtimeEnvironment(paths, apiKey) {env.CODEX_MCP_NODE_PATH = (0, import_node_path4.join)(paths.root, "bin", "node");}if (paths.runnerLibraryPath !== void 0) env.LD_LIBRARY_PATH = paths.runnerLibraryPath;- if (apiKey !== void 0) {- if (!apiKey || /[\r\n\u0000]/.test(apiKey)) throw new Error("OPENAI_API_KEY must be a nonempty single-line value.");- env.OPENAI_API_KEY = apiKey;+ if (credentials?.provider === "amazon-bedrock") {+ Object.assign(env, credentials.environment);+ } else if (credentials) {+ const { apiKey } = credentials;+ const name = API_KEY_ENVIRONMENT_VARIABLES[credentials.provider];+ if (!apiKey || /[\r\n\u0000]/.test(apiKey)) throw new Error(`${name} must be a nonempty single-line value.`);+ env[name] = apiKey;}return env;}@@ -56011,7 +56051,7 @@ async function setupRuntime(options) {const cliPath = await regularFile((0, import_node_path4.join)(destination, "node_modules", "@openai", "codex-security", "bin", "codex-security.mjs"));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: (apiKey) => runtimeEnvironment(paths, apiKey) };+ return { ...paths, nodePath, cliPath, resultsDirectory, env: (credentials) => runtimeEnvironment(paths, credentials) };} catch (error2) {await cleanupRuntime(root, tempRoot);throw error2;@@ -99259,8 +99299,8 @@ async function runAction(actionRoot, overrides = {}) {setOutput("report-status", "failed");setOutput("sarif-upload-ready", "false");try {- const apiKey = process.env.OPENAI_API_KEY || process.env.CODEX_API_KEY || "";inputs = parseInputs((name) => getInput(name), process.env.GITHUB_WORKSPACE ?? "");+ const credentials = scanCredentials(inputs.provider, process.env);const event = await context5();target = await resolveTarget(inputs, event);setOutput("scanned-sha", target.scannedSha);@@ -99274,7 +99314,9 @@ async function runAction(actionRoot, overrides = {}) {finalSummary = "The requested diff is empty. No scan ran and no model cost was incurred.";info(finalSummary);} else {- if (!inputs.dryRun && (!apiKey || /[\r\n\u0000]/.test(apiKey))) throw new Error("Set CODEX_SECURITY_API_KEY in Actions secrets (or Dependabot secrets for Dependabot runs) and pass it as OPENAI_API_KEY to this step. No scan was started.");+ if (!inputs.dryRun && credentials.provider !== "amazon-bedrock" && (!credentials.apiKey || /[\r\n\u0000]/.test(credentials.apiKey))) {+ throw new Error(credentials.provider === "openai" ? "Set CODEX_SECURITY_API_KEY in Actions secrets (or Dependabot secrets for Dependabot runs) and pass it as OPENAI_API_KEY to this step. No scan was started." : `Pass ${API_KEY_ENVIRONMENT_VARIABLES[credentials.provider]} from Actions secrets to this step. No scan was started.`);+ }tempRoot = await (0, import_promises9.realpath)(process.env.RUNNER_TEMP ?? "");if (!process.env.RUNNER_TEMP) throw new Error("RUNNER_TEMP is required.");info(`Preparing Codex Security ${SUPPORTED_CLI_VERSION}. Scope: ${inputs.scope}; mode: ${inputs.mode}; effort: ${inputs.effort}.`);@@ -99294,7 +99336,7 @@ async function runAction(actionRoot, overrides = {}) {};log2(`Target commit: ${target.scannedSha}.${target.diffBase ? ` Diff: ${target.diffBase}..${target.diffHead}.` : ""}`);if (inputs.paths.length) log2(`Paths: ${inputs.paths.join(", ")}.`);- log2(`Model: ${inputs.model}; estimated cost stop threshold: ${inputs.maxCost === void 0 ? "unset" : `$${inputs.maxCost}`}; findings failure threshold: ${inputs.failOnSeverity}.`);+ log2(`Model: ${inputs.model || "(not specified)"}; estimated cost stop threshold: ${inputs.maxCost === void 0 ? "unset" : `$${inputs.maxCost}`}; findings failure threshold: ${inputs.failOnSeverity}.`);if (inputs.cyberAccessProgram) log2(`Requested Cyber access program: ${inputs.cyberAccessProgram}.`);const scanLabel = inputs.dryRun ? "CLI configuration validation" : "Security scan";const scanStarted = performance.now();@@ -99304,7 +99346,7 @@ async function runAction(actionRoot, overrides = {}) {try {execution = await deps.runProcess(runtime.nodePath, [runtime.cliPath, ...args], {cwd: target.repository,- env: inputs.dryRun ? runtimeEnvironment(runtime) : runtime.env(apiKey),+ env: inputs.dryRun ? runtimeEnvironment(runtime) : runtime.env(credentials),// Stream stderr with terminal controls escaped; structured stdout is consumed below.log: inputs.verbose ? info : void 0});diff --git a/github-action/scripts/check-metadata.ts b/github-action/scripts/check-metadata.tsindex 9e50db01e..4ec741297 100644--- a/github-action/scripts/check-metadata.ts+++ b/github-action/scripts/check-metadata.ts@@ -15,6 +15,12 @@ assert.equal(defaults.failOnSeverity, 'none');assert.equal(defaults.scope, 'repository');assert.equal(defaults.uploadArtifacts, false);assert.equal(defaults.verbose, true);+assert.equal(defaults.provider, 'openai');+assert.equal(defaults.model, 'gpt-5.6-sol');+for (const provider of ['amazon-bedrock', 'openrouter', 'fireworks']) {+ const inputs = parseInputs(name => name === 'provider' ? provider : String(metadata.inputs[name]?.default ?? ''), '/checkout');+ assert.equal(inputs.model, '', 'Non-OpenAI providers must not inherit an OpenAI model default');+}for (const group of [metadata.inputs, metadata.outputs]) for (const value of Object.values(group) as {description: string}[]) assert.ok(value.description);const examples = await readFile(new URL('../README.md', import.meta.url), 'utf8');let workflowCount = 0;@@ -30,5 +36,5 @@ for (const match of examples.matchAll(/```yaml\n([\s\S]*?)\n```/g)) {}}}-assert.equal(workflowCount, 2, 'README must include complete PR and repository workflows');+assert.equal(workflowCount, 3, 'README must include complete PR, repository, and Bedrock workflows');console.log('Action metadata and implementation contract agree.');diff --git a/github-action/scripts/cli-integration.ts b/github-action/scripts/cli-integration.tsindex b877c18e8..7a76ee3ad 100644--- a/github-action/scripts/cli-integration.ts+++ b/github-action/scripts/cli-integration.ts@@ -97,6 +97,23 @@ try {assert.equal(preflight.mode, mode);}+ // Pass provider/model through the locked CLI without copying its provider setup or validation.+ for (const provider of ['amazon-bedrock', 'openrouter', 'fireworks']) for (const mode of ['standard', 'deep']) {+ const values: Record<string, string> = {provider, model:'synthetic/model', mode, 'dry-run':'true'};+ const args = scanArguments(parseInputs(name => values[name] ?? '', repository),+ {repository}, join(root, `${provider}-${mode}`));+ const preflight = JSON.parse(run(args, 0));+ assert.equal(preflight.dryRun, true); assert.equal(preflight.mode, mode);+ assert.equal(preflight.modelProvider, provider);+ if (provider === 'amazon-bedrock') assert.equal(preflight.authentication.method, 'aws_credentials');+ values.model = '';+ const missingModelArgs = scanArguments(parseInputs(name => values[name] ?? '', repository), {repository}, join(root, 'missing-model'));+ const missing = spawnSync(process.execPath, [cli, ...missingModelArgs], {cwd:repository, env, encoding:'utf8', timeout:120_000});+ if (missing.error) throw missing.error;+ assert.equal(missing.status, 2);+ assert.match(missing.stderr + missing.stdout, /--model is required when using --provider/);+ }+// Normalization must not let a literal repository path become a framework option.await mkdir(join(repository, '--help'));await writeFile(join(repository, '--help/example.ts'), 'export const example = 1;\n');diff --git a/github-action/src/inputs.ts b/github-action/src/inputs.tsindex 97c3320c0..afd9ac8d4 100644--- a/github-action/src/inputs.ts+++ b/github-action/src/inputs.ts@@ -1,6 +1,6 @@export const INPUT_NAMES = ['repository', 'scope', 'paths', 'diff-base', 'mode',- 'model', 'cyber-access-program', 'effort', 'max-cost', 'max-time-hours', 'fail-on-severity', 'verbose', 'dry-run',+ 'provider', 'model', 'cyber-access-program', 'effort', 'max-cost', 'max-time-hours', 'fail-on-severity', 'verbose', 'dry-run','summary', 'annotations','upload-artifacts', 'artifact-name', 'retention-days',] as const;@@ -42,12 +42,14 @@ 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 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'): undefined;return {repository: str('repository', workspace), scope, paths, diffBase, mode, cyberAccessProgram,- model: str('model', 'gpt-5.6-sol'), effort: choice('effort', ['minimal','low','medium','high','xhigh','max'], 'xhigh'),+ provider, model, effort: choice('effort', ['minimal','low','medium','high','xhigh','max'], 'xhigh'),maxCost: num('max-cost', false, Number.MIN_VALUE), maxTimeHours, failOnSeverity: choice('fail-on-severity', ['none','low','medium','high','critical'], 'none'),verbose: bool('verbose', true), dryRun,summary: bool('summary', true), annotations: bool('annotations', true),@@ -58,9 +60,10 @@ export function parseInputs(read: (name: string) => string, workspace: string) {export function scanArguments(inputs: Inputs, target: {repository: string; diffBase?: string; diffHead?: string}, resultsDirectory: string): string[] {// The pinned CLI checks API-key presence even during local preflight. Its// dry-run branch never starts a model session; auto allows keyless preflight- // with our empty private credential home. Real scans always use api-key.- const args = ['scan', target.repository, '--auth', inputs.dryRun ? 'auto' : 'api-key', '--provider', 'openai', '--mode', inputs.mode,- `--model=${inputs.model}`, '--effort', inputs.effort, '--headless',+ // with our empty private credential home. Bedrock selects native AWS auth.+ const auth = inputs.dryRun || inputs.provider === 'amazon-bedrock' ? 'auto' : 'api-key';+ const args = ['scan', target.repository, '--auth', auth, '--provider', inputs.provider, '--mode', inputs.mode,+ ...(inputs.model ? [`--model=${inputs.model}`] : []), '--effort', inputs.effort, '--headless','--output-dir', resultsDirectory, '--format', 'json'];// Preserve the pinned CLI's sandbox and automatic approval-review defaults.// Forcing approval_policy="never" prevents recovery from hosted Linux sandbox errors.diff --git a/github-action/src/main.ts b/github-action/src/main.tsindex ec424dbf2..498cd5c42 100644--- a/github-action/src/main.ts+++ b/github-action/src/main.ts@@ -2,7 +2,7 @@ import * as core from '@actions/core';import { readFile, realpath } from 'node:fs/promises';import { parseInputs, scanArguments, type Inputs } from './inputs.js';import { resolveTarget, type EventContext, type Target } from './targets.js';-import { SUPPORTED_CLI_VERSION, setupRuntime, cleanupRuntime, runtimeEnvironment, type Runtime } from './runtime.js';+import { SUPPORTED_CLI_VERSION, setupRuntime, cleanupRuntime, runtimeEnvironment, scanCredentials, API_KEY_ENVIRONMENT_VARIABLES, type Runtime } from './runtime.js';import { runProcess, safeLogLines } from './process.js';import { analyzeResults, type ScanResults } from './results.js';import { collectReports, uploadReports } from './artifacts.js';@@ -64,8 +64,8 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenccore.setOutput('report-status', 'failed');core.setOutput('sarif-upload-ready', 'false');try {- const apiKey = process.env.OPENAI_API_KEY || process.env.CODEX_API_KEY || '';inputs = parseInputs(name => core.getInput(name), process.env.GITHUB_WORKSPACE ?? '');+ const credentials = scanCredentials(inputs.provider, process.env);const event = await context();target = await resolveTarget(inputs, event);core.setOutput('scanned-sha', target.scannedSha);@@ -79,7 +79,11 @@ export async function runAction(actionRoot: string, overrides: Partial<DependencfinalSummary = 'The requested diff is empty. No scan ran and no model cost was incurred.';core.info(finalSummary);} else {- if (!inputs.dryRun && (!apiKey || /[\r\n\u0000]/.test(apiKey))) throw new Error('Set CODEX_SECURITY_API_KEY in Actions secrets (or Dependabot secrets for Dependabot runs) and pass it as OPENAI_API_KEY to this step. No scan was started.');+ if (!inputs.dryRun && credentials.provider !== 'amazon-bedrock' && (!credentials.apiKey || /[\r\n\u0000]/.test(credentials.apiKey))) {+ throw new Error(credentials.provider === 'openai'+ ? 'Set CODEX_SECURITY_API_KEY in Actions secrets (or Dependabot secrets for Dependabot runs) and pass it as OPENAI_API_KEY to this step. No scan was started.'+ : `Pass ${API_KEY_ENVIRONMENT_VARIABLES[credentials.provider]} from Actions secrets to this step. No scan was started.`);+ }tempRoot = await realpath(process.env.RUNNER_TEMP ?? '');if (!process.env.RUNNER_TEMP) throw new Error('RUNNER_TEMP is required.');core.info(`Preparing Codex Security ${SUPPORTED_CLI_VERSION}. Scope: ${inputs.scope}; mode: ${inputs.mode}; effort: ${inputs.effort}.`);@@ -96,7 +100,7 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenc};log(`Target commit: ${target.scannedSha}.${target.diffBase ? ` Diff: ${target.diffBase}..${target.diffHead}.` : ''}`);if (inputs.paths.length) log(`Paths: ${inputs.paths.join(', ')}.`);- log(`Model: ${inputs.model}; estimated cost stop threshold: ${inputs.maxCost === undefined ? 'unset' : `$${inputs.maxCost}`}; findings failure threshold: ${inputs.failOnSeverity}.`);+ log(`Model: ${inputs.model || '(not specified)'}; estimated cost stop threshold: ${inputs.maxCost === undefined ? 'unset' : `$${inputs.maxCost}`}; findings failure threshold: ${inputs.failOnSeverity}.`);if (inputs.cyberAccessProgram) log(`Requested Cyber access program: ${inputs.cyberAccessProgram}.`);const scanLabel = inputs.dryRun ? 'CLI configuration validation' : 'Security scan';const scanStarted = performance.now();@@ -105,7 +109,7 @@ export async function runAction(actionRoot: string, overrides: Partial<Dependenclet execution;try {execution = await deps.runProcess(runtime.nodePath, [runtime.cliPath, ...args], {- cwd: target.repository, env: inputs.dryRun ? runtimeEnvironment(runtime) : runtime.env(apiKey),+ cwd: target.repository, env: inputs.dryRun ? runtimeEnvironment(runtime) : runtime.env(credentials),// Stream stderr with terminal controls escaped; structured stdout is consumed below.log: inputs.verbose ? core.info : undefined,});diff --git a/github-action/src/runtime.ts b/github-action/src/runtime.tsindex 6266a7619..aa5e0c782 100644--- a/github-action/src/runtime.ts+++ b/github-action/src/runtime.ts@@ -9,6 +9,30 @@ import runtimeManifest from '../runtime/package.json' with { type: 'json' };export const SUPPORTED_CLI_VERSION = runtimeManifest.dependencies['@openai/codex-security'];const REGISTRY = 'https://registry.npmjs.org/';+const AWS_ENVIRONMENT_VARIABLES = [+ 'AWS_BEARER_TOKEN_BEDROCK', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN',+ 'AWS_REGION', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_CONFIG_FILE', 'AWS_SHARED_CREDENTIALS_FILE',+ 'AWS_ROLE_ARN', 'AWS_ROLE_SESSION_NAME', 'AWS_WEB_IDENTITY_TOKEN_FILE',+ 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI', 'AWS_CONTAINER_CREDENTIALS_FULL_URI',+ 'AWS_CONTAINER_AUTHORIZATION_TOKEN', 'AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE',+] as const;++export const API_KEY_ENVIRONMENT_VARIABLES = {+ openai: 'OPENAI_API_KEY', openrouter: 'OPENROUTER_API_KEY', fireworks: 'FIREWORKS_API_KEY',+} as const;++export type ScanCredentials = {provider: keyof typeof API_KEY_ENVIRONMENT_VARIABLES; apiKey: string}+ | {provider: 'amazon-bedrock'; environment: NodeJS.ProcessEnv};++/** Capture only the selected provider's credentials before asynchronous setup. */+export function scanCredentials(provider: ScanCredentials['provider'], source: NodeJS.ProcessEnv): ScanCredentials {+ if (provider !== 'amazon-bedrock') return {provider,+ apiKey: source[API_KEY_ENVIRONMENT_VARIABLES[provider]] || (provider === 'openai' ? source.CODEX_API_KEY : undefined) || ''};+ const environment: NodeJS.ProcessEnv = {};+ for (const name of AWS_ENVIRONMENT_VARIABLES) if (source[name] !== undefined) environment[name] = source[name];+ return {provider, environment};+}+export interface RuntimeOptions {actionRoot: string;tempRoot: string;@@ -25,11 +49,11 @@ export interface Runtime {runnerPath?: string;runnerTrackingId?: string;runnerLibraryPath?: string;- env: (apiKey: string) => NodeJS.ProcessEnv;+ env: (credentials: ScanCredentials) => NodeJS.ProcessEnv;}/** Deliberately construct a new environment: never copy process.env. */-export function runtimeEnvironment(paths: Pick<Runtime, 'root' | 'home' | 'codexHome' | 'stateDirectory' | 'runnerPath' | 'runnerTrackingId' | 'runnerLibraryPath'>, apiKey?: string): NodeJS.ProcessEnv {+export function runtimeEnvironment(paths: Pick<Runtime, 'root' | 'home' | 'codexHome' | 'stateDirectory' | 'runnerPath' | 'runnerTrackingId' | 'runnerLibraryPath'>, credentials?: ScanCredentials): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {PATH: `${join(paths.root, 'bin')}:${paths.runnerPath ?? '/usr/bin:/bin'}`,HOME: paths.home, CODEX_HOME: paths.codexHome,@@ -52,9 +76,13 @@ export function runtimeEnvironment(paths: Pick<Runtime, 'root' | 'home' | 'codexenv.CODEX_MCP_NODE_PATH = join(paths.root, 'bin', 'node');}if (paths.runnerLibraryPath !== undefined) env.LD_LIBRARY_PATH = paths.runnerLibraryPath;- if (apiKey !== undefined) {- if (!apiKey || /[\r\n\u0000]/.test(apiKey)) throw new Error('OPENAI_API_KEY must be a nonempty single-line value.');- env.OPENAI_API_KEY = apiKey;+ if (credentials?.provider === 'amazon-bedrock') {+ Object.assign(env, credentials.environment);+ } else if (credentials) {+ const { apiKey } = credentials;+ const name = API_KEY_ENVIRONMENT_VARIABLES[credentials.provider];+ if (!apiKey || /[\r\n\u0000]/.test(apiKey)) throw new Error(`${name} must be a nonempty single-line value.`);+ env[name] = apiKey;}return env;}@@ -142,7 +170,7 @@ export async function setupRuntime(options: RuntimeOptions): Promise<Runtime> {// root so downstream upload-sarif remains usable after the post action.const resultsDirectory = await mkdtemp(join(tempRoot, 'codex-security-reports-'));await chmod(resultsDirectory, 0o700);- return { ...paths, nodePath, cliPath, resultsDirectory, env: (apiKey) => runtimeEnvironment(paths, apiKey) };+ return { ...paths, nodePath, cliPath, resultsDirectory, env: (credentials) => runtimeEnvironment(paths, credentials) };} catch (error) {await cleanupRuntime(root, tempRoot);throw error;diff --git a/github-action/tests/bedrock-example.test.ts b/github-action/tests/bedrock-example.test.tsnew file mode 100644index 000000000..765a02a3d--- /dev/null+++ b/github-action/tests/bedrock-example.test.ts@@ -0,0 +1,35 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { test } from 'node:test';+import { parse } from 'yaml';+import { parseInputs, scanArguments } from '../src/inputs.js';++test('Bedrock OIDC example scopes temporary credentials to the native scan step', async () => {+ const readme = await readFile(new URL('../README.md', import.meta.url), 'utf8');+ const workflows = [...readme.matchAll(/```yaml\n([\s\S]*?)\n```/g)].map(match => parse(match[1]));+ const workflow = workflows.find(value => value.name === 'Codex Security Bedrock');+ assert.ok(workflow);+ assert.deepEqual(Object.keys(workflow.on), ['workflow_dispatch']);+ const job = workflow.jobs.security;+ assert.equal(job.permissions['id-token'], 'write');+ assert.equal(job.env, undefined);+ const aws = job.steps.find((step: any) => step.id === 'aws');+ const scan = job.steps.find((step: any) => step.id === 'security');+ assert.ok(job.steps.indexOf(aws) < job.steps.indexOf(scan));+ assert.match(aws.uses, /^aws-actions\/configure-aws-credentials@[a-f0-9]{40}$/);+ assert.equal(aws.with['output-env-credentials'], false);+ assert.equal(aws.with['output-credentials'], true);+ assert.equal(aws.with['role-to-assume'], '${{ vars.AWS_ROLE_ARN }}');+ assert.equal(aws.with['aws-region'], '${{ vars.AWS_REGION }}');+ assert.deepEqual(scan.env, {+ AWS_REGION:'${{ vars.AWS_REGION }}',+ AWS_ACCESS_KEY_ID:'${{ steps.aws.outputs.aws-access-key-id }}',+ AWS_SECRET_ACCESS_KEY:'${{ steps.aws.outputs.aws-secret-access-key }}',+ AWS_SESSION_TOKEN:'${{ steps.aws.outputs.aws-session-token }}',+ });+ assert.equal(scan.with.model, '${{ vars.BEDROCK_MODEL_ID }}');+ const inputs = parseInputs(name => scan.with[name] ?? '', '/checkout');+ const args = scanArguments(inputs, {repository:'/checkout'}, '/results');+ assert.equal(args[args.indexOf('--provider') + 1], 'amazon-bedrock');+ assert.equal(args[args.indexOf('--auth') + 1], 'auto');+});diff --git a/github-action/tests/inputs.test.ts b/github-action/tests/inputs.test.tsindex b862b7634..e91b98d0d 100644--- a/github-action/tests/inputs.test.ts+++ b/github-action/tests/inputs.test.ts@@ -7,7 +7,7 @@ test('defaults are stable across events', () => {const input = parse();assert.deepEqual(input, {repository: '/checkout', scope: 'repository', paths: [], diffBase: undefined, mode: 'standard', cyberAccessProgram: undefined,- model: 'gpt-5.6-sol', effort: 'xhigh', maxCost: undefined, maxTimeHours: undefined, failOnSeverity: 'none',+ provider: 'openai', model: 'gpt-5.6-sol', effort: 'xhigh', maxCost: undefined, maxTimeHours: undefined, failOnSeverity: 'none',verbose: true, dryRun: false, summary: true, annotations: true,uploadArtifacts: false, artifactName: 'codex-security', retentionDays: 7,});@@ -18,6 +18,23 @@ test('defaults are stable across events', () => {assert.ok(!args.includes('--python'));assert.ok(!args.includes('--cyber-access-program'));});+test('provider and model inputs map directly to scan CLI arguments in both modes', () => {+ for (const provider of ['openai', 'openrouter', 'fireworks', 'amazon-bedrock'])+ for (const mode of ['standard', 'deep']) for (const dryRun of ['false', 'true']) {+ const input = parse({provider, model:'synthetic/model', mode, 'dry-run':dryRun});+ const args = scanArguments(input, {repository:'/checkout'}, '/results');+ assert.equal(args[args.indexOf('--provider') + 1], provider);+ assert.equal(args[args.indexOf('--auth') + 1], provider === 'amazon-bedrock' || dryRun === 'true' ? 'auto' : 'api-key');+ assert.ok(args.includes('--model=synthetic/model'));+ assert.equal(args.includes('--dry-run'), dryRun === 'true');+ }+ assert.throws(() => parse({provider:'unsupported'}), /provider must be one of/);+ for (const provider of ['amazon-bedrock', 'openrouter', 'fireworks']) for (const model of ['', ' ']) {+ const args = scanArguments(parse({provider, model}), {repository:'/checkout'}, '/results');+ assert.ok(!args.some(arg => arg.startsWith('--model')), 'Leave missing model validation to the CLI');+ }+ assert.equal(parse({provider:'openai'}).model, 'gpt-5.6-sol');+});test('Cyber access selections reach both standard and Deep scan CLI invocations', () => {for (const mode of ['standard', 'deep']) for (const program of ['standard', 'daybreak_blue', 'daybreak_red']) {const args = scanArguments(parse({mode, 'cyber-access-program':program}), {repository:'/checkout'}, '/results');diff --git a/github-action/tests/main.test.ts b/github-action/tests/main.test.tsindex a9c3ef30d..c30f3d074 100644--- a/github-action/tests/main.test.ts+++ b/github-action/tests/main.test.ts@@ -9,7 +9,7 @@ import { DefaultArtifactClient } from '@actions/artifact';import { runAction } from '../src/main.js';import { INPUT_NAMES } from '../src/inputs.js';import { gitEnvironment } from '../src/targets.js';-import type { Runtime } from '../src/runtime.js';+import { runtimeEnvironment, type Runtime } from '../src/runtime.js';import type { ProcessResult } from '../src/process.js';import { copyCompletedScan } from './fixtures.js';@@ -79,7 +79,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule') {root: join(root, 'runtime'), home: join(root, 'runtime/home'), codexHome: join(root, 'runtime/codex'),stateDirectory: join(root, 'runtime/state'), resultsDirectory: join(root, 'results'),nodePath: '/never-executed/node', cliPath: '/never-executed/cli.js',- env: (key) => ({ OPENAI_API_KEY: key }),+ env: (credentials) => runtimeEnvironment(runtime, credentials),};let setups = 0;let processes = 0;@@ -242,9 +242,94 @@ test('same-repository Dependabot PR scans with a supplied key', async (t) => {assert.equal(result.outputs['sarif-upload-ready'], 'true');});+for (const mode of ['standard', 'deep']) {+ test(`Bedrock ${mode} scans use captured AWS credentials without an OpenAI key`, async t => {+ const app = await harness(t);+ app.setInput('provider', 'amazon-bedrock'); app.setInput('model', 'openai.synthetic-model'); app.setInput('mode', mode);+ delete process.env.OPENAI_API_KEY;+ Object.assign(process.env, {AWS_ACCESS_KEY_ID:'synthetic-access-key', AWS_SECRET_ACCESS_KEY:'synthetic-secret-key',+ AWS_SESSION_TOKEN:'synthetic-session-token', AWS_REGION:'us-east-2', GITHUB_TOKEN:'must-not-reach-scan'});+ app.configure({prepare: () => { process.env.AWS_SESSION_TOKEN = 'changed-during-setup'; }});+ const result = await app.run();+ assert.equal(result.exitCode, 0); assert.equal(result.outputs['scan-status'], 'completed');+ assert.equal(result.outputs['sarif-upload-ready'], 'true');+ assert.equal(result.args[result.args.indexOf('--provider') + 1], 'amazon-bedrock');+ assert.equal(result.args[result.args.indexOf('--auth') + 1], 'auto');+ assert.equal(result.environment.AWS_ACCESS_KEY_ID, 'synthetic-access-key');+ assert.equal(result.environment.AWS_SECRET_ACCESS_KEY, 'synthetic-secret-key');+ assert.equal(result.environment.AWS_SESSION_TOKEN, 'synthetic-session-token');+ assert.equal(result.environment.AWS_REGION, 'us-east-2');+ assert.equal(result.environment.OPENAI_API_KEY, undefined); assert.equal(result.environment.GITHUB_TOKEN, undefined);+ });+}++for (const [provider, key] of [['openrouter', 'OPENROUTER_API_KEY'], ['fireworks', 'FIREWORKS_API_KEY']]) {+ for (const mode of ['standard', 'deep']) test(`${provider} ${mode} scans use only the captured provider key`, async t => {+ const app = await harness(t);+ app.setInput('provider', provider); app.setInput('model', 'synthetic/model'); app.setInput('mode', mode);+ Object.assign(process.env, {OPENROUTER_API_KEY:'synthetic-openrouter', FIREWORKS_API_KEY:'synthetic-fireworks',+ AWS_SESSION_TOKEN:'unrelated-aws', GITHUB_TOKEN:'unrelated-github'});+ const expectedKey = process.env[key];+ app.configure({prepare: () => { process.env[key] = 'changed-during-setup'; }});+ const result = await app.run();+ assert.equal(result.exitCode, 0); assert.equal(result.outputs['scan-status'], 'completed');+ assert.equal(result.args[result.args.indexOf('--provider') + 1], provider);+ assert.equal(result.args[result.args.indexOf('--auth') + 1], 'api-key');+ assert.equal(result.environment[key], expectedKey);+ for (const other of ['OPENAI_API_KEY', 'CODEX_API_KEY', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY', 'AWS_SESSION_TOKEN', 'GITHUB_TOKEN'])+ if (other !== key) assert.equal(result.environment[other], undefined);+ });+ test(`${provider} requires its own key and keeps dry-run credential-free`, async t => {+ const app = await harness(t);+ app.setInput('provider', provider); app.setInput('model', 'synthetic/model');+ delete process.env[key];+ const missing = await app.run();+ assert.equal(missing.exitCode, 1); assert.equal(missing.setups, 0);+ assert.ok(missing.summary.includes(key));+ process.env[key] = 'synthetic-provider-key';+ app.setInput('dry-run', 'true');+ const dry = await app.run();+ assert.equal(dry.exitCode, 0); assert.equal(dry.outputs['skip-reason'], 'dry-run');+ assert.equal(dry.environment[key], undefined); assert.equal(dry.environment.OPENAI_API_KEY, undefined);+ });+}++test('Bedrock PR scans retain diff scope and severity failure outputs', async t => {+ const app = await harness(t, 'pr');+ app.setInput('provider', 'amazon-bedrock'); app.setInput('model', 'openai.synthetic-model'); app.setInput('fail-on-severity', 'high');+ process.env.AWS_BEARER_TOKEN_BEDROCK = 'synthetic-bedrock-bearer';+ const result = await app.run();+ assert.equal(result.exitCode, 1); assert.equal(result.outputs['scan-status'], 'completed');+ assert.equal(result.outputs['policy-status'], 'failed'); assert.equal(result.outputs['sarif-upload-ready'], 'true');+ assert.ok(result.args.includes('--diff')); assert.ok(result.args.includes('--head'));+ assert.equal(result.environment.AWS_BEARER_TOKEN_BEDROCK, 'synthetic-bedrock-bearer');+ assert.equal(result.environment.OPENAI_API_KEY, undefined);+});++test('Bedrock dry-run forwards no credentials and remains a skipped scan', async t => {+ const app = await harness(t);+ app.setInput('provider', 'amazon-bedrock'); app.setInput('model', 'openai.synthetic-model'); app.setInput('dry-run', 'true');+ process.env.AWS_BEARER_TOKEN_BEDROCK = 'synthetic-bedrock-bearer';+ const result = await app.run();+ assert.equal(result.exitCode, 0); assert.equal(result.outputs['scan-status'], 'skipped');+ assert.equal(result.outputs['skip-reason'], 'dry-run');+ assert.equal(result.environment.AWS_BEARER_TOKEN_BEDROCK, undefined); assert.equal(result.environment.OPENAI_API_KEY, undefined);+});++test('Bedrock authentication errors remain scan failures', async t => {+ const app = await harness(t);+ app.setInput('provider', 'amazon-bedrock'); app.setInput('model', 'openai.synthetic-model');+ delete process.env.OPENAI_API_KEY;+ app.configure({exitCode:2, cliFailure:true});+ const result = await app.run();+ assert.equal(result.exitCode, 1); assert.equal(result.processes, 1);+ assert.equal(result.outputs['scan-status'], 'failed'); assert.equal(result.outputs['sarif-upload-ready'], 'false');+});+for (const scenario of ['schedule', 'pr'] as const) {test(`missing API key fails a ${scenario === 'pr' ? 'Dependabot PR' : 'scheduled scan'} with setup guidance`, async (t) => {const app = await harness(t, scenario); delete process.env.OPENAI_API_KEY;+ process.env.AWS_BEARER_TOKEN_BEDROCK = 'synthetic-bedrock-bearer';if (scenario === 'pr') process.env.GITHUB_ACTOR = 'dependabot[bot]';const result = await app.run();assert.equal(result.exitCode, 1); assert.equal(result.setups, 0); assert.equal(result.processes, 0);diff --git a/github-action/tests/runtime.test.ts b/github-action/tests/runtime.test.tsindex 8ca95b679..7543d3317 100644--- a/github-action/tests/runtime.test.ts+++ b/github-action/tests/runtime.test.ts@@ -5,7 +5,7 @@ import { mkdtemp, mkdir, writeFile, readFile, realpath, symlink, rm, stat } fromimport { tmpdir } from 'node:os';import { join, relative } from 'node:path';import { fileURLToPath } from 'node:url';-import { captureRunnerPath, checkPython, cleanupRuntime, resolveTool, runtimeEnvironment, setupRuntime, writeRuntimeLauncher } from '../src/runtime.js';+import { captureRunnerPath, checkPython, cleanupRuntime, resolveTool, runtimeEnvironment, scanCredentials, setupRuntime, writeRuntimeLauncher } from '../src/runtime.js';import { runProcess } from '../src/process.js';test('tool discovery preserves the selected PATH launcher spelling', async (t) => {@@ -92,14 +92,15 @@ NODEassert.equal(invocation.env.LD_LIBRARY_PATH, libraryPath);assert.equal(invocation.env.OPENAI_API_KEY, undefined);assert.equal(invocation.env.ACTIONS_RUNTIME_TOKEN, undefined);- assert.equal(runtime.env('synthetic-scan-key').PYTHON, 'python3');- assert.equal(runtime.env('synthetic-scan-key').CODEX_MCP_NODE_PATH, join(runtime.root, 'bin', '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'));process.env.RUNNER_TRACKING_ID = 'synthetic-later-job';process.env.LD_LIBRARY_PATH = '/synthetic-later-library';- assert.equal(runtime.env('synthetic-scan-key').RUNNER_TRACKING_ID, 'synthetic-first-job');- assert.equal(runtime.env('synthetic-scan-key').LD_LIBRARY_PATH, libraryPath);+ assert.equal(runtime.env(credentials).RUNNER_TRACKING_ID, 'synthetic-first-job');+ assert.equal(runtime.env(credentials).LD_LIBRARY_PATH, libraryPath);const child = await runProcess(join(runtime.root, 'bin', 'node'), ['-e', 'console.log(process.env.RUNNER_TRACKING_ID)'],- {cwd:root, env:{...runtime.env('synthetic-scan-key'), RUNNER_TRACKING_ID:undefined}});+ {cwd:root, env:{...runtime.env(credentials), RUNNER_TRACKING_ID:undefined}});assert.equal(child.exitCode, 0, child.stderr);assert.equal(child.stdout.trim(), 'synthetic-first-job');await cleanupRuntime(runtime.root, root);@@ -208,7 +209,7 @@ test('scan environment excludes all inherited credential/config channels', () =>try {const paths = { root: '/tmp/owned', home: '/tmp/owned/home', codexHome: '/tmp/owned/codex', stateDirectory: '/tmp/owned/state' };const installer = runtimeEnvironment(paths);- const scanner = runtimeEnvironment(paths, 'scan-only-key');+ const scanner = runtimeEnvironment(paths, scanCredentials('openai', {OPENAI_API_KEY:'scan-only-key'}));for (const key of Object.keys(poison)) { assert.equal(installer[key], undefined); assert.equal(scanner[key], undefined); }assert.equal(installer.OPENAI_API_KEY, undefined);assert.equal(scanner.OPENAI_API_KEY, 'scan-only-key');@@ -225,8 +226,8 @@ test('each scan retains its runner tool path while keeping its environment isolaconst tool = join(tools, 'synthetic-tool');await writeFile(tool, '#!/bin/sh\nprintf selected-runner-tool\n', { mode: 0o755 });const paths = { root, home: root, codexHome: root, stateDirectory: root, runnerPath: tools, runnerTrackingId:'synthetic-first-job', runnerLibraryPath:'/synthetic-first-library' };- const first = runtimeEnvironment(paths, 'first-scan-key');- const second = runtimeEnvironment({...paths, runnerPath:'/other/tools', runnerTrackingId:'synthetic-second-job', runnerLibraryPath:'/synthetic-second-library'}, 'second-scan-key');+ const first = runtimeEnvironment(paths, scanCredentials('openai', {OPENAI_API_KEY:'first-scan-key'}));+ const second = runtimeEnvironment({...paths, runnerPath:'/other/tools', runnerTrackingId:'synthetic-second-job', runnerLibraryPath:'/synthetic-second-library'}, scanCredentials('openai', {OPENAI_API_KEY:'second-scan-key'}));const result = await runProcess('/bin/sh', ['-c', 'synthetic-tool'], {cwd:root, env:first});assert.equal(result.stdout, 'selected-runner-tool');assert.equal(first.PATH, `${join(root, 'bin')}:${tools}`);@@ -244,6 +245,71 @@ test('each scan retains its runner tool path while keeping its environment isolaassert.equal(runtimeEnvironment({...paths, runnerTrackingId:undefined}).CODEX_MCP_NODE_PATH, undefined);});+test('Bedrock credentials reach child processes without unrelated runner credentials', async t => {+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-bedrock-')));+ t.after(() => rm(root, {recursive:true, force:true}));+ const paths = {root, home:join(root, 'home'), codexHome:join(root, 'codex'), stateDirectory:join(root, 'state')};+ const sources = [+ {AWS_ACCESS_KEY_ID:'synthetic-access-key', AWS_SECRET_ACCESS_KEY:'synthetic-secret-key', AWS_SESSION_TOKEN:'synthetic-session-token', AWS_REGION:'us-east-2'},+ {AWS_BEARER_TOKEN_BEDROCK:'synthetic-bearer-token', AWS_DEFAULT_REGION:'us-west-2'},+ {AWS_PROFILE:'synthetic-profile', AWS_CONFIG_FILE:'/synthetic/config', AWS_SHARED_CREDENTIALS_FILE:'/synthetic/credentials'},+ {AWS_ROLE_ARN:'arn:aws:iam::123456789012:role/synthetic-role', AWS_ROLE_SESSION_NAME:'synthetic-session', AWS_WEB_IDENTITY_TOKEN_FILE:'/synthetic/token'},+ {AWS_CONTAINER_CREDENTIALS_FULL_URI:'http://127.0.0.1/synthetic', AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE:'/synthetic/token'},+ ];+ for (const aws of sources) {+ const source = {...aws, OPENAI_API_KEY:'must-not-forward', CODEX_API_KEY:'must-not-forward',+ GITHUB_TOKEN:'must-not-forward', ACTIONS_RUNTIME_TOKEN:'must-not-forward',+ NODE_OPTIONS:'--require=unrelated', CODEX_CLI_PATH:'/unrelated/codex', AWS_UNRELATED_SECRET:'must-not-forward'};+ const credentials = scanCredentials('amazon-bedrock', source);+ const env = runtimeEnvironment(paths, credentials);+ const child = await runProcess(process.execPath, ['-e', 'console.log(JSON.stringify(process.env))'], {cwd:root, env});+ assert.equal(child.exitCode, 0, child.stderr);+ const actual = JSON.parse(child.stdout);+ assert.deepEqual(Object.fromEntries(Object.entries(actual).filter(([name]) => name.startsWith('AWS_'))), aws);+ for (const name of ['OPENAI_API_KEY', 'CODEX_API_KEY', 'GITHUB_TOKEN', 'ACTIONS_RUNTIME_TOKEN', 'NODE_OPTIONS', 'CODEX_CLI_PATH'])+ assert.equal(actual[name], undefined);+ assert.equal(actual.HOME, paths.home); assert.equal(actual.CODEX_HOME, paths.codexHome);+ const installer = runtimeEnvironment(paths);+ for (const name of Object.keys(aws)) assert.equal(installer[name], undefined);+ }+});++test('API providers forward only their own captured key to child processes', async t => {+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-provider-')));+ t.after(() => rm(root, {recursive:true, force:true}));+ const paths = {root, home:root, codexHome:root, stateDirectory:root};+ const source = {OPENAI_API_KEY:'synthetic-openai', CODEX_API_KEY:'synthetic-alias',+ OPENROUTER_API_KEY:'synthetic-openrouter', FIREWORKS_API_KEY:'synthetic-fireworks',+ AWS_SESSION_TOKEN:'unrelated-aws', GITHUB_TOKEN:'unrelated-github'};+ const cases = [['openai', 'OPENAI_API_KEY'], ['openrouter', 'OPENROUTER_API_KEY'], ['fireworks', 'FIREWORKS_API_KEY']] as const;+ const captured = cases.map(([provider, key]) => ({credentials:scanCredentials(provider, source), key, value:source[key]}));+ source.OPENROUTER_API_KEY = source.FIREWORKS_API_KEY = 'changed-after-capture';+ await Promise.all(captured.map(async ({credentials, key, value}) => {+ const child = await runProcess(process.execPath, ['-e', 'console.log(JSON.stringify(process.env))'],+ {cwd:root, env:runtimeEnvironment(paths, credentials)});+ assert.equal(child.exitCode, 0, child.stderr);+ const actual = JSON.parse(child.stdout);+ for (const name of Object.keys(source)) assert.equal(actual[name], name === key ? value : undefined);+ for (const name of Object.keys(source)) assert.equal(runtimeEnvironment(paths)[name], undefined);+ }));+});++test('Bedrock credential snapshots stay isolated when the caller changes credentials', async t => {+ const root = await realpath(await mkdtemp(join(tmpdir(), 'runtime-bedrock-snapshot-')));+ t.after(() => rm(root, {recursive:true, force:true}));+ const paths = {root, home:root, codexHome:root, stateDirectory:root};+ const source = {AWS_BEARER_TOKEN_BEDROCK:'synthetic-first-token', AWS_REGION:'us-east-2'};+ const first = scanCredentials('amazon-bedrock', source);+ source.AWS_BEARER_TOKEN_BEDROCK = 'synthetic-second-token'; source.AWS_REGION = 'us-west-2';+ const second = scanCredentials('amazon-bedrock', source);+ const results = await Promise.all([first, second].map(credentials => runProcess(process.execPath,+ ['-e', 'console.log(JSON.stringify([process.env.AWS_BEARER_TOKEN_BEDROCK,process.env.AWS_REGION]))'],+ {cwd:root, env:runtimeEnvironment(paths, credentials)})));+ assert.deepEqual(results.map(result => JSON.parse(result.stdout)), [+ ['synthetic-first-token', 'us-east-2'], ['synthetic-second-token', 'us-west-2'],+ ]);+});+test('shipped runtime lock matches the manifest and records dependency integrity', async () => {const lock = JSON.parse(await readFile(new URL('../runtime/package-lock.json', import.meta.url), 'utf8'));const manifest = JSON.parse(await readFile(new URL('../runtime/package.json', import.meta.url), 'utf8'));diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex 2510b1ba9..cbcc0d11f 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -138,6 +138,8 @@ try {await testPreflightBindsExecutableAndHomeBeforeChangingCwd();await testSdkInvocationAndThreadCapture();await testBedrockCredentialsReachWorker();+ await testBedrockCredentialsReachWorker("oidc");+ await testExternalProviderCredentialsReachWorker();await testArtifactServerUsesExtendedStartupTimeout();await testZeroSubagentsPreservesHostRestrictions();await testSdkResumesExistingThread();@@ -2532,38 +2534,72 @@ async function testWorkerCyberAccessSettings() {}}-async function testBedrockCredentialsReachWorker() {+async function testBedrockCredentialsReachWorker(+ credentials: "all" | "oidc" = "all",+) {const fixture = await fakeCodexFixture();const mcpConfig = await readJson(import.meta.dirname, "../../.mcp.json");+ const awsNames: string[] = mcpConfig.mcpServers[+ "codex-security"+ ].env_vars.filter((name: string) => name.startsWith("AWS_"));+ const oidcNames = [+ "AWS_ACCESS_KEY_ID",+ "AWS_SECRET_ACCESS_KEY",+ "AWS_SESSION_TOKEN",+ "AWS_REGION",+ ];const awsEnvironment = Object.fromEntries(- mcpConfig.mcpServers["codex-security"].env_vars- .filter((name: string) => name.startsWith("AWS_"))+ awsNames+ .filter((name) => credentials === "all" || oidcNames.includes(name)).map((name: string) => [name, `synthetic-bedrock-${name.toLowerCase()}`]),);- assert.ok(awsEnvironment.AWS_BEARER_TOKEN_BEDROCK);+ if (credentials === "all") assert.ok(awsEnvironment.AWS_BEARER_TOKEN_BEDROCK);assert.ok(awsEnvironment.AWS_ACCESS_KEY_ID);assert.ok(awsEnvironment.AWS_SECRET_ACCESS_KEY);+ assert.ok(awsEnvironment.AWS_SESSION_TOKEN);+ const configPath = path.join(fixture.root, "bedrock.toml");+ await writeFile(+ configPath,+ 'model_provider = "amazon-bedrock"\nmodel_reasoning_summary = "none"\n',+ );+ const deepConfigPath = path.join(fixture.root, "bedrock-workers.toml");+ await writeFile(+ deepConfigPath,+ '[worker_runtime]\nmodel_provider = "amazon-bedrock"\nmodel_reasoning_summary = "none"\n',+ );const environment = {- ...awsEnvironment,+ ...Object.fromEntries(awsNames.map((name) => [name, awsEnvironment[name]])),+ OPENAI_API_KEY: undefined,+ CODEX_API_KEY: undefined,+ CODEX_SECURITY_CONFIG_PATH: configPath,+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: deepConfigPath,CODEX_CLI_PATH: fixture.executablePath,- FAKE_CODEX_BEDROCK_ENV_KEYS: JSON.stringify(Object.keys(awsEnvironment)),+ FAKE_CODEX_BEDROCK_ENV_KEYS: JSON.stringify(awsNames),};const previousEnvironment = Object.keys(environment).map((name) => [name, process.env[name]] as const,);- Object.assign(process.env, environment);+ for (const [name, value] of Object.entries(environment))+ restoreEnv(name, value);try {const promptPath = path.join(fixture.root, "prompt.md");const workingDirectory = path.join(fixture.root, "artifacts");await mkdir(workingDirectory);- await writeFile(promptPath, "CAPTURE_SYNTHETIC_BEDROCK_AUTH\n");+ await writeFile(+ promptPath,+ "CAPTURE_SYNTHETIC_BEDROCK_AUTH\nCAPTURE_SYNTHETIC_OPENAI_AUTH\n",+ );const executor = new CodexSdkWorkerExecutor({parentSandbox: trustedParentSandbox,});for (const kind of ["discovery", "dedup"] as const) {for (const resumeThreadId of [undefined, "fixture-bedrock-resume"]) {- awsEnvironment.AWS_BEARER_TOKEN_BEDROCK = `synthetic-${kind}-${resumeThreadId ?? "fresh"}`;+ awsEnvironment[+ credentials === "oidc"+ ? "AWS_SESSION_TOKEN"+ : "AWS_BEARER_TOKEN_BEDROCK"+ ] = `synthetic-${kind}-${resumeThreadId ?? "fresh"}`;awsEnvironment.AWS_REGION = resumeThreadId ? "us-west-2" : "us-east-2";Object.assign(process.env, awsEnvironment);const result = await executor.run(@@ -2572,12 +2608,15 @@ async function testBedrockCredentialsReachWorker() {assert.equal(result.threadId, resumeThreadId ?? "fixture-thread-id");const invocation = await readJson(fixture.markerPath);assert.deepEqual(invocation.bedrockAuthentication, awsEnvironment);+ assert.deepEqual(invocation.openaiAuthentication, {});assert.equal(invocation.argv.includes("resume"),resumeThreadId !== undefined,);assertConfigOverrides(invocation.argv, {"mcp_servers.codex-security.enabled": false,+ model_provider: "amazon-bedrock",+ model_reasoning_summary: "none",});}}@@ -2588,6 +2627,114 @@ async function testBedrockCredentialsReachWorker() {}}+async function testExternalProviderCredentialsReachWorker() {+ for (const [provider, key] of [+ ["openrouter", "OPENROUTER_API_KEY"],+ ["fireworks", "FIREWORKS_API_KEY"],+ ]) {+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {+ const configPath = path.join(fixture.root, "provider.toml");+ const deepPath = path.join(fixture.root, "workers.toml");+ const profile = `scan-${provider}`;+ const selectedKey = `synthetic-${provider}-scan-key`;+ const settings = {+ model_provider: provider,+ native_profile: profile,+ environment: { [key]: selectedKey },+ };+ await writeFile(configPath, stringifyToml({ model_provider: provider }));+ await writeFile(deepPath, stringifyToml({ worker_runtime: settings }));+ await writeFile(+ path.join(fixture.root, `${profile}.config.toml`),+ stringifyToml({+ model_provider: provider,+ model_providers: {+ [provider]: {+ name: provider,+ base_url: `https://${provider}.example.test/v1`,+ wire_api: "responses",+ env_key: key,+ },+ },+ }),+ );+ await writeFile(promptPath, "synthetic provider credential fixture");+ const environment = {+ CODEX_HOME: fixture.root,+ CODEX_SECURITY_CONFIG_PATH: configPath,+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: deepPath,+ OPENAI_API_KEY: undefined,+ CODEX_API_KEY: undefined,+ OPENROUTER_API_KEY: undefined,+ FIREWORKS_API_KEY: undefined,+ };+ const saved = Object.keys(environment).map(+ (name) => [name, process.env[name]] as const,+ );+ const originalSpawn = childProcess.spawn;+ const launches: {+ args: readonly string[];+ environment: NodeJS.ProcessEnv;+ }[] = [];+ try {+ for (const [name, value] of Object.entries(environment))+ restoreEnv(name, value);+ childProcess.spawn = ((+ command: string,+ args: readonly string[],+ options: SpawnOptions,+ ) => {+ if (args[0] === "exec")+ launches.push({ args, environment: { ...options.env } });+ return originalSpawn(command, args, options);+ }) as typeof childProcess.spawn;+ syncBuiltinESMExports();+ const executor = new CodexSdkWorkerExecutor({+ parentSandbox: trustedParentSandbox,+ });+ for (const kind of ["discovery", "dedup"] as const)+ for (const resumeThreadId of [undefined, "fixture-provider-resume"]) {+ launches.length = 0;+ process.env[key] = "changed-ambient-key";+ await executor.run(+ workerRequest(promptPath, workingDirectory, {+ kind,+ resumeThreadId,+ }),+ );+ assert.equal(launches.length, 1);+ const launch = launches[0];+ assert.equal(launch.environment[key], selectedKey);+ assert.equal(launch.environment.OPENAI_API_KEY, undefined);+ assert.equal(launch.environment.CODEX_API_KEY, undefined);+ assertFlagPair(launch.args, "--profile", profile);+ assertConfigOverrides(launch.args, {+ model_provider: provider,+ "mcp_servers.codex-security.enabled": false,+ });+ assert.equal(+ launch.args.includes("resume"),+ resumeThreadId !== undefined,+ );+ await writeFile(+ deepPath,+ stringifyToml({+ worker_runtime: {+ ...settings,+ environment: { [key]: "changed-snapshot-key" },+ },+ }),+ );+ }+ } finally {+ childProcess.spawn = originalSpawn;+ syncBuiltinESMExports();+ for (const [name, value] of saved) restoreEnv(name, value);+ }+ });+ }+}+async function testZeroSubagentsPreservesHostRestrictions() {for (const model of ["gpt-5.6-luna", "gpt-5.6-sol"]) {await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 36129cbef..005f22757 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -1167,6 +1167,7 @@ export class CodexSecurity {options.auth,modelProvider,hasCommandAuth(configuration),+ true,),...model,...(typeof modelProvider === "string" ? { modelProvider } : {}),@@ -4965,6 +4966,7 @@ export function scanAuthentication(auth: ScanAuthMode = DEFAULT_SCAN_AUTH,modelProvider?: unknown,commandAuth = false,+ preflight = false,): ScanAuthentication {if (!SCAN_AUTH_MODES.includes(auth)) {throw new TypeError(@@ -4994,6 +4996,9 @@ export function scanAuthentication(const key = environmentApiKeyEntry(environment, modelProvider);if (key === null && isExternalModelProvider(modelProvider)) {const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];+ if (preflight && auth === "auto") {+ return { method: "api_key", source: provider.env_key, verified: false };+ }throw new AuthenticationRequiredError(`Set ${provider.env_key} to run a scan through ${provider.name}.`,);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex dc094e2ab..46fc3a242 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -8445,6 +8445,7 @@ async function executeScan(auth,provider,hasCommandAuth(effectiveConfiguration),+ arguments_.dryRun,);diagnostic("scan.configuration", {cli_version: VERSION,diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 41399e3b5..34eba77a2 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1541,16 +1541,58 @@ describe("CodexSecurity orchestration", () => {},);- for (const operation of ["preflight", "run"] as const) {- await expect(client[operation](repository)).rejects.toThrow(+ for (const auth of ["api-key", "chatgpt"] as const) {+ await expect(client.preflight(repository, { auth })).rejects.toThrow(`Set ${apiKey} to run a scan through ${name}.`,);}+ for (const mode of ["standard", "deep"] as const) {+ for (const auth of [undefined, "auto", "api-key", "chatgpt"] as const) {+ await expect(client.run(repository, { mode, auth })).rejects.toThrow(+ `Set ${apiKey} to run a scan through ${name}.`,+ );+ }+ }expect(prepareRuntime).not.toHaveBeenCalled();await client.close();},);+ test.each(EXTERNAL_PROVIDER_CASES)(+ "preflights %s with auto authentication without credentials or runtime startup",+ async (_name, provider, apiKey, model, providerConfig) => {+ const { repository } = await repositoryDirectories();+ const prepareRuntime = mock(rejecting("runtime must not start"));+ await using client = new TestClient(+ {+ codexOverrides: {+ model,+ model_provider: provider,+ model_providers: { [provider]: providerConfig },+ },+ },+ { environment: {}, prepareRuntime },+ );++ for (const mode of ["standard", "deep"] as const) {+ for (const auth of [undefined, "auto"] as const) {+ await expect(+ client.preflight(repository, { mode, auth }),+ ).resolves.toMatchObject({+ mode,+ modelProvider: provider,+ authentication: {+ method: "api_key",+ source: apiKey,+ verified: false,+ },+ });+ }+ }+ expect(prepareRuntime).not.toHaveBeenCalled();+ },+ );+test.each(EXTERNAL_PROVIDER_CASES)("runs %s scans without signing in to OpenAI",async (_name, provider, apiKey, model, providerConfig) => {