diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c46414..ca41694 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Security and behavior changes +- Add primary Fully Autonomous merging (0 humans), optional Human-in-the-Loop (1–6), owner-opted-in merge-on-approval and a repository/installation-scoped live acceptance gate. Preserve GitHub protections, native approval and exact-head checks. +- Add explicit CLI consent and protected repository assignment for unattended reviews of authorized contributors without provider accounts. Migration 0006 scopes grants by installation/repository/owner and fences each consent generation through leases, refresh and privileged publication. Manual commands never borrow an assigned connection. +- Make CLI provisioning the current public onboarding path; browser OAuth remains deferred and disabled until its separate client is provisioned. + - Admission feedback: precise atomic quota/duplicate/cooldown/concurrency outcomes, calculated UTC retry times and durable App-owned rejection comments; deterministic denials no longer churn webhook retries. Additive migration 0005 and bounded ambiguity-safe publication recovery. ## Unreleased — security remediation pass diff --git a/README.md b/README.md index 6f5d694..1b7d9cd 100644 --- a/README.md +++ b/README.md @@ -18,26 +18,28 @@ Set `bot.trigger: "@CBReview"` to use the example above. The legacy default `@co ## Status -**Pre-release.** The existing production review pipeline is operational; this change preserves it. The browser onboarding and management flow is implemented and tested locally against real workerd/D1 with synthetic GitHub/OpenAI providers. It remains disabled until the operator provisions the actual approved website OAuth client, callbacks, inference scopes and workspace claim, then completes staged acceptance. No production deployment follows from a PR or local test. +**Release acceptance in progress.** The existing production review pipeline is operational. The browser onboarding and management flow is implemented and tested locally against real workerd/D1 with synthetic GitHub/OpenAI providers. It remains disabled until the operator provisions the actual approved website OAuth client, callbacks, inference scopes and workspace claim, then completes staged acceptance. No production deployment follows from a PR or local test. -See [web onboarding, credentials and activation](docs/web-onboarding.md) for the explicit hosted credential trust boundary and remaining live gates. AI reviews can miss defects; keep independent human review and CI. Automatic merging remains disabled. +See [web onboarding, credentials and activation](docs/web-onboarding.md) for the explicit hosted credential trust boundary and remaining live gates. AI reviews can miss defects; keep required CI and choose human oversight according to repository policy. Automatic merging remains disabled. ## What is implemented -- Browser GitHub PKCE sign-in, installation reconciliation, responsive repository dashboard, reviewed setup/configuration PRs and approved-client hosted ChatGPT OAuth with encrypted Environment provisioning; signed webhook intake, installation suspension/deletion handling and replay protection. +- Signed webhook intake, installation lifecycle handling, replay protection, durable admission feedback and isolated review execution. - Configurable handle and command parser, default-deny whitelist/blacklist policy, RE2 matching, live GitHub identity/permission checks, separate merge policy. - ChatGPT OSS OAuth with PKCE, state, nonce, issued-client/account validation, encrypted session provisioning, persistent host IDs, serialized refresh and token rotation/revocation. - Independent personal API-key mode; no billing fallback between modes. - Official Codex app-server, model-catalog effort validation and JSON-schema output validation. - Read-only, resource-limited review container with **no network namespace connectivity and no credentials**. A Unix-socket proxy injects credentials only into fixed OpenAI Responses requests. -- Separate publishing job, native inline reviews, exact-commit checks, conservative approvals, and explicitly requested native exact-head merge; pending CI is held behind an App-bound required check and durable intent. +- Separate publishing job, native inline reviews, exact-commit checks, conservative approvals, and owner-opted-in or explicitly requested native exact-head merge; pending CI is held behind an App-bound required check and durable intent. - App-authored setup PR when Workflows permission is granted; a temporary user-credential setup alternative and manual installation. -## Browser setup +## Installation -When the operator has activated web onboarding, open the [website](https://codexbot.appsolves.workers.dev/), sign in with GitHub, install/select repositories through GitHub, choose a repository you administer, create its setup PR and connect ChatGPT or your own API key. Review and merge the PR; refresh to verify readiness. Settings propose further PRs, never silent default-branch commits. Normal onboarding requires no terminal. Public repositories support protected Environments on GitHub Free; private repositories require suitable Pro/Team/Enterprise support. Existing CLI connections remain compatible and need an explicit disconnect before switching management mode. +This release uses **CLI-based ChatGPT connection during initial setup**. Install the GitHub App, protect the default branch, create/merge the pinned caller setup PR, and connect the repository administrator's account with the commands below. Subsequent reviews, approvals and merges run unattended on GitHub Actions; no personal computer or running CLI is required. -## CLI and self-hosted setup +Browser onboarding and browser ChatGPT connection remain deferred: `WEB_ENABLED=false` and `OPENAI_HOSTED_INFERENCE_AUTHORIZED=false`. The separate website OAuth client has not been provisioned. The approved existing CLI deployment remains supported; do not copy its client registration into website settings. + +## CLI setup and self-hosting Requirements: Node 24+, GitHub CLI (`gh auth login`), a GitHub App/Worker deployment, a protected default branch, and GitHub-hosted Ubuntu runners with Docker. The onboarding CLI currently requires repository administrator access to create/protect credential Environments. Windows/macOS can run onboarding; production review orchestration runs on Linux. @@ -67,7 +69,15 @@ npm run cli -- connect --repository OWNER/REPO --backend https://codexbot.appsol 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. +The ChatGPT flow displays an official **Continue with ChatGPT** 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. + +For automatic reviews of authorized contributors without provider accounts, the administrator explicitly provisions a repository-scoped assignment once: + +```sh +npm run cli -- connect --repository OWNER/REPO --backend https://codexbot.appsolves.workers.dev --allow-automatic-reviews +``` + +Then propose `review.auto_review: true` and `credentials.automatic_reviewer: YOUR_LOGIN` in the protected configuration. The event actor must still pass the review policy; allow the intended contributors explicitly. Quotas are charged to the consenting credential owner. Manual commands never borrow that connection. See [unattended credential consent](docs/configuration.md#unattended-credential-consent). 5. Review and merge the setup PR. Configure whitelist/merge policies and an optional custom handle in `.codexbot.yml`. Protect both the default branch and credential/publishing Environments. Comment using the handle from your setup PR. New setup chooses `@CBReview` to reduce collisions; existing/manual `@codexbot` configurations remain supported. @@ -77,17 +87,17 @@ Accepted requests receive one editable App-owned progress comment, separate from OpenAI documents dynamic registration for OSS/local integrations and a local-to-self-hosted credential transfer. **Paid/remotely hosted ChatGPT-plan integrations require additional OpenAI authorization.** This repository does not infer that ephemeral GitHub Actions or a centrally operated public service is automatically covered. The Worker rejects ChatGPT requests until the operator sets `CHATGPT_DEPLOYMENT_AUTHORIZED=true` after establishing deployment eligibility. See [authentication](docs/authentication.md) and the [official OSS guide](https://developers.openai.com/siwc/token-sharing-open-source). -That gate does not affect API-key mode. The Worker has no OpenAI key and cannot spend the operator's personal allowance for users. +That gate does not affect API-key mode. The Worker has no shared OpenAI key. Unattended reviews may use a repository administrator’s own connection only after explicit CLI consent and trusted repository assignment; no implicit credential fallback exists. ## Configuration -See [the reference](docs/configuration.md) and [example](examples/codexbot.yml). Configuration comes from the default branch, never the PR. A clean, complete result can approve; sufficiently confident high/critical findings request changes; uncertain, incomplete or advisory results comment. Quotas, cooldowns and explicit bounded --rerun prevent repeated unbounded reviews. Automatic reviews and merge are opt-in. `--merge` cannot bypass GitHub protections. +See [the reference](docs/configuration.md) and [example](examples/codexbot.yml). Configuration comes from the default branch, never the PR. A clean, complete result can approve; sufficiently confident high/critical findings request changes; uncertain, incomplete or advisory results comment. Quotas, cooldowns and explicit bounded --rerun prevent repeated unbounded reviews. Automatic reviews and merging are opt-in. Fully Autonomous uses `merge.auto_merge_on_approval: true` and `minimum_human_approvals: 0`; Human-in-the-Loop adds 1–6 independent human approvals. With automatic merging off, `--merge` remains the explicit request. Both modes honor GitHub protections and the separate merge whitelist. See [supported merge-mode protection settings](docs/configuration.md#merge-modes). ## Development and security [Architecture](docs/architecture.md) · [Threat model](docs/security.md) · [Development](docs/development.md) · [Validation](docs/validation.md) · [Security reporting](SECURITY.md) · [Contributing](CONTRIBUTING.md) -AI review can miss defects and is vulnerable to semantic prompt manipulation. Isolation protects credentials and GitHub capabilities; it cannot prove that a model's clean verdict is correct. Keep independent required CI and human review rules. Context limits intentionally disable approval when coverage is limited. +AI review can miss defects and is vulnerable to semantic prompt manipulation. Isolation protects credentials and GitHub capabilities; it cannot prove that a model's clean verdict is correct. Keep required CI and choose additional human review rules according to your repository policy. Context limits intentionally disable approval when coverage is limited. ## Security remediation and release gates diff --git a/SECURITY.md b/SECURITY.md index 9e33e2b..7e99dfe 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,6 +8,6 @@ Include the affected immutable release, boundary violated, a minimal fixture-bas If a credential is exposed: stop workflow dispatch, revoke the credential with its provider, suspend the affected installation if needed, rotate App/webhook keys or Environment secrets as appropriate, and inspect authorized metadata privately. Removing a log or git commit does not revoke credentials or erase previous disclosure. -Recovery and release gates: [operations](docs/operations.md), [acceptance](docs/acceptance.md), [finding evidence](docs/remediation.md). The deterministic local output scanner reduces leakage risk but cannot detect all secrets or encodings. A clean AI verdict is not a security guarantee; independent human reviews and CI remain required. Disable/cancel App-owned auto-merge in GitHub during an incident; stopping the Worker alone does not cancel a previously enabled native intent. +Recovery and release gates: [operations](docs/operations.md), [acceptance](docs/acceptance.md), [finding evidence](docs/remediation.md). The deterministic local output scanner reduces leakage risk but cannot detect all secrets or encodings. A clean AI verdict is not a security guarantee; required CI and repository protection remain enforced; independent human review is configurable, and any GitHub human-review requirement still applies. Disable/cancel App-owned auto-merge in GitHub during an incident; stopping the Worker alone does not cancel a previously enabled native intent. Browser-managed OAuth introduces an explicit trusted Worker decryption boundary; CLI vaults retain their existing isolation. See [hosted security and key management](docs/web-onboarding.md). Report website/session/CSRF/provisioning issues privately. Include only fixed error codes and synthetic reproductions; never submit callback URLs, browser cookies, exported D1 credentials or raw traces. diff --git a/app-manifest.json b/app-manifest.json index 8373c34..d648250 100644 --- a/app-manifest.json +++ b/app-manifest.json @@ -8,6 +8,6 @@ "public": true, "request_oauth_on_install": false, "setup_on_update": true, - "default_permissions": { "metadata": "read", "contents": "write", "pull_requests": "write", "actions": "write", "workflows": "write", "administration": "write", "environments": "write" }, + "default_permissions": { "metadata": "read", "contents": "write", "pull_requests": "write", "actions": "write", "checks": "write", "workflows": "write", "administration": "write", "environments": "write" }, "default_events": ["issue_comment", "pull_request"] } diff --git a/docs/acceptance.md b/docs/acceptance.md index ddaea59..9671798 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -42,7 +42,7 @@ Perform each mutation through reviewed disposable configuration/PR changes. Do n | Advisory/uncertain/binary/large/truncated/essential-context missing | COMMENT and no merge; irrelevant supplementary omissions alone do not invalidate a tiny PR | | Head/base/default-policy/source pin changes during review | Old result cannot approve or merge the new context; new request required | | Review accepted then response lost / publisher crash | Reconcile same pending/submitted App review; no duplicate approval; merge separate | -| Ready protected PR, passing required CI and current independent humans | Native expected-head merge only after separate merge authorization and explicit --merge | +| Ready protected PR, passing required CI and the mode/GitHub-required independent humans | Native expected-head merge only after separate merge authorization and explicit --merge or admitted automatic policy intent | | Pending required CI with App-bound required guard | Native intent may queue; guard stays pending; backend rechecks before disabling intent/releasing guard/final guarded merge | | Known failed/missing/unknown CI, conflicts or required human missing | No merge; no native intent when failure/human denial is known | | Bot approval would otherwise satisfy human count | Independent exact-head non-author humans still required at configured/branch/ruleset minimum | @@ -51,7 +51,7 @@ Perform each mutation through reviewed disposable configuration/PR changes. Do n | Required merge queue | Explicit manual-only outcome; no direct merge or queue bypass | | Two installations, same repository/actor history | Installation-bound session lookup/lease/AAD; old ciphertext cannot be used in the new installation | -Enable MERGE_DEPLOYMENT_AUTHORIZED only after recording the applicable rows as passed, then opt in repository policy and the separate whitelist. The check source must be this App's ID (REST app_id / ruleset integration_id), not any integration. For human approvals, count current-head APPROVED reviews from distinct write-capable users other than the author. Include CODEOWNERS, stale-approval dismissal and rulesets in the live matrix; bot approval is never counted as a human. +Enable MERGE_DEPLOYMENT_AUTHORIZED only after recording the applicable rows as passed, then opt in repository policy and the separate whitelist. The check source must be this App's ID (REST app_id / ruleset integration_id), not any integration. When human approvals are required by the selected mode or GitHub, count current-head APPROVED reviews from distinct write-capable users other than the author. Include CODEOWNERS, stale-approval dismissal and rulesets in the live matrix; bot approval is never counted as a human. ## Optional real OpenAI protocol acceptance diff --git a/docs/configuration.md b/docs/configuration.md index 206ea31..aeab38a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -19,12 +19,14 @@ See [the complete example](../examples/codexbot.yml). | review.effort | null | Effective Codex model default; no override | | review.blocking_confidence | 0.9 | Critical/high threshold, range 0.5–1 | | review.advisory_confidence | 0.7 | Advisory versus manual-verification label, at most blocking threshold | -| merge.enabled | false | Explicit --merge may request a guarded merge | +| merge.enabled | false | Owner opt-in to guarded merging; separate merge authorization always applies | +| merge.auto_merge_on_approval | false | Owner opt-in to merging after an eligible authorized clean review; otherwise --merge is required | | merge.method | squash | squash, merge, rebase | | merge.authorization.* | empty / * | Independent policy plus live write/maintain/admin role | -| merge.minimum_human_approvals | 1 | Current-head approvals by distinct non-author humans with write access; maximum 6 | +| merge.minimum_human_approvals | 0 | Fully Autonomous: 0; Human-in-the-Loop: 1–6 current-head approvals by distinct non-author humans with write access. Stricter GitHub rules still apply | | merge.guard_check | CodexBot reviewed commit | For pending CI, a required check bound to this App's numeric ID | | credentials.mode | chatgpt | chatgpt or api-key; no fallback | +| credentials.automatic_reviewer | null | Explicitly consenting administrator login for PR-event reviews; no manual-command credential sharing | | quotas.user_per_day | 10 | Sliding 24-hour count per installation/actor | | quotas.repository_per_day | 40 | Sliding repository count | | quotas.installation_per_day | 200 | Sliding installation count | @@ -67,3 +69,36 @@ Supplementary coverage is reported separately and does not alone disable approva ## Browser settings The repository dashboard renders the same canonical fields, validates syntax/policy/thresholds and the generated pinned Codex model/effort catalog, and creates a reviewed configuration/workflow PR against the exact default-branch commit shown. Active settings remain unchanged until merge. Unsupported selections fail explicitly; model membership does not establish actual account entitlement. Existing configurations are not silently rewritten. Suspected secrets in a proposed policy are rejected before GitHub writes. Credentials are connected separately to the owning protected Environment, never YAML. + +## Merge modes + +Fully Autonomous is the primary mode. It requires explicit owner opt-in: + +```yaml +merge: + enabled: true + auto_merge_on_approval: true + minimum_human_approvals: 0 + method: squash + authorization: + whitelist: AppSolves # Replace with authorized requesters; review permission alone is insufficient. + blacklist: "*" +``` + +Human-in-the-Loop uses the same configuration with `minimum_human_approvals: 1` through `6`. Each counted human must be independent of the PR author, approve the exact current head and currently have write access. Native AI approval is never counted as a human. The default disables merging and automatic merge-on-approval; choosing a mode alone does not enable either. Missing required humans leaves a bounded durable intent for cron reconciliation, with native auto-merge disabled. A later qualifying real approval resumes the same review without another inference. Known failed checks and changes requested remain non-merging outcomes. + +With automatic merge-on-approval disabled, only an authorized `--merge` can request merging. With it enabled, a separately merge-authorized review/event actor receives a durable automatic intent at admission. Review-only actors still receive reviews but cannot cause merging. The publisher, retries, cancellation and recovery use that same intent, recheck current authorization/policy/credentials and require a genuine native APPROVE. Any finding, incomplete analysis or failed check prevents merging. + +Compatible autonomous GitHub protection requires a protected PR-only default branch and required CI, with no bot/admin bypass. Set GitHub's required human approval count to zero and do not require CODEOWNER or last-push approval if no human will participate. CodexBot conservatively honors the larger configured/branch/ruleset count; CODEOWNER or last-push requirements impose at least one independent human. Keep signature and other rules enabled when desired: GitHub's native expected-head merge remains the final authority and does not bypass them. Required merge queues remain unsupported/manual. Pending CI requires the guard check bound to this App's numeric ID, Checks write and Administration read. Unknown evidence never authorizes merging. + +Without an explicit assignment, automatic PR events use the authorized event actor’s own connection. The assignment below permits unattended reviews of authorized contributors without their own provider connection. + +## Unattended credential consent + +The owner/administrator connects their own credential for this repository with `--allow-automatic-reviews`. The authenticated provisioning endpoint records only that administrator's explicit consent in migration 0006, after checking the protected default branch, default-branch-only Environment and named credential metadata. Trusted configuration separately opts in with `credentials.automatic_reviewer: OWNER_LOGIN` and `review.auto_review: true`. Configuration alone cannot authorize borrowing. Both ChatGPT and API-key modes remain explicit and independent. + +The incoming PR-event actor still needs review authorization under `authorization`; use an appropriate whitelist, including `"*"` only when all read-capable contributors are intentionally authorized. Verified GitHub Bot actors are supported only with this explicit assignment; manual bot commands remain denied. Responsible owner identity, original trigger identity and the consent generation are snapshotted separately. The owner must remain an administrator and pass the review policy; merging additionally requires the owner's separate merge policy and an admitted automatic merge intent. No human approval is fabricated: GitHub reviews use the App identity. + +The protected runner Environment, encryption AAD, session lease and all user quotas bind to the consenting owner, installation and repository. Contributions cannot spread usage across actor IDs or select another user's Environment. Owner credentials are never returned to contributors or placed in the model container. Manual commands always use the command author's own connection, even when unattended assignment is enabled. + +Revoking/disconnecting consent, replacing the connection, changing the configured owner/mode or losing administrator authority stops new delegated execution and privileged publication. Refresh and publication lease SQL fence the exact consent generation, so reauthorizing the same owner cannot revive an old merge intent. Already started inference may have consumed usage; revocation does not undo it. Configure `automatic_reviewer: null` through a reviewed PR to stop assignment; disconnect the owner connection to revoke its stored grant. No CLI process is needed after provisioning. diff --git a/docs/installation.md b/docs/installation.md index f8e7e74..124fe5d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,6 +1,6 @@ -# Repository installation and browser onboarding +# Repository installation and CLI provisioning -Use the website's Get Started flow for GitHub sign-in, native App installation/repository selection, verified repository setup, credential connection and policy management. The browser implementation is opt-in until the operator completes [hosted registration and activation](web-onboarding.md). Existing configured repositories are reconciled live; setup and policy updates create PRs for review. The CLI below remains an independent/self-hosted and recovery alternative, not a requirement for normal browser onboarding. +This release uses the CLI once for credential provisioning. Install/select the GitHub App, protect the default branch, create and merge the workflow/configuration setup PR, then connect ChatGPT using the commands below. Ongoing automatic reviews and merges run on GitHub Actions without a running CLI or personal machine. Browser OAuth is deferred; WEB_ENABLED and OPENAI_HOSTED_INFERENCE_AUTHORIZED remain false until the separate website client is provisioned. 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. @@ -93,4 +93,6 @@ Disconnect retrieves/revokes the latest ChatGPT session, deletes the encrypted r ## Verify before enabling privileges -Run [advisory acceptance](acceptance.md), then independently enable approval if appropriate. Merge needs a separate whitelist, human approvals, protected branch, explicit --merge and the operator's deployment acceptance gate. Pending CI also requires the App-bound required guard and optional merge permissions. Ready PRs use a native exact-head merge. Unknown/conflicting/queue states are manual-only; the bot never bypasses protections. +Run [advisory acceptance](acceptance.md), then independently enable approval if appropriate. Merge needs a separate whitelist, protected branch, either explicit --merge or owner-opted-in automatic merge-on-approval, and the operator's deployment acceptance gate. Choose Fully Autonomous (0 humans) or Human-in-the-Loop (1–6); stricter GitHub human requirements remain enforced. Pending CI also requires the App-bound required guard and optional merge permissions. Ready PRs use a native exact-head merge. Unknown/conflicting/queue states are manual-only; the bot never bypasses protections. + +For unattended reviews from authorized contributors without provider accounts, connect the administrator's own repository credential with `--allow-automatic-reviews`, then opt into `credentials.automatic_reviewer: YOUR_LOGIN` and `review.auto_review: true` through protected configuration. The event actor still passes the repository review policy. Never copy another repository's vault, refresh token or Environment secrets. See [explicit credential consent](configuration.md#unattended-credential-consent). diff --git a/docs/operations.md b/docs/operations.md index 74af77c..1167c90 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -9,7 +9,7 @@ Migration 0003 adds leased progress-comment recovery and sanitized failure/run m 3. Migration 0002 adds receipt/outbox and publication state, quotas and a session table keyed by installation/repository/actor. It invalidates legacy in-flight requests. The old encrypted session table is quarantined and purged at the first cleanup. **Every ChatGPT user must reconnect**; the Worker cannot safely re-encrypt old AAD without their key. Reuse the local issued client/host profile, not a shared token. Revoke superseded sessions in ChatGPT settings if needed. Existing API-key secrets remain in their old GitHub Environments but are never reused automatically. All users, including API-key users, must explicitly provision the new installation-scoped Environment; then remove/revoke obsolete secrets. 4. Deploy the reviewed new Worker and select a real immutable source commit. Update each caller workflow through a reviewed PR: add required string inputs `dispatch_attempt` and `installation_id`, pass installation_id to the reusable workflow, and run-name `CodexBot ${{ inputs.request_id }} ${{ inputs.dispatch_attempt }}`. Keep the new reusable workflow pinned and match backend TRUSTED_WORKFLOW. Old dispatch inputs/workflow names intentionally cannot acquire credentials under the new attempt-binding protocol. 5. Keep CHATGPT_DEPLOYMENT_AUTHORIZED and MERGE_DEPLOYMENT_AUTHORIZED false until their separate external gates pass. Reconnect using the CLI's capability/installation preflight. Private Free repositories cannot store credentials through this topology. Protect the default branch first; preserve Environment reviewers and set a default-branch-only custom deployment policy. -6. Complete advisory acceptance in a disposable repository before re-enabling normal approvals. Automated merge now requires an independently approved human review and protected branch. For pending CI, configure the App-bound required guard and explicitly consent to Checks write/Administration read. Do not grant bypass rights. +6. Complete advisory acceptance in a disposable repository before re-enabling normal approvals. Automated merge requires a protected branch and the selected merge mode: zero independent humans in compatible autonomous repositories, or the configured/GitHub-required human approvals. For pending CI, configure the App-bound required guard and explicitly consent to Checks write/Administration read. Do not grant bypass rights. ## Recovery state machines @@ -68,3 +68,11 @@ GitHub issue-comment POST has no idempotency key. Before POST, the outbox durabl Inspect safe state with `SELECT id,outcome,phase,attempts,comment_id,retry_at FROM review_rejections`; do not select identity/payload/session data into logs. After an ambiguous terminal failure, inspect App-owned comments before any manual response; do not reset `creating` to `pending`. Recovery of an already-recorded denial never re-enters admission. Old deliveries without a durable outcome still obey the original freshness checks and must not be revived to start inference. After normal protected source merge, run `scripts/prepare-pin-upgrade.mjs` first with `--check-only`, then without it, using the actual source PR number. Merge both reviewed pin PRs, apply migration 0005, and deploy the new Worker with existing gates preserved. Verify version details, pins, `/health`, a fresh authorized exhausted-quota comment and the terminal delivery/outbox state. No paid inference or quota reset is needed for this test. + +## Autonomous release acceptance and owner consent + +Apply additive migration 0006 before deploying the owner-consent code. CLI session encryption/AAD and existing owner connections remain unchanged. New unattended assignment requires a fresh explicit `--allow-automatic-reviews` consent for the owning repository and trusted `credentials.automatic_reviewer`; no copied credentials or secret export is supported. A reconnect clears prior consent, refresh preserves it, and each new consent generation invalidates old automatic intents. + +While `MERGE_DEPLOYMENT_AUTHORIZED=false`, the operator can temporarily configure **both** `MERGE_ACCEPTANCE_REPOSITORY_ID` and `MERGE_ACCEPTANCE_INSTALLATION_ID` for the one disposable acceptance repository. Empty/missing or mismatched scope remains closed. The caller cannot supply this scope. All normal review, native approval, owner consent, merge authorization, OIDC, GitHub rules, exact-head and CI checks still apply. This permits a real happy-path test before globally authorizing merging. Clear the temporary scope after acceptance; enable the global gate only after the required live evidence passes. Keep browser and hosted website inference flags false for the CLI release. + +No human approval is required by CodexBot in Fully Autonomous mode when the compatible GitHub rules also require zero humans. Human-in-the-Loop and stricter GitHub review/CODEOWNER/last-push requirements are independently enforced. Never relax valuable-repository protection or manufacture a reviewer to complete a live gate. If an actual account sign-in or independent reviewer is unavailable, record that exact acceptance as blocked and complete independent validation/deployment; do not publish a verified full release. diff --git a/examples/codexbot.yml b/examples/codexbot.yml index 93236a0..edcfb7c 100644 --- a/examples/codexbot.yml +++ b/examples/codexbot.yml @@ -16,14 +16,16 @@ review: advisory_confidence: 0.7 merge: enabled: false + auto_merge_on_approval: false # Explicit opt-in; otherwise --merge is required. method: squash - minimum_human_approvals: 1 + minimum_human_approvals: 0 # Fully Autonomous. Use 1–6 for Human-in-the-Loop. guard_check: "CodexBot reviewed commit" authorization: whitelist: "" blacklist: "*" credentials: mode: chatgpt # Or api-key. No automatic paid fallback. + automatic_reviewer: null # Administrator login, after explicit --allow-automatic-reviews consent. quotas: user_per_day: 10 repository_per_day: 40 diff --git a/migrations/0006_automatic_review_grants.sql b/migrations/0006_automatic_review_grants.sql new file mode 100644 index 0000000..de76fad --- /dev/null +++ b/migrations/0006_automatic_review_grants.sql @@ -0,0 +1,8 @@ +-- Explicit administrator consent; no tokens, keys or sessions are copied. +CREATE TABLE automatic_review_grants ( + installation_id INTEGER NOT NULL, repository_id INTEGER NOT NULL, + id TEXT NOT NULL UNIQUE, actor_id INTEGER NOT NULL, actor TEXT NOT NULL, + credential_mode TEXT NOT NULL CHECK(credential_mode IN ('chatgpt','api-key')), + granted_at INTEGER NOT NULL, + PRIMARY KEY(installation_id,repository_id) +); diff --git a/src/cli.ts b/src/cli.ts index f8e4515..48550a0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -72,7 +72,7 @@ async function login(oauth: OAuth, profile: Profile, persist: () => Promise { - const parsed = parseArgs({ allowPositionals: true, options: { repository: { type: 'string' }, backend: { type: 'string' }, source: { type: 'string' }, ref: { type: 'string' }, 'setup-as-user': { type: 'boolean', default: false }, 'new-account': { type: 'boolean', default: false } } }); + const parsed = parseArgs({ allowPositionals: true, options: { repository: { type: 'string' }, backend: { type: 'string' }, source: { type: 'string' }, ref: { type: 'string' }, 'setup-as-user': { type: 'boolean', default: false }, 'new-account': { type: 'boolean', default: false }, 'allow-automatic-reviews': {type:'boolean',default:false} } }); 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); @@ -111,12 +111,20 @@ async function main(): Promise { // Existing restrictions are preserved; disconnect must remain possible without creating an Environment. if (command !== 'disconnect') for (const name of [environment, publishingEnvironment(Number(capability.installation_id))]) { operation = name === environment ? 'configuring the protected credential Environment' : 'configuring the protected publishing Environment'; - await ensureProtectedEnvironment(github, repository, name); + await ensureProtectedEnvironment(github, repository, name,undefined,parsed.values['allow-automatic-reviews']); } + const consent=async(enabled:boolean,mode:'chatgpt'|'api-key')=>{ + operation=enabled?'authorizing unattended reviews with this repository-owned connection':'revoking unattended credential assignment'; + const response=await fetch(`${backend}/v1/session?repository=${encodeURIComponent(repository)}`,{method:'POST',headers:{Authorization:`Bearer ${token}`,'Content-Type':'application/json'},body:JSON.stringify({enabled,mode}),redirect:'error',signal:AbortSignal.timeout(15000)}); + requireCliResponse(response,'automatic_review_consent_failed'); + if(enabled)process.stdout.write(`Automatic PR-event reviews explicitly authorized for ${repository} using your connection. Set credentials.automatic_reviewer to ${user.login} through the trusted configuration. Manual commands never borrow this connection.\n`); + }; if (command === 'connect-api-key') { + await consent(false,'api-key'); operation = 'storing the API key in the credential Environment'; requireCondition(process.env.CODEXBOT_API_KEY && !/[\r\n]/.test(process.env.CODEXBOT_API_KEY), 'set_CODEXBOT_API_KEY_in_process_environment'); await gh(['secret', 'set', 'CODEXBOT_API_KEY', '--repo', repository, '--env', environment], process.env.CODEXBOT_API_KEY); + if(parsed.values['allow-automatic-reviews'])await consent(true,'api-key'); process.stdout.write(`API key saved in ${environment}. Set credentials.mode to api-key in .codexbot.yml. Remove any old CODEXBOT_VAULT_KEY secret before switching modes. Billing is separate from ChatGPT.\n`); return; } const stateDirectory = join(homedir(), '.config', 'codexbot'); @@ -174,6 +182,7 @@ async function main(): Promise { // Rotation belongs exclusively to the remote runtime from now on. Retain only registration/key/host locally. operation = 'clearing local tokens after session provisioning'; profile.session = null; delete profile.pendingClient; await atomicPrivateFile(path, profile); + if(parsed.values['allow-automatic-reviews'])await consent(true,'chatgpt'); const label = [...(session.email ?? session.subject)].filter(x => x.charCodeAt(0) >= 32 && x.charCodeAt(0) !== 127).join(''); process.stdout.write(`ChatGPT account ${label} (${session.client_id}) connected for ${user.login} in ${repository}. Account/workspace access to the selected model is verified by the first successful inference, not by the model catalog. Remove any old CODEXBOT_API_KEY secret before switching modes.\n`); }); diff --git a/src/core/config.ts b/src/core/config.ts index 32ed952..38531b1 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -11,15 +11,15 @@ export interface Config { bot: { trigger: string; aliases: string[] }; authorization: Policy; review: { enabled: boolean; auto_review: boolean; auto_approve: boolean; request_changes: boolean; model: string | null; effort: Effort | null; blocking_confidence: number; advisory_confidence: number }; - merge: { enabled: boolean; method: 'squash' | 'merge' | 'rebase'; authorization: Policy; minimum_human_approvals: number; guard_check: string }; - credentials: { mode: 'chatgpt' | 'api-key' }; + merge: { enabled: boolean; auto_merge_on_approval: boolean; method: 'squash' | 'merge' | 'rebase'; authorization: Policy; minimum_human_approvals: number; guard_check: string }; + credentials: { mode: 'chatgpt' | 'api-key'; automatic_reviewer: string | null }; quotas: { user_per_day: number; repository_per_day: number; installation_per_day: number; concurrent_repository: number; concurrent_installation: number; cooldown_seconds: number; reruns_per_day: number }; } export const DEFAULT_CONFIG: Config = { version: 1, bot: { trigger: '@codexbot', aliases: [] }, authorization: { whitelist: '', blacklist: '*' }, review: { enabled: true, auto_review: false, auto_approve: true, request_changes: true, model: null, effort: null, blocking_confidence: 0.9, advisory_confidence: 0.7 }, - merge: { enabled: false, method: 'squash', authorization: { whitelist: '', blacklist: '*' }, minimum_human_approvals: 1, guard_check: 'CodexBot reviewed commit' }, - credentials: { mode: 'chatgpt' }, + merge: { enabled: false, auto_merge_on_approval: false, method: 'squash', authorization: { whitelist: '', blacklist: '*' }, minimum_human_approvals: 0, guard_check: 'CodexBot reviewed commit' }, + credentials: { mode: 'chatgpt', automatic_reviewer: null }, quotas: { user_per_day: 10, repository_per_day: 40, installation_per_day: 200, concurrent_repository: 1, concurrent_installation: 4, cooldown_seconds: 60, reruns_per_day: 2 } }; const policySchema = { type: 'object', additionalProperties: false, properties: { @@ -34,10 +34,10 @@ const schema = { type: 'object', additionalProperties: false, properties: { effort: { enum: [null, ...EFFORTS] }, blocking_confidence: { type: 'number', minimum: 0.5, maximum: 1 }, advisory_confidence: { type: 'number', minimum: 0, maximum: 1 } } }, merge: { type: 'object', additionalProperties: false, properties: { - enabled: { type: 'boolean' }, method: { enum: ['squash', 'merge', 'rebase'] }, authorization: policySchema, - minimum_human_approvals: { type: 'integer', minimum: 1, maximum: 6 }, guard_check: { type: 'string', minLength: 1, maxLength: 80, pattern: '^[A-Za-z0-9 _.-]+$' } + enabled: { type: 'boolean' }, auto_merge_on_approval: { type: 'boolean' }, method: { enum: ['squash', 'merge', 'rebase'] }, authorization: policySchema, + minimum_human_approvals: { type: 'integer', minimum: 0, maximum: 6 }, guard_check: { type: 'string', minLength: 1, maxLength: 80, pattern: '^[A-Za-z0-9 _.-]+$' } } }, - credentials: { type: 'object', additionalProperties: false, properties: { mode: { enum: ['chatgpt', 'api-key'] } } }, + credentials: { type: 'object', additionalProperties: false, properties: { mode: { enum: ['chatgpt', 'api-key'] }, automatic_reviewer: {type:['string','null'],pattern:'^[A-Za-z0-9][A-Za-z0-9-]{0,38}$',maxLength:39} } }, quotas: { type: 'object', additionalProperties: false, properties: Object.fromEntries(Object.keys(DEFAULT_CONFIG.quotas).map(key => [key, { type: 'integer', minimum: key === 'cooldown_seconds' ? 0 : 1, maximum: key === 'cooldown_seconds' ? 86400 : key.startsWith('concurrent') ? 10 : 1000 }])) } } }; const validate = new Ajv({ strict: true, allowUnionTypes: true }).compile>(schema); diff --git a/src/core/diagnostics.ts b/src/core/diagnostics.ts index e6f1035..3694297 100644 --- a/src/core/diagnostics.ts +++ b/src/core/diagnostics.ts @@ -19,7 +19,7 @@ bearer_required request_not_found request_expired invalid_webhook_signature inst oidc_repository_mismatch oidc_event_mismatch oidc_caller_workflow_mismatch oidc_reusable_workflow_mismatch oidc_environment_mismatch oidc_subject_mismatch oidc_run_missing oidc_invalid_run_identity oidc_token_expired oidc_token_invalid oidc_jwks_unavailable workflow_run_mismatch workflow_not_dispatched_by_this_app workflow_dispatch_attempt_mismatch -chatgpt_deployment_authorization_revoked use_authorized_rerun_command_instead_of_workflow_rerun request_already_started stale_pull_request +automatic_review_authorization_revoked chatgpt_deployment_authorization_revoked use_authorized_rerun_command_instead_of_workflow_rerun request_already_started stale_pull_request trusted_default_branch_changed_or_unprotected review_authorization_revoked session_missing_or_in_use chatgpt_session_not_connected hosted_connection_requires_reconnect hosted_refresh_reconnect_required hosted_session_unavailable hosted_session_identity_changed repository_operation_in_progress hosted_oauth_registration_not_configured hosted_inference_scopes_not_configured hosted_workspace_claim_not_configured oauth_refresh_workspace_mismatch diff --git a/src/core/policy.ts b/src/core/policy.ts index f06044f..87e1047 100644 --- a/src/core/policy.ts +++ b/src/core/policy.ts @@ -18,7 +18,7 @@ export function validatePolicy(policy: Policy): void { for (const pattern of [...patterns(policy.whitelist), ...patterns(policy.blacklist)]) compile(pattern); } export function policyAllows(login: string, policy: Policy): boolean { - if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}$/.test(login)) return false; + if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}(?:\[bot\])?$/.test(login)) return false; const denies = patterns(policy.blacklist).filter(x => x !== '*'); if (denies.some(x => compile(x).matcher(login).matches())) return false; return patterns(policy.whitelist).some(x => compile(x).matcher(login).matches()); diff --git a/src/core/review.ts b/src/core/review.ts index b38b106..bf81fe4 100644 --- a/src/core/review.ts +++ b/src/core/review.ts @@ -129,12 +129,19 @@ export function publicText(text: string): string { const redacted = scanSecrets(text).length ? '[Content quarantined by output policy]' : SOURCE_TOKEN.matcher(text).replaceAll('[REDACTED]'); return redacted.replace(/&/g, '&').replace(//g, '>').replace(/@/g, '@\u200b').replace(/\[/g, '\\[').replace(/!\[/g, '!\\['); } +/** Operator-controlled disposable acceptance scope; the public merge gate stays closed during live tests. */ +export function deploymentMergeEnabled(env: {MERGE_DEPLOYMENT_AUTHORIZED:string;MERGE_ACCEPTANCE_REPOSITORY_ID?:string;MERGE_ACCEPTANCE_INSTALLATION_ID?:string}, request: {repositoryId:number;installationId:number}): boolean { + return env.MERGE_DEPLOYMENT_AUTHORIZED==='true' || (env.MERGE_ACCEPTANCE_REPOSITORY_ID===String(request.repositoryId) && env.MERGE_ACCEPTANCE_INSTALLATION_ID===String(request.installationId)); +} +export function mergeRequested(snapshot: { command: { merge: boolean }; mergeIntent?: 'automatic' }): boolean { + return snapshot.command.merge || snapshot.mergeIntent === 'automatic'; +} export interface MergeState { head: string; expectedHead: string; open: boolean; draft: boolean; mergeStateStatus: string; reviewDecision: string | null; authorized: boolean; explicitlyRequested: boolean; event: string; checks: 'passed' | 'pending' | 'failed'; humans: boolean; protected: boolean; queue: boolean; } export function mergeDisposition(state: MergeState, config: Config): string { - if (!config.merge.enabled || !state.authorized || !state.explicitlyRequested || state.event !== 'APPROVE') return 'policy_denied'; + if (!config.merge.enabled || !state.authorized || (!state.explicitlyRequested && !config.merge.auto_merge_on_approval) || state.event !== 'APPROVE') return 'policy_denied'; if (state.head !== state.expectedHead || !state.open || state.draft) return 'stale_or_closed'; if (!state.protected) return 'protection_required'; if (state.queue) return 'manual_merge_queue'; diff --git a/src/worker/github.ts b/src/worker/github.ts index bc19256..715097a 100644 --- a/src/worker/github.ts +++ b/src/worker/github.ts @@ -25,9 +25,9 @@ export async function installationClient(env: GitHubCredentials, installation: n const { data } = await app.rest.apps.createInstallationAccessToken({ installation_id: installation, repository_ids: [repositoryId], permissions }); return { github: client(data.token), token: data.token }; } -export async function permission(github: Octokit, repository: string, login: string, expectedId?: number): Promise { +export async function permission(github: Octokit, repository: string, login: string, expectedId?: number, expectedType: 'User' | 'Bot' = 'User'): Promise { const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ ...splitRepo(repository), username: login }); - if (expectedId !== undefined) requireCondition(data.user?.id === expectedId && data.user.type === 'User', 'permission_identity_changed', 403); + if (expectedId !== undefined) requireCondition(data.user?.id === expectedId && data.user.type === expectedType, 'permission_identity_changed', 403); return data.permission as RepositoryPermission; } export async function verifyActor(github: Octokit, login: string, id: number): Promise { diff --git a/src/worker/index.ts b/src/worker/index.ts index b0d2036..f4449eb 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -1,3 +1,4 @@ +import { mergeRequested, deploymentMergeEnabled } from '../core/review.js'; import { verifyWebhook, sha256 } from '../core/crypto.js'; import type { Envelope } from '../core/crypto.js'; import { AppError, requireCondition, record } from '../core/errors.js'; @@ -9,7 +10,7 @@ import type { RequestSnapshot } from './store.js'; import { publish, discardPendingReview } from './publish.js'; import { invalidateMerge } from './merge.js'; import { onboarding } from './onboarding.js'; -import { setupPullRequest } from '../setup.js'; +import { setupPullRequest, ensureProtectedEnvironment } from '../setup.js'; import { processDelivery, recover } from './recovery.js'; import { MAX_RESULT_BODY_BYTES } from '../core/limits.js'; import { repositoryCapabilities } from '../capabilities.js'; @@ -114,9 +115,9 @@ async function route(request: Request, env: Env): Promise { requireCondition(body.action === undefined || ['retry','cancel','retry-progress'].includes(String(body.action)), 'invalid_recovery_action'); if (body.action === 'cancel') { const snapshot = await store.cancellable(body.id, repo.id, installation.id); - const { github: cleanup } = await installationClient(env, installation.id, repo.id, { pull_requests: 'write', ...(snapshot.command.merge ? { checks: 'write' } as const : {}) }); + const { github: cleanup } = await installationClient(env, installation.id, repo.id, { pull_requests: 'write', ...(mergeRequested(snapshot) ? { checks: 'write' } as const : {}) }); await discardPendingReview(cleanup, snapshot, env.GITHUB_APP_SLUG); - const merged = snapshot.command.merge ? await invalidateMerge(cleanup, snapshot, env.GITHUB_APP_SLUG, Number(env.GITHUB_APP_ID)) : false; + const merged = mergeRequested(snapshot) ? await invalidateMerge(cleanup, snapshot, env.GITHUB_APP_SLUG, Number(env.GITHUB_APP_ID)) : false; await store.terminateIntent(snapshot.id, merged); await store.release(snapshot); } else if (body.action === 'retry-progress') await store.operatorRetryProgress(body.id, repo.id, installation.id); else await store.operatorRetry(body.id, repo.id, installation.id); @@ -159,7 +160,7 @@ async function route(request: Request, env: Env): Promise { return Response.json({ status }, { status: status === 'dispatched' ? 202 : 200 }); } // Interactive provisioning uses a caller-owned, transient GitHub token, never a central user credential. - if (url.pathname === '/v1/session' && ['GET', 'PUT', 'DELETE'].includes(request.method)) { + if (url.pathname === '/v1/session' && ['GET', 'PUT', 'POST', 'DELETE'].includes(request.method)) { const github = client(bearer(request)); const { data: user } = await github.rest.users.getAuthenticated(); const repository = url.searchParams.get('repository') ?? ''; @@ -168,6 +169,18 @@ async function route(request: Request, env: Env): Promise { const { data: installation } = await (await appClient(env)).rest.apps.getRepoInstallation(splitRepo(repository)); requireCondition(!installation.suspended_at, 'installation_suspended', 403); if (request.method !== 'GET') requireCondition(!await env.DB.prepare('SELECT 1 FROM web_connections WHERE installation_id=? AND repository_id=? AND actor_id=?').bind(installation.id, repo.id, user.id).first(), 'hosted_connections_must_be_managed_in_dashboard', 409); + if (request.method === 'POST') { + requireCondition(user.type==='User','human_credential_owner_required',403); + const body=record(JSON.parse(new TextDecoder().decode(await boundedBody(request,1024))) as unknown); + requireCondition(Object.keys(body).every(key=>['enabled','mode'].includes(key)) && typeof body.enabled==='boolean' && (body.enabled===false || ['chatgpt','api-key'].includes(String(body.mode))),'invalid_automatic_review_consent'); + if (body.enabled) { + const {data:branch}=await github.rest.repos.getBranch({...splitRepo(repository),branch:repo.default_branch}); requireCondition(branch.protected,'protected_branch_required_for_automatic_reviews',403); + await ensureProtectedEnvironment(github,repository,credentialEnvironment(installation.id,user.id),undefined,true); + await github.rest.actions.getEnvironmentSecret({...splitRepo(repository),environment_name:credentialEnvironment(installation.id,user.id),secret_name:body.mode==='chatgpt'?'CODEXBOT_VAULT_KEY':'CODEXBOT_API_KEY'}); + } + await store.automaticConsent(repo.id,installation.id,user.id,user.login,body.enabled ? body.mode as 'chatgpt'|'api-key' : null); + return Response.json({status:body.enabled?'automatic_reviews_authorized':'automatic_reviews_revoked'}); + } if (request.method === 'PUT') { requireCondition(env.CHATGPT_DEPLOYMENT_AUTHORIZED === 'true', 'chatgpt_deployment_not_authorized', 403); await store.saveSession(repo.id, user.id, envelope(JSON.parse(new TextDecoder().decode(await boundedBody(request, 66_000))) as unknown), installation.id); @@ -207,6 +220,7 @@ async function route(request: Request, env: Env): Promise { if (failed || current.row.state === 'failed') await store.release(snapshot); await notify(env, store, snapshot); return Response.json({ status: 'failed' }); } + await store.authorizeAutomatic(snapshot); requireCondition(snapshot.config.credentials.mode !== 'chatgpt' || env.CHATGPT_DEPLOYMENT_AUTHORIZED === 'true', 'chatgpt_deployment_authorization_revoked', 403); requireCondition(operation === 'publish' || identity.attempt === '1', 'use_authorized_rerun_command_instead_of_workflow_rerun', 403); if (operation === 'stage') { @@ -224,7 +238,8 @@ async function route(request: Request, env: Env): Promise { requireCondition(branch.protected && branch.commit.sha === snapshot.workflowSha, 'trusted_default_branch_changed_or_unprotected', 409); const config = await trustedConfig(github, snapshot.repository, snapshot.defaultBranch); await verifyActor(github, snapshot.actor, snapshot.actorId); - const livePermission = await permission(github, snapshot.repository, snapshot.actor); + const livePermission = await permission(github, snapshot.repository, snapshot.actor,snapshot.actorId); + requireCondition(!snapshot.triggerActor || (livePermission==='admin' && config.credentials.automatic_reviewer?.toLowerCase()===snapshot.actor.toLowerCase()),'automatic_review_authorization_revoked',403); requireCondition(config.review.enabled && authorize(snapshot.actor, livePermission, config.authorization), 'review_authorization_revoked', 403); requireCondition(await store.prepare(id, identity.runId), 'request_already_started', 409); // Acquire before reading: reconnect must not replace the record between snapshot and lease. @@ -275,13 +290,13 @@ async function route(request: Request, env: Env): Promise { await notify(env, store, snapshot); try { const { github: publisher } = await installationClient(env, snapshot.installationId, snapshot.repositoryId, { - contents: snapshot.command.merge ? 'write' : 'read', pull_requests: 'write', - ...(snapshot.command.merge && env.MERGE_DEPLOYMENT_AUTHORIZED === 'true' ? { checks: 'write', administration: 'read' } as const : {}) + contents: mergeRequested(snapshot) ? 'write' : 'read', pull_requests: 'write', + ...(mergeRequested(snapshot) && deploymentMergeEnabled(env,snapshot) ? { checks: 'write', administration: 'read' } as const : {}) }); const result = await publish(publisher, snapshot, JSON.parse(row.result) as unknown, row.context_complete === 1 && input.review_job_failed !== true, env.GITHUB_APP_SLUG, { checkpoint: (reviewId, phase, merge) => store.checkpoint(id, lease, reviewId, phase, merge), - merge: { enabled: env.MERGE_DEPLOYMENT_AUTHORIZED === 'true', appId: Number(env.GITHUB_APP_ID) }, - beforeWrite: () => store.heartbeat(id, lease) + merge: { enabled: deploymentMergeEnabled(env,snapshot), appId: Number(env.GITHUB_APP_ID) }, + beforeWrite: async () => {await store.authorizeAutomatic(snapshot);await store.heartbeat(id,lease);} }); await store.published(id, result.reviewId, lease); await notify(env, store, snapshot); return Response.json(result); } catch (error) { await store.publicationFailed(id, lease, error instanceof AppError && error.status < 500 && error.status !== 429); throw error; } diff --git a/src/worker/merge.ts b/src/worker/merge.ts index 6dd341d..99400fe 100644 --- a/src/worker/merge.ts +++ b/src/worker/merge.ts @@ -4,7 +4,7 @@ import type { RequestSnapshot } from './store.js'; import { splitRepo, permission, trustedConfig, verifyActor } from './github.js'; import { authorize } from '../core/policy.js'; import { requireCondition } from '../core/errors.js'; -import { mergeDisposition } from '../core/review.js'; +import { mergeDisposition, mergeRequested } from '../core/review.js'; import { REQUEST_LIFETIME_MS } from '../core/limits.js'; export interface MergeOptions { enabled: boolean; appId: number } @@ -32,6 +32,7 @@ export async function invalidateMerge(github: Octokit, snapshot: RequestSnapshot } export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, config: Config, appSlug: string, options: MergeOptions, beforeWrite: () => Promise = async () => {}): Promise { if (!options.enabled) return 'deployment_merge_acceptance_gate_closed'; + if (!mergeRequested(snapshot)) return 'policy_denied'; requireCondition(Date.now() - snapshot.createdAt < REQUEST_LIFETIME_MS, 'merge_intent_expired', 410); const repo = splitRepo(snapshot.repository); const state = await github.graphql(QUERY, { ...repo, number: snapshot.pr }), pr = state.repository.pullRequest; @@ -39,7 +40,8 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c const stop = async (reason: string) => { await invalidateMerge(github, snapshot, appSlug, options.appId); return reason; }; const liveConfig = await trustedConfig(github, snapshot.repository, snapshot.defaultBranch); await verifyActor(github, snapshot.actor, snapshot.actorId); - const role = await permission(github, snapshot.repository, snapshot.actor); + const role = await permission(github, snapshot.repository, snapshot.actor, snapshot.actorId); + if (snapshot.triggerActor && (role!=='admin' || liveConfig.credentials.automatic_reviewer?.toLowerCase()!==snapshot.actor.toLowerCase())) return stop('automatic_review_authorization_revoked'); if (!liveConfig.review.enabled || !liveConfig.review.auto_approve || !liveConfig.merge.enabled || !authorize(snapshot.actor, role, liveConfig.merge.authorization, true)) return stop('merge_authorization_revoked'); if (JSON.stringify(liveConfig) !== JSON.stringify(config)) return stop('merge_policy_changed'); if (pr.headRefOid !== snapshot.head || pr.baseRefOid !== snapshot.base || pr.state !== 'OPEN' || pr.isDraft) return stop('stale_or_closed_pull_request'); @@ -54,7 +56,9 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c let protection: Awaited>['data'] | undefined; try { protection = (await github.rest.repos.getBranchProtection({ ...repo, branch: pr.baseRefName })).data; } catch (error) { requireCondition(error && typeof error === 'object' && 'status' in error && error.status === 404 && rules.length > 0, 'branch_protection_not_verifiable', 403); } - const humanMinimum = Math.max(config.merge.minimum_human_approvals, protection?.required_pull_request_reviews?.required_approving_review_count ?? 0, + const specialHumanRules = protection?.required_pull_request_reviews?.require_code_owner_reviews || protection?.required_pull_request_reviews?.require_last_push_approval || + rules.some(rule => rule.type === 'pull_request' && (rule.parameters?.require_code_owner_review || rule.parameters?.require_last_push_approval)); + const humanMinimum = Math.max(config.merge.minimum_human_approvals, specialHumanRules ? 1 : 0, protection?.required_pull_request_reviews?.required_approving_review_count ?? 0, ...rules.filter(x => x.type === 'pull_request').map(x => x.parameters?.required_approving_review_count ?? 0)); const reviews = await github.paginate(github.rest.pulls.listReviews, { ...repo, pull_number: snapshot.pr, per_page: 100 }, response => { requireCondition(response.data.length < 100, 'human_review_history_requires_manual_review'); return response.data; @@ -71,7 +75,7 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c if (['write','maintain','admin'].includes(await permission(github, snapshot.repository, review.user!.login, userId))) humans++; if (humans >= humanMinimum) break; } - if (humans < humanMinimum || ['CHANGES_REQUESTED','REVIEW_REQUIRED'].includes(pr.reviewDecision ?? '')) return stop('independent_human_approvals_required'); + if (pr.reviewDecision==='CHANGES_REQUESTED') return stop('human_changes_requested'); const contexts = pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts; if (!contexts || contexts.pageInfo.hasNextPage) return stop('check_evidence_unavailable'); const checks = contexts.nodes.filter(x => !(x.__typename === 'CheckRun' && x.name === config.merge.guard_check && x.checkSuite?.app?.databaseId === options.appId)); @@ -81,6 +85,11 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c ...rules.filter(x => x.type === 'required_status_checks').flatMap(x => x.parameters?.required_status_checks ?? []).map(x => ({ name: x.context, app: x.integration_id }))]; const guarded = required.some(x => x.name === config.merge.guard_check && x.app === options.appId); const missing = required.filter(x => x.name !== config.merge.guard_check).some(required => !checks.some(x => (x.name ?? x.context) === required.name && (!required.app || required.app === -1 || x.checkSuite?.app?.databaseId === required.app))); + if (humans < humanMinimum || pr.reviewDecision==='REVIEW_REQUIRED') { + await stop('independent_human_approvals_required'); + // Keep only the durable worker intent. Native auto-merge stays disabled until real humans qualify. + return 'queued'; + } const disposition = mergeDisposition({ head: pr.headRefOid, expectedHead: snapshot.head, open: pr.state === 'OPEN', draft: pr.isDraft, mergeStateStatus: pr.mergeStateStatus, reviewDecision: pr.reviewDecision, authorized: true, explicitlyRequested: snapshot.command.merge, event: 'APPROVE', checks: missing ? 'pending' : status, humans: humans >= humanMinimum, protected: branch.protected, queue: false }, config); diff --git a/src/worker/onboarding.ts b/src/worker/onboarding.ts index ab3ece6..a68e220 100644 --- a/src/worker/onboarding.ts +++ b/src/worker/onboarding.ts @@ -4,11 +4,13 @@ import type { Config } from '../core/config.js'; import catalog from '../core/model-catalog.json' with { type: 'json' }; export function html(value: unknown): string { return String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' })[c]!); } export function page(title: string, content: string, session?: BrowserSession, canonical?: string): Response { - return new Response(`${html(title)} · CodexBot${canonical ? `` : ''}
C/B CodexBot
${content}
CodexBot · Apache 2.0Your repository. Your infrastructure.
`, { headers: { 'Content-Type':'text/html; charset=utf-8' } }); + return new Response(`${html(title)} · CodexBot${canonical ? `` : ''}
C/B CodexBot
${content}
CodexBot · Apache 2.0Your repository. Your infrastructure.
`, { headers: { 'Content-Type':'text/html; charset=utf-8' } }); } -export function onboarding(env: BackendConfig): Response { +export function onboarding(env: BackendConfig & {WEB_ENABLED?:string}): Response { const slug = /^[a-zA-Z0-9-]+$/.test(env.GITHUB_APP_SLUG) ? env.GITHUB_APP_SLUG : 'codexbot'; - return page('Code review with context', `

