diff --git a/CHANGELOG.md b/CHANGELOG.md index a707bff..6ae9ebb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased — security remediation pass +- Stage the hosted origin on codexbot.appsolves.workers.dev with Workers.dev enabled and previews disabled; preserve the existing custom domain for controlled cutover. Default CLI/generated callers and the onboarding page/manifest to the new URL. Reject all privileged requests on noncanonical aliases, keep exact OIDC audiences and require fresh origin-bound ChatGPT connection. No deployment, zone-security change or credential migration is automatic; see docs/origin-migration.md. + - Correct Environment secret forwarding: generate named references after a required environment-free caller guard rejects repository/organization credentials. Empty literals did not enable Environment lookup; named references alone would allow fallback. Existing callers must update through a PR; reusable/Worker pins and credentials remain unchanged. See docs/review-rollout.md. - Explicitly forward only named Environment credential grants; add a credential-only availability diagnostic, safe runner/broker/OIDC failure codes and failed-job publication safeguards. diff --git a/README.md b/README.md index 068644f..a90d507 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ An Apache-2.0 GitHub App for Codex pull request reviews on repository-owned GitHub Actions runners. The Cloudflare Worker authenticates requests and publishes native reviews; it never runs Codex. +Hosted backend: **[https://codexbot.appsolves.workers.dev](https://codexbot.appsolves.workers.dev/)**. This is the CLI and generated-workflow default. The hostname migration is staged; production availability and credential acceptance must be verified during the [operator cutover](docs/origin-migration.md). Independent installations pass their own HTTPS origin with `--backend`. + ```text @CBReview review --effort xhigh --merge @@ -14,7 +16,7 @@ Set `bot.trigger: "@CBReview"` to use the example above. The legacy default `@co ## Status -**Pre-release implementation; no public hosted App has been deployed by this repository setup.** Unit/integration tests exercise signed webhooks, official OAuth contracts, OIDC, actual SQLite persistence, setup PR creation and GitHub publishing against mocked external APIs. The pinned official Codex binary is tested without credentials. A separate Docker check uses synthetic inference; it does not claim to have performed a real AI review. See [validation and live acceptance](docs/validation.md). +**Pre-release; full production review acceptance remains pending.** Unit/integration tests exercise signed webhooks, official OAuth contracts, OIDC, actual SQLite persistence, setup PR creation and GitHub publishing against mocked external APIs. The pinned official Codex binary is tested without credentials. A separate Docker check uses synthetic inference; it does not claim to have performed a real AI review. See [validation and live acceptance](docs/validation.md). Live GitHub installation, real OpenAI inference/allowance, OAuth eligibility and Cloudflare production resource usage require operator credentials and acceptance testing. Do not market this as battle-tested or deploy with automatic merge before completing those checks. @@ -43,8 +45,8 @@ npm run check 3. Create the setup PR (replace the uppercase values): ```sh -npm run cli -- setup --repository OWNER/REPO --backend https://YOUR-WORKER \ - --source YOUR-ORG/codexbot --ref FULL_40_CHARACTER_COMMIT_SHA +npm run cli -- setup --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev \ + --source AppSolves/codexbot --ref 4ed668864cac0682e09ec49a2515a6e1893a2780 ``` The source must match the Worker's trusted reusable workflow. If you prefer a temporary personal setup token to granting the App Workflows write, add `--setup-as-user`; the user credential needs Contents/Pull requests/Workflows write. No files are overwritten. See [manual setup](docs/installation.md). @@ -53,10 +55,10 @@ The source must match the Worker's trusted reusable workflow. If you prefer a te ```sh # Preferred, when your deployment is eligible for OpenAI's OSS/hosted policy: -npm run cli -- connect --repository OWNER/REPO --backend https://YOUR-WORKER +npm run cli -- connect --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev # Alternative: set CODEXBOT_API_KEY securely in your local process environment first. -npm run cli -- connect-api-key --repository OWNER/REPO --backend https://YOUR-WORKER +npm run cli -- connect-api-key --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev ``` The ChatGPT flow displays **Continue with ChatGPT** and opens an official authorization URL using a loopback callback. Manual `auth.json` export is unnecessary. API-key mode requires `credentials.mode: api-key` in trusted configuration. Do not keep both mode secrets in the Environment. diff --git a/app-manifest.json b/app-manifest.json index 28a074d..b98ff56 100644 --- a/app-manifest.json +++ b/app-manifest.json @@ -1,9 +1,9 @@ { "name": "CodexBot", - "url": "https://YOUR-WORKER.example", - "hook_attributes": { "url": "https://YOUR-WORKER.example/webhook", "active": true }, - "redirect_url": "https://YOUR-WORKER.example/", - "setup_url": "https://YOUR-WORKER.example/", + "url": "https://codexbot.appsolves.workers.dev", + "hook_attributes": { "url": "https://codexbot.appsolves.workers.dev/webhook", "active": true }, + "redirect_url": "https://codexbot.appsolves.workers.dev/", + "setup_url": "https://codexbot.appsolves.workers.dev/", "public": true, "default_permissions": { "metadata": "read", "contents": "write", "pull_requests": "write", "actions": "write" }, "default_events": ["issue_comment", "pull_request"] diff --git a/docs/authentication.md b/docs/authentication.md index 1ff93f0..2f4c0b6 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -1,5 +1,7 @@ # Authentication and credential ownership +The hosted canonical origin is `https://codexbot.appsolves.workers.dev`; independent operators explicitly select their own origin. OAuth AAD includes this exact origin, installation, repository and actor, and local profile files are separated by backend host. Existing ChatGPT connections require [safe revocation and fresh sign-in](origin-migration.md#chatgpt-reconnection) when the origin changes. Do not copy profiles, rebind ciphertext or accept both OIDC audiences during a cutover. API-key mode keeps its existing owning Environment; it does not have OAuth ciphertext to migrate. + Reusable callers must use explicit named secret references after the environment-free `credential-scope` guard rejects nonempty repository/organization credentials under either name. The called installation/actor Environment supplies the actual credential. Literal empty grants do not enable Environment secret resolution. Named references alone would permit a global-secret fallback if an Environment secret were missing; keep the guard and its required dependency. [Credential diagnostics and rollout](review-rollout.md) explain the GitHub contract and no-inference check. No reusable-workflow/Worker pin or session format changes are needed for this caller-only correction. ## Official ChatGPT OAuth diff --git a/docs/deployment.md b/docs/deployment.md index dd51ba8..da4cefe 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1,5 +1,7 @@ # Deployment checklist +Hosted canonical origin: **https://codexbot.appsolves.workers.dev**. Use the [staged origin migration](origin-migration.md) for the existing App/Worker; it preserves the current D1, secrets, immutable review pin and zone Bot Fight Mode. This repository prepares the change; merging or a dry-run does not deploy it. + For Worker/reusable-workflow upgrades, follow [the coordinated immutable-pin upgrade](review-rollout.md), apply required migrations and set the caller pin and Worker TRUSTED_WORKFLOW to the same actual merged commit. The caller-only Environment-secret correction uses named references plus a scope guard; it keeps the existing `4ed668864cac0682e09ec49a2515a6e1893a2780` pin and needs no Worker deployment or migration. Keep merge disabled. Report validation before any production change; a temporary pin mismatch fails closed. The shared setup generator is bundled into `/v1/setup`. Publishing its corrected templates for future hosted installations requires a separately authorized Worker bundle deployment, with the existing trusted review pin preserved. The existing caller can be repaired independently; no backend deployment is performed by the fix PR. @@ -8,12 +10,12 @@ This document is operator instructions, not evidence of an existing hosted deplo ## GitHub App -Register a public GitHub App with installation access for any account, selecting repositories narrowly. [app-manifest.json](../app-manifest.json) is a settings reference; replace example URLs. Manifest-code conversion is not implemented: use GitHub's App settings or your own approved registration tooling. +Register a public GitHub App with installation access for any account, selecting repositories narrowly. [app-manifest.json](../app-manifest.json) contains the hosted URL defaults; independent operators replace all four origin-bearing fields with their own backend. Manifest-code conversion is not implemented: use GitHub's App settings or your own approved registration tooling. | Setting | Required value | |---|---| -| Homepage/setup URL | https://YOUR-WORKER/ | -| Webhook | https://YOUR-WORKER/webhook | +| Homepage/setup URL | https://codexbot.appsolves.workers.dev/ (or the independent backend) | +| Webhook | https://codexbot.appsolves.workers.dev/webhook (or the independent backend) | | Secret | Cryptographically random, at least 32 bytes | | Default permissions | Metadata read; Actions write; Contents write; Pull requests write | | Optional automated setup | Workflows write, explicit installer consent; otherwise manual/temporary-user setup | diff --git a/docs/installation.md b/docs/installation.md index 7e69eea..5d01dbd 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -2,6 +2,8 @@ Install the operator's public App and select repositories. Its Worker landing page is an operational checklist, not a hosted OAuth wizard. All credential sign-in runs in the local CLI. Each installation can instead use its own App, Worker and immutable source fork. +The hosted backend and CLI default is `https://codexbot.appsolves.workers.dev`. Self-hosted operators supply their own `--backend` and source pin. Existing ChatGPT connections must follow the [origin cutover and reconnect procedure](origin-migration.md) before using this new origin; they are not transferable ciphertext. + ## Setup permissions and supported plans The default manifest deliberately omits Workflows write. App-authored setup requires an explicit operator permission upgrade and installer consent. Otherwise use the first-class manual workflow below, or add `--setup-as-user` with a temporary single-repository administrator credential granting Contents/Pull requests/Workflows write. It creates the same reviewed setup PR under your own identity; no automatic elevation or retained user token is used. @@ -10,7 +12,7 @@ Before creating a setup PR or connecting credentials, the CLI probes Environment ```sh npm ci --ignore-scripts -npm run cli -- setup --repository OWNER/REPO --backend https://YOUR-WORKER \ +npm run cli -- setup --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev \ --source YOUR-ORG/codexbot --ref FULL_COMMIT_SHA --setup-as-user ``` @@ -65,7 +67,7 @@ jobs: request_id: ${{ inputs.request_id }} credential_owner: ${{ inputs.credential_owner }} installation_id: ${{ inputs.installation_id }} - backend: https://YOUR-WORKER + backend: https://codexbot.appsolves.workers.dev credential_check_only: ${{ inputs.credential_check_only }} ``` @@ -78,9 +80,9 @@ Use the two named secret references, not literal empty grants. The `credential-s Protect the default branch **before** connecting. New codexbot-INSTALLATION_ID-NUMERIC_USER_ID and codexbot-publish-INSTALLATION_ID Environments use a default-branch-only custom deployment policy. The installation namespace isolates both API keys and OAuth vault keys across independent Apps/reinstalls. Existing reviewers/timers are preserved. Unrestricted Environments and custom policies allowing other branches/tags are rejected. Existing protected-branch policies require an actually protected default branch: GitHub otherwise permits every branch when no protected branches exist. Private Free repositories are unsupported. ```sh -npm run cli -- connect --repository OWNER/REPO --backend https://YOUR-WORKER +npm run cli -- connect --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev # Or, after securely setting CODEXBOT_API_KEY in the local process: -npm run cli -- connect-api-key --repository OWNER/REPO --backend https://YOUR-WORKER +npm run cli -- connect-api-key --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev ``` ChatGPT connection checks the backend deployment gate before sign-in. Use your own eligible account/workspace; manual auth.json export is unnecessary and not supported. API keys go to GitHub through gh stdin; never the Worker. Set credentials.mode appropriately and remove the other mode's secret. API billing and ChatGPT allowance never fall back into one another. diff --git a/docs/origin-migration.md b/docs/origin-migration.md new file mode 100644 index 0000000..79d6898 --- /dev/null +++ b/docs/origin-migration.md @@ -0,0 +1,107 @@ +# Hosted origin cutover and rollback + +Canonical target: **https://codexbot.appsolves.workers.dev**. The Worker is `codexbot` in the existing account subdomain `appsolves.workers.dev`. The old `codexbot.appsolves.dev` custom domain is retained initially for controlled cutover, not as another authentication identity. Bot Fight Mode for the entire `appsolves.dev` zone stays enabled. No domain purchase, zone change, new database, paid plan or interactive Access login is part of this migration. + +This is a prepared, operator-authorized rollout, not evidence of deployment. The last read-only account check found Workers.dev disabled. A Node health request returned 404 without a challenge while disabled; this does not prove the deployed route, webhook or OIDC works. [Workers.dev routing](https://developers.cloudflare.com/workers/configuration/routing/workers-dev/) and the project's pinned Wrangler define the configuration. Workers.dev also has Cloudflare-managed Browser Integrity Check: verify the actual GitHub runner, not just a browser. Stop on an edge challenge; do not disable zone protection, impersonate a browser or relax application authentication. + +## Invariants + +- Preserve the Worker name, compatibility date/flags, D1 ID/binding, secrets, both cron triggers, logging policy and `MERGE_DEPLOYMENT_AUTHORIZED=false`. +- Keep `TRUSTED_WORKFLOW` and the repository caller at `AppSolves/codexbot/.github/workflows/review.yml@4ed668864cac0682e09ec49a2515a6e1893a2780`. The reusable workflow needs no change: it takes the backend input as its exact OIDC audience. A backend-only bundle update does not require changing this pin. +- Preserve the caller's mandatory environment-free credential guard, named secret references, actor/installation inputs, concurrency and protected default-branch Environment policy. Only its `with.backend` changes. +- The Worker accepts privileged requests, including webhooks, **only on `PUBLIC_URL`'s exact origin**. Noncanonical aliases return HTTP 421 without redirects, even with a valid canonical token or forwarded-host header. Only unauthenticated GET `/` and `/health` remain public on retained aliases; cross-origin browser requests still fail. +- All old in-flight workflows must drain or expire before the caller/default branch and canonical audience change. Never replay an old Actions attempt to borrow a new origin or credential. There is no dual-audience grace period. + +## Stage 0: prepare and pause + +Review the source PR and separate caller PR using normal branch protections. Record the currently deployed Worker version, config, exact caller commit, GitHub App webhook/setup values and the existing D1 ID. Preserve secrets in their current stores; do not export them. Pause new review commands and automatic reviews, inspect operations, and wait for active runs/session leases/publications/merge intents to finish or recover normally. Keep automatic merging disabled. This release adds no SQL migration. + +For remote commands, explicitly select the existing AppSolves Cloudflare account with `CLOUDFLARE_ACCOUNT_ID` and verify `node node_modules/wrangler/bin/wrangler.js whoami`. Its existing Workers subdomain must be `appsolves`; do not select another account, create a Worker environment or provision another D1 database. This account selection is not needed for local dry-runs. + +Read-only verification and local validation: + +```sh +npm ci --ignore-scripts +npm run check +npm run test:clean +npm run test:workers +node node_modules/wrangler/bin/wrangler.js deploy --dry-run --outdir .local/worker +``` + +## Stage 1: enable the hostname while preserving the old canonical identity + +Only after explicit deployment authorization, deploy the reviewed bundle with Workers.dev enabled but the **old canonical origin explicitly overridden**. The checked-in config retains the existing custom-domain route. The CLI override changes only PUBLIC_URL; verify the dry-run's effective bindings first. + +```sh +node node_modules/wrangler/bin/wrangler.js deploy --dry-run --var PUBLIC_URL:https://codexbot.appsolves.dev --outdir .local/worker-stage1 +# Operator-authorized remote action, not executed by this PR: +node node_modules/wrangler/bin/wrangler.js deploy --var PUBLIC_URL:https://codexbot.appsolves.dev +node --input-type=module -e "const r=await fetch('https://codexbot.appsolves.workers.dev/health',{redirect:'error'});if(r.status!==200)process.exitCode=1;console.log('health status',r.status);await r.body?.cancel()" +``` + +The new hostname's `/health` may succeed, but its privileged endpoints must return 421 until stage 2. Health is public and proves transport/liveness only. `preview_urls` remains false. Do not modify the account subdomain or any zone-wide protection. If verification fails, stop here with the old canonical identity intact. + +## ChatGPT reconnection + +Reconnection **is required**. `sessionBinding()` includes the exact backend origin, installation, repository and actor. The CLI profile filename also changes with the backend host. The same old vault key cannot decrypt old ciphertext under new-origin AAD. Do not copy the old profile to the new filename, rewrite AAD, decrypt/re-encrypt a stored session for transfer, export tokens or reuse a session across identities. + +Preferred path, while old-origin access still works and all runs are drained: + +```sh +npm run cli -- disconnect --repository OWNER/REPO --backend https://codexbot.appsolves.dev +``` + +This explicitly addresses the retired origin (do not omit `--backend` now that the CLI defaults to Workers.dev). The supported disconnect path loads the latest rotated session, revokes it using OpenAI's discovered revocation endpoint, removes its backend session/owning Environment secrets and clears local tokens. Do not treat a failed or unconfirmed disconnect as revocation success. + +If Bot Fight Mode prevents this old-origin CLI request, **leave it enabled**. Disconnect the old client in [ChatGPT Settings / Usage and app access](https://chatgpt.com/settings/usage), identifying the old registration by its client/account metadata. This is the [official fallback when remote revocation cannot be confirmed](https://developers.openai.com/siwc/token-sharing-open-source/profiles-and-sessions#end-the-renewable-session). If revocation cannot be confirmed, keep reviews paused. No origin alias or manual ciphertext transfer is needed. + +After stage 2, sign in freshly using the new-origin profile: + +```sh +npm run cli -- connect --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev +``` + +Use ordinary `connect` for this new profile, not `--new-account` against a still-present retired session. Official OAuth validates the new registration/session; a new local vault key and new-origin ciphertext replace the drained, revoked old row through the existing authenticated provisioning path. No old ciphertext is decrypted or rebound. The database must have no live session lease; a lease conflict is a stop/recovery condition, not permission to reset it manually. Confirm the CLI reports success; provisioning failure leaves acceptance blocked. API-key mode has no origin-bound OAuth ciphertext and needs no key transfer: keep its existing personal Environment key and only update the caller URL. + +## Stage 2: canonical cutover, App settings and caller + +After operator approval, deploy the reviewed config without the stage-1 override: + +```sh +node node_modules/wrangler/bin/wrangler.js deploy +``` + +This sets `PUBLIC_URL=https://codexbot.appsolves.workers.dev`. Keep existing D1/secrets and all authorization gates. Old-origin privileged requests now return 421. Coordinate these manual changes during the paused window; temporary URL/audience mismatch fails closed: + +1. Open [GitHub App settings](https://github.com/settings/apps/codexbot-review), then **Webhook → Webhook URL**: set `https://codexbot.appsolves.workers.dev/webhook`. Leave Active, the existing webhook secret, App ID/key, permissions and event subscriptions unchanged. Do not copy the App key to any repository. +2. Set the App's **Setup URL** to `https://codexbot.appsolves.workers.dev/`. If its homepage points to the retired backend, update it to the new landing page. A homepage pointing to the GitHub source repository is legitimate and can stay. The checked-in manifest uses the new homepage/setup/manifest-redirect defaults; manifest changes do not update a registered App automatically. GitHub user OAuth is not used here: do not invent a web OAuth callback. OpenAI sign-in retains its local loopback callback. +3. Merge the caller PR using ordinary protection/independent approval. Its only change is `with.backend: https://codexbot.appsolves.workers.dev`; preserve the trusted SHA, credential guard and named references. Read back the actual default-branch workflow and Worker PUBLIC_URL/TRUSTED_WORKFLOW values. +4. If the GitHub repository's About website still points to the retired backend, update it after the hostname passes health: `gh repo edit AppSolves/codexbot --homepage https://codexbot.appsolves.workers.dev`. Keep source/documentation links that are not backend URLs. No repository setting is changed by this PR. +5. Complete the fresh ChatGPT connection above. Do not mix modes or silently use an API key when OAuth fails. + +The required [GitHub App settings changes](https://docs.github.com/en/apps/maintaining-github-apps/modifying-a-github-app-registration) are manual operator actions. No App registration/settings, production credentials or deployment is modified while preparing the PRs. + +## Verification gates before inference + +1. Check new-origin `/health` using Node with `redirect: 'error'`, then GET `/v1/capabilities` through the CLI's authenticated preflight. Do not print the GitHub token or raw responses. +2. In the App's **Advanced → Recent Deliveries**, send/redeliver a **ping**, not a review command. Confirm its actual target is the new `/webhook`, HMAC validation succeeds and GitHub receives HTTP 200. Keep webhook secrets/signatures and payloads out of artifacts. Resolve missed deliveries deliberately; do not guess delivery order. +3. After reconnection and caller merge, dispatch a fresh credential-only run on `main`. In PowerShell: + + ```powershell + gh workflow run codexbot.yml --repo OWNER/REPO --ref main ` + -f request_id=([guid]::NewGuid().Guid) -f dispatch_attempt=([guid]::NewGuid().Guid) ` + -f credential_owner=YOUR_NUMERIC_USER_ID -f installation_id=YOUR_INSTALLATION_ID ` + -f credential_check_only=true + ``` + + Expect `credential-scope` success, `credential_availability_verified` and `workload_diagnostic_verified` with `no_session_no_inference`; publishing must be skipped. Verify the actual runner reaches the Worker without a Cloudflare challenge. The diagnostic checks availability and read-only OIDC only, not ciphertext decryption, OAuth entitlement or provider inference. +4. Confirm old-host `/v1/*` and `/webhook` cannot act as alternate entry points (421 from the Worker or an existing zone challenge, no redirect). Confirm `MERGE_DEPLOYMENT_AUTHORIZED=false`, `preview_urls=false` and unchanged zone Bot Fight Mode. Keep the old custom-domain route in config until a separate explicit removal is authorized; remaining alias access is only public landing/health. +5. Only after these gates pass and the owner separately authorizes using their allowance, request a **new advisory/no-merge review**. Confirm its progress comment, exact head and native COMMENT review. No paid or subscription inference is performed by the migration tests. + +## Rollback + +Pause reviews and drain/reconcile active new-origin requests first. Before reverting, use supported new-origin disconnect or the provider's Settings fallback to revoke new-origin renewable sessions. D1 is shared: old-origin ciphertext is not preserved by a Worker version rollback, and credentials/profile files must never be copied or restored across origins. + +Deploy the reviewed origin-enforcing bundle with `--var PUBLIC_URL:https://codexbot.appsolves.dev`, preserving both routes initially. Revert the caller URL through normal branch protection and restore the recorded App webhook/setup URLs. Keep the immutable review pin unchanged and merging disabled. Reconnect on the restored canonical origin using fresh OAuth; old revoked sessions do not become valid again. A rollback does **not** fix the original Bot Fight Mode challenge: keep reviews paused if machine access remains blocked. Do not roll back to pre-origin-check code while two routable aliases exist. + +Disable the new Workers.dev route only after separately approving that routing change and aligning `workers_dev: false` in config; dashboard-only changes can be undone by Wrangler. Keep additive D1 schema and current data; no database restore or global-security change belongs to this rollback. diff --git a/docs/validation.md b/docs/validation.md index 5bdc513..a1bdd3c 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -1,5 +1,11 @@ # Validation record and release gates +## Workers.dev origin migration + +The configured hosted origin, CLI and generated caller defaults, manifest and onboarding website now use `https://codexbot.appsolves.workers.dev`. Focused tests cover the real CLI default/self-hosted override/profile separation, exact OIDC audience, HMAC on the new origin, strict Origin/host rejection, nonredirecting retired aliases and inability to decrypt old-origin OAuth ciphertext under new AAD. The workerd/D1 test also exercises onboarding, Origin rejection and authenticated endpoint denial without a bearer. [Cutover/rollback](origin-migration.md) separates local evidence from pending deployment, GitHub App ping delivery, protected-default-branch credential diagnostic and fresh OAuth connection. No production change or inference is performed by these tests. + +Local validation passed: `npm run check` (130 tests, strict typecheck, lint and build), `npm run test:clean`, `npm run test:workers`, actionlint for repository and actual proposed caller, and Wrangler deploy dry-runs for both final config and the stage-1 PUBLIC_URL override. Preview URLs remain disabled and the immutable review pin is unchanged. A successful dry-run is not a production route/OIDC/provider acceptance result. + ## Environment secret forwarding correction — 2026-11-14 A real [GitHub Actions contract probe](https://github.com/AppSolves/codexbot/actions/runs/43602684286) used synthetic, non-credential canaries in two separate test Environments and a uniquely named repository canary. No OpenAI credentials, production Environment changes, OIDC bypass, inference or deployment were involved. All six assertions passed: @@ -13,7 +19,7 @@ A real [GitHub Actions contract probe](https://github.com/AppSolves/codexbot/act | Named reference; key absent from Environment, present in repository | Repository fallback, demonstrating why references alone are unsafe | | Caller job without Environment | Sees global canary presence but cannot see the Environment-only canary | -The [probe commit](https://github.com/AppSolves/codexbot/commit/9e602025fdb2ff5c2176584d0d40f1af58222118) preserves the exact assertions and workflow definitions; its diagnostic branch is retained as evidence. The temporary canary secret and both test Environments were removed after successful completion. The production generator now combines named references with a required environment-free guard that rejects either global credential name. Regression tests execute its fail-closed script, enforce its dependency/permissions/boolean-only inputs and compare the manual example against the generator. Static tests do not implement or mock GitHub's secret resolver. `npm run check` (124 tests, typecheck, lint, build), `npm run test:clean`, actionlint for repository/generated/caller workflows and `git diff --check` passed. The production reusable workflow and Worker pin remain `4ed668864cac0682e09ec49a2515a6e1893a2780`. +The [probe commit](https://github.com/AppSolves/codexbot/commit/9e602025fdb2ff5c2176584d0d40f1af58222118) preserves the exact assertions and workflow definitions; its diagnostic branch was removed after acceptance at the owner's request. The temporary canary secret and both test Environments were removed after successful completion. The production generator now combines named references with a required environment-free guard that rejects either global credential name. Regression tests execute its fail-closed script, enforce its dependency/permissions/boolean-only inputs and compare the manual example against the generator. Static tests do not implement or mock GitHub's secret resolver. `npm run check` (124 tests, typecheck, lint, build), `npm run test:clean`, actionlint for repository/generated/caller workflows and `git diff --check` passed. The production reusable workflow and Worker pin remain `4ed668864cac0682e09ec49a2515a6e1893a2780`. The real owning-repository credential/OIDC diagnostic must be freshly dispatched on its protected default branch after the caller PR receives normal approval and is merged. The canary probe does not establish that repository's OAuth session, broker admission or inference success. See [the caller-only migration](review-rollout.md#credential-diagnosis). diff --git a/src/cli.ts b/src/cli.ts index d51a44c..f8e4515 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -15,7 +15,7 @@ import { client, splitRepo } from './worker/github.js'; import { setupPullRequest, ensureProtectedEnvironment } from './setup.js'; import { backendUrl } from './runner/broker.js'; import { repositoryCapabilities } from './capabilities.js'; -import { credentialEnvironment, publishingEnvironment } from './core/identity.js'; +import { credentialEnvironment, publishingEnvironment, DEFAULT_BACKEND } from './core/identity.js'; import { formatCliError, requireCliResponse } from './cli-errors.js'; let operation = 'parsing command-line arguments'; @@ -76,7 +76,7 @@ async function main(): Promise { const command = parsed.positionals[0]; requireCondition(['setup', 'connect', 'connect-api-key', 'disconnect'].includes(command ?? ''), 'usage_setup_connect_connect_api_key_or_disconnect_with_repository_and_backend'); const repository = parsed.values.repository ?? ''; splitRepo(repository); - const backend = backendUrl(parsed.values.backend ?? ''); + const backend = backendUrl(parsed.values.backend ?? DEFAULT_BACKEND); operation = 'reading GitHub CLI authentication'; const token = await gh(['auth', 'token']); const github = client(token); diff --git a/src/core/identity.ts b/src/core/identity.ts index df8f937..b96c254 100644 --- a/src/core/identity.ts +++ b/src/core/identity.ts @@ -1,5 +1,7 @@ import { requireCondition } from './errors.js'; +export const DEFAULT_BACKEND = 'https://codexbot.appsolves.workers.dev'; + export function credentialEnvironment(installation: number, actor: number): string { requireCondition(Number.isSafeInteger(installation) && installation > 0 && Number.isSafeInteger(actor) && actor > 0, 'invalid_credential_owner'); return `codexbot-${installation}-${actor}`; diff --git a/src/setup.ts b/src/setup.ts index 6eafd3d..efa7851 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -4,6 +4,7 @@ import { DEFAULT_CONFIG } from './core/config.js'; import { requireCondition } from './core/errors.js'; import { splitRepo } from './worker/github.js'; import { repositoryCapabilities } from './capabilities.js'; +import { DEFAULT_BACKEND } from './core/identity.js'; export async function ensureProtectedEnvironment(github: Octokit, repository: string, name: string): Promise { const repo = splitRepo(repository); await repositoryCapabilities(github, repository); @@ -22,7 +23,7 @@ export async function ensureProtectedEnvironment(github: Octokit, repository: st await github.rest.repos.createOrUpdateEnvironment({ ...repo, environment_name: name, deployment_branch_policy: { protected_branches: false, custom_branch_policies: true } }); await github.rest.repos.createDeploymentBranchPolicy({ ...repo, environment_name: name, name: metadata.default_branch, type: 'branch' }); } -export function callerWorkflow(source: string, ref: string, backend: string): string { +export function callerWorkflow(source: string, ref: string, backend = DEFAULT_BACKEND): string { splitRepo(source); requireCondition(/^[a-f0-9]{40}$/.test(ref), 'workflow_ref_must_be_full_commit_sha'); return stringify({ name: 'CodexBot', 'run-name': 'CodexBot ${{ inputs.request_id }} ${{ inputs.dispatch_attempt }}', on: { workflow_dispatch: { inputs: { request_id: { description: 'Backend-bound request id', required: true, type: 'string' }, diff --git a/src/worker/index.ts b/src/worker/index.ts index 3159ddc..3b317ce 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -56,8 +56,13 @@ async function notify(env: Env, store: Store, snapshot: RequestSnapshot): Promis async function route(request: Request, env: Env): Promise { const url = new URL(request.url), store = new Store(env.DB); + const canonical = new URL(env.PUBLIC_URL).origin; + const publicPage = request.method === 'GET' && ['/', '/health'].includes(url.pathname); + // Retained custom domains are public landing/liveness aliases only. Never + // redirect credentials or accept a canonical audience through another host. + requireCondition(publicPage || url.origin === canonical, 'non_canonical_backend_origin', 421); const origin = request.headers.get('origin'); - requireCondition(!origin || origin === new URL(env.PUBLIC_URL).origin, 'cross_origin_request_denied', 403); + requireCondition(!origin || origin === canonical, 'cross_origin_request_denied', 403); if (url.pathname === '/health' && request.method === 'GET') return Response.json({ status: 'ok', version: '0.1.0' }); if (url.pathname === '/' && request.method === 'GET') return onboarding(env); if (url.pathname === '/v1/workload/check' && request.method === 'POST') { diff --git a/src/worker/onboarding.ts b/src/worker/onboarding.ts index f7e8664..600a3d0 100644 --- a/src/worker/onboarding.ts +++ b/src/worker/onboarding.ts @@ -2,12 +2,15 @@ import type { BackendConfig } from './webhook.js'; export function onboarding(env: BackendConfig): Response { const slug = /^[a-zA-Z0-9-]+$/.test(env.GITHUB_APP_SLUG) ? env.GITHUB_APP_SLUG : 'codexbot'; + const backend = new URL(env.PUBLIC_URL).origin.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!); return new Response(`Set up CodexBot +

CODEXBOT · CLI-ASSISTED SETUP

Your repository. Your review.

Reviews run on your GitHub Actions runners, using your own credentials. This service never receives your plaintext OpenAI credentials. This page is a checklist; account connection runs in the local CLI, not a hosted web wizard.

+

Backend: ${backend}. Use this exact origin for setup and credentials.

  1. Install the GitHub App and select repositories.
  2. -
  3. Use the source repository's CLI: npm run cli -- setup --repository OWNER/REPO --backend WORKER_URL --source OWNER/CODEXBOT --ref FULL_COMMIT_SHA. It opens a setup pull request for you to review. The default App permission profile omits Workflows write: use the documented manual installation or explicit temporary --setup-as-user fallback unless your operator has obtained a permission upgrade.
  4. -
  5. Choose ChatGPT or API-key authentication. Continue with ChatGPT uses the local CLI's official browser sign-in with a loopback callback. Run npm run cli -- connect --repository OWNER/REPO --backend WORKER_URL. For API-key mode use connect-api-key.
  6. +
  7. Use the source repository's CLI: npm run cli -- setup --repository OWNER/REPO --backend ${backend} --source OWNER/CODEXBOT --ref FULL_COMMIT_SHA. It opens a setup pull request for you to review. The default App permission profile omits Workflows write: use the documented manual installation or explicit temporary --setup-as-user fallback unless your operator has obtained a permission upgrade.
  8. +
  9. Choose ChatGPT or API-key authentication. Continue with ChatGPT uses the local CLI's official browser sign-in with a loopback callback. Run npm run cli -- connect --repository OWNER/REPO --backend ${backend}. For API-key mode use connect-api-key.
  10. Protect the default branch and the per-user credential Environment before connecting credentials. Private repositories require GitHub Pro, Team or Enterprise Environment support; the CLI probes this feature and never substitutes repository secrets. Merge the setup PR, then comment @codexbot review. Configure another alphanumeric handle in .codexbot.yml. Aliases are text commands and may notify an unrelated GitHub user with that name.

ChatGPT deployment authorization: ${env.CHATGPT_DEPLOYMENT_AUTHORIZED === 'true' ? 'operator attested' : 'disabled pending eligibility / hosted approval'}. Hosted plan usage requires OpenAI approval. Local OSS sign-in is not a hosted OAuth callback.

Automatic reviews are opt-in. Merge authorization is separate and disabled by default. API billing is separate from ChatGPT plan usage; there is no automatic fallback.

`, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); diff --git a/tests/backend.test.ts b/tests/backend.test.ts new file mode 100644 index 0000000..7f600e4 --- /dev/null +++ b/tests/backend.test.ts @@ -0,0 +1,37 @@ +import { test, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { parse } from 'yaml'; +import { DEFAULT_BACKEND } from '../src/core/identity.js'; +import { callerWorkflow } from '../src/setup.js'; +import { backendUrl, checkWorkload } from '../src/runner/broker.js'; +import { RELEASE } from './fixtures.js'; + +await test('hosted config, manifest and generated callers agree on Workers.dev while explicit self-hosted origins remain supported', async () => { + assert.equal(DEFAULT_BACKEND, 'https://codexbot.appsolves.workers.dev'); + const config = JSON.parse(await readFile('wrangler.jsonc', 'utf8')); + assert.equal(config.name, 'codexbot'); assert.equal(config.workers_dev, true); assert.equal(config.preview_urls, false); + assert.equal(config.vars.PUBLIC_URL, DEFAULT_BACKEND); assert.equal(config.vars.MERGE_DEPLOYMENT_AUTHORIZED, 'false'); + assert.equal(config.vars.TRUSTED_WORKFLOW, 'AppSolves/codexbot/.github/workflows/review.yml@4ed668864cac0682e09ec49a2515a6e1893a2780'); + assert.deepEqual(config.routes, [{ pattern: 'codexbot.appsolves.dev', custom_domain: true }]); + const manifest = JSON.parse(await readFile('app-manifest.json', 'utf8')); + assert.equal(manifest.url, DEFAULT_BACKEND); assert.equal(manifest.hook_attributes.url, `${DEFAULT_BACKEND}/webhook`); + assert.equal(manifest.setup_url, `${DEFAULT_BACKEND}/`); assert.equal(manifest.redirect_url, `${DEFAULT_BACKEND}/`); + const generated = parse(callerWorkflow('operator/codexbot', RELEASE)); assert.equal(generated.jobs.review.with.backend, DEFAULT_BACKEND); + const independent = parse(callerWorkflow('operator/codexbot', RELEASE, 'https://independent.invalid')); + assert.equal(independent.jobs.review.with.backend, 'https://independent.invalid'); + assert.deepEqual(independent.jobs['credential-scope'], generated.jobs['credential-scope']); + assert.deepEqual(independent.jobs.review.secrets, generated.jobs.review.secrets); + for (const invalid of ['http://plain.invalid', `${DEFAULT_BACKEND}/v1`, `${DEFAULT_BACKEND}?code=fixture`, 'https://user:password@host.invalid']) assert.throws(() => backendUrl(invalid)); +}); +await test('credential-only broker requests use the exact backend origin as OIDC audience, without redirects or fallback', async () => { + const saved = { ...process.env }, observed: string[] = []; + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = 'https://oidc.invalid/token'; process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'fixture-only'; + const intercepted = mock.method(globalThis, 'fetch', async (input: Parameters[0], init?: RequestInit) => { + const url = new URL(String(input)); assert.equal(init?.redirect, 'error'); + if (url.origin === 'https://oidc.invalid') { assert.equal(url.searchParams.get('audience'), DEFAULT_BACKEND); return Response.json({ value: 'fixture-jwt' }); } + observed.push(url.href); assert.equal(init?.method, 'POST'); return Response.json({ status: 'verified', scope: 'diagnostic_only' }); + }); + try { await checkWorkload(DEFAULT_BACKEND); assert.deepEqual(observed, [`${DEFAULT_BACKEND}/v1/workload/check`]); } + finally { intercepted.mock.restore(); for (const name of Object.keys(process.env)) if (!(name in saved)) delete process.env[name]; Object.assign(process.env, saved); } +}); diff --git a/tests/cli-errors.test.ts b/tests/cli-errors.test.ts index 03b581c..7305a28 100644 --- a/tests/cli-errors.test.ts +++ b/tests/cli-errors.test.ts @@ -1,11 +1,12 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, readdirSync, existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { formatCliError } from '../src/cli-errors.js'; import { AppError } from '../src/core/errors.js'; import { client } from '../src/worker/github.js'; +import { DEFAULT_BACKEND } from '../src/core/identity.js'; const secrets = ['ghp_' + 'a'.repeat(36), 'github_pat_' + 'b'.repeat(60), 'sk-proj-' + 'c'.repeat(60), 'opaque-oauth-code', 'opaque-refresh-token']; const sensitive = secrets.join(' ') + ' Authorization: Bearer password-value\n-----BEGIN PRIVATE KEY-----\u001b[31m'; @@ -75,7 +76,12 @@ childProcess.spawn = (file, args, options) => { syncBuiltinESMExports(); globalThis.fetch = async (input, init) => { const url = new URL(typeof input === 'string' ? input : input.url ?? input.href); - if (url.origin === 'https://broker.invalid' && url.pathname === '/v1/capabilities') { + if (url.origin === process.env.CODEXBOT_TEST_BACKEND && url.pathname === '/v1/setup' && scenario === 'setup-success') { + const body=JSON.parse(init.body); + if(body.source!=='operator/codexbot'||body.ref!=='d'.repeat(40))throw new Error('Unexpected setup source'); + return Response.json({pull_request:'https://github.com/owner/repo/pull/1'}); + } + if (url.origin === process.env.CODEXBOT_TEST_BACKEND && url.pathname === '/v1/capabilities') { if (scenario === 'backend-failure') return Response.json({error:${JSON.stringify(sensitive)}},{status:503}); return Response.json({environmentSecrets:true,installation_id:123,chatgpt_deployment_authorized:true}); } @@ -92,12 +98,16 @@ globalThis.fetch = async (input, init) => { } throw new Error('Unexpected fixture HTTP operation'); };`; -function runCli(scenario: string, command = 'connect') { +function runCli(scenario: string, command = 'connect', backend: string | null = 'https://broker.invalid') { const root = resolve('.local'); mkdirSync(root, { recursive: true }); const home = mkdtempSync(join(root, 'cli-errors-')); - const env = Object.assign(Object.create(null) as NodeJS.ProcessEnv, { CODEXBOT_TEST_SCENARIO: scenario, CODEXBOT_API_KEY: secrets[2]!, HOME: home, USERPROFILE: home }); + const env = Object.assign(Object.create(null) as NodeJS.ProcessEnv, { CODEXBOT_TEST_SCENARIO: scenario, CODEXBOT_TEST_BACKEND: backend ?? DEFAULT_BACKEND, CODEXBOT_API_KEY: secrets[2]!, HOME: home, USERPROFILE: home }); for (const name of ['PATH', 'Path', 'SystemRoot', 'WINDIR', 'TMP', 'TEMP']) if (process.env[name]) env[name] = process.env[name]!; - try { return spawnSync(process.execPath, ['--import', 'tsx', '--import', `data:text/javascript,${encodeURIComponent(preload)}`, 'src/cli.ts', command, '--repository', 'owner/repo', '--backend', 'https://broker.invalid'], { encoding: 'utf8', env, timeout: 20_000 }); } + try { + const result = spawnSync(process.execPath, ['--import', 'tsx', '--import', `data:text/javascript,${encodeURIComponent(preload)}`, 'src/cli.ts', command, '--repository', 'owner/repo', ...(backend ? ['--backend', backend] : []), ...(command === 'setup' ? ['--source', 'operator/codexbot', '--ref', 'd'.repeat(40)] : [])], { encoding: 'utf8', env, timeout: 20_000 }); + const profiles = join(home, '.config', 'codexbot'); + return { ...result, profiles: existsSync(profiles) ? readdirSync(profiles).filter(name => name.endsWith('.session.json')) : [] }; + } finally { assert.equal(dirname(home), root); rmSync(home, { recursive: true, force: true }); } } await test('actual connect reports Environment failure after successful capability preflight, with exit 1 and no secret output', () => { @@ -120,3 +130,16 @@ await test('OAuth discovery failure closes the callback listener and exits with assert.match(result.stderr, /discovering OpenAI OAuth configuration.*ENOTFOUND/); assert.equal(result.stdout, ''); noSecrets(result.stderr); }); +await test('actual CLI setup/connect defaults to Workers.dev, preserves self-hosted overrides and separates local OAuth profiles', () => { + for (const backend of [null, 'https://independent.invalid']) { + const setup = runCli('setup-success', 'setup', backend); + assert.equal(setup.status, 0, setup.stderr); assert.match(setup.stdout, /github.com\/owner\/repo\/pull\/1/); + const api = runCli('api-key-success', 'connect-api-key', backend); assert.equal(api.status, 0, api.stderr); + } + for (const backend of [null, 'https://retired.invalid']) { + const connected = runCli('oauth-discovery-failure', 'connect', backend); + assert.equal(connected.status, 1, connected.stderr); assert.match(connected.stderr, /discovering OpenAI OAuth configuration.*ENOTFOUND/); + assert.deepEqual(connected.profiles, [`${new URL(backend ?? DEFAULT_BACKEND).host}-2-5.session.json`]); + noSecrets(connected.stderr); + } +}); diff --git a/tests/crypto.test.ts b/tests/crypto.test.ts index d45a922..839e62b 100644 --- a/tests/crypto.test.ts +++ b/tests/crypto.test.ts @@ -1,8 +1,17 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createHmac } from 'node:crypto'; -import { verifyWebhook, randomSecret, seal, unseal } from '../src/core/crypto.js'; +import { verifyWebhook, randomSecret, seal, unseal, sessionBinding } from '../src/core/crypto.js'; +import { DEFAULT_BACKEND } from '../src/core/identity.js'; import { boundedBody } from '../src/worker/index.js'; +await test('backend migration cannot reuse or rebind old OAuth ciphertext even with the original vault key', async () => { + const oldBinding = sessionBinding('https://retired.invalid', 1, 2, 5), newBinding = sessionBinding(DEFAULT_BACKEND, 1, 2, 5); + const key = randomSecret(), encrypted = await seal({ refresh_token: 'fixture-only' }, key, oldBinding); + assert.deepEqual(await unseal(encrypted, key, oldBinding), { refresh_token: 'fixture-only' }); + await assert.rejects(unseal(encrypted, key, newBinding)); + const fresh = await seal({ refresh_token: 'fresh-fixture' }, key, newBinding); + await assert.rejects(unseal(fresh, key, oldBinding)); +}); await test('GitHub HMAC requires authentic bytes, valid secret and sha256 signature', async () => { const body = Buffer.from('{"sender":{"login":"alice"}}'), secret = 'fixture-webhook-secret'.repeat(2); const signature = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`; diff --git a/tests/worker.test.ts b/tests/worker.test.ts index 0a5505e..bc74578 100644 --- a/tests/worker.test.ts +++ b/tests/worker.test.ts @@ -5,16 +5,17 @@ import { generateKeyPair, exportPKCS8, exportJWK, SignJWT } from 'jose'; import worker from '../src/worker/index.js'; import { database } from './sqlite.js'; import { githubFixture } from './github-fixture.js'; -import { clean, RELEASE, WORKFLOW, HEAD, BASE } from './fixtures.js'; +import { clean, RELEASE, WORKFLOW, HEAD, BASE, snapshot } from './fixtures.js'; import { Store } from '../src/worker/store.js'; import { seal, randomSecret } from '../src/core/crypto.js'; +import { DEFAULT_BACKEND } from '../src/core/identity.js'; const keys = await generateKeyPair('RS256', { extractable: true }); const pem = await exportPKCS8(keys.privateKey), jwk = { ...await exportJWK(keys.publicKey), kid: 'fixture', use: 'sig', alg: 'RS256' }; -async function oidc(environment: string, overrides: Record = {}): Promise { +async function oidc(environment: string, overrides: Record = {}, audience = 'https://broker.invalid'): Promise { return new SignJWT({ repository: 'owner/repo', repository_id: '2', repository_owner_id: '3', actor: 'alice', actor_id: '5', event_name: 'workflow_dispatch', ref: 'refs/heads/main', ref_type: 'branch', workflow_ref: 'owner/repo/.github/workflows/codexbot.yml@refs/heads/main', workflow_sha: WORKFLOW, job_workflow_ref: `operator/codexbot/.github/workflows/review.yml@${RELEASE}`, job_workflow_sha: RELEASE, runner_environment: 'github-hosted', environment, sub: `repo:owner/repo:environment:${environment}`, run_id: '123', run_attempt: '1', jti: crypto.randomUUID(), ...overrides }) - .setProtectedHeader({ alg: 'RS256', kid: 'fixture' }).setIssuer('https://token.actions.githubusercontent.com').setAudience('https://broker.invalid').setIssuedAt().setNotBefore('0s').setExpirationTime('5m').sign(keys.privateKey); + .setProtectedHeader({ alg: 'RS256', kid: 'fixture' }).setIssuer('https://token.actions.githubusercontent.com').setAudience(audience).setIssuedAt().setNotBefore('0s').setExpirationTime('5m').sign(keys.privateKey); } function payload(body = '@codexbot review') { return { action: 'created', installation: { id: 1 }, repository: { id: 2, full_name: 'owner/repo' }, sender: { id: 5, login: 'alice', type: 'User' }, comment: { body, created_at: new Date().toISOString(), user: { id: 5 } }, issue: { number: 4, pull_request: {} } }; @@ -30,6 +31,43 @@ async function fixture(action: (env: Env, github: ReturnType fixture(async (env, f) => { + env.PUBLIC_URL = DEFAULT_BACKEND; + const endpoints: [string, string][] = [['/webhook','POST'], ['/v1/workload/check','POST'], ['/v1/capabilities','GET'], ['/v1/setup','POST'], + ['/v1/session','GET'], ['/v1/session','PUT'], ['/v1/session','DELETE'], ['/v1/operations','GET'], + ...['prepare','rotate','result','publish','release','failure','stage'].map(operation => [`/v1/requests/${snapshot().id}/${operation}`, 'POST'] as [string, string])]; + for (const [path, method] of endpoints) { + const response = await worker.fetch(new Request(`https://retired.invalid${path}`, { method, headers: { Origin: DEFAULT_BACKEND, 'X-Forwarded-Host': new URL(DEFAULT_BACKEND).host } }), env); + assert.equal(response.status, 421); assert.equal(response.headers.get('location'), null); + assert.deepEqual(await response.json(), { error: 'non_canonical_backend_origin' }); + } + assert.equal(f.calls.length, 0); + for (const path of ['/', '/health']) { + const response = await worker.fetch(new Request(`https://retired.invalid${path}`), env); assert.equal(response.status, 200); + if (path === '/') { + const page = await response.text(); assert.ok(page.includes(`--backend ${DEFAULT_BACKEND}`)); + assert.ok(page.includes(``)); assert.ok(!page.includes('WORKER_URL')); + } + } + env.PUBLIC_URL = 'https://retired.invalid'; + assert.equal((await worker.fetch(new Request(`${DEFAULT_BACKEND}/health`), env)).status, 200); + assert.equal((await worker.fetch(new Request(`${DEFAULT_BACKEND}/v1/session`), env)).status, 421); +})); +await test('canonical webhook HMAC and read-only OIDC work only with the exact new audience and Origin', async () => fixture(async (env, f) => { + env.PUBLIC_URL = DEFAULT_BACKEND; f.state.permission = 'admin'; f.state.runActor = { id: 5, type: 'User', login: 'alice' }; + const check = async (audience: string, origin = DEFAULT_BACKEND) => worker.fetch(new Request(`${DEFAULT_BACKEND}/v1/workload/check`, { + method: 'POST', headers: { Authorization: `Bearer ${await oidc('codexbot-1-5', {}, audience)}`, Origin: origin } + }), env); + assert.equal((await check('https://retired.invalid')).status, 401); + assert.equal((await check(DEFAULT_BACKEND, 'https://retired.invalid')).status, 403); + assert.equal((await check(DEFAULT_BACKEND)).status, 200); + const body = signed(payload(), env.GITHUB_WEBHOOK_SECRET); + const invalid = await worker.fetch(new Request(`${DEFAULT_BACKEND}/webhook`, { method: 'POST', headers: body.headers, body: '{}' }), env); + assert.equal(invalid.status, 401); + const valid = await worker.fetch(new Request(`${DEFAULT_BACKEND}/webhook`, { method: 'POST', headers: body.headers, body: await body.text() }), env); + assert.equal(valid.status, 202); + assert.equal((await env.DB.prepare('SELECT count(*) AS n FROM sessions').first<{ n: number }>())!.n, 0); +})); await test('signed webhook, OIDC preflight, committed result and separate publication work end to end', async () => fixture(async (env, f) => { const started = await worker.fetch(signed(payload(), env.GITHUB_WEBHOOK_SECRET), env); assert.equal(started.status, 202); const dispatch = f.calls.find(x => x.path.endsWith('/dispatches'))!; diff --git a/tests/workers-runtime.mjs b/tests/workers-runtime.mjs index 3167bab..0c664e2 100644 --- a/tests/workers-runtime.mjs +++ b/tests/workers-runtime.mjs @@ -33,6 +33,10 @@ try { assert.ok(ready, 'Local workerd did not start'); const body = '{}', delivery = randomUUID(); const post = signature => globalThis.fetch(`${origin}/webhook`, { method: 'POST', body, headers: { 'x-github-event': 'ping', 'x-github-delivery': delivery, 'x-hub-signature-256': signature } }); + const page = await globalThis.fetch(`${origin}/`); assert.equal(page.status, 200); assert.ok((await page.text()).includes(`--backend ${origin}`)); + const foreign = await globalThis.fetch(`${origin}/v1/session`, { headers: { Origin: 'https://retired.invalid' } }); + assert.equal(foreign.status, 403); assert.equal(foreign.headers.get('location'), null); + assert.equal((await globalThis.fetch(`${origin}/v1/session`)).status, 401); assert.equal((await post('sha256=' + '0'.repeat(64))).status, 401); const signature = 'sha256=' + createHmac('sha256', secret).update(body).digest('hex'); assert.equal((await post(signature)).status, 200); assert.equal((await post(signature)).status, 200); diff --git a/tests/workflows.test.ts b/tests/workflows.test.ts index 259d311..0e75c95 100644 --- a/tests/workflows.test.ts +++ b/tests/workflows.test.ts @@ -76,7 +76,7 @@ await test('cached builds are opt-in, source/input scoped, pinned and loaded onl assert.match(String(publish.if), /!inputs.credential_check_only/); }); await test('documentation local links resolve and Apache license is canonical', async () => { - const documents = ['README.md', 'CHANGELOG.md', 'docs/architecture.md', 'docs/authentication.md', 'docs/configuration.md', 'docs/deployment.md', 'docs/development.md', 'docs/installation.md', 'docs/security.md', 'docs/validation.md', 'docs/review-rollout.md', 'docs/operations.md', 'docs/acceptance.md', 'docs/remediation.md', 'SECURITY.md', 'CONTRIBUTING.md']; + const documents = ['README.md', 'CHANGELOG.md', 'docs/architecture.md', 'docs/authentication.md', 'docs/configuration.md', 'docs/deployment.md', 'docs/development.md', 'docs/installation.md', 'docs/security.md', 'docs/validation.md', 'docs/review-rollout.md', 'docs/origin-migration.md', 'docs/operations.md', 'docs/acceptance.md', 'docs/remediation.md', 'SECURITY.md', 'CONTRIBUTING.md']; for (const path of documents) { const text = await readFile(path, 'utf8'); for (const match of text.matchAll(/\]\(([^)]+)\)/g)) { diff --git a/wrangler.jsonc b/wrangler.jsonc index fa85e52..610e5a3 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -6,7 +6,7 @@ "compatibility_flags": [ "nodejs_compat" ], - "workers_dev": false, + "workers_dev": true, "preview_urls": false, "send_metrics": false, "routes": [ @@ -33,7 +33,7 @@ } }, "vars": { - "PUBLIC_URL": "https://codexbot.appsolves.dev", + "PUBLIC_URL": "https://codexbot.appsolves.workers.dev", "GITHUB_APP_ID": "5754181", "GITHUB_APP_SLUG": "codexbot-review", "TRUSTED_WORKFLOW": "AppSolves/codexbot/.github/workflows/review.yml@4ed668864cac0682e09ec49a2515a6e1893a2780",