AN INDEPENDENT SECOND LOOK

The diff is small.
The consequences
might not be.

CodexBot follows changes into the code around them. Get actionable, inline pull request reviews from Codex, on your own GitHub Actions infrastructure.

PR #42 · permissions.tsIllustrative example
  function canAccess(role) {\n−   return role === 'admin' || role === 'owner';\n+   return role === 'admin' || 'owner';\n  }
HIGH · A truthy string grants access to every role

The unchanged caller treats this result as an authorization decision. Compare the role explicitly on both sides.

01 / CONTEXT

Beyond the changed lines.

Inspect relevant callers, tests and trusted project guidance. Findings stay attached to the exact commit and changed line.

02 / CONTROL

Your account. Your policy.

Use approved ChatGPT access or your own API key. Set who can request reviews, the model and review policy. Usage limits still apply; API billing is separate.

03 / ISOLATION

Read-only by design.

Analysis runs in an isolated container with no network or credentials. A separate publisher validates results. Incomplete reviews never approve a PR.

A considered review.
A reviewable setup.

Connect GitHub, choose a repository and review the setup PR. Branch protections remain in charge. AI reviews can miss bugs; keep your tests and human reviewers.

Set up your repository ↗
`, undefined, env.PUBLIC_URL); + const browserSetup=env.WEB_ENABLED==='true', setupUrl=browserSetup?'/auth/github':'https://github.com/AppSolves/codexbot#installation'; + const connect=`${browserSetup?'Get started with GitHub':'CLI setup instructions'} ↗`; + return page('Code review with context', `

AN INDEPENDENT SECOND LOOK

The diff is small.
The consequences
might not be.

CodexBot follows changes into the code around them. Get actionable, inline pull request reviews from Codex, on your own GitHub Actions infrastructure.

PR #42 · permissions.tsIllustrative example
  function canAccess(role) {\n−   return role === 'admin' || role === 'owner';\n+   return role === 'admin' || 'owner';\n  }
HIGH · A truthy string grants access to every role

The unchanged caller treats this result as an authorization decision. Compare the role explicitly on both sides.

01 / CONTEXT

Beyond the changed lines.

Inspect relevant callers, tests and trusted project guidance. Findings stay attached to the exact commit and changed line.

02 / CONTROL

Your account. Your policy.

Use approved ChatGPT access or your own API key. Set who can request reviews, the model and review policy. Usage limits still apply; API billing is separate.

03 / ISOLATION

Read-only by design.

Analysis runs in an isolated container with no network or credentials. A separate publisher validates results. Incomplete reviews never approve a PR.

A considered review.
A reviewable setup.

Connect GitHub, choose a repository and review the setup PR. Branch protections remain in charge. AI reviews can miss bugs. Keep required tests; choose autonomous merging or additional human review according to your repository policy.

Set up your repository ↗
`, undefined, env.PUBLIC_URL); } export function csrf(session: BrowserSession): string { return ``; } export function configurationFields(config: Config): string { @@ -16,6 +18,7 @@ export function configurationFields(config: Config): string { const name = prefix + key, id = 'field-' + name.replaceAll('.', '-'); if (value && typeof value === 'object' && !Array.isArray(value)) return `
${html(name.replaceAll('_',' '))}${fields(value as Record, name + '.')}
`; const label = html(key.replaceAll('_',' ')); + if (name === 'merge.minimum_human_approvals') return `

Fully Autonomous: CodexBot reviews, approves and merges eligible pull requests automatically after required checks pass. No human reviewer required.

Human-in-the-Loop: CodexBot performs the review automatically, but merging waits for the configured number of human approvals.

GitHub repository protections still apply. Enable merging and automatic merge on approval explicitly; otherwise only an authorized --merge command can request merging. Automatic reviews use the actor’s own connection or an explicitly consenting assigned administrator. Manual commands never borrow the assigned connection.

`; if (name === 'review.model' || name === 'review.effort') { const options = name === 'review.model' ? catalog.models.map(model => model.model) : [...new Set(catalog.models.flatMap(model => model.efforts))]; if (typeof value === 'string' && !options.includes(value)) options.push(value); diff --git a/src/worker/progress.ts b/src/worker/progress.ts index aa0dbc4..82face2 100644 --- a/src/worker/progress.ts +++ b/src/worker/progress.ts @@ -26,12 +26,13 @@ export function progressBody(snapshot: RequestSnapshot, row: RequestRow, statusU const status = row.workflow_status && STATUSES.has(row.workflow_status) ? row.workflow_status : 'not yet confirmed'; const conclusion = row.workflow_conclusion && CONCLUSIONS.has(row.workflow_conclusion) ? ` / ${row.workflow_conclusion}` : ''; const review = row.review_id && Number.isSafeInteger(row.review_id) ? `\n\n[Native review](https://github.com/${snapshot.repository}/pull/${snapshot.pr}#pullrequestreview-${row.review_id}).` : ''; + const merge = row.state==='published' && row.merge_phase==='queued' ? '\n\nMerge is waiting for repository checks or required independent human approval. GitHub protections remain enforced.' : ''; const failure = phase(row) !== 'failed' ? '' : row.state === 'published' ? '\n\nAnalysis failed. A non-approving fallback report was published; this is not a completed AI review. Check the workflow diagnostics before requesting a new review.' : '\n\nReview processing did not complete. Check the workflow diagnostics, resolve the reported prerequisite and request a new review.'; // Every variable is a validated identifier/count or a fixed vocabulary. No prompt, // model text, source, remote URL or internal error is part of this public channel. - return `${marker(snapshot)}\nCodexBot accepted review request \`${snapshot.id.slice(0, 8)}\`.\n\n${counts}\n\n**Stage: ${phase(row)}.**\n\n${statusUnavailable ? 'Workflow details are temporarily unavailable; no current run status is asserted.' : `Workflow: ${status}${conclusion}. ${run}`}${review}${failure}`; + return `${marker(snapshot)}\nCodexBot accepted review request \`${snapshot.id.slice(0, 8)}\`.\n\n${counts}\n\n**Stage: ${phase(row)}.**\n\n${statusUnavailable ? 'Workflow details are temporarily unavailable; no current run status is asserted.' : `Workflow: ${status}${conclusion}. ${run}`}${review}${merge}${failure}`; } async function observe(github: Octokit, store: Store, snapshot: RequestSnapshot, row: RequestRow, slug: string): Promise { if (row.workflow_status === 'completed' || Date.now() - row.workflow_checked_at < 15_000 || !row.dispatch_attempt) return; diff --git a/src/worker/publish.ts b/src/worker/publish.ts index 89b5b30..580046c 100644 --- a/src/worker/publish.ts +++ b/src/worker/publish.ts @@ -1,6 +1,6 @@ import type { Octokit } from '@octokit/rest'; import { authorize } from '../core/policy.js'; -import { decision, publicText, validateReview, failedReview, completePatch, normalizeReview, findingDisposition, reviewSummary } from '../core/review.js'; +import { decision, publicText, validateReview, failedReview, completePatch, normalizeReview, findingDisposition, reviewSummary, mergeRequested } from '../core/review.js'; import { sha256 } from '../core/crypto.js'; import { requireCondition, AppError } from '../core/errors.js'; import { splitRepo, permission, trustedConfig, verifyActor } from './github.js'; @@ -23,14 +23,15 @@ export async function discardPendingReview(github: Octokit, snapshot: RequestSna export async function publish(github: Octokit, snapshot: RequestSnapshot, output: unknown, contextComplete: boolean, appSlug: string, options: PublishOptions = {}): Promise<{ reviewId: number; event: string; merge: string }> { const repo = splitRepo(snapshot.repository); const { data: current } = await github.rest.pulls.get({ ...repo, pull_number: snapshot.pr }); - requireCondition(current.head.sha === snapshot.head && current.base.sha === snapshot.base && (current.state === 'open' || (current.merged && snapshot.command.merge)) && !current.draft, 'stale_or_closed_pull_request', 409); + requireCondition(current.head.sha === snapshot.head && current.base.sha === snapshot.base && (current.state === 'open' || (current.merged && mergeRequested(snapshot))) && !current.draft, 'stale_or_closed_pull_request', 409); const { data: repository } = await github.rest.repos.get(repo); requireCondition(repository.id === snapshot.repositoryId && repository.owner.id === snapshot.ownerId, 'repository_identity_changed', 403); const { data: trustedBranch } = await github.rest.repos.getBranch({ ...repo, branch: repository.default_branch }); requireCondition(repository.default_branch === snapshot.defaultBranch && trustedBranch.commit.sha === snapshot.workflowSha, 'trusted_policy_or_workflow_revision_changed', 409); const config = await trustedConfig(github, snapshot.repository, repository.default_branch); await verifyActor(github, snapshot.actor, snapshot.actorId); - const livePermission = await permission(github, snapshot.repository, snapshot.actor); + const livePermission = await permission(github, snapshot.repository, snapshot.actor, snapshot.actorId); + requireCondition(!snapshot.triggerActor || (livePermission==='admin' && config.credentials.automatic_reviewer?.toLowerCase()===snapshot.actor.toLowerCase()),'automatic_review_authorization_revoked',403); requireCondition(config.review.enabled && authorize(snapshot.actor, livePermission, config.authorization), 'review_authorization_revoked', 403); const files = await github.paginate(github.rest.pulls.listFiles, { ...repo, pull_number: snapshot.pr, per_page: 100 }); requireCondition(files.length === current.changed_files && files.length <= 200, 'diff_incomplete'); @@ -41,7 +42,7 @@ export async function publish(github: Octokit, snapshot: RequestSnapshot, output const computedEvent = decision(review, config, contextComplete); const event = current.user?.login === `${appSlug}[bot]` ? 'COMMENT' : computedEvent; const marker = ``; - const fingerprint = ``; + const fingerprint = ``; let historyPages = 0; const reviews = await github.paginate(github.rest.pulls.listReviews, { ...repo, pull_number: snapshot.pr, per_page: 100 }, response => { requireCondition(++historyPages <= 10, 'review_history_limit_requires_reconciliation'); @@ -60,7 +61,8 @@ export async function publish(github: Octokit, snapshot: RequestSnapshot, output requireCondition(branch.commit.sha === snapshot.workflowSha, 'trusted_policy_or_workflow_revision_changed', 409); const liveConfig = await trustedConfig(github, snapshot.repository, branch.commit.sha); await verifyActor(github, snapshot.actor, snapshot.actorId); - requireCondition(JSON.stringify(liveConfig) === JSON.stringify(config) && liveConfig.review.enabled && authorize(snapshot.actor, await permission(github, snapshot.repository, snapshot.actor), liveConfig.authorization), 'review_authorization_revoked', 403); + if (snapshot.triggerActor) requireCondition(await permission(github,snapshot.repository,snapshot.actor,snapshot.actorId)==='admin' && liveConfig.credentials.automatic_reviewer?.toLowerCase()===snapshot.actor.toLowerCase(),'automatic_review_authorization_revoked',403); + requireCondition(JSON.stringify(liveConfig) === JSON.stringify(config) && liveConfig.review.enabled && authorize(snapshot.actor, await permission(github, snapshot.repository, snapshot.actor, snapshot.actorId), liveConfig.authorization), 'review_authorization_revoked', 403); }; const existing = reviews.find(x => (x.body?.includes(marker) || x.body?.includes(fingerprint)) && [expectedState, 'PENDING'].includes(x.state) && x.user?.type === 'Bot' && x.user?.login === `${appSlug}[bot]` && x.commit_id === snapshot.head); let reviewId: number; @@ -73,7 +75,7 @@ export async function publish(github: Octokit, snapshot: RequestSnapshot, output await assertPublicationAllowed(); await options.beforeWrite?.(); const { data } = await github.rest.pulls.createReview({ ...repo, pull_number: snapshot.pr, commit_id: snapshot.head, - body: `${marker}\n${fingerprint}\n${reviewSummary(review, event, contextComplete)}${snapshot.command.merge ? `\n\nConditional merge explicitly requested by ${publicText(snapshot.actor)}.` : ''}`, + body: `${marker}\n${fingerprint}\n${reviewSummary(review, event, contextComplete)}${mergeRequested(snapshot) ? `\n\nConditional merge ${snapshot.command.merge ? 'explicitly requested' : 'enabled by repository policy for authorized requester'} ${publicText(snapshot.actor)}.` : ''}`, comments: review.findings.map(f => ({ path: f.path, line: f.line, side: f.side, body: `**${f.severity.toUpperCase()}: ${publicText(f.title)}**\n\n${publicText(f.explanation)}\n\n${publicText(f.remediation)}\n\nConfidence: ${f.confidence}; policy: ${findingDisposition(f, config)}.` })) }); reviewId = data.id; @@ -87,7 +89,7 @@ export async function publish(github: Octokit, snapshot: RequestSnapshot, output } await options.checkpoint?.(reviewId, 'submitted', 'pending'); if (current.merged) { await options.checkpoint?.(reviewId, 'submitted', 'merged'); return { reviewId, event, merge: 'merged' }; } - if (!snapshot.command.merge || event !== 'APPROVE') return { reviewId, event, merge: 'not_requested_or_not_approved' }; + if (!mergeRequested(snapshot) || event !== 'APPROVE') return { reviewId, event, merge: 'not_requested_or_not_approved' }; let merge: string; try { merge = await controlMerge(github, snapshot, config, appSlug, options.merge ?? { enabled: false, appId: 0 }, async () => { await options.checkpoint?.(reviewId, 'submitted', 'arming'); diff --git a/src/worker/recovery.ts b/src/worker/recovery.ts index eca8c53..d7f45f1 100644 --- a/src/worker/recovery.ts +++ b/src/worker/recovery.ts @@ -1,3 +1,4 @@ +import { mergeRequested, deploymentMergeEnabled } from '../core/review.js'; import { Store } from './store.js'; import { ingest } from './webhook.js'; import { AppError, requireCondition } from '../core/errors.js'; @@ -54,13 +55,14 @@ export async function recover(env: Env): Promise { requireCondition(data.id === snapshot.installationId && !data.suspended_at, 'installation_no_longer_valid', 403); requireCondition(snapshot.config.credentials.mode !== 'chatgpt' || env.CHATGPT_DEPLOYMENT_AUTHORIZED === 'true', 'chatgpt_deployment_authorization_revoked', 403); if (snapshot.config.credentials.mode === 'chatgpt') requireCondition(await store.session(snapshot.repositoryId, snapshot.actorId, snapshot.installationId), 'chatgpt_connection_revoked', 403); - const { github } = await installationClient(env, snapshot.installationId, snapshot.repositoryId, { contents: snapshot.command.merge ? 'write' : 'read', pull_requests: 'write', - ...(snapshot.command.merge && env.MERGE_DEPLOYMENT_AUTHORIZED === 'true' ? { checks: 'write', administration: 'read' } as const : {}) }); + await store.authorizeAutomatic(snapshot); + const { github } = await installationClient(env, snapshot.installationId, snapshot.repositoryId, { contents: mergeRequested(snapshot) ? 'write' : 'read', pull_requests: 'write', + ...(mergeRequested(snapshot) && deploymentMergeEnabled(env,snapshot) ? { checks: 'write', administration: 'read' } as const : {}) }); const result = await publish(github, snapshot, JSON.parse(row.result!) as unknown, row.context_complete === 1, env.GITHUB_APP_SLUG, - { checkpoint: (reviewId, phase, merge) => store.checkpoint(id, lease!, reviewId, phase, merge), beforeWrite: () => store.heartbeat(id, lease!), merge: { enabled: env.MERGE_DEPLOYMENT_AUTHORIZED === 'true', appId: Number(env.GITHUB_APP_ID) } }); + { checkpoint: (reviewId, phase, merge) => store.checkpoint(id, lease!, reviewId, phase, merge), beforeWrite: async () => {await store.authorizeAutomatic(snapshot);await store.heartbeat(id,lease!);}, merge: { enabled: deploymentMergeEnabled(env,snapshot), appId: Number(env.GITHUB_APP_ID) } }); await store.published(id, result.reviewId, lease); } catch (error) { - if (active?.command.merge && env.MERGE_DEPLOYMENT_AUTHORIZED === 'true') { + if (active && mergeRequested(active) && deploymentMergeEnabled(env,active)) { try { const { github } = await installationClient(env, active.installationId, active.repositoryId, { pull_requests: 'write', checks: 'write' }); await invalidateMerge(github, active, env.GITHUB_APP_SLUG, Number(env.GITHUB_APP_ID)); diff --git a/src/worker/store.ts b/src/worker/store.ts index b8a7b0d..4c45993 100644 --- a/src/worker/store.ts +++ b/src/worker/store.ts @@ -10,7 +10,7 @@ import { MAX_REVIEW_BYTES, MAX_RECOVERY_ATTEMPTS, RECOVERY_LEASE_MS, REQUEST_LIF export interface RequestSnapshot { id: string; installationId: number; repositoryId: number; ownerId: number; repository: string; defaultBranch: string; workflowSha: string; head: string; base: string; pr: number; actor: string; actorId: number; command: ReviewCommand; config: Config; createdAt: number; - commits?: number; changedFiles?: number; commandId?: number; + commits?: number; changedFiles?: number; commandId?: number; mergeIntent?: 'automatic'; triggerActor?: { login: string; id: number; type?: 'User' | 'Bot' }; automaticGrantId?: string; } export interface RequestRow { id: string; snapshot: string; state: string; run_id: string | null; review_id: number | null; result: string | null; context_complete: number; @@ -56,7 +56,7 @@ export class Store { const command = { ...snapshot.command }; delete command.rerun; const key = await sha256(JSON.stringify({ installation: snapshot.installationId, repository: snapshot.repositoryId, owner: snapshot.ownerId, actor: snapshot.actorId, pr: snapshot.pr, head: snapshot.head, base: snapshot.base, branch: snapshot.defaultBranch, - workflow: snapshot.workflowSha, trustedWorkflow, config: snapshot.config, command, rerun: snapshot.command.rerun ? snapshot.commandId ?? snapshot.id : null })); + workflow: snapshot.workflowSha, trustedWorkflow, config: snapshot.config, command, mergeIntent: snapshot.mergeIntent ?? null, automaticGrantId:snapshot.automaticGrantId ?? null, rerun: snapshot.command.rerun ? snapshot.commandId ?? snapshot.id : null })); const now = Date.now(), q = snapshot.config.quotas, day = now - 86_400_000, cooldown = now - q.cooldown_seconds * 1000; const insert = this.db.prepare(`INSERT OR IGNORE INTO requests(id,installation_id,repository_id,actor_id,snapshot,created_at,request_key,rerun) SELECT ?,?,?,?,?,?,?,? WHERE @@ -126,7 +126,7 @@ export class Store { const newer = await this.db.prepare(`SELECT 1 FROM requests current JOIN requests newer ON newer.installation_id=current.installation_id AND newer.repository_id=current.repository_id AND json_extract(newer.snapshot,'$.pr')=json_extract(current.snapshot,'$.pr') AND newer.created_at>=current.created_at AND newer.id!=current.id WHERE current.id=? LIMIT 1`).bind(id).first(); requireCondition(!newer, 'review_request_superseded', 409); - const result = await this.db.prepare(`UPDATE requests SET publish_until=? WHERE id=? AND publish_lease=? AND publish_until>? AND state='publishing'`) + const result = await this.db.prepare(`UPDATE requests SET publish_until=? WHERE id=? AND publish_lease=? AND publish_until>? AND state='publishing' AND (json_extract(snapshot,'$.triggerActor') IS NULL OR EXISTS(SELECT 1 FROM automatic_review_grants g WHERE g.installation_id=requests.installation_id AND g.repository_id=requests.repository_id AND g.actor_id=requests.actor_id AND g.id=json_extract(snapshot,'$.automaticGrantId')))`) .bind(Date.now() + RECOVERY_LEASE_MS, id, lease, Date.now()).run(); requireCondition(result.meta.changes === 1, 'publication_lease_lost', 409); } async published(id: string, reviewId: number, lease: string): Promise { @@ -191,10 +191,10 @@ export class Store { .bind(encoded, complete ? 1 : 0, id, runId).run(); requireCondition(result.meta.changes === 1, 'review_result_already_recorded', 409); } async removeInstallation(id: number): Promise { - await this.db.batch([this.db.prepare('DELETE FROM review_rejections WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM sessions WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM requests WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM legacy_sessions WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM web_connections WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM web_operations WHERE installation_id=?').bind(id)]); + await this.db.batch([this.db.prepare('DELETE FROM automatic_review_grants WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM review_rejections WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM sessions WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM requests WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM legacy_sessions WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM web_connections WHERE installation_id=?').bind(id), this.db.prepare('DELETE FROM web_operations WHERE installation_id=?').bind(id)]); } async removeRepository(repositoryId: number, installationId: number): Promise { - await this.db.batch([this.db.prepare('DELETE FROM review_rejections WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM sessions WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), + await this.db.batch([this.db.prepare('DELETE FROM automatic_review_grants WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM review_rejections WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM sessions WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM requests WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM legacy_sessions WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId)]); await this.db.batch([this.db.prepare('DELETE FROM web_connections WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId), this.db.prepare('DELETE FROM web_operations WHERE repository_id=? AND installation_id=?').bind(repositoryId, installationId)]); @@ -204,21 +204,45 @@ export class Store { return row ? { envelope: JSON.parse(row.envelope) as Envelope, version: row.version } : null; } async saveSession(repositoryId: number, actorId: number, envelope: Envelope, installationId: number): Promise { - const result = await this.db.prepare(`INSERT INTO sessions(repository_id,actor_id,envelope,installation_id) SELECT ?,?,?,? WHERE NOT EXISTS(SELECT 1 FROM web_operations WHERE installation_id=? AND repository_id=? AND lease_until>?) + const value=JSON.stringify(envelope); + const insert=this.db.prepare(`INSERT INTO sessions(repository_id,actor_id,envelope,installation_id) SELECT ?,?,?,? WHERE NOT EXISTS(SELECT 1 FROM web_operations WHERE installation_id=? AND repository_id=? AND lease_until>?) ON CONFLICT(installation_id,repository_id,actor_id) DO UPDATE SET envelope=excluded.envelope,version=sessions.version+1 WHERE sessions.lease_until { + return this.db.prepare('SELECT id,actor_id,actor,credential_mode FROM automatic_review_grants WHERE installation_id=? AND repository_id=?').bind(installationId,repositoryId).first(); + } + async authorizeAutomatic(snapshot: RequestSnapshot): Promise { + if (!snapshot.triggerActor) return; + const grant=await this.automaticGrant(snapshot.repositoryId,snapshot.installationId); + requireCondition(grant && grant.id===snapshot.automaticGrantId && grant.actor_id===snapshot.actorId && grant.actor.toLowerCase()===snapshot.actor.toLowerCase() && + grant.credential_mode===snapshot.config.credentials.mode && snapshot.config.credentials.automatic_reviewer?.toLowerCase()===snapshot.actor.toLowerCase(),'automatic_review_authorization_revoked',403); + } + async automaticConsent(repositoryId:number,installationId:number,actorId:number,actor:string,mode:'chatgpt'|'api-key'|null): Promise { + if (!mode) {await this.db.prepare('DELETE FROM automatic_review_grants WHERE installation_id=? AND repository_id=? AND actor_id=?').bind(installationId,repositoryId,actorId).run();return;} + const result=await this.db.prepare(`INSERT INTO automatic_review_grants(installation_id,repository_id,id,actor_id,actor,credential_mode,granted_at) + SELECT ?,?,?,?,?,?,? WHERE ?='api-key' OR EXISTS(SELECT 1 FROM sessions WHERE installation_id=? AND repository_id=? AND actor_id=?) + ON CONFLICT(installation_id,repository_id) DO UPDATE SET id=excluded.id,actor_id=excluded.actor_id,actor=excluded.actor,credential_mode=excluded.credential_mode,granted_at=excluded.granted_at`) + .bind(installationId,repositoryId,crypto.randomUUID(),actorId,actor,mode,Date.now(),mode,installationId,repositoryId,actorId).run(); + requireCondition(result.meta.changes===1,'connect_own_credentials_before_automatic_consent',409); } + async acquire(snapshot: RequestSnapshot): Promise { - const result = await this.db.prepare('UPDATE sessions SET lease_request=?,lease_until=? WHERE repository_id=? AND actor_id=? AND installation_id=? AND (lease_until?)') - .bind(snapshot.id, Date.now() + REQUEST_LIFETIME_MS, snapshot.repositoryId, snapshot.actorId, snapshot.installationId, Date.now(), snapshot.id, snapshot.installationId, snapshot.repositoryId, Date.now()).run(); requireCondition(result.meta.changes === 1, 'session_missing_or_in_use', 409); + await this.authorizeAutomatic(snapshot); + const result = await this.db.prepare('UPDATE sessions SET lease_request=?,lease_until=? WHERE repository_id=? AND actor_id=? AND installation_id=? AND (lease_until?) AND (?=0 OR EXISTS(SELECT 1 FROM automatic_review_grants WHERE installation_id=? AND repository_id=? AND actor_id=? AND actor=? AND credential_mode=? AND id=?))') + .bind(snapshot.id, Date.now() + REQUEST_LIFETIME_MS, snapshot.repositoryId, snapshot.actorId, snapshot.installationId, Date.now(), snapshot.id, snapshot.installationId, snapshot.repositoryId, Date.now(), snapshot.triggerActor ? 1 : 0, snapshot.installationId,snapshot.repositoryId,snapshot.actorId,snapshot.actor,snapshot.config.credentials.mode,snapshot.automaticGrantId ?? null).run(); requireCondition(result.meta.changes === 1, 'session_missing_or_in_use', 409); } async rotate(snapshot: RequestSnapshot, version: number, envelope: Envelope, operationLease: string | null = null): Promise { - const result = await this.db.prepare('UPDATE sessions SET envelope=?,version=version+1 WHERE repository_id=? AND actor_id=? AND installation_id=? AND version=? AND lease_request=? AND lease_until>? AND (? IS NULL OR EXISTS(SELECT 1 FROM web_operations WHERE installation_id=? AND repository_id=? AND lease=? AND lease_until>?))') - .bind(JSON.stringify(envelope), snapshot.repositoryId, snapshot.actorId, snapshot.installationId, version, snapshot.id, Date.now(), operationLease, snapshot.installationId, snapshot.repositoryId, operationLease, Date.now()).run(); requireCondition(result.meta.changes === 1, 'session_rotation_conflict_reconnect_required', 409); + const result = await this.db.prepare('UPDATE sessions SET envelope=?,version=version+1 WHERE repository_id=? AND actor_id=? AND installation_id=? AND version=? AND lease_request=? AND lease_until>? AND (? IS NULL OR EXISTS(SELECT 1 FROM web_operations WHERE installation_id=? AND repository_id=? AND lease=? AND lease_until>?)) AND (?=0 OR EXISTS(SELECT 1 FROM automatic_review_grants WHERE installation_id=? AND repository_id=? AND actor_id=? AND id=?))') + .bind(JSON.stringify(envelope), snapshot.repositoryId, snapshot.actorId, snapshot.installationId, version, snapshot.id, Date.now(), operationLease, snapshot.installationId, snapshot.repositoryId, operationLease, Date.now(),snapshot.triggerActor?1:0,snapshot.installationId,snapshot.repositoryId,snapshot.actorId,snapshot.automaticGrantId??null).run(); requireCondition(result.meta.changes === 1, 'session_rotation_conflict_reconnect_required', 409); } async deleteSession(repositoryId: number, actorId: number, installationId: number): Promise { const removed = await this.db.prepare('DELETE FROM sessions WHERE repository_id=? AND actor_id=? AND installation_id=? AND NOT EXISTS(SELECT 1 FROM web_operations WHERE installation_id=? AND repository_id=? AND lease_until>?)') .bind(repositoryId, actorId, installationId, installationId, repositoryId, Date.now()).run(); + if (!await this.session(repositoryId,actorId,installationId)) await this.automaticConsent(repositoryId,installationId,actorId,'',null); requireCondition(removed.meta.changes || !await this.session(repositoryId, actorId, installationId), 'session_busy', 409); } async release(snapshot: RequestSnapshot): Promise { diff --git a/src/worker/webhook.ts b/src/worker/webhook.ts index 80f6e5a..854b134 100644 --- a/src/worker/webhook.ts +++ b/src/worker/webhook.ts @@ -72,7 +72,7 @@ export async function ingest(event: string, payload: unknown, requestId: string, if (typeof comment.body !== 'string' || !/^@[a-zA-Z0-9]{1,39}\s+review(?=\s|$)/i.test(comment.body.trimStart().split(/\r?\n/, 1)[0] ?? '')) return 'no_command'; } const sender = record(input.sender), repository = record(input.repository), installation = record(input.installation); - requireCondition(sender.type === 'User' && Number.isSafeInteger(sender.id) && typeof sender.login === 'string', 'human_sender_required', 403); + requireCondition((sender.type === 'User' || (automatic && sender.type === 'Bot')) && Number.isSafeInteger(sender.id) && typeof sender.login === 'string', 'human_sender_required', 403); const fullName = String(repository.full_name), repo = splitRepo(fullName); await verifiedInstallation(await appClient(env), fullName, Number(installation.id)); const { github } = await installationClient(env, Number(installation.id), Number(repository.id), { contents: 'read', pull_requests: 'write', actions: 'write' }); @@ -81,8 +81,18 @@ export async function ingest(event: string, payload: unknown, requestId: string, const { data: branch } = await github.rest.repos.getBranch({ ...repo, branch: liveRepo.default_branch }); const config = await trustedConfig(github, fullName, branch.commit.sha); if (!config.review.enabled || (!manual && !config.review.auto_review)) return 'disabled'; - const livePermission = await permission(github, fullName, sender.login, Number(sender.id)); + requireCondition(sender.type === 'User' || Boolean(config.credentials.automatic_reviewer), 'human_sender_required', 403); + let livePermission = await permission(github, fullName, sender.login, Number(sender.id), sender.type as 'User' | 'Bot'); requireCondition(authorize(sender.login, livePermission, config.authorization), 'review_not_authorized', 403); + let actor=sender.login,actorId=Number(sender.id),automaticGrantId:string|undefined; + if (automatic && config.credentials.automatic_reviewer) { + const grant=await store.automaticGrant(liveRepo.id,Number(installation.id)); + if (!grant || grant.actor.toLowerCase()!==config.credentials.automatic_reviewer.toLowerCase() || grant.credential_mode!==config.credentials.mode) return 'automatic_credential_not_authorized'; + actor=grant.actor;actorId=grant.actor_id;automaticGrantId=grant.id; + livePermission=await permission(github,fullName,actor,actorId); + requireCondition(livePermission==='admin' && authorize(actor,livePermission,config.authorization),'automatic_reviewer_not_authorized',403); + if (config.credentials.mode==='chatgpt' && !await store.session(liveRepo.id,actorId,Number(installation.id))) return 'automatic_credential_not_connected'; + } let prNumber: number; let command; const reject = async (code: RejectionCode): Promise => { @@ -123,8 +133,9 @@ export async function ingest(event: string, payload: unknown, requestId: string, requireCondition(Number.isSafeInteger(pr.commits) && pr.commits > 0 && Number.isSafeInteger(pr.changed_files) && pr.changed_files >= 0, 'invalid_pr_counts'); let snapshot: RequestSnapshot = { id: requestId, installationId: Number(installation.id), repositoryId: liveRepo.id, ownerId: liveRepo.owner.id, + ...(!command.merge && config.merge.enabled && config.merge.auto_merge_on_approval && authorize(actor,livePermission,config.merge.authorization,true) ? {mergeIntent:'automatic' as const} : {}), repository: liveRepo.full_name, defaultBranch: liveRepo.default_branch, workflowSha: branch.commit.sha, - head: pr.head.sha, base: pr.base.sha, pr: prNumber, actor: sender.login, actorId: Number(sender.id), command, config, createdAt: Date.now(), ...(manual && Number.isSafeInteger(record(input.comment).id) ? {commandId:Number(record(input.comment).id)} : {}), commits: pr.commits, changedFiles: pr.changed_files + head: pr.head.sha, base: pr.base.sha, pr: prNumber, actor, actorId, ...(automaticGrantId ? {triggerActor:{login:sender.login,id:Number(sender.id),...(sender.type==='Bot'?{type:'Bot' as const}:{})},automaticGrantId} : {}), command, config, createdAt: Date.now(), ...(manual && Number.isSafeInteger(record(input.comment).id) ? {commandId:Number(record(input.comment).id)} : {}), commits: pr.commits, changedFiles: pr.changed_files }; try { snapshot = await store.create(snapshot, env.TRUSTED_WORKFLOW, manual); } catch (error) { diff --git a/tests/admission-runtime-worker.ts b/tests/admission-runtime-worker.ts index 4dc8734..9c165b1 100644 --- a/tests/admission-runtime-worker.ts +++ b/tests/admission-runtime-worker.ts @@ -1,3 +1,5 @@ +import {randomSecret,seal} from '../src/core/crypto.js'; +import {clean} from './fixtures.js'; // Local workerd harness only; this module is never a production entry point. import worker from '../src/worker/index.js'; import { Store } from '../src/worker/store.js'; @@ -6,6 +8,14 @@ import { snapshot } from './fixtures.js'; export default { ...worker, async fetch(request: Request,env: Env): Promise { + if(new URL(request.url).pathname==='/__automatic-contract') { + const store=new Store(env.DB),candidate={...snapshot(),id:crypto.randomUUID(),installationId:11,repositoryId:22,actorId:55,triggerActor:{login:'bob',id:6},automaticGrantId:''};candidate.config.credentials.automatic_reviewer='alice'; + const envelope=await seal({},randomSecret(),'runtime-owner');await store.saveSession(22,55,envelope,11);await store.automaticConsent(22,11,55,'alice','chatgpt');candidate.automaticGrantId=(await store.automaticGrant(22,11))!.id; + await store.create(candidate);await store.acquire(candidate);await store.transition(candidate.id,'created','running','123');await store.result(candidate.id,clean(),true,'123');const lease=await store.claimPublication(candidate.id,'123');await store.heartbeat(candidate.id,lease); + await store.automaticConsent(22,11,55,'alice','chatgpt');let rotateDenied=false,publishDenied=false; + try{await store.rotate(candidate,1,envelope);}catch{rotateDenied=true;}try{await store.heartbeat(candidate.id,lease);}catch{publishDenied=true;} + return Response.json({rotateDenied,publishDenied,otherInstallation:await store.automaticGrant(22,12)}); + } if(new URL(request.url).pathname!=='/__admission-contract')return worker.fetch(request,env); const candidate=snapshot();candidate.config.quotas.cooldown_seconds=0; const attempts=await Promise.allSettled([new Store(env.DB).create(candidate,'',true),new Store(env.DB).create({...candidate,id:crypto.randomUUID()},'',true)]); diff --git a/tests/backend.test.ts b/tests/backend.test.ts index 268edd1..1a008c7 100644 --- a/tests/backend.test.ts +++ b/tests/backend.test.ts @@ -13,6 +13,8 @@ await test('hosted config, manifest and generated callers agree on Workers.dev w 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@badae8262bc531c8dd02a4f7357d2dbb25b3e754'); + assert.equal(config.vars.WEB_ENABLED,'false');assert.equal(config.vars.OPENAI_HOSTED_INFERENCE_AUTHORIZED,'false'); + assert.equal(config.vars.MERGE_ACCEPTANCE_REPOSITORY_ID,'');assert.equal(config.vars.MERGE_ACCEPTANCE_INSTALLATION_ID,''); assert.deepEqual(config.routes, []); 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`); diff --git a/tests/cli-errors.test.ts b/tests/cli-errors.test.ts index 7305a28..b6ae571 100644 --- a/tests/cli-errors.test.ts +++ b/tests/cli-errors.test.ts @@ -65,12 +65,12 @@ await test('known AppError codes survive, while arbitrary messages, codes, malfo const preload = ` import childProcess from 'node:child_process'; import {syncBuiltinESMExports} from 'node:module'; -const spawn = childProcess.spawn, scenario = process.env.CODEXBOT_TEST_SCENARIO; +const spawn = childProcess.spawn, scenario = process.env.CODEXBOT_TEST_SCENARIO;let consentPhase=0,keyStored=false; childProcess.spawn = (file, args, options) => { if (file !== 'gh') return spawn(file, args, options); if (scenario === 'missing-gh') throw Object.assign(new Error(${JSON.stringify(sensitive)}), {code:'ENOENT'}); if (args.join(' ') === 'auth token') return spawn(process.execPath, ['-e', 'process.stdout.write("fixture-github-token")'], options); - if (scenario === 'api-key-success' && args[0] === 'secret' && args[1] === 'set') return spawn(process.execPath, ['-e', 'process.stdin.resume()'], options); + if (scenario.startsWith('api-key') && args[0] === 'secret' && args[1] === 'set') {if(scenario==='api-key-consent'&&consentPhase!==1)throw new Error('Consent must be reset before replacement');keyStored=true;return spawn(process.execPath, ['-e', 'process.stdin.resume()'], options);} throw new Error('Unexpected fixture gh operation'); }; syncBuiltinESMExports(); @@ -85,6 +85,7 @@ globalThis.fetch = async (input, init) => { 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}); } + if (url.origin === process.env.CODEXBOT_TEST_BACKEND && url.pathname === '/v1/session' && init.method === 'POST') { const body=JSON.parse(init.body);if(body.mode!=='api-key')throw new Error('Unexpected consent mode');if(body.enabled===false){consentPhase=1;return Response.json({status:'automatic_reviews_revoked'});}if(scenario==='api-key-consent'&&body.enabled===true&&consentPhase===1&&keyStored){consentPhase=2;return Response.json({status:'automatic_reviews_authorized'});}throw new Error('Unexpected consent'); } if (scenario === 'oauth-discovery-failure' && url.origin === 'https://auth.openai.com') throw new TypeError(${JSON.stringify(sensitive)}, {cause:Object.assign(new Error('fixture DNS failure'),{code:'ENOTFOUND'})}); if (url.origin !== 'https://api.github.com') throw new Error('Fixture denied external network'); if (url.pathname === '/user') return Response.json({id:5,login:'fixtureuser'}); @@ -92,19 +93,20 @@ globalThis.fetch = async (input, init) => { if (url.pathname === '/repos/owner/repo/environments') return Response.json({environments:[],total_count:0}); if (url.pathname === '/repos/owner/repo/branches/main') return Response.json({protected:true}); if (url.pathname.startsWith('/repos/owner/repo/environments/')) { + if (scenario === 'api-key-consent') {if(url.pathname.endsWith('/deployment-branch-policies'))return Response.json({total_count:1,branch_policies:[{name:'main',type:'branch'}]});return Response.json({deployment_branch_policy:{protected_branches:false,custom_branch_policies:true}});} if (scenario === 'api-key-success' || scenario === 'oauth-discovery-failure') return Response.json({deployment_branch_policy:{protected_branches:true}}); if (init.method === 'GET') return Response.json({message:'Not Found'},{status:404}); return Response.json({message:${JSON.stringify(sensitive)},errors:[{code:'invalid',message:${JSON.stringify(sensitive)}}]},{status:422}); } throw new Error('Unexpected fixture HTTP operation'); };`; -function runCli(scenario: string, command = 'connect', backend: string | null = 'https://broker.invalid') { +function runCli(scenario: string, command = 'connect', backend: string | null = 'https://broker.invalid', automatic = false) { 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_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 { - 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 result = spawnSync(process.execPath, ['--import', 'tsx', '--import', `data:text/javascript,${encodeURIComponent(preload)}`, 'src/cli.ts', command, '--repository', 'owner/repo', ...(backend ? ['--backend', backend] : []), ...(automatic?['--allow-automatic-reviews']:[]), ...(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')) : [] }; } @@ -143,3 +145,8 @@ await test('actual CLI setup/connect defaults to Workers.dev, preserves self-hos noSecrets(connected.stderr); } }); + +await test('actual API-key CLI grants unattended consent only after strict owning Environment provisioning and explicit opt-in',()=>{ + const result=runCli('api-key-consent','connect-api-key','https://broker.invalid',true); + assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/Automatic PR-event reviews explicitly authorized/);assert.equal(result.stderr,'');noSecrets(result.stdout); +}); diff --git a/tests/core.test.ts b/tests/core.test.ts index 9ebba94..7383703 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -1,3 +1,4 @@ +import { deploymentMergeEnabled } from '../src/core/review.js'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import { parseCommand, validateHandle, EFFORTS } from '../src/core/command.js'; @@ -114,3 +115,25 @@ await test('review text neutralizes remote-image markdown, HTML and mass mention assert.ok(!value.includes('{ + const defaults=parseConfig('');assert.equal(defaults.merge.minimum_human_approvals,0);assert.equal(defaults.merge.auto_merge_on_approval,false);assert.equal(defaults.merge.enabled,false); + for(let humans=0;humans<=6;humans++)assert.equal(parseConfig(`merge: {enabled: true, auto_merge_on_approval: true, minimum_human_approvals: ${humans}}`).merge.minimum_human_approvals,humans); + for(const value of [-1,0.5,7])assert.throws(()=>parseConfig(`merge: {minimum_human_approvals: ${value}}`)); +}); + +await test('disposable merge acceptance never enables a foreign repository, installation or the global gate',()=>{ + const env={MERGE_DEPLOYMENT_AUTHORIZED:'false',MERGE_ACCEPTANCE_REPOSITORY_ID:'2',MERGE_ACCEPTANCE_INSTALLATION_ID:'1'}; + assert.equal(deploymentMergeEnabled(env,{repositoryId:2,installationId:1}),true); + assert.equal(deploymentMergeEnabled(env,{repositoryId:3,installationId:1}),false);assert.equal(deploymentMergeEnabled(env,{repositoryId:2,installationId:9}),false); + assert.equal(deploymentMergeEnabled({MERGE_DEPLOYMENT_AUTHORIZED:'false'},{repositoryId:2,installationId:1}),false); + assert.equal(deploymentMergeEnabled({...env,MERGE_ACCEPTANCE_REPOSITORY_ID:''},{repositoryId:2,installationId:1}),false); + assert.equal(env.MERGE_DEPLOYMENT_AUTHORIZED,'false'); +}); + +await test('verified bot policy identities allow only the literal platform suffix without changing command handles', () => { + assert.equal(policyAllows('github-actions[bot]',{whitelist:'*',blacklist:'*'}),true); + assert.equal(policyAllows('github-actions[bot]',{whitelist:'*',blacklist:'re:github-actions\\[bot\\]'}),false); + for(const login of ['github-actions[other]','github-actions[bot]x','github-actions[bot]\n','github-actions[bot]@other']) assert.equal(policyAllows(login,{whitelist:'*',blacklist:'*'}),false); + assert.throws(()=>validateHandle('@github-actions[bot]')); +}); diff --git a/tests/github-fixture.ts b/tests/github-fixture.ts index c8ab9ad..3a934fb 100644 --- a/tests/github-fixture.ts +++ b/tests/github-fixture.ts @@ -8,6 +8,7 @@ export function githubFixture() { ci: 'SUCCESS', guarded: false, requiredHumans: 1, rules: [] as Record[], autoMergeOwner: null as string | null, humans: [{ id: 80, state: 'APPROVED', commit_id: HEAD, user: { id: 6, login: 'bob', type: 'User' } }] as Record[], checks: [] as Record[], contextTruncated: false, comments: [] as Record[], runStatus: 'in_progress', runConclusion: null as string | null, + permissionsByLogin: {} as Record, runActor: { id: 42, type: 'Bot', login: 'codexbot[bot]' } }; const calls: { method: string; path: string; body: Record }[] = []; const fetcher: typeof fetch = async (input, init) => { @@ -24,7 +25,12 @@ export function githubFixture() { if (path === '/repos/owner/repo/rules/branches/main') return ok(state.rules); if (path === '/repos/owner/repo/branches/main/protection') return ok({ required_status_checks: { checks: [{ context: 'ci', app_id: null }, ...(state.guarded ? [{ context: config.merge.guard_check, app_id: 42 }] : [])] }, required_pull_request_reviews: { required_approving_review_count: state.requiredHumans } }); if (path === '/repos/owner/repo/contents/.codexbot.yml') return ok({ type: 'file', size: 1000, content: Buffer.from(stringify(config)).toString('base64') }); - if (path.includes('/collaborators/') && path.endsWith('/permission')) { const login = decodeURIComponent(path.split('/').at(-2)!); return ok({ permission: state.permission, user: { id: login === 'alice' ? state.userId : 6, login, type: 'User' } }); } + if (path.includes('/collaborators/') && path.endsWith('/permission')) { const login = decodeURIComponent(path.split('/').at(-2)!); return ok({ permission: state.permissionsByLogin[login] ?? state.permission, user: { id: login === 'github-actions[bot]' ? 41898282 : login === 'alice' ? state.userId : 6, login, type: login === 'github-actions[bot]' ? 'Bot' : 'User' } }); } + if(path==='/users/bob')return ok({id:6,login:'bob',type:'User'}); + if(path==='/repos/owner/repo/environments')return ok({total_count:1,environments:[{name:'codexbot-1-5'}]}); + if(path==='/repos/owner/repo/environments/codexbot-1-5')return ok({deployment_branch_policy:{protected_branches:false,custom_branch_policies:true}}); + if(path==='/repos/owner/repo/environments/codexbot-1-5/deployment-branch-policies')return ok({total_count:1,branch_policies:[{name:'main',type:'branch'}]}); + if(path.startsWith('/repos/owner/repo/environments/codexbot-1-5/secrets/'))return ok({name:path.split('/').at(-1),created_at:'2026-01-01T00:00:00Z',updated_at:'2026-01-01T00:00:00Z'}); if (path === '/users/alice' || path === '/user') return ok({ id: state.userId, login: 'alice', type: 'User' }); if (path === '/repos/owner/repo/pulls/4') return ok({ number: 4, head: { sha: state.head }, base: { sha: state.base, ref: 'main', repo }, user: { id: state.author === 'alice' ? 5 : 7, login: state.author }, state: state.merged ? 'closed' : 'open', merged: state.merged, draft: false, changed_files: 1, commits: 1 }); if (path === '/repos/owner/repo/issues/4/comments') { diff --git a/tests/merge.test.ts b/tests/merge.test.ts index 11fa9a5..f90df16 100644 --- a/tests/merge.test.ts +++ b/tests/merge.test.ts @@ -44,7 +44,7 @@ await test('bot approval cannot satisfy an extra required human, and stale/autho if (condition === 'stale') f.state.humans[0]!.commit_id = BASE; if (condition === 'author') f.state.humans[0]!.user = { type: 'User', login: 'alice' }; if (condition === 'bot') f.state.humans[0]!.user = { type: 'Bot', login: 'another[bot]' }; - assert.equal((await publish(f.github, f.request, clean(), true, 'codexbot', enabled)).merge, 'independent_human_approvals_required'); + assert.equal((await publish(f.github, f.request, clean(), true, 'codexbot', enabled)).merge, 'queued'); } }); await test('every GitHub merge state has an explicit safe outcome and merge queues are never bypassed', async () => { @@ -74,8 +74,68 @@ await test('CI state policy rejects all failure conclusions and treats unknown/n await test('human approval counts immutable IDs once and live permissions must belong to the reviewed user ID', async () => { const f = mergeFixture(); f.state.requiredHumans = 2; f.state.humans.push({ id: 81, state: 'APPROVED', commit_id: HEAD, user: { id: 6, login: 'renamed-bob', type: 'User' } }); - assert.equal((await publish(f.github, f.request, clean(), true, 'codexbot', enabled)).merge, 'independent_human_approvals_required'); + assert.equal((await publish(f.github, f.request, clean(), true, 'codexbot', enabled)).merge, 'queued'); const forged = mergeFixture(); forged.state.humans[0]!.user = { id: 999, login: 'bob', type: 'User' }; await assert.rejects(publish(forged.github, forged.request, clean(), true, 'codexbot', enabled), /permission_identity_changed/); assert.equal(forged.calls.some(x => String(x.body.query).includes('mutation') && String(x.body.query).includes('mergePullRequest')), false); }); + +function autonomousFixture() { + const f=githubFixture(),request=snapshot(); + request.mergeIntent='automatic'; + Object.assign(f.config.merge,{enabled:true,auto_merge_on_approval:true,minimum_human_approvals:0}); + f.config.merge.authorization.whitelist='alice';f.state.requiredHumans=0;f.state.humans=[]; + return {...f,request}; +} +await test('fully autonomous policy publishes a genuine native approval and exact-head merge without a human or --merge',async()=>{ + const f=autonomousFixture();assert.equal(f.request.command.merge,false); + const result=await publish(f.github,f.request,clean(),true,'codexbot',enabled); + assert.equal(result.event,'APPROVE');assert.equal(result.merge,'merged');assert.equal(f.state.reviews[0]!.state,'APPROVED'); + assert.equal(f.state.humans.length,0);assert.ok(String(f.state.reviews[0]!.body).includes('repository policy')); + const mutation=f.calls.find(call=>String(call.body.query).includes('mutation')&&String(call.body.query).includes('mergePullRequest'));assert.ok(mutation);assert.equal((mutation.body.variables as Record).head,HEAD); + assert.equal((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'merged');assert.equal(f.state.reviews.length,1); +}); +await test('automatic merging remains opt-in and requires an admission-bound intent plus independent merge authorization',async()=>{ + for(const scenario of ['no-intent','explicit-only','disabled','unauthorized','gate-closed'] as const){ + const f=autonomousFixture(); + if(scenario==='no-intent')delete f.request.mergeIntent; + if(scenario==='explicit-only')f.config.merge.auto_merge_on_approval=false; + if(scenario==='disabled')f.config.merge.enabled=false; + if(scenario==='unauthorized')f.config.merge.authorization.whitelist='bob'; + const result=await publish(f.github,f.request,clean(),true,'codexbot',scenario==='gate-closed'?{}:enabled); + assert.notEqual(result.merge,'merged',scenario);assert.equal(f.state.merged,false); + } +}); +await test('autonomous mode cannot override GitHub human counts, CODEOWNERS or last-push approval rules',async()=>{ + for(const condition of ['count','codeowners','last-push'] as const){ + const f=autonomousFixture(); + if(condition==='count')f.state.requiredHumans=1; + else f.state.rules=[{type:'pull_request',parameters:{required_approving_review_count:0,...(condition==='codeowners'?{require_code_owner_review:true}:{require_last_push_approval:true})}}]; + assert.equal((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'queued'); + assert.equal(f.state.merged,false); + } + const human=autonomousFixture();human.config.merge.minimum_human_approvals=1; + assert.equal((await publish(human.github,human.request,clean(),true,'codexbot',enabled)).merge,'queued'); + assert.equal(human.state.autoMergeOwner,null);assert.equal(human.state.merged,false); + human.state.humans.push({id:80,state:'APPROVED',commit_id:HEAD,user:{id:6,login:'bob',type:'User'}}); + assert.equal((await publish(human.github,human.request,clean(),true,'codexbot',enabled)).merge,'merged'); +}); +await test('autonomous pending-CI intent uses the same App-bound guard and fails closed on adverse evidence',async()=>{ + const f=autonomousFixture();f.state.mergeState='BLOCKED';f.state.ci='PENDING';f.state.guarded=true; + assert.equal((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'queued');assert.equal(f.state.checks[0]!.status,'in_progress'); + f.state.ci='SUCCESS';assert.equal((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'queued'); + f.state.mergeState='CLEAN';assert.equal((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'merged'); + for(const issue of ['failed','conflict','unknown','queue','missing-guard'] as const){ + const f=autonomousFixture();f.state.ci='PENDING';f.state.mergeState='BLOCKED'; + if(issue==='failed')f.state.ci='FAILURE'; + if(issue==='conflict')f.state.mergeState='DIRTY'; + if(issue==='unknown')f.state.mergeState='UNKNOWN'; + if(issue==='queue')f.state.rules=[{type:'merge_queue'}]; + assert.notEqual((await publish(f.github,f.request,clean(),true,'codexbot',enabled)).merge,'merged');assert.equal(f.state.autoMergeOwner,null); + } +}); +await test('no autonomous merge for advisory, incomplete or blocking AI output',async()=>{ + for(const output of [{...clean(),complete:false,result:'inconclusive'}, {...clean(),result:'findings',findings:[{severity:'medium',confidence:0.99,path:'src/auth.ts',line:2,side:'RIGHT',title:'Regression',explanation:'Observed issue.',remediation:'Restore the check.'}]}, {...clean(),result:'findings',findings:[{severity:'high',confidence:0.99,path:'src/auth.ts',line:2,side:'RIGHT',title:'Missing authorization',explanation:'Observed access bypass.',remediation:'Restore the check.'}]}]){ + const f=autonomousFixture();const result=await publish(f.github,f.request,output,true,'codexbot',enabled);assert.notEqual(result.event,'APPROVE');assert.equal(f.state.merged,false); + } +}); diff --git a/tests/store.test.ts b/tests/store.test.ts index 7ccc639..f2f9820 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -1,4 +1,4 @@ -import { test } from 'node:test'; +import { test, mock } from 'node:test'; import assert from 'node:assert/strict'; import { database } from './sqlite.js'; import { Store } from '../src/worker/store.js'; @@ -58,3 +58,31 @@ await test('cleanup releases only terminal or expired session leases, preserving await store.acquire({ ...request, id: crypto.randomUUID() }); await assert.rejects(store.acquire({ ...other, id: crypto.randomUUID() })); } finally { sqlite.close(); } }); + +await test('automatic owner consent is installation/repository scoped, survives refresh and is revoked by reprovisioning or disconnect',async()=>{ + const {db,sqlite}=database(),store=new Store(db),request=snapshot();request.config.credentials.automatic_reviewer='alice';request.triggerActor={login:'bob',id:6}; + try{ + await assert.rejects(store.automaticConsent(2,1,5,'alice','chatgpt'),/connect_own_credentials/); + await store.saveSession(2,5,await seal({},randomSecret(),'fixture'),1);await store.automaticConsent(2,1,5,'alice','chatgpt');request.automaticGrantId=(await store.automaticGrant(2,1))!.id; + await store.acquire(request);await store.rotate(request,1,await seal({},randomSecret(),'rotated'));await store.authorizeAutomatic(request);await store.release(request); + await assert.rejects(store.authorizeAutomatic({...request,installationId:9}),/authorization_revoked/);await assert.rejects(store.authorizeAutomatic({...request,repositoryId:9}),/authorization_revoked/); + await store.saveSession(2,5,await seal({},randomSecret(),'reconnected'),1);await assert.rejects(store.authorizeAutomatic(request),/authorization_revoked/); + await store.automaticConsent(2,1,5,'alice','chatgpt');await store.deleteSession(2,5,1);assert.equal(await store.automaticGrant(2,1),null); + }finally{sqlite.close();} +}); + +await test('revoked or replaced owner consent cannot rotate credentials, renew a publication lease or revive an old automatic intent',async()=>{ + const {db,sqlite}=database(),store=new Store(db),request=snapshot();request.config.credentials.automatic_reviewer='alice';request.triggerActor={login:'bob',id:6}; + const value=await seal({},randomSecret(),'owner'); + try{ + await store.saveSession(2,5,value,1);await store.automaticConsent(2,1,5,'alice','chatgpt');request.automaticGrantId=(await store.automaticGrant(2,1))!.id; + await store.create(request);await store.acquire(request);await store.transition(request.id,'created','running','123');await store.result(request.id,clean(),true,'123');const lease=await store.claimPublication(request.id,'123');await store.heartbeat(request.id,lease); + await store.automaticConsent(2,1,5,'alice','chatgpt');assert.notEqual((await store.automaticGrant(2,1))!.id,request.automaticGrantId); + await assert.rejects(store.authorizeAutomatic(request),/authorization_revoked/);await assert.rejects(store.rotate(request,1,value),/rotation_conflict/);assert.equal((await store.session(2,5,1))!.version,1); + await assert.rejects(store.heartbeat(request.id,lease),/publication_lease_lost/); + const current={...request,automaticGrantId:(await store.automaticGrant(2,1))!.id};await store.release(request); + const prepare=db.prepare.bind(db);const race=mock.method(db,'prepare',(sql:string)=>{if(sql.startsWith('UPDATE sessions SET lease_request='))sqlite.prepare('DELETE FROM automatic_review_grants').run();return prepare(sql);}); + try{await assert.rejects(store.acquire(current),/session_missing_or_in_use/);}finally{race.mock.restore();} + assert.equal(sqlite.prepare('SELECT lease_request FROM sessions').get()!.lease_request,null); + }finally{sqlite.close();} +}); diff --git a/tests/web-auth.test.ts b/tests/web-auth.test.ts index b4d98bd..13d35af 100644 --- a/tests/web-auth.test.ts +++ b/tests/web-auth.test.ts @@ -1,3 +1,4 @@ +import { configurationFields } from '../src/worker/onboarding.js'; import { test, mock } from 'node:test'; import assert from 'node:assert/strict'; import { generateKeyPair, exportPKCS8 } from 'jose'; @@ -179,3 +180,11 @@ await test('browser encryption is bound to origin and ID; uninstall removes only assert.deepEqual(f.sqlite.prepare('SELECT installation_id FROM web_connections').all().map(row => row.installation_id), [9]); } finally { f.close(); } }); + +await test('browser merge modes use canonical reviewed settings and retain explicit opt-in and human limits',()=>{ + const html=configurationFields(DEFAULT_CONFIG);assert.ok(html.includes('Fully Autonomous'));assert.ok(html.includes('Human-in-the-Loop'));assert.ok(html.includes('GitHub repository protections still apply')); + const form=configForm();form.set('merge.enabled','true');form.set('merge.auto_merge_on_approval','true');form.set('merge.minimum_human_approvals','0'); + const autonomous=configurationFromForm(form);assert.equal(autonomous.merge.minimum_human_approvals,0);assert.equal(autonomous.merge.auto_merge_on_approval,true); + form.set('merge.minimum_human_approvals','2');assert.equal(configurationFromForm(form).merge.minimum_human_approvals,2); + form.append('merge.minimum_human_approvals','0');assert.throws(()=>configurationFromForm(form),/duplicate_configuration_field/); +}); diff --git a/tests/web-browser.mjs b/tests/web-browser.mjs index 02c68ca..c91f1e1 100644 --- a/tests/web-browser.mjs +++ b/tests/web-browser.mjs @@ -62,10 +62,13 @@ try { assert.equal((await (await context.request.get(origin+'/__fixture/state')).json()).pulls,1); await page.goto(repository); await page.getByText('Review policy & configuration',{exact:true}).click(); await page.locator('[name="review.model"]').selectOption('gpt-6.1-sol'); await page.locator('[name="review.effort"]').selectOption('high'); await page.locator('[name="review.auto_approve"]').uncheck(); + await page.getByLabel('Merge mode',{exact:true}).selectOption('0'); await page.locator('[name="merge.auto_merge_on_approval"]').check(); + await page.getByLabel('Merge mode',{exact:true}).selectOption('2'); await page.getByRole('button',{name:'Propose configuration / workflow update'}).click(); await page.getByRole('heading',{name:'Changes proposed.'}).waitFor(); assert.equal((await (await context.request.get(origin+'/__fixture/state')).json()).pulls,2); await page.goto(repository); await page.getByText('Review policy & configuration',{exact:true}).click(); assert.equal(await page.locator('[name="review.auto_approve"]').isChecked(),true,'Policy cannot change before PR merge'); + assert.equal(await page.locator('[name="merge.auto_merge_on_approval"]').isChecked(),false); assert.equal(await page.getByLabel('Merge mode',{exact:true}).inputValue(),'0'); const csrfRejected = await context.request.post(origin+'/dashboard/setup',{headers:{origin:'https://evil.invalid'},form:{installation:'1',repository:'2',csrf:'forged'}}); assert.equal(csrfRejected.status(),403); const foreign = await page.goto(`${origin}/dashboard/repository?installation=9&repository=2`); assert.equal(foreign.status(),403); await page.goto(repository); await page.setViewportSize({width:390,height:844}); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); await page.setViewportSize({width:1440,height:1000}); diff --git a/tests/worker.test.ts b/tests/worker.test.ts index 514c7b4..39ed20b 100644 --- a/tests/worker.test.ts +++ b/tests/worker.test.ts @@ -27,7 +27,7 @@ function signed(input: unknown, secret: string, delivery = crypto.randomUUID()): } async function fixture(action: (env: Env, github: ReturnType) => Promise): Promise { const { db, sqlite } = database(), github = githubFixture(); github.config.credentials.mode = 'api-key'; - const env: Env = { WEB_ENABLED: 'false', GITHUB_CLIENT_ID: '', OPENAI_WEB_CLIENT_ID: '', OPENAI_WEB_AUTH_METHOD: '', OPENAI_WEB_SCOPES: '', OPENAI_HOSTED_INFERENCE_AUTHORIZED: 'false', DB: db, PUBLIC_URL: 'https://broker.invalid', GITHUB_APP_ID: '42', GITHUB_APP_SLUG: 'codexbot', GITHUB_PRIVATE_KEY: pem, GITHUB_WEBHOOK_SECRET: 'fixture-webhook-secret'.repeat(2), TRUSTED_WORKFLOW: `operator/codexbot/.github/workflows/review.yml@${RELEASE}`, CHATGPT_DEPLOYMENT_AUTHORIZED: 'false', MERGE_DEPLOYMENT_AUTHORIZED: 'false' }; + const env: Env = { MERGE_ACCEPTANCE_REPOSITORY_ID:'',MERGE_ACCEPTANCE_INSTALLATION_ID:'',WEB_ENABLED: 'false', GITHUB_CLIENT_ID: '', OPENAI_WEB_CLIENT_ID: '', OPENAI_WEB_AUTH_METHOD: '', OPENAI_WEB_SCOPES: '', OPENAI_HOSTED_INFERENCE_AUTHORIZED: 'false', DB: db, PUBLIC_URL: 'https://broker.invalid', GITHUB_APP_ID: '42', GITHUB_APP_SLUG: 'codexbot', GITHUB_PRIVATE_KEY: pem, GITHUB_WEBHOOK_SECRET: 'fixture-webhook-secret'.repeat(2), TRUSTED_WORKFLOW: `operator/codexbot/.github/workflows/review.yml@${RELEASE}`, CHATGPT_DEPLOYMENT_AUTHORIZED: 'false', MERGE_DEPLOYMENT_AUTHORIZED: 'false' }; const replacement: typeof fetch = async (input, init) => String(input).includes('token.actions.githubusercontent.com/.well-known/jwks') ? Response.json({ keys: [jwk] }) : github.fetcher(input, init); const intercepted = mock.method(globalThis, 'fetch', replacement); try { return await action(env, github); } finally { intercepted.mock.restore(); sqlite.close(); } @@ -46,7 +46,7 @@ await test('retained aliases expose only public pages; privileged routes never r 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('Get started with GitHub')); + const page = await response.text(); assert.ok(page.includes('CLI setup instructions')); assert.ok(page.includes(``)); assert.ok(!page.includes('WORKER_URL')); } } @@ -354,3 +354,64 @@ await test('fresh invalid commands get fixed feedback; unauthorized, other-bot, assert.equal((await worker.fetch(signed(payload('@codexbot review --bad sensitive-fixture'),env.GITHUB_WEBHOOK_SECRET),env)).status,200); assert.equal(f.state.comments.length,1);assert.ok(!String(f.state.comments[0]!.body).includes('sensitive-fixture'));assert.equal(f.state.reviews.length,0); })); + +await test('policy-based merge intent is admitted only for independently merge-authorized reviewers without changing the original flag',async()=>{ + for(const allowed of [true,false])await fixture(async(env,f)=>{ + Object.assign(f.config.merge,{enabled:true,auto_merge_on_approval:true,minimum_human_approvals:0});f.config.merge.authorization.whitelist=allowed?'alice':'bob'; + assert.equal((await worker.fetch(signed(payload(),env.GITHUB_WEBHOOK_SECRET),env)).status,202); + const row=await env.DB.prepare('SELECT snapshot FROM requests').first<{snapshot:string}>();const request=JSON.parse(row!.snapshot); + assert.equal(request.command.merge,false);assert.equal(request.mergeIntent,allowed?'automatic':undefined); + }); +}); +await test('automatic reviews on PR events bind credentials and optional merge intent to the authorized event actor',async()=>fixture(async(env,f)=>{ + f.config.review.auto_review=true;f.config.authorization.whitelist='bob';Object.assign(f.config.merge,{enabled:true,auto_merge_on_approval:true});f.config.merge.authorization.whitelist='bob';f.config.quotas.cooldown_seconds=0; + for(const [index,action] of ['opened','synchronize','ready_for_review'].entries()){ + f.state.head=String(index+1).repeat(40); + const input={action,installation:{id:1},repository:{id:2,full_name:'owner/repo'},sender:{id:6,login:'bob',type:'User'},number:4,pull_request:{updated_at:new Date().toISOString(),head:{sha:f.state.head}}}; + const body=JSON.stringify(input);const response=await worker.fetch(new Request('https://broker.invalid/webhook',{method:'POST',body,headers:{'x-github-event':'pull_request','x-github-delivery':crypto.randomUUID(),'x-hub-signature-256':`sha256=${createHmac('sha256',env.GITHUB_WEBHOOK_SECRET).update(body).digest('hex')}`}}),env); + assert.equal(response.status,202);const dispatch=f.calls.filter(call=>call.path.endsWith('/dispatches')).at(-1)!;assert.equal((dispatch.body.inputs as Record).credential_owner,'6'); + const row=await env.DB.prepare("SELECT id,snapshot FROM requests WHERE actor_id=6 AND state='dispatched'").first<{id:string;snapshot:string}>();assert.ok(row);assert.equal(JSON.parse(row.snapshot).mergeIntent,'automatic'); + // Synthetic test completion permits the next distinct PR event; no provider is invoked. + await env.DB.prepare("UPDATE requests SET state='failed' WHERE id=?").bind(row.id).run(); + assert.equal(await new Store(env.DB).session(2,6,1),null);await assert.rejects(new Store(env.DB).acquire(JSON.parse(row.snapshot)),/session_missing_or_in_use/); + } + assert.equal(f.calls.filter(call=>call.path.endsWith('/dispatches')).length,3); +})); + +await test('unconnected authorized contributor uses only an explicitly consenting assigned administrator for PR events, never manual commands',async()=>fixture(async(env,f)=>{ + env.CHATGPT_DEPLOYMENT_AUTHORIZED='true';f.config.credentials={mode:'chatgpt',automatic_reviewer:'alice'};f.config.authorization.whitelist='*';f.config.review.auto_review=true; + f.state.permissionsByLogin={alice:'admin',bob:'read'}; + const store=new Store(env.DB);await store.saveSession(2,5,await seal({},randomSecret(),'synthetic-owner'),1); + const event={action:'opened',installation:{id:1},repository:{id:2,full_name:'owner/repo'},sender:{id:6,login:'bob',type:'User'},number:4,pull_request:{updated_at:new Date().toISOString(),head:{sha:HEAD}}}; + const send=async(action:string)=>{const body=JSON.stringify({...event,action});return worker.fetch(new Request('https://broker.invalid/webhook',{method:'POST',body,headers:{'x-github-event':'pull_request','x-github-delivery':crypto.randomUUID(),'x-hub-signature-256':`sha256=${createHmac('sha256',env.GITHUB_WEBHOOK_SECRET).update(body).digest('hex')}`}}),env);}; + assert.equal((await send('opened')).status,200);assert.equal(f.calls.filter(call=>call.path.endsWith('/dispatches')).length,0,'Configuration alone cannot borrow credentials'); + const consent=async(body:unknown)=>worker.fetch(new Request('https://broker.invalid/v1/session?repository=owner%2Frepo',{method:'POST',headers:{Authorization:'Bearer fixture-user-token'},body:JSON.stringify(body)}),env); + assert.equal((await consent({enabled:true,mode:'chatgpt',actor_id:6})).status,400); + assert.equal((await consent({enabled:true,mode:'chatgpt'})).status,200);assert.equal((await store.automaticGrant(2,1))!.actor_id,5); + assert.equal((await send('reopened')).status,202); + const row=await env.DB.prepare('SELECT snapshot FROM requests').first<{snapshot:string}>();const request=JSON.parse(row!.snapshot); + assert.equal(request.actorId,5);assert.equal(request.actor,'alice');assert.deepEqual(request.triggerActor,{login:'bob',id:6});assert.equal(await store.session(2,6,1),null); + assert.equal((f.calls.find(call=>call.path.endsWith('/dispatches'))!.body.inputs as Record).credential_owner,'5'); + await store.acquire(request);await store.release(request); + assert.equal((await consent({enabled:false})).status,200);await assert.rejects(store.acquire(request),/automatic_review_authorization_revoked/); + assert.equal((await worker.fetch(new Request(`https://broker.invalid/v1/requests/${request.id}/publish`,{method:'POST',headers:{Authorization:`Bearer ${await oidc('codexbot-publish-1')}`},body:'{}'}),env)).status,403); + await store.transition(request.id,'dispatched','failed'); + const manual={...payload(),sender:{id:6,login:'bob',type:'User'},comment:{...payload().comment,user:{id:6}}}; + assert.equal((await worker.fetch(signed(manual,env.GITHUB_WEBHOOK_SECRET),env)).status,202); + const own=await env.DB.prepare('SELECT snapshot FROM requests WHERE actor_id=6').first<{snapshot:string}>();assert.ok(own);assert.equal(JSON.parse(own.snapshot).triggerActor,undefined);assert.equal(await store.session(2,6,1),null); +})); + +await test('unconnected automation contributor requires explicit owner assignment and cannot use it for manual commands', async () => fixture(async (env,f) => { + f.config.credentials={mode:'api-key',automatic_reviewer:'alice'};f.config.authorization.whitelist='*';f.config.review.auto_review=true;f.state.permissionsByLogin={alice:'admin','github-actions[bot]':'read'}; + const store=new Store(env.DB); + const event={action:'opened',installation:{id:1},repository:{id:2,full_name:'owner/repo'},sender:{id:41898282,login:'github-actions[bot]',type:'Bot'},number:4,pull_request:{updated_at:new Date().toISOString(),head:{sha:HEAD}}}; + const send=async()=>{const request=signed(event,env.GITHUB_WEBHOOK_SECRET);request.headers.set('x-github-event','pull_request');return worker.fetch(request,env);}; + assert.equal((await send()).status,200);assert.equal(f.calls.filter(call=>call.path.endsWith('/dispatches')).length,0); + await store.automaticConsent(2,1,5,'alice','api-key');event.action='reopened'; + assert.equal((await send()).status,202); + const row=await env.DB.prepare('SELECT snapshot FROM requests').first<{snapshot:string}>();const request=JSON.parse(row!.snapshot); + assert.equal(request.actorId,5);assert.deepEqual(request.triggerActor,{login:'github-actions[bot]',id:41898282,type:'Bot'}); + const manual={...payload(),sender:event.sender,comment:{...payload().comment,user:{id:41898282}}}; + assert.equal((await worker.fetch(signed(manual,env.GITHUB_WEBHOOK_SECRET),env)).status,403); + assert.equal(f.calls.filter(call=>call.path.endsWith('/dispatches')).length,1); +})); diff --git a/tests/workers-runtime.mjs b/tests/workers-runtime.mjs index 7f389db..511f39f 100644 --- a/tests/workers-runtime.mjs +++ b/tests/workers-runtime.mjs @@ -33,7 +33,7 @@ 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('Get started with GitHub')); + const page = await globalThis.fetch(`${origin}/`); assert.equal(page.status, 200); assert.ok((await page.text()).includes('CLI setup instructions')); 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); @@ -53,7 +53,8 @@ try { assert.deepEqual(leases, [{ installation_id: 1, lease_request: null }, { installation_id: 9, lease_request: 'other-installation' }]); const admission=await (await globalThis.fetch(`${origin}/__admission-contract`)).json(); assert.deepEqual(admission,{accepted:1,rejected:true,outcomes:[{outcome:'duplicate_review',phase:'pending'}]}); - process.stdout.write('Real workerd + D1: atomic admission/outbox, migrations, HMAC, receipts, cron, expired requests and cross-installation lease cleanup passed.\n'); + const automatic=await(await globalThis.fetch(`${origin}/__automatic-contract`)).json();assert.deepEqual(automatic,{rotateDenied:true,publishDenied:true,otherInstallation:null}); + process.stdout.write('Real workerd + D1: owner-consent generation fencing, atomic admission/outbox, migrations, HMAC, receipts, cron, expired requests and cross-installation lease cleanup passed.\n'); } finally { if (child?.pid) { if (process.platform === 'win32') execFileSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore' }); diff --git a/wrangler.jsonc b/wrangler.jsonc index 5a1f899..1defd2f 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -34,6 +34,8 @@ "TRUSTED_WORKFLOW": "AppSolves/codexbot/.github/workflows/review.yml@badae8262bc531c8dd02a4f7357d2dbb25b3e754", "CHATGPT_DEPLOYMENT_AUTHORIZED": "true", "MERGE_DEPLOYMENT_AUTHORIZED": "false", + "MERGE_ACCEPTANCE_REPOSITORY_ID": "", + "MERGE_ACCEPTANCE_INSTALLATION_ID": "", "WEB_ENABLED": "false", "GITHUB_CLIENT_ID": "Iv23liRS1tl8zCodzTEr", "OPENAI_WEB_CLIENT_ID": "",