From 72b1a4edfa176f299deb397602fbfac67bdb263e Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:56:53 +0000 Subject: [PATCH] One instance-wide GitHub identity (box account or GitHub App) replaces the per-repo identity and the login-app variable; app keys are read again when the keys file changes --- README.md | 3 +- deploy/compose/container.env.example | 3 -- docs/dashboard-spec.md | 4 +- docs/deploy-checklist.md | 7 ++- docs/migration.md | 2 +- docs/operations.md | 3 +- docs/pipeline.md | 12 ++--- src/conversations/act.ts | 6 +-- src/dash/api/admin.ts | 20 +------- src/dash/api/index.ts | 1 - src/dash/server/config.ts | 34 ++++++++++--- src/dash/server/github-app.ts | 28 +++++++---- src/dash/server/index.ts | 26 ++++++---- src/dash/server/provider.ts | 22 ++++++-- src/db.ts | 6 ++- src/discord/index.ts | 3 +- src/fixissue/index.ts | 6 +-- src/github/identity.ts | 64 ++++++++++++++---------- src/github/user-lane.ts | 12 ++--- src/github/vault.ts | 8 +-- src/github/write.ts | 6 +-- src/labels/github.ts | 6 +-- src/repos.ts | 35 +++++++------ src/review/post.ts | 4 +- src/security/land.ts | 4 +- src/settlers.ts | 12 ++--- test/api.test.ts | 2 +- test/app-lane.test.ts | 4 +- test/discord-alerts.test.ts | 2 +- test/github-app.test.ts | 29 ++++++++--- test/identity.test.ts | 31 +++++++++--- test/needs-order.test.ts | 2 +- test/own-logins.test.ts | 2 +- test/review-post-carried.test.ts | 2 +- test/user-lane.test.ts | 6 +-- test/write-pacing.test.ts | 2 +- web/src/api/client.ts | 4 +- web/src/api/http.ts | 2 +- web/src/api/mock/adminMock.ts | 36 +++++++------ web/src/api/types.ts | 6 +-- web/src/modules/admin/githubAppViews.tsx | 42 ++++++++++++++-- web/src/modules/admin/repoDetail.tsx | 8 +-- web/src/modules/admin/repoParts.tsx | 38 +------------- 43 files changed, 312 insertions(+), 243 deletions(-) diff --git a/README.md b/README.md index 4e7e3f103..3da8d9a22 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ Write the client ID, client secret and a random session key (at least 32 charact Point `AUTOCRAFT_SECRETS_FILE` at it. The server refuses to start if the file is missing, incomplete, or readable by group or others. -To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Set `AUTOCRAFT_LOGIN_APP=github-app` afterwards; the server refuses to start in that mode without the keys. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. +To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Then choose "GitHub App" as the GitHub identity on the same page; it is refused unless the app covers every tracked repo. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. | Variable | Meaning | |---|---| @@ -99,7 +99,6 @@ To sign in through a GitHub App instead, register it from the dashboard's GitHub | `AUTOCRAFT_LISTEN` | `host:port`, default `127.0.0.1:8993` | | `AUTOCRAFT_DB` | Database path | | `AUTOCRAFT_SECRETS_FILE` | The secrets file above | -| `AUTOCRAFT_LOGIN_APP` | `oauth` (default) or `github-app` | | `AUTOCRAFT_GITHUB_APP_NAME` | App name suggested on the registration form, default `AutoCraft` | | `AUTOCRAFT_WEB_DIST` | Built frontend, default `web/dist` | | `AUTOCRAFT_TRUST_PROXY` | `1` behind a proxy that sets `X-Forwarded-For` | diff --git a/deploy/compose/container.env.example b/deploy/compose/container.env.example index fd97c7c45..c0538b93d 100644 --- a/deploy/compose/container.env.example +++ b/deploy/compose/container.env.example @@ -10,9 +10,6 @@ AUTOCRAFT_TRUST_PROXY=1 # GitHub token for gh (classic token with repo, read:org and workflow). Set the value here only. GH_TOKEN= -# Optional. Sign-in through the GitHub App (needs the github_app_* keys in secrets.json): github-app. Default oauth. -#AUTOCRAFT_LOGIN_APP=oauth - # Optional. Discord: files under /config, mode 0600, owner uid 10001. The key must be the old install's file byte for byte. #AUTOCRAFT_DISCORD_TOKEN_FILE=/config/discord-token #AUTOCRAFT_DISCORD_KEY_FILE=/config/discord-key diff --git a/docs/dashboard-spec.md b/docs/dashboard-spec.md index bee240fa0..c43fa1adc 100644 --- a/docs/dashboard-spec.md +++ b/docs/dashboard-spec.md @@ -196,7 +196,7 @@ The whole dashboard sits behind GitHub sign-in: every page, asset and endpoint e The pipeline runs Claude agents under the operator's own Claude account on the operator's machine, and the operator is responsible for what they do. So nothing a dashboard user enters may steer the pipeline unless the operator has approved it, and a compromised dashboard account must not be able to cause harm. - **Operator**: one or more logins with role `operator` (today only the owner). An operator's answer is **actionable**, including an answer made by adopting someone's opinion. The pipeline reads only actionable answers (`autocraft decisions list --actionable`), and only their option keys: never free text. -- **Who settles a decision.** A login **settles** a decision (answers it, adopts an opinion, uses Backlog, undoes its own answer, presses or edits a resolution card in the item's conversation) when it is an operator, or when all of these hold: its role is `maintainer`; `settings.maintainer_writes` is on; every repo the decision covers has `repo_identity` `app`, so the GitHub writes run as that person through the user lane and never as the box account; and the person has GitHub write permission on every covered repo (read live on a request, from the cached `repo_permissions` value in views and in the pipeline). One helper, `canSettle` in `src/settlers.ts`, holds the rule, and views carry its result as `canSettle` on each decision and card. A maintainer's answer is actionable under the same rule: the pipeline stops counting it when the setting goes off, the repo leaves the app identity, or the login stops being a maintainer. An operator alone undoes someone else's answer, writes to the model in a conversation, edits a fix-up's instructions, switches the pipeline, steps or limits, and manages access, accounts and settings. +- **Who settles a decision.** A login **settles** a decision (answers it, adopts an opinion, uses Backlog, undoes its own answer, presses or edits a resolution card in the item's conversation) when it is an operator, or when all of these hold: its role is `maintainer`; `settings.maintainer_writes` is on; the GitHub identity is `app`, so the GitHub writes run as that person through the user lane and never as the box account; and the person has GitHub write permission on every covered repo (read live on a request, from the cached `repo_permissions` value in views and in the pipeline). One helper, `canSettle` in `src/settlers.ts`, holds the rule, and views carry its result as `canSettle` on each decision and card. A maintainer's answer is actionable under the same rule: the pipeline stops counting it when the setting goes off, the GitHub identity goes back to the box account, or the login stops being a maintainer. An operator alone undoes someone else's answer, writes to the model in a conversation, edits a fix-up's instructions, switches the pipeline, steps or limits, and manages access, accounts and settings. - **A settling maintainer's free text stays out of prompts.** The answer note and a card's note are stored and shown, never put in a model prompt or conversation block, and are left out of the memory of operator statements. A maintainer may edit a card's public comment and issue title and body (posted under their own name), and not a fix-up's instructions, which go to the fix-up model. A Merge answer by a settling maintainer counts for a pre-approved merge like an operator's. - **Maintainers give feedback.** Maintainers who do not settle a decision, and operators, use one Feedback box on a decision: an optional pick of one option and free text, at least one of them, whatever their GitHub permission. A pick (an **opinion**: who, which option, the text as its note) is stored in `decision_opinions`; text without a pick is a comment in `decision_comments`. Viewers read only. Picks are shown to everyone with the person's GitHub permission on that repo (`write` or `none`) and a tally per option. They are non-binding: the operator answers, or **adopts** an opinion with one tap, which records the operator's answer with that option and credits the opinion. A person can change or retract their pick until the decision is answered; plain text stays. - **Feedback never reaches the pipeline.** They are display-only: no agent prompt, brief or CLI output used by agents includes them, adopted or not. @@ -250,7 +250,7 @@ GitHub permissions: after sign-in, read the user's permission on each repo with ### Secrets and configuration - The OAuth client secret and the session key are never in the repo, in logs or in error pages. The server reads them from a file named by `AUTOCRAFT_SECRETS_FILE` (mode 0600, JSON) and refuses to start if it's missing, readable by others, or incomplete. -- With a GitHub App, the same file holds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner`. The dashboard writes them itself when an operator registers the app (temporary file in the same directory, mode 0600, renamed over the file). `AUTOCRAFT_LOGIN_APP=github-app` makes the server refuse to start without them; `AUTOCRAFT_GITHUB_APP_NAME` sets the suggested app name. +- With a GitHub App, the same file holds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner`. The dashboard writes them itself when an operator registers the app (temporary file in the same directory, mode 0600, renamed over the file). The keys are read again whenever the file changes, so registering or removing the app needs no restart; `AUTOCRAFT_GITHUB_APP_NAME` sets the suggested app name. - Other configuration (base URL, listen address, port, database path) comes from environment variables, documented in the README with no values specific to one machine. ### Hosting for now diff --git a/docs/deploy-checklist.md b/docs/deploy-checklist.md index 9f3472025..201d2cd45 100644 --- a/docs/deploy-checklist.md +++ b/docs/deploy-checklist.md @@ -44,7 +44,6 @@ The image sets every path (`/data/...`, `/config/...`). A deployment sets only t |---|---|---|---| | `AUTOCRAFT_BASE_URL` | dashboard: yes | none | Public origin, `https://autocraft.example.com`, no path. Used for sign-in callbacks and links. | | `AUTOCRAFT_TRUST_PROXY` | behind a proxy | off | `1` reads the client address from the last `X-Forwarded-For` entry, for rate limits. Set it only when the proxy sets that header. | -| `AUTOCRAFT_LOGIN_APP` | no | `oauth` | `github-app` signs users in through the GitHub App; refused at start unless the app's keys are in `secrets.json`. See "Moving to a new domain". | | `GH_TOKEN` | yes, on dashboard, runner and periodic | none | GitHub token for `gh` (the dashboard's image proxy and repository adds, sync, pipeline calls): a classic token with `repo`, `read:org` and `workflow` scopes. Keep it in a Secret. | | `AUTOCRAFT_STOP_TIMEOUT` | no | `25` | Seconds the runner may take to stop. Keep the pod's `terminationGracePeriodSeconds` above it (30). | | `AUTOCRAFT_HEALTH_LISTEN` | no | off | `host:port` of a runner listener that serves only `/healthz` and `/readyz`. | @@ -125,11 +124,11 @@ Sign-in and the GitHub App are tied to the public origin. Do these in order. `AU - Webhook URL: `https://new.example.com/webhooks/github` (see "Webhooks" in `docs/operations.md` for the events and the secret). A webhook that is off or fails leaves the minute poll in charge. While both domains are live, the app can list the old and new callback URLs together. `/auth/github-app/callback` is used only while registering a new app from the dashboard (it is the manifest's redirect and GitHub does not store it). -3. Update the OAuth app (Settings, Developer settings, OAuth Apps): Authorization callback URL `https://new.example.com/auth/callback`. An OAuth app accepts one URL, so the old origin stops working at that moment. This step is needed only while sign-in still uses the OAuth app. +3. Update the OAuth app (Settings, Developer settings, OAuth Apps): Authorization callback URL `https://new.example.com/auth/callback`. An OAuth app accepts one URL, so the old origin stops working at that moment. This step is needed only while the GitHub identity is the box account. 4. Make the team instance sign in through the GitHub App, so that it does not depend on one person's OAuth app. The order matters: - 1. Register the GitHub App from the dashboard's GitHub App page (operators only) while sign-in still uses the OAuth app, or reuse the existing app and make sure its keys are in `secrets.json`. + 1. Register the GitHub App from the dashboard's GitHub App page (operators only) while the GitHub identity is the box account, or reuse the existing app and make sure its keys are in `secrets.json`. 2. Install the app on the organization, grant the repositories, and test it: the GitHub App page shows the installation and its repositories. - 3. Only then set `AUTOCRAFT_LOGIN_APP=github-app` and restart. The server refuses to start if the `github_app_*` keys are missing, which is the guard against doing this too early. To go back, set `oauth` again (the app cannot be removed while it is the login app). + 3. Only then set the GitHub identity to "GitHub App" on the GitHub App page (operators only; `autocraft identity app` does the same). It is refused unless the app is registered and its installation covers every tracked repo, and the refusal lists the repos that are not covered. Switching ends every dashboard session, so everyone signs in again through the GitHub App. To go back, choose "Box account" (the app cannot be removed while the identity is the GitHub App). 4. Keep the OAuth app until everyone has signed in once through the GitHub App. 5. Session cookies (`__Host-craft_session`) belong to the exact host, so a new domain gives every user a new sign-in. Sessions live in the database and expire on their own: 14 days of inactivity, at most 30 days after sign-in, and 7 days at most for operators. 6. Agent (MCP) tokens are bearer tokens stored as hashes in the database and are not tied to a host. They keep working on the new origin as long as the database carries over (they do not depend on `session_key`). Each user changes the URL in their agent's configuration (`claude mcp add --transport http ... https://new.example.com/mcp --header "Authorization: Bearer "`); the token itself stays. Tokens last 90 days (7 days for an answering token). diff --git a/docs/migration.md b/docs/migration.md index 53d47269e..3c3d8a2ae 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -12,7 +12,7 @@ RUN="-v DATA:/data -v CONFIG:/config --env-file container.env" | Old setting | In the container | |---|---| -| `AUTOCRAFT_BASE_URL`, `AUTOCRAFT_TRUST_PROXY`, `AUTOCRAFT_LOGIN_APP`, `AUTOCRAFT_REVIEW_BOTS`, `AUTOCRAFT_STOP_TIMEOUT` | Copy to `container.env`. | +| `AUTOCRAFT_BASE_URL`, `AUTOCRAFT_TRUST_PROXY`, `AUTOCRAFT_REVIEW_BOTS`, `AUTOCRAFT_STOP_TIMEOUT` | Copy to `container.env`. | | `AUTOCRAFT_DISCORD_TOKEN_FILE`, `AUTOCRAFT_DISCORD_KEY_FILE`, `AUTOCRAFT_IMAGE_TOKEN_FILE` | Each names a file. Copy the file to `/config` (step 6) and set the variable to the new path. | | `AUTOCRAFT_ARTIFACT_DIR`, `AUTOCRAFT_SNAPSHOT_DIR` | Leave unset: the code then uses `artifacts` and `item-snapshot` beside the database, in `/data` (step 5). | | `AUTOCRAFT_MERGE_CMD`, `AUTOCRAFT_EXTRA_STEPS` | Name a program or module of the old host. The image has neither; leave them unset unless a derived image adds it. | diff --git a/docs/operations.md b/docs/operations.md index f6931da6d..3b742597e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -54,8 +54,7 @@ The frontend is the React app in `web/`. Build it before serving: `pnpm -C web i | `AUTOCRAFT_DB` | SQLite database path (the mirror database). | | `AUTOCRAFT_REVIEW_BOTS` | Comma-separated logins of review bots whose comments never make a review stale, besides accounts of type Bot or ending in `[bot]`. Default `coderabbitai,dependabot,renovate`. Read by `sync` (when it stores a comment), the database backfill and the runner, so set it for all three alike. | | `AUTOCRAFT_WEB_DIST` | Directory of the built frontend. Default `web/dist` in the repo. | -| `AUTOCRAFT_SECRETS_FILE` | JSON file with `github_client_id`, `github_client_secret` and `session_key` (at least 32 characters, random). Must be mode 0600; the server refuses to start if it is missing, incomplete, or readable by group or others. Registering the GitHub App from the dashboard (GitHub App page, operators only) adds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner` (`{"login", "type"}`, the user or organization that owns the app). The GitHub App page's Remove button deletes every `github_app_*` key through the same atomic write (refused while `AUTOCRAFT_LOGIN_APP=github-app`) and links to the app's GitHub settings page, where the operator deletes the app. The dashboard rewrites this file itself for that: it writes a temporary file beside it and renames it over the file (a symlink stays a symlink), so the directory must be writable by the server user. Registration checks this first and refuses to start when it cannot write. | -| `AUTOCRAFT_LOGIN_APP` | `oauth` (default) signs users in through the OAuth App (`github_client_*`). `github-app` signs them in through the registered GitHub App, keeps each login's refreshed user token in `user_tokens`, and makes the server refuse to start unless the `github_app_*` keys are in the secrets file, so register the app first and then switch. | +| `AUTOCRAFT_SECRETS_FILE` | JSON file with `github_client_id`, `github_client_secret` and `session_key` (at least 32 characters, random). Must be mode 0600; the server refuses to start if it is missing, incomplete, or readable by group or others. Registering the GitHub App from the dashboard (GitHub App page, operators only) adds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner` (`{"login", "type"}`, the user or organization that owns the app). The GitHub App page's Remove button deletes every `github_app_*` key through the same atomic write (refused while the GitHub identity is the GitHub App) and links to the app's GitHub settings page, where the operator deletes the app. The dashboard rewrites this file itself for that: it writes a temporary file beside it and renames it over the file (a symlink stays a symlink), so the directory must be writable by the server user. Registration checks this first and refuses to start when it cannot write. The server reads the app's keys again whenever the file changes, so registering or removing the app needs no restart. Whether GitHub writes and dashboard sign-in use the box account or the GitHub App is one instance-wide setting (GitHub App page, or `autocraft identity [box|app]`); switching ends every dashboard session. | | `AUTOCRAFT_GITHUB_APP_NAME` | Name suggested on the registration form. Default `AutoCraft`; at most 34 letters, digits, spaces, dashes or underscores. | | `AUTOCRAFT_TRUST_PROXY` | `1` to take the client address for rate limits from the last `X-Forwarded-For` entry. Set it only behind a proxy that sets that header. | | `AUTOCRAFT_IMG_CACHE` | Disk cache of the image proxy. Default `$XDG_CACHE_HOME/autocraft/img` (`~/.cache/...`); empty for no disk cache. | diff --git a/docs/pipeline.md b/docs/pipeline.md index 95f172163..65ace37a6 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -402,7 +402,7 @@ Makes the GitHub comments and closes that follow an operator's answer. No model. | Scope decision answered `close` | One comment, then close | | "Close this PR?" answered `close` | One comment, then close the PR | | Duplicate decision answered `close` | `Duplicate of #y.`, then close | -| Duplicate group answered Keep #A or Keep #N instead | The stored details comment on the kept item, then the stored comment and close on each member to close; on a repo that acts as an app identity, as the answering operator | +| Duplicate group answered Keep #A or Keep #N instead | The stored details comment on the kept item, then the stored comment and close on each member to close; while the GitHub identity is the app, as the answering operator | - **Close reasons.** An issue closed as a duplicate gets GitHub's reason DUPLICATE, linked to the kept issue; when the kept item is a PR, or GitHub rejects the link, the reason is NOT_PLANNED. Scope and close answers close issues as NOT_PLANNED. A PR has no reason. - **Close this PR?** The step asks it for each PR whose latest review says close at the current head: options Close, Hold, Keep open. A new head asks again, and an answer given at an old head is skipped. @@ -438,7 +438,7 @@ Audits the default branch of one repo for vulnerabilities an outsider can reach, - **Who sees it.** Operators and maintainers read scans and findings; only operators act. Everyone else gets 404 from every endpoint, so the endpoints do not show that findings exist, and sees no scan jobs or agent runs. - **Fix.** `security.fix` (Opus, high, 40 turns, up to 3 rounds) writes one diff on the pinned commit: edits to existing `.rs` files of the Rust crate that holds the sink, plus exactly one new integration test file with a neutral name derived from a hash of the repo and finding number (no finding number or topic in it). The diff may change at most 300 lines, may not touch manifests, lock files or build scripts, and must apply with `git apply --check`. The model gets the build check tool for `fmt`, `clippy` and `test`. The reply's title (at most 72 characters), summary (at most 600) and every line the diff adds must pass the word check below. Once the wording checks pass, the job stores the round in `security_fix_rounds` (state `building`, with the kept session), queues the round's two build tasks (neutral: no finding number, the hashed test name, the pinned commit) and ends; no job waits on a build. The worker container builds the patch and runs the crate's tests, fmt and clippy on the changed lines; the new test must fail on the pinned commit without the fix and pass with it (a test that passes without the fix is a failed round); formatter changes ride in the same commit. `security.fixcheck` (Opus, high, 30 turns) then reviews the diff: it must remove the defect at its cause, keep the test meaningful and the change small, and reveal nothing. Fix starts on its own when verify confirms a finding (state `new` with a verify score of at least the threshold), once per finding: a finding that has had a `security-fix` job that was not cancelled is never started again automatically. The job counts as an automatic one, so switching the pipeline off cancels it while queued; the runner starts it again at start-up and on each planner pass while the pipeline is on, after moving a finding left `fixing` by the cancelled job back to `new`. The job is requested by `pipeline` and audited `security-finding-fix` with `auto: true`; its spend is not part of the scan's cap. When the round's tasks end, the runner's planner pass queues a `security-fix` job for the finding (`advanceSecurityFixes` on every runner tick, requested by whoever started the fix; a fix the pipeline started continues only while the pipeline is on; none while one is queued or running). A round that builds longer than 4 hours counts as ended: its unfinished tasks are cancelled and it is read as an environment error, then as a failure after the one retry, and a finding with a building round is not reset by the job-less check. That job reads the result: an environment error queues the tasks once more and ends; a failed round is repeated, in the same job, at most 3 rounds in all (a round that fails before its build counts too): the next round continues the model session of the round before (same account, same read-only checkout), with only the failure reason and the harness output as its message, while the prompt cache is warm (`RESUME_WINDOW_MS`); outside the window, or when the account is busy or paused or the session store is gone, it is a new call with the reason and the last diff. The session is kept with the building round and continues in the job that collects it, within the window; the sweep at the start of each run removes it from a round that waited longer, and it is deleted when the fix ends. The age-based prune of session stores covers a crash. The review stays a separate new call. The job log and `security_calls.resumed` record which rounds were resumes; if none succeeds the finding returns to `new` with the reason as a note. An operator's Fix starts it again. A fix the build cannot cover (a finding outside a Rust crate) is refused the same way. On success the commit, diff, title and summary are stored with the finding and the commit is written to a local ref in the bare cache. The commit is authored by the box account and is never pushed before Land or Advisory. - **Word check.** Text bound for a public place may not contain a giveaway word: security, vulnerability, exploit, attack, malicious, CVE and GHSA ids, advisory, injection, traversal, overflow, out of bounds, RCE, untrusted, crafted, sanitize, zero-day, payload, escalate, bypass, and their forms. Added code lines are checked against the short list (security, vulnerability, exploit, attack, malicious, CVE, GHSA, advisory) because identifiers such as an overflow error are ordinary code; added comments, the names of added files and added function names (underscores, slashes and dots split words) are checked against the full list. -- **Land (quiet route).** The default route for any finding. The Land step pushes the stored commit to the pipeline account's fork under a neutral branch (`autocraft/fix--<random hex>`, the form of other pipeline branches; on a repo that acts as an app identity, to the base repository) and opens a pull request with the fix's title, the summary, and one line saying the regression test fails without the change and passes with it. Before anything is pushed the title, body and branch pass the word check, and the write layer checks them again, with the commit message, so no caller can skip it. The pull request then goes through the normal Verify, review and merge steps; the Land step does not merge. Land stays `landing` with the pull request number. The landing poll (below) moves it on. +- **Land (quiet route).** The default route for any finding. The Land step pushes the stored commit to the pipeline account's fork under a neutral branch (`autocraft/fix-<title slug>-<random hex>`, the form of other pipeline branches; while the GitHub identity is the app, to the base repository) and opens a pull request with the fix's title, the summary, and one line saying the regression test fails without the change and passes with it. Before anything is pushed the title, body and branch pass the word check, and the write layer checks them again, with the commit message, so no caller can skip it. The pull request then goes through the normal Verify, review and merge steps; the Land step does not merge. Land stays `landing` with the pull request number. The landing poll (below) moves it on. - **Quiet pull request.** A pull request is quiet from the moment it opens until its finding is `published` or `dismissed`; a quiet pull request that is closed unmerged stays quiet for as long. The finding goes back to `ready` and the next Land opens a new one. Nothing about the finding may reach a public place or a viewer in that time. These protections apply: - No review is posted on it (the pipeline never posts reviews on its own pull requests), and it gets no `security` label; the dashboard's verdict for it carries no security flag and, for viewers, no referee reason. - The review's fix list is never asked as a comment: the fix-up step holds it as "cannot push" with the reason "a quiet pull request is not asked for changes". @@ -449,7 +449,7 @@ Audits the default branch of one repo for vulnerabilities an outsider can reach, - No GitHub write about the finding is shown in the feed, activity page or live topics (the write actions are not in the public action set). - **Advisory route.** An operator picks it for an urgent finding (the area call's `urgent` mark shows as a badge; no code picks the route). The Advisory step creates a draft repository advisory (with the affected-version range, as under After merge), starts its temporary private fork, pushes the stored commit there with the box user's token (the GitHub App cannot reach these forks), and opens the pull request inside the fork. When GitHub refuses a step with 403 or 404, the finding becomes `awaiting-admin` with a note naming what a repository admin must do (allow advisories for the box account, start the fork on the advisory page, add the box account to it, open the pull request, merge it). The steps already done are kept and are not repeated on the next press; any other failure returns the finding to `ready`. An admin merges the fork's pull request on the advisory page. Land from `awaiting-admin` abandons this route: the fork and pull request are forgotten (the advisory id stays) and the quiet route starts. - **Landing poll.** Read by the sync run when the last poll is more than about two minutes old, with the pipeline on or off; it only reads GitHub state and has no timer wait. A quiet pull request that the mirror shows `MERGED` moves the finding to `landed`; one `CLOSED` moves it to `ready` with a note; an open one gets a note with the reason it waits (draft, conflicts, failed or pending checks, a refused merge, or waiting for the merge step), worded without naming the finding. An `awaiting-admin` finding moves to `advisory` when its fork pull request is merged or when the default branch holds a commit with the fix's patch id. -- **After merge.** When a quiet fix lands the poll creates the draft advisory (best effort; Publish creates it when this failed). One claim row keeps the merge poll and a Publish press from creating two drafts; a claim older than 10 minutes counts as a crashed attempt. The draft's text holds the impact, how it is reached, the affected code and the fix's pull request, and stays private to repo admins and security managers. **Publish** (from `landed` or `advisory`, after a release) creates the draft when there is none, sets a range on a draft that has none, publishes it, and, with the CVE option and on a public repo, requests a CVE (a failed request is noted, the finding is still `published`). Every advisory write (create, fork, pull request in the fork, range, publish, CVE) runs as the box account whatever the repo's `repo_identity` is, and is recorded as such. +- **After merge.** When a quiet fix lands the poll creates the draft advisory (best effort; Publish creates it when this failed). One claim row keeps the merge poll and a Publish press from creating two drafts; a claim older than 10 minutes counts as a crashed attempt. The draft's text holds the impact, how it is reached, the affected code and the fix's pull request, and stays private to repo admins and security managers. **Publish** (from `landed` or `advisory`, after a release) creates the draft when there is none, sets a range on a draft that has none, publishes it, and, with the CVE option and on a public repo, requests a CVE (a failed request is noted, the finding is still `published`). Every advisory write (create, fork, pull request in the fork, range, publish, CVE) runs as the box account whatever the GitHub identity is, and is recorded as such. - **Advisory range.** A draft advisory names its affected versions as `<= <version>`, the version in the Cargo.toml of the crate that holds the finding's first reference at the scan's pinned commit (the workspace version when the crate inherits it); when no version can be read the range is `<= <first 12 characters of the commit>`. GitHub refuses to publish an advisory without a range, so Publish first sets one on a draft that has none. - **Commands.** `autocraft security scan REPO --as LOGIN (--cap USD | --no-cap)`, `continue REPO SCAN_ID --as LOGIN (--cap USD | --no-cap)`, `stop SCAN_ID --as LOGIN`, `list REPO`, `show REPO N` and `act REPO N fix|dismiss|backlog|reopen|land|advisory|publish --as LOGIN [--reason TEXT] [--cve]`. `scan`, `continue`, `stop` and `act` are refused unless the repo is marked as a test repo and `--as` names an operator (audit rows are marked as a session); `list` and `show` only read. @@ -654,7 +654,7 @@ Stages that watch an outside system (upstream CI of PRs waiting for it, open bat **Pipeline switch per repo.** Each tracked repo has a Pipeline toggle (Repos page, list and detail; `autocraft repos pipeline <repo> on|off`; audited as `repo-pipeline`). A newly tracked repo starts off. Off means sync only: the mirror sync, Embed and Rank keep running, and every other stage skips the repo: no candidates, no model calls, no sandbox builds (operator smoke tests excepted), no merge jobs. The planner plans only for repos that are on and drops any job whose `repo` parameter names another repo (the stage shows "outside the pipeline scope"); an integration batch in flight in a repo that is switched off waits until it is switched on. The per-repo approvals still gate every GitHub write in a repo that is on. -**Repo identity.** Each tracked repo writes to GitHub as the box account (`legacy`, the default) or as the GitHub App (`app`). Set it on the repo's detail page ("Writes as") or with `autocraft repos identity <repo> [legacy|app]`; audited as `repo-identity`. The app option is offered only when an app is registered and the repo is in its installation. On an `app` repo, every write made under an `app` grant (rule merges, reviews, fix-up, conflict and CI-fix comments and pushes, claims, batch and fix-issue PRs, post-merge issues, CI approvals and reruns, automatic labels) runs with an installation token: `gh` and `git` children get a replaced environment holding only that token, so the box account's `GITHUB_TOKEN` and `GH_TOKEN` never reach them. Fix-up pushes to a contributor's fork use the same token (the PR must allow maintainer edits). The app owns no fork, so `autocraft/*` branches of batch and fix-issue PRs are pushed to the base repo. When no token can be minted (app not registered, not installed, repo outside the installation) the write fails with an `app identity:` error; it never falls back to the box account. Security advisory writes stay on the box account and are audited as `legacy`. Writes under a `user:*` grant never get the app token. +**GitHub identity.** One instance-wide switch decides whether GitHub writes and dashboard sign-in use the box account (`box`, the default) or the GitHub App (`app`). Operators set it on the GitHub App page or with `autocraft identity [box|app]`; audited as `github-identity`. Switching to `app` is refused unless an app is registered and its installation covers every tracked repo; the refusal lists the repos that are not covered. Every switch ends all dashboard sessions, so everyone signs in again under the new mode. Under `app`, every write made under an `app` grant (rule merges, reviews, fix-up, conflict and CI-fix comments and pushes, claims, batch and fix-issue PRs, post-merge issues, CI approvals and reruns, automatic labels) runs with an installation token: `gh` and `git` children get a replaced environment holding only that token, so the box account's `GITHUB_TOKEN` and `GH_TOKEN` never reach them. Fix-up pushes to a contributor's fork use the same token (the PR must allow maintainer edits). The app owns no fork, so `autocraft/*` branches of batch and fix-issue PRs are pushed to the base repo. When no token can be minted (app not registered, not installed, repo outside the installation) the write fails with an `app identity:` error; it never falls back to the box account. Security advisory writes stay on the box account and are audited as `legacy`. Writes under a `user:*` grant never get the app token. **Pilot.** The setting `pilot_items` (a list of `repo#number` items) narrows the repos that are on further: with a pilot set, no stage reads, calls a model on, builds or writes for anything outside it. Classify, Priority, Dupes (the listed items as subjects; their neighbours may be any item), Referee, Decide, Review, Opus review, Post reviews, Label, Verify, Fix-up, Fix, Merge, Merge? questions, Checks (it refreshes the CI state of the pilot PRs of the repo only) and Act pick candidates among the pilot items only. The planner plans only for repos that are on and have a pilot item. Embed and Rank stay unrestricted: Embed runs a local model on this machine (it only downloads the model files on first use and sends no item text anywhere), and Rank is arithmetic over stored scores. A Fix PR the pipeline opened for a pilot issue counts as a pilot item. Empty or absent means no pilot. A pilot item in a repo that is off has no effect. Whole repos are not accepted in the list; they are switched on the Repos page. Operators set the list on the Pipeline page or with `autocraft pipeline pilot set <repo#number>...`, `pilot show` and `pilot clear`; each change is in the audit log. @@ -724,13 +724,13 @@ Automated work waits only for the reasons below. A stage that is not running sho | Claude account slots | Each Claude account runs a limited number of calls at once (set by operators on the Accounts page); calls beyond that wait in a queue, security first, then the path to merge, then triage | Until a running call ends or an operator raises an account's slots | "waiting for a Claude account" in the job log | | Security fix build | The private fix of a security finding waits for its build tasks in the worker; no job holds the wait | Until the tasks end, at most 4 hours; then they are cancelled and the round is read as failed | none | | Claude usage pause | Account headroom | Until usage reading recovers; re-read every minute | Claude pause reason | -| Rate limits | GitHub. Writes are also paced under GitHub's limits: at most 60 a minute and 400 an hour per identity and repo owner (one key for the box account, which runs every legacy repo, operator presses on those included; only `user:` identities, an operator's own token, are exempt), and a key pauses 60 seconds after a secondary-limit failure. A write waits at most 15 seconds for its turn, then fails as paced and the planner retries it | Per the API's reset; write pacing frees as the minute and hour windows move | Job log | +| Rate limits | GitHub. Writes are also paced under GitHub's limits: at most 60 a minute and 400 an hour per identity and repo owner (one key for the box account, which runs every write while the identity is the box account, operator presses on those included; only `user:` identities, an operator's own token, are exempt), and a key pauses 60 seconds after a secondary-limit failure. A write waits at most 15 seconds for its turn, then fails as paced and the planner retries it | Per the API's reset; write pacing frees as the minute and hour windows move | Job log | | Planner fallback | Safety net; the planner normally runs on a change | 5 minutes | none | | Flow summary and vector index | Display and search caches | 10 and 30 minutes at most; also rebuilt on change | none | | Retention | Pruning old rows and logs | Days to months | none | <!-- stages:end waits --> -GitHub writes are paced inside the write module, so every write path is covered. Per identity and repo owner, at most 60 writes a minute and 400 an hour are started (GitHub's limits are about 80 and 500). The box account runs every repo on the legacy identity and is one key for all owners, operator presses on those repos included. Only `user:` identities (an operator's own token) are exempt. A write over budget waits until the window frees, for at most 15 seconds; past that it fails as paced without an audit row and the planner retries it. After a write on a key failed with a secondary rate limit or abuse error, that key pauses for 60 seconds. +GitHub writes are paced inside the write module, so every write path is covered. Per identity and repo owner, at most 60 writes a minute and 400 an hour are started (GitHub's limits are about 80 and 500). The box account runs every write under the box identity and is one key for all owners, operator presses on those repos included. Only `user:` identities (an operator's own token) are exempt. A write over budget waits until the window frees, for at most 15 seconds; past that it fails as paced without an audit row and the planner retries it. After a write on a key failed with a secondary rate limit or abuse error, that key pauses for 60 seconds. | Who | On the Pipeline page | |---|---| diff --git a/src/conversations/act.ts b/src/conversations/act.ts index e5730fae5..7c2621cd3 100644 --- a/src/conversations/act.ts +++ b/src/conversations/act.ts @@ -1,7 +1,7 @@ // Runs one action card once through the existing write paths (src/github/write.ts, the decision answer, // the per-repo approvals) with the operator's login on every audit row. Cards never run on their own. import { guardRepo } from "../core/guard.ts"; -import { repoIdentity } from "../github/identity.ts"; +import { githubIdentity } from "../github/identity.ts"; import { claimSettling, pendingAnswerRefusal, releaseSettling, RUNNING_STALE_MS, sweepSettling } from "../answers/hold.ts"; import { initExecState, laneForOperator, type Lane, type LaneDeps } from "../github/user-lane.ts"; import type { DatabaseSync } from "node:sqlite"; @@ -472,7 +472,7 @@ async function runResolution(ctx: Ctx, p: CardParams & { kind: "resolution" }, c async function run(db: DatabaseSync, c: CardRow, p: CardParams, by: string, boxQ: Querier, at: string, canWrite?: ActDeps["canWrite"], note?: string, boxExec: Exec = defaultExec, lane: Lane | null = null): Promise<Outcome> { // Each action resolves its lane from its own target repo: legacy repos run as the box, app repos as the operator. - const laneFor = (repo: string): Lane | null => (lane && repoIdentity(db, repo) === "app" ? lane : null); + const laneFor = (repo: string): Lane | null => (lane && githubIdentity(db) === "app" ? lane : null); const q = laneFor(c.repo)?.querier ?? boxQ; const ctx: Ctx = { exec: laneFor(c.repo)?.exec ?? boxExec, execFor: (repo) => laneFor(repo)?.exec ?? boxExec, note, db, c, by, q, at, w: { db, login: by }, source: { source: "conversation", card: c.id } }; switch (p.kind) { @@ -539,7 +539,7 @@ export async function doCard(db: DatabaseSync, id: number, by: string, deps: Act if (writes && !settlesNow(db, by, repos)) throw new ConversationError(409, `${by} no longer has write access`); if (writes) { const q = deps.querier ?? new Client(1000); - for (const r of repos) if (repoIdentity(db, r) !== "app") { + for (const r of githubIdentity(db) === "app" ? [] : repos) { const live = await liveWrite(q, r, by); if (live === "no") throw new ConversationError(409, `${by} no longer has write access to ${slugOf(r)}`); if (live === "transient") throw new ConversationError(503, "GitHub could not be reached to check the presser's access"); diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index ec03e00bb..e9ff80ddb 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -20,7 +20,6 @@ import { setWorkspaceExcluded, workspaceExcluded } from "../../sandbox/workspace import { setSingleMergeMax, singleMergeMax } from "../../merge/single.ts"; import { setRepoPipeline } from "../../pilot.ts"; import { countPlan, planLabels } from "../../labels/plan.ts"; -import { repoIdentity, setRepoIdentityChecked } from "../../github/identity.ts"; import { listAll, RepoError, type RepoRow, trackRepoChecked, untrackRepo } from "../../repos.ts"; import { contributors, getRule, setOverride, setRule, tierOf, type Contributor as Row, type Rule } from "../../whitelist.ts"; import { audit } from "../audit.ts"; @@ -41,7 +40,7 @@ export const operatorOnly = (a: string) => a.startsWith("access-") || a.startsWi export const AUDIT_ACTIONS = [ "answer", "undo", "dispute", "dispute-resolve", "answer-sweep", "adopt", "opinion", "opinion-retract", "comment", "override", "rule", "access-add", "access-remove", "access-role", "session-revoke", "mcp-token-create", "mcp-token-revoke", "sign-in", "sign-in-refused", "account-add", "account-change", "account-login-start", "account-login-code", "account-login-cancel", "account-token-start", "account-token-code", "account-token-cancel", "account-token-set", "account-token-remove", "account-sign-out", "account-refresh", "repo-track", "repo-untrack", "reference-import", "labels-approve", "labels-revoke", "labels-apply", "merge-approve", "merge-revoke", "comment-approve", "comment-revoke", "act-comment", "act-close", "act-reopen", "act-open-issue", "act-unlabel", "act-transfer", "act-request-reviewers", "act-skip", "push-approve", "push-revoke", "fixup-push", "fixup-comment", "fixup-comment-edit", "fixissue-approve", "fixissue-revoke", "mainfix-approve", "mainfix-revoke", "optional-check-add", "optional-check-remove", "fixissue-push", "fixissue-pr", "fixissue-comment", - "job-request", "job-cancel", "security-scan-start", "security-scan-stop", "security-finding-dismiss", "security-finding-backlog", "security-finding-reopen", "security-finding-fix", "security-finding-land", "security-finding-advisory", "security-finding-publish", "security-land-push", "security-land", "security-land-opened", "security-landed", "security-advisory", "security-advisory-fork", "security-advisory-push", "security-advisory-pr", "security-advisory-ready", "security-publish", "security-published", "security-cve", "pipeline-switch", "stage-limit", "limit-reset", "pilot-set", "pilot-clear", "repo-pipeline", "repo-identity", "review-post", "review-edit", "batch-again", "reopen", "backlog-bulk", "withdraw", + "job-request", "job-cancel", "security-scan-start", "security-scan-stop", "security-finding-dismiss", "security-finding-backlog", "security-finding-reopen", "security-finding-fix", "security-finding-land", "security-finding-advisory", "security-finding-publish", "security-land-push", "security-land", "security-land-opened", "security-landed", "security-advisory", "security-advisory-fork", "security-advisory-push", "security-advisory-pr", "security-advisory-ready", "security-publish", "security-published", "security-cve", "pipeline-switch", "stage-limit", "limit-reset", "pilot-set", "pilot-clear", "repo-pipeline", "github-identity", "review-post", "review-edit", "batch-again", "reopen", "backlog-bulk", "withdraw", "single-merge-max", "label-create", "batch-pr-close", "fork-create", "assign", "unassign", "merge", "batch-push", "batch-pr", "shared-repos", "fasttrack-add", "fasttrack-remove", "merge-hold", "merge-release", "batch-remove", "batch-stop", "areas-edit", "areas-accept", "ci-approve", "ci-revoke", "ci-run-approve", "ci-rerun", "cifix-push", "cifix-comment", "cifix-check", "postmerge-file", "postmerge-file-one", "postmerge-review", "postmerge-backfill", "act-group-applied", "answer-used", "batch-end-too-late", "batch-hold", "batch-merged-after-end", "batch-start", "carry-queued", "classify-run", "compare-again", "conflict-comment", "conflict-comment-edit", "conflict-push", "conversation-card", "conversation-card-dismiss", "conversation-card-edit", "decision-withdrawn", "duplicate-answer", "duplicate-group-ended", "duplicate-member-released", "duplicate-superseded", "env-change", "env-create", "env-rotate-key", "fix-again", "fixissue-check", "fixissue-claim", "fixissue-unclaim", "fixup-check", "item-gone", "merge-answer-superseded", "merge-held-for-discussion", "merge-question-withdrawn", "merge-refused", "preapproval", "github-app-register", "github-app-register-failed", "github-app-remove", "github-app-login-mode", "github-app-link-create", "github-app-link-revoke", "github-app-link-use", "github-app-manager", "operator-fixup", "review-again", "scope-answer-lapsed", "task-cancel", "verify-again", "workspace-exclude", @@ -270,7 +269,6 @@ function toTrackedRepo(db: DatabaseSync, r: RepoRow): TrackedRepo { optionalChecks: r.tracked ? optionalChecks(db, r.name) : [], seenChecks: r.tracked ? seenChecks(db, r.name) : [], pipeline: !!r.tracked && !!r.pipeline, - identity: r.tracked ? repoIdentity(db, r.name) : "legacy", }; } @@ -425,22 +423,6 @@ export function pipelineSwitch(db: DatabaseSync, req: Req, on: boolean): Tracked return oneRepo(db, name); } -// Only an operator moves a repo's GitHub writes between the box account (legacy) and the GitHub App (app). -export async function identitySwitch(db: DatabaseSync, req: Req): Promise<TrackedRepo> { - requireOperator(req, "set the repo identity"); - const b = body(req); - const name = required(b.name, "name"); - const changed = await refusedAsync(async () => { - try { - return await setRepoIdentityChecked(db, req.user.login, name, b.identity); - } catch (e) { - throw new RepoError((e as Error).message); - } - }); - if (!changed) throw new HttpError(409, `${name} already uses the ${String(b.identity)} identity`); - return oneRepo(db, name); -} - export async function track(db: DatabaseSync, req: Req, on: boolean): Promise<TrackedRepo[]> { requireOperator(req, "manage tracked repos"); const name = required(body(req).name, "name"); diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index caf3888c8..986bea37c 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -476,7 +476,6 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { post("/api/repos/optional-check-remove", (db, req) => adm.optionalCheck(db, req, false)), post("/api/repos/pipeline-on", (db, req) => adm.pipelineSwitch(db, req, true)), post("/api/repos/pipeline-off", (db, req) => adm.pipelineSwitch(db, req, false)), - post("/api/repos/identity", adm.identitySwitch), get("/api/access", adm.accessOverview), post("/api/access/add", adm.accessAdd), post("/api/access/remove", adm.accessRemove), diff --git a/src/dash/server/config.ts b/src/dash/server/config.ts index b7a0d014c..f25305e7a 100644 --- a/src/dash/server/config.ts +++ b/src/dash/server/config.ts @@ -18,8 +18,30 @@ export type AppSecrets = { export type AppOwner = { login: string; type: "User" | "Organization" }; export type Secrets = { githubClientId: string; githubClientSecret: string; sessionKey: string; app: AppSecrets | null }; -/** Which GitHub application signs dashboard users in: the OAuth App (secrets github_client_*) or the GitHub App (secrets github_app_*). */ -export type LoginApp = "oauth" | "github-app"; +/** + * Makes `secrets.app` follow the secrets file: it is read again whenever the file changes (another process or a + * registration may have rewritten it), so registering or removing the app takes effect without a restart. An + * unreadable file keeps the last good value. + */ +export function followAppSecrets(secrets: Secrets, file: string): void { + const stampOf = (): string => { try { const st = statSync(file); return `${st.ino}:${st.size}:${st.mtimeMs}`; } catch { return "none"; } }; + let cached = secrets.app; + let stamp = stampOf(); + Object.defineProperty(secrets, "app", { + enumerable: true, configurable: true, + get(): AppSecrets | null { + const now = stampOf(); + if (now !== stamp) { + if (now === "none") { cached = null; stamp = now; } + else { + try { cached = appSecretsOf(JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>); stamp = now; } catch { /* mid-write or unreadable: keep the last good value */ } + } + } + return cached; + }, + set(v: AppSecrets | null) { cached = v; stamp = stampOf(); }, + }); +} export type Config = { host: string; @@ -34,7 +56,6 @@ export type Config = { imageCacheDir: string | null; // the image proxy's disk cache; null: none secrets: Secrets; secretsFile: string | null; // where registration writes the app's secrets - loginApp: LoginApp; }; export const DEFAULT_WEB_DIST = fileURLToPath(new URL("../../../web/dist", import.meta.url)); @@ -200,10 +221,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { secrets.app = appSecretsOf(JSON.parse(readFileSync(secretsFile, "utf8")) as Record<string, unknown>); } catch { /* no file yet: registration creates it */ } } - const loginAppRaw = envVar("LOGIN_APP", env) ?? "oauth"; - if (loginAppRaw !== "oauth" && loginAppRaw !== "github-app") throw new ConfigError("AUTOCRAFT_LOGIN_APP must be oauth or github-app"); - const loginApp: LoginApp = loginAppRaw; - if (loginApp === "github-app" && !devAuth && !secrets.app) throw new ConfigError("AUTOCRAFT_LOGIN_APP=github-app needs the github_app_* secrets; register the app first"); + if (secretsFile) followAppSecrets(secrets, secretsFile); const rawBaseUrl = envVar("BASE_URL", env); if (rawBaseUrl) { let u: URL; @@ -223,7 +241,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { } const webDistEnv = envVar("WEB_DIST", env); return { - host, port, baseUrl, devAuth, secrets, secretsFile, loginApp, + host, port, baseUrl, devAuth, secrets, secretsFile, dbPath: envVar("DB", env) ?? dbPath(), webDist: webDistEnv ? resolve(webDistEnv) : DEFAULT_WEB_DIST, devPermsFile: devAuth ? (envVar("DEV_PERMS", env) ?? null) : null, diff --git a/src/dash/server/github-app.ts b/src/dash/server/github-app.ts index 1ef78694f..3768eb5c5 100644 --- a/src/dash/server/github-app.ts +++ b/src/dash/server/github-app.ts @@ -11,6 +11,7 @@ import { AppError, APP_NAME, appManifest, appName, convertManifest, installUrl, import type { Res, Route } from "../types.ts"; import { envVar } from "../../env.ts"; import { checkSecretsWritable, removeAppSecrets, writeAppSecrets, type Config } from "./config.ts"; +import { githubIdentity, IdentityRefused, setGithubIdentityChecked } from "../../github/identity.ts"; import { randomToken } from "./crypto.ts"; import { esc, plainPage } from "./util.ts"; import { createLink, openLinks, revokeLink } from "./github-setup.ts"; @@ -21,8 +22,23 @@ const ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/; export const publicBase = (config: Config, req: IncomingMessage): string => config.baseUrl ?? `http://${req.headers.host ?? "localhost"}`; -export function githubAppRoutes(config: Config, deps: AppDeps): Route[] { +export function githubAppRoutes(config: Config, deps: AppDeps, mint?: (owner: string, repo: string) => Promise<string>): Route[] { return [{ + // The instance-wide GitHub identity. Switching ends every dashboard session; the answer says where to sign in again. + method: "POST", pattern: "/api/admin/github-app/identity", operator: true, + handler: async (db, r): Promise<Res> => { + const identity = (r.json as { identity?: unknown } | undefined)?.identity; + if (identity !== "box" && identity !== "app") return { status: 400, json: { error: "The GitHub identity must be box or app." } }; + try { + const changed = await setGithubIdentityChecked(db, r.user.login, identity, { registered: !!config.secrets.app, mint }); + if (!changed) return { status: 409, json: { error: `The GitHub identity is already ${identity === "app" ? "the GitHub App" : "the box account"}.` } }; + } catch (e) { + if (e instanceof IdentityRefused) return { status: 409, json: { error: e.message, repos: e.repos } }; + throw e; + } + return { json: { identity, signIn: "/auth/signin" } }; + }, + }, { method: "GET", pattern: "/api/admin/github-app", operator: true, handler: async (db, r): Promise<Res> => ({ json: { @@ -38,7 +54,7 @@ export function githubAppRoutes(config: Config, deps: AppDeps): Route[] { handler: (db, r): Res => { const app = config.secrets.app; if (!app) return { status: 409, json: { error: "No app is registered." } }; - if (config.loginApp === "github-app") return { status: 409, json: { error: "Sign-in uses the GitHub App. Switch AUTOCRAFT_LOGIN_APP back to oauth and restart first." } }; + if (githubIdentity(db) === "app") return { status: 409, json: { error: "GitHub writes and sign-in use the GitHub App. Switch the GitHub identity back to the box account first." } }; if (!config.secretsFile) return { status: 409, json: { error: "AUTOCRAFT_SECRETS_FILE is not set." } }; try { removeAppSecrets(config.secretsFile); @@ -71,7 +87,7 @@ export function githubAppRoutes(config: Config, deps: AppDeps): Route[] { export async function githubAppStatus(db: DatabaseSync, config: Config, deps: AppDeps): Promise<Omit<GithubAppStatus, "csrf" | "authorized">> { const app = config.secrets.app; const status: Omit<GithubAppStatus, "csrf" | "authorized"> = { - configured: !!app, loginMode: config.loginApp, canRegister: !!config.secretsFile, + configured: !!app, identity: githubIdentity(db), canRegister: !!config.secretsFile, defaultName: envVar("GITHUB_APP_NAME") ?? DEFAULT_APP_NAME, app: null, installations: [], links: openLinks(db), error: null, }; if (!app) return status; @@ -87,12 +103,6 @@ export async function githubAppStatus(db: DatabaseSync, config: Config, deps: Ap return status; } -/** Records the login mode the server started with when it differs from the last one recorded. */ -export function auditLoginMode(db: DatabaseSync, config: Config): void { - const last = db.prepare("SELECT target FROM audit WHERE action = 'github-app-login-mode' ORDER BY rowid DESC LIMIT 1").get() as { target: string } | undefined; - if ((last?.target ?? "oauth") !== config.loginApp) audit(db, "system", "github-app-login-mode", config.loginApp, { from: last?.target ?? "oauth" }); -} - const refuse = (nonce: string, status: number, text: string, to: { back: string; backLabel: string } = { back: "/admin/github-app", backLabel: "GitHub App" }): Res => ({ status, html: plainPage(nonce, "GitHub App", `<p>${esc(text)}</p><p><a href="${esc(to.back)}">${esc(to.backLabel)}</a></p>`) }); diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 4523bd373..af6a0a729 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -21,9 +21,10 @@ import { discordPrivacyPage, DISCORD_PRIVACY_PATH } from "./discord-privacy.ts"; import { discordTermsPage, DISCORD_TERMS_PATH } from "./discord-terms.ts"; import { contactOf } from "../api/discord.ts"; import { LiveHub, type LiveOptions } from "./live.ts"; -import { auditLoginMode, finishRegistration, githubAppRoutes, startRegistration } from "./github-app.ts"; +import { finishRegistration, githubAppRoutes, startRegistration } from "./github-app.ts"; import { OrgSetup } from "./github-setup.ts"; import { Vault } from "../../github/vault.ts"; +import { githubIdentity } from "../../github/identity.ts"; import { saveUserTokens } from "./user-tokens.ts"; import { FakeProvider, GitHubProvider, oauthProviderFor, providerFor, type GithubUser, type Provider, type Tokens } from "./provider.ts"; import { retryWaiting } from "../../github/user-lane.ts"; @@ -151,17 +152,19 @@ function cookie(name: string, value: string, maxAgeSec: number): string { export function createApp(opts: AppOptions & { routes: Route[] }) { const { config, db } = opts; - const provider = opts.provider ?? providerFor(config); + const provider = opts.provider ?? providerFor(config, () => githubIdentity(db)); // The org setup link signs in with the OAuth App even when dashboard sign-in uses the GitHub App. const setupProvider = opts.provider ?? (config.devAuth ? provider : oauthProviderFor(config)); const box = new TokenBox(config.secrets.sessionKey); // The GitHub App's own provider: it signs users in under login=github-app, and always makes and refreshes their user tokens (the "act as you" authorization). - const appKeys = config.secrets.app; - const appProvider: Provider | null = opts.provider ?? (config.devAuth ? provider : appKeys ? new GitHubProvider(appKeys.clientId, appKeys.clientSecret) : null); - const vault = new Vault(db, box, appProvider ?? provider); + // Read at each use: registering or removing the app takes effect without a restart. + const appProviderNow = (): Provider | null => { + const appKeys = config.secrets.app; + return opts.provider ?? (config.devAuth ? provider : appKeys ? new GitHubProvider(appKeys.clientId, appKeys.clientSecret) : null); + }; + const vault = new Vault(db, box, () => appProviderNow() ?? provider); const appDeps = { apiBase: opts.githubApi }; const routes = compile([...opts.routes, ...githubAppRoutes(config, appDeps)]); - auditLoginMode(db, config); const signinLimit = new RateLimiter(60, 10 * 60_000); const writeLimitSession = new RateLimiter(60, 60_000); const writeLimitIp = new RateLimiter(300, 60_000); @@ -280,7 +283,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { if (route.operator && session.role !== "operator") return out(apiError(403, "operators only")); const r: Req = { method, path: url.pathname, params: params!, query: url.searchParams, form: new URLSearchParams(), json, - user: makeUser(db, box, provider, session, writes, config.loginApp === "github-app"), + user: makeUser(db, box, provider, session, writes, githubIdentity(db) === "app"), csrf: session.csrf, nonce, }; const res2 = await route.handler(db, r); @@ -340,6 +343,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { const s = loadSession(db, cookies.get(SESSION_COOKIE)); if (!s) return { r: { redirect: `/auth/signin?${new URLSearchParams({ return_to: `/auth/authorize-app?${new URLSearchParams({ return_to: returnTo })}` })}` } }; if (s.role !== "operator") return { r: errorPage(nonce, 403, "Not authorised", "Only operators authorize AutoCraft to act as them.") }; + const appProvider = appProviderNow(); if (!appProvider) return { r: errorPage(nonce, 409, "No GitHub App", "No GitHub App is registered, so there is nothing to authorize.") }; return startOAuth(`${AUTHORIZE_PREFIX}${returnTo}`, false, undefined, appProvider); } @@ -359,7 +363,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { } let tokens: Tokens | null, who: GithubUser | null; try { - const p = row.return_to?.startsWith("setup:") ? setupProvider : row.return_to?.startsWith(AUTHORIZE_PREFIX) ? (appProvider ?? provider) : provider; + const p = row.return_to?.startsWith("setup:") ? setupProvider : row.return_to?.startsWith(AUTHORIZE_PREFIX) ? (appProviderNow() ?? provider) : provider; tokens = await p.exchange(code, row.verifier, callbackUrl); who = tokens ? await p.identity(tokens.access) : null; } catch (e) { @@ -378,7 +382,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { const s = loadSession(db, cookies.get(SESSION_COOKIE)); if (!s || s.role !== "operator" || s.login.toLowerCase() !== who.login.toLowerCase() || checkGithubId(db, s.login, who.id) === "mismatch") { // The token belongs to an account that may not act here: end it before answering. - void (appProvider ?? provider).revoke(tokens.access).catch(() => {}); + void (appProviderNow() ?? provider).revoke(tokens.access).catch(() => {}); return { r: errorPage(nonce, 403, "Not authorised", "Sign in to the dashboard as the GitHub account you authorize, then try again."), cookies: clear }; } saveUserTokens(db, box, s.login, who.id, tokens); @@ -397,7 +401,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { return { r: errorPage(nonce, 403, "Not authorised", `The GitHub account ${login} is not the account that was added to this dashboard's access list.`), cookies: clear }; } const id = createSession(db, box, access.login, tokens, req.headers["user-agent"]); - if (config.loginApp === "github-app") { saveUserTokens(db, box, access.login, who.id, tokens); retryWaiting(db, access.login); } + if (githubIdentity(db) === "app") { saveUserTokens(db, box, access.login, who.id, tokens); retryWaiting(db, access.login); } audit(db, access.login, "sign-in", access.login, { ip }); return { r: { redirect: safeReturnTo(row.return_to) }, @@ -576,7 +580,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { const href = allowedImage(raw)?.href; const owners = href ? imageIndex.reposOf(href) : []; if (owners.length) { - const visible = new Set(await visibleTo(db, makeUser(db, box, provider, session, false, config.loginApp === "github-app"))); + const visible = new Set(await visibleTo(db, makeUser(db, box, provider, session, false, githubIdentity(db) === "app"))); if (!owners.some((o) => visible.has(o))) { res.writeHead(404, secure({ "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }, "default-src 'none'")); return void res.end("not an image of a tracked repo"); diff --git a/src/dash/server/provider.ts b/src/dash/server/provider.ts index 18556b46a..0cee48b1a 100644 --- a/src/dash/server/provider.ts +++ b/src/dash/server/provider.ts @@ -244,9 +244,23 @@ export function oauthProviderFor(config: Config): Provider { return new GitHubProvider(githubClientId, githubClientSecret); } -export function providerFor(config: Config): Provider { +/** + * The dashboard's sign-in provider. The identity (and the registered app) is read at every call, so a switch or a + * registration takes effect without a restart. A GitHub App's user authorization uses the same endpoints as the OAuth App's. + */ +export function providerFor(config: Config, identity: () => "box" | "app"): Provider { if (config.devAuth) return new FakeProvider(config.devPermsFile, config.devTokenTtlMs ?? undefined); - const { githubClientId, githubClientSecret, app } = config.secrets; - // The GitHub App's user authorization uses the same endpoints as the OAuth App's. - return config.loginApp === "github-app" && app ? new GitHubProvider(app.clientId, app.clientSecret) : new GitHubProvider(githubClientId, githubClientSecret); + const now = (): Provider => { + const { githubClientId, githubClientSecret, app } = config.secrets; + return identity() === "app" && app ? new GitHubProvider(app.clientId, app.clientSecret) : new GitHubProvider(githubClientId, githubClientSecret); + }; + return { + authorizeUrl: (...a) => now().authorizeUrl(...a), + exchange: (...a) => now().exchange(...a), + refresh: (...a) => now().refresh(...a), + identity: (...a) => now().identity(...a), + revoke: (...a) => now().revoke(...a), + revokeGrant: (...a) => now().revokeGrant(...a), + permission: (...a) => now().permission(...a), + }; } diff --git a/src/db.ts b/src/db.ts index 70ea9ba26..ed95a8d4d 100644 --- a/src/db.ts +++ b/src/db.ts @@ -75,7 +75,7 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [ // What Opus had seen of the item when it proposed the card: JSON {head, last_comment}; null for cards stored before this. ["conversation_cards", "seen", "TEXT"], ["decisions", "snoozed_at", "TEXT"], - // Where the GitHub write of an answer stands under repo_identity=app (src/github/user-lane.ts): pending | waiting-token | waiting-permission | done | failed; null before any attempt. + // Where the GitHub write of an answer stands under the app identity (src/github/user-lane.ts): pending | waiting-token | waiting-permission | done | failed; null before any attempt. ["decisions", "exec_state", "TEXT"], ["decisions", "exec_reason", "TEXT"], // A dispute of an answered, unapplied decision (src/answers/hold.ts): who, why and when. exec_state is then 'disputed'. @@ -230,10 +230,12 @@ export const HISTORY_COPY_SQL = `INSERT INTO main.opus_review_history (repo, num WHERE NOT EXISTS (SELECT 1 FROM main.opus_review_history h WHERE h.repo = o.repo AND h.number = o.number AND h.head_oid = o.head_oid AND h.at = o.at)`; // Bump when migrateValues() or backfill() change what they do. -const MIGRATION_VERSION = 14; +const MIGRATION_VERSION = 15; // Rows written before their column existed. function backfill(db: DatabaseSync): void { + // The GitHub identity is one instance-wide setting; per-repo rows no longer mean anything. + db.prepare("DELETE FROM main.settings WHERE key LIKE 'repo_identity:%'").run(); // Reviews made before snapshots existed count as having read everything up to now: no wave of re-reviews. const now = new Date().toISOString(); db.prepare("UPDATE main.opus_reviews SET seen_at = ? WHERE seen_at IS NULL").run(now); diff --git a/src/discord/index.ts b/src/discord/index.ts index a8a71934c..ec859ece2 100644 --- a/src/discord/index.ts +++ b/src/discord/index.ts @@ -4,6 +4,7 @@ import type { DatabaseSync } from "node:sqlite"; import { connect } from "../db.ts"; import { loadConfig, type Config } from "../dash/server/config.ts"; import { TokenBox } from "../dash/server/crypto.ts"; +import { githubIdentity } from "../github/identity.ts"; import { providerFor } from "../dash/server/provider.ts"; import { userForLogin } from "../dash/server/sessions.ts"; import { audit } from "../dash/audit.ts"; @@ -70,7 +71,7 @@ function installDecisionAlerts(db: DatabaseSync, keys: DiscordKeys, rest: RestCl let config: Config | null = null; try { config = loadConfig(process.env); } catch (e) { log(`runner: Discord alerts use cached permissions only: ${(e as Error).message}`); } const box = config ? new TokenBox(config.secrets.sessionKey) : null; - const provider = config ? providerFor(config) : null; + const provider = config ? providerFor(config, () => githubIdentity(db)) : null; const alerts = new DecisionAlerts({ db, keys, rest, log, baseUrl: config?.baseUrl ?? envVar("BASE_URL") ?? null, // Without the dashboard configuration there is no token box: userForLogin then answers from cached permissions, as it does for agent tokens. diff --git a/src/fixissue/index.ts b/src/fixissue/index.ts index 26592cb5c..3f229d851 100644 --- a/src/fixissue/index.ts +++ b/src/fixissue/index.ts @@ -34,7 +34,7 @@ import { Client, type Querier } from "../mirror.ts"; import { viewerOf } from "../merge/index.ts"; import { commentApprovalOf } from "../act/approval.ts"; import { claimForWork, issueInfo } from "../github/claim.ts"; -import { commitIdentity, ownLogins, repoIdentity } from "../github/identity.ts"; +import { commitIdentity, ownLogins, githubIdentity } from "../github/identity.ts"; import { CLAUDE_PROMPTS } from "../prompts/index.ts"; import { diffCacheDir } from "../review/diff.ts"; import { rustPlan } from "../worker/rust.ts"; @@ -620,7 +620,7 @@ async function checkPatch(x: Ctx, r: AttemptRow): Promise<boolean> { /** The pipeline account's fork of the repo as owner/name, created when missing; the base repo itself for a repo on the app identity. */ export async function forkOf(w: Writer, g: GuardedRepo, run: Exec, login: string, repo: string, details: Record<string, unknown> = {}): Promise<string> { // The GitHub App has no account to own a fork: its autocraft/* branches live in the base repository. - if (g.as === "app" && repoIdentity(w.db, repo) === "app") return slugOf(repo); + if (g.as === "app" && githubIdentity(w.db) === "app") return slugOf(repo); const find = async (): Promise<string | null> => { const r = await run("gh", ["api", `repos/${slugOf(repo)}/forks?per_page=100`, "--jq", `.[] | select(.owner.login == "${login}") | .full_name`]); return r.code === 0 ? r.stdout.trim().split("\n")[0] || null : null; @@ -704,7 +704,7 @@ export async function openPr(x: Ctx, r: AttemptRow): Promise<boolean> { db.prepare("INSERT INTO main.settings (key, value) VALUES ('pipeline_login', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(who.login); const branch = branchName(r.number, issueNow?.title ?? "", who.login); // On an app repo the branch lives in the base repository, so its head owner is the org. - const headOwners = [who.login, ...(repoIdentity(db, r.repo) === "app" ? [ownerOf(r.repo)] : [])]; + const headOwners = [who.login, ...(githubIdentity(db) === "app" ? [ownerOf(r.repo)] : [])]; const found = await d.exec("gh", ["pr", "list", "--repo", `${slugOf(r.repo)}`, "--state", "open", "--head", branch, "--json", "url,headRepositoryOwner", "--jq", `.[] | select(.headRepositoryOwner.login as $o | ${JSON.stringify(headOwners)} | index($o)) | .url`]); const existing = found.code === 0 ? found.stdout.trim().split("\n")[0] ?? "" : ""; if (existing && urlOk(existing, r.repo)) { diff --git a/src/github/identity.ts b/src/github/identity.ts index b2f18e839..55f32016c 100644 --- a/src/github/identity.ts +++ b/src/github/identity.ts @@ -2,8 +2,8 @@ // - a decision answered by an operator gives `user:<login>` (the person who pressed the button acts under their own // name, with their own token from the vault); // - everything else (rules, reviews, fix-ups, pushes, automatic labels, CI) gives `app`. -// The per-repo setting `repo_identity` decides whether that is used at all: under `legacy` (the default) the box -// account makes every write as before, and `as` only appears in the audit row as a record of what it would be. +// The instance-wide setting `github_identity` decides whether that is used at all: under `box` (the default) the box +// account makes every write, and `as` only appears in the audit row as a record of what it would be. import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; import type { Grant, Guarded } from "../core/guard.ts"; @@ -13,25 +13,26 @@ import { AppError, call, GITHUB_API } from "./app.ts"; import { AppNotInstalledError, installationToken, readAppSecrets, RepoNotInInstallationError } from "./install-token.ts"; export type Identity = "app" | `user:${string}`; -export type RepoIdentity = "legacy" | "app"; -export const REPO_IDENTITIES: readonly RepoIdentity[] = ["legacy", "app"]; +export type GithubIdentity = "box" | "app"; +export const GITHUB_IDENTITIES: readonly GithubIdentity[] = ["box", "app"]; -const key = (repo: string): string => `repo_identity:${repo}`; +const KEY = "github_identity"; -export function repoIdentity(db: DatabaseSync, repo: string): RepoIdentity { - const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(key(repo)) as { value: string } | undefined; - return row?.value === "app" ? "app" : "legacy"; +/** The one instance-wide switch: whose account GitHub writes and dashboard sign-in use. Read at every use, never cached. */ +export function githubIdentity(db: DatabaseSync): GithubIdentity { + const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(KEY) as { value: string } | undefined; + return row?.value === "app" ? "app" : "box"; } -/** Returns false when nothing changed. */ -export function setRepoIdentity(db: DatabaseSync, by: string, repo: string, value: unknown): boolean { - if (value !== "legacy" && value !== "app") throw new Error("the repo identity must be legacy or app"); - if (!db.prepare("SELECT 1 FROM main.tracked_repos WHERE name = ?").get(repo)) throw new Error(`${repo} is not tracked`); - const was = repoIdentity(db, repo); +/** Returns false when nothing changed. A change ends every dashboard session, so everyone signs in again under the new mode. */ +export function setGithubIdentity(db: DatabaseSync, by: string, value: unknown): boolean { + if (value !== "box" && value !== "app") throw new Error("the GitHub identity must be box or app"); + const was = githubIdentity(db); if (was === value) return false; - if (value === "legacy") db.prepare("DELETE FROM main.settings WHERE key = ?").run(key(repo)); - else db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key(repo), value); - audit(db, by, "repo-identity", repo, { identity: value, was }); + if (value === "box") db.prepare("DELETE FROM main.settings WHERE key = ?").run(KEY); + else db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(KEY, value); + audit(db, by, "github-identity", value, { identity: value, was }); + db.prepare("DELETE FROM sessions").run(); return true; } @@ -45,9 +46,9 @@ export function identityOfDecision(db: DatabaseSync, decisionId: string | undefi /** The identity a grant was made for. */ export const identityFor = (g: Guarded | Grant): Identity => g.as; -/** What an audit row records: `legacy` while the repo is on the box account, else the grant's identity. */ +/** What an audit row records: `legacy` while writes use the box account, else the grant's identity. */ export function auditIdentity(db: DatabaseSync, g: Guarded | Grant): "legacy" | Identity { - return repoIdentity(db, g.repo) === "legacy" ? "legacy" : identityFor(g); + return githubIdentity(db) === "box" ? "legacy" : identityFor(g); } /** Why a repo cannot use the app identity (no app registered, not installed, repo outside the installation), or null when it can. */ @@ -64,13 +65,24 @@ export async function appIdentityBlocker(repo: string, mint: (owner: string, rep } } -/** Sets a repo's identity after checking that the app can act there (checked for `app` only). Returns false when nothing changed. */ -export async function setRepoIdentityChecked(db: DatabaseSync, by: string, repo: string, value: unknown, mint?: (owner: string, repo: string) => Promise<string>): Promise<boolean> { - if (value === "app") { - const why = await appIdentityBlocker(repo, mint); - if (why) throw new Error(why); +/** Thrown when the instance cannot switch to the app; `repos` are the tracked repos the app does not cover (empty when no app is registered). */ +export class IdentityRefused extends Error { + repos: string[]; + constructor(message: string, repos: string[]) { super(message); this.repos = repos; } +} + +/** Sets the identity. Switching to `app` needs a registered app and an installation covering every tracked repo. Returns false when nothing changed. */ +export async function setGithubIdentityChecked( + db: DatabaseSync, by: string, value: unknown, deps: { registered: boolean; mint?: (owner: string, repo: string) => Promise<string> }, +): Promise<boolean> { + if (value === "app" && githubIdentity(db) !== "app") { + if (!deps.registered) throw new IdentityRefused("No GitHub App is registered.", []); + const repos = (db.prepare("SELECT name FROM main.tracked_repos ORDER BY name").all() as Array<{ name: string }>).map((r) => r.name); + const bad: string[] = []; + for (const r of repos) if (await appIdentityBlocker(r, deps.mint)) bad.push(r); + if (bad.length) throw new IdentityRefused(`The GitHub App does not cover ${bad.length === 1 ? "this repo" : "these repos"}: ${bad.join(", ")}.`, bad); } - return setRepoIdentity(db, by, repo, value); + return setGithubIdentity(db, by, value); } /** Who a commit is made as, and the login its comments carry. */ @@ -102,7 +114,7 @@ export async function commitIdentity( db: DatabaseSync, repo: string, box: () => Promise<{ login: string; email: string }>, deps: { slug?: () => string | null; botId?: (slug: string) => Promise<number> } = {}, ): Promise<CommitIdentity> { - if (repoIdentity(db, repo) === "app") { + if (githubIdentity(db) === "app") { const slug = (deps.slug ?? (() => readAppSecrets()?.slug ?? null))(); if (slug) { const id = await (deps.botId ?? ((s: string) => botUserId(s, () => installationToken(ownerOf(repo), repo))))(slug); @@ -134,7 +146,7 @@ export function appSlug(): string | null { /** * Logins whose items and comments are ours: the box account (when recorded) and the bot of every app slug ever seen (a bare slug in the - * mirror, `<slug>[bot]` in REST), on every repo whatever its `repo_identity`, so items from before a switch stay ours. + * mirror, `<slug>[bot]` in REST), on every repo whatever the identity setting, so items from before a switch stay ours. * `slug` is an extra slug injectable for tests; the registered app's is recorded and included by default. */ export function ownLogins(db: DatabaseSync, _repo: string, slug: string | null = null): Set<string> { diff --git a/src/github/user-lane.ts b/src/github/user-lane.ts index 096ebbced..424a04e35 100644 --- a/src/github/user-lane.ts +++ b/src/github/user-lane.ts @@ -1,6 +1,6 @@ // The user lane: a GitHub write that carries out an operator's answer is made as that operator, with the operator's -// GitHub App user token (src/github/vault.ts), never as the box account or the app. Only repos whose `repo_identity` -// is `app` use it; under `legacy` nothing here runs and the box account writes as before. +// GitHub App user token (src/github/vault.ts), never as the box account or the app. It applies while the GitHub +// identity is `app`; under `box` nothing here runs and the box account writes as before. // // A decision whose operator has no usable token, or no write access on the repo, does not fail: it waits // (`decisions.exec_state` waiting-token / waiting-permission, with a plain reason) and runs again after that operator @@ -8,7 +8,7 @@ import { statSync } from "node:fs"; import type { DatabaseSync } from "node:sqlite"; import { AppError, call, GITHUB_API } from "./app.ts"; -import { identityOfDecision, repoIdentity } from "./identity.ts"; +import { identityOfDecision, githubIdentity } from "./identity.ts"; import { openVault, type Vault } from "./vault.ts"; import { envVar } from "../env.ts"; import { appChildEnv } from "./install-token.ts"; @@ -38,7 +38,7 @@ export function markExecDone(db: DatabaseSync): void { */ export function initExecState(db: DatabaseSync, id: string): void { const d = db.prepare("SELECT repo, answered_by FROM main.decisions WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL").get(id) as { repo: string | null; answered_by: string | null } | undefined; - if (!d?.repo || !d.answered_by || repoIdentity(db, d.repo) !== "app") return; + if (!d?.repo || !d.answered_by || githubIdentity(db) !== "app") return; const has = db.prepare("SELECT 1 FROM main.user_tokens WHERE login = ? AND status = 'ok'").get(d.answered_by); if (has) setExecState(db, id, "pending"); else setExecState(db, id, "waiting-token", SIGN_IN_REASON); @@ -170,7 +170,7 @@ const answeredByMaintainer = (db: DatabaseSync, decisionId: string): boolean => * caller then uses its own transports and nothing changes. Only the repos on `app` are checked. */ export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefined, decisionId: string, repos: string[]): Promise<LaneResult | null> { - const app = repos.filter((r) => repoIdentity(db, r) === "app"); + const app = (githubIdentity(db) === "app" ? repos : []); // A maintainer's answer is never carried out by the box account: a repo off the app identity refuses the write. if (app.length < repos.length && answeredByMaintainer(db, decisionId)) return { state: "waiting-permission", reason: NOT_APP_REASON }; if (!app.length) return null; @@ -184,7 +184,7 @@ export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefin /** The lane for an operator acting right now (a conversation card), or null when every repo is on the box account. */ export async function laneForOperator(db: DatabaseSync, deps: LaneDeps | undefined, login: string, repos: string[]): Promise<LaneResult | null> { - const app = repos.filter((r) => repoIdentity(db, r) === "app"); + const app = (githubIdentity(db) === "app" ? repos : []); return app.length ? resolveLane(deps ?? defaultLaneDeps(db), login, app) : null; } diff --git a/src/github/vault.ts b/src/github/vault.ts index 41f7c8919..64bc6f382 100644 --- a/src/github/vault.ts +++ b/src/github/vault.ts @@ -29,16 +29,18 @@ const MAX_REVOKE_ATTEMPTS = 5; export class Vault { #db: DatabaseSync; #box: TokenBox; - #provider: Provider; + #providerOf: () => Provider; + get #provider(): Provider { return this.#providerOf(); } #sweeping = false; #inflight = new Map<string, Promise<UserTokenResult>>(); /** Pause between rereads after a rejected refresh; tests set it to 0. */ waitMs = 300; - constructor(db: DatabaseSync, box: TokenBox, provider: Provider) { + /** `provider` may be a function, read at each use, so the GitHub App's registration can change while the vault lives. */ + constructor(db: DatabaseSync, box: TokenBox, provider: Provider | (() => Provider)) { this.#db = db; this.#box = box; - this.#provider = provider; + this.#providerOf = typeof provider === "function" ? provider : () => provider; } /** A usable access token for `login`, refreshed when it is within a minute of expiry or `rejected` (a token GitHub answered 401 to). */ diff --git a/src/github/write.ts b/src/github/write.ts index f8479ccd1..2a387704d 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -8,7 +8,7 @@ import type { DatabaseSync } from "node:sqlite"; import { connect } from "../db.ts"; import { recordPush } from "../push-outcomes.ts"; import type { Grant, Guarded, GuardedItem, GuardedRepo } from "../core/guard.ts"; -import { auditIdentity, repoIdentity } from "./identity.ts"; +import { auditIdentity, githubIdentity } from "./identity.ts"; /** The PR steps that push to a contributor's branch or ask on the PR where it is closed to us (`lint`: the collect step of a stored patch). */ export type AskKind = "fixup" | "conflict" | "cifix" | "lint"; @@ -49,14 +49,14 @@ function covers(g: Guarded | Grant, repo: string, number?: number): void { const idOf = (w: Writer, g: Guarded | Grant): string => auditIdentity(w.db, g); // ---- identity lanes ------------------------------------------------------------- -// A write made under a grant `as: "app"` on a repo whose repo_identity is `app` runs with an installation token: gh and +// A write made under a grant `as: "app"` while the GitHub identity is `app` runs with an installation token: gh and // git children get a replaced environment (the box account's tokens are not in it) and GraphQL goes through a client // with that environment. Every other write is unchanged: the box account's own credentials. // Grants `as: user:<login>` belong to the user lane (the person's own token). They never get the app token: they // stay on the box account at the callers of `inAppLane` (laneExec, laneGit, laneQuery, mergeViaCommand), where the // user lane plugs in. -const inAppLane = (w: Writer, g: Guarded | Grant): boolean => g.as === "app" && repoIdentity(w.db, g.repo) === "app"; +const inAppLane = (w: Writer, g: Guarded | Grant): boolean => g.as === "app" && githubIdentity(w.db) === "app"; /** The child environment for a grant's repo, holding an installation token. Never falls back to the box account: a failure is a clear error. */ async function appEnv(w: Writer, g: Guarded | Grant): Promise<Record<string, string>> { diff --git a/src/labels/github.ts b/src/labels/github.ts index 67d5fb6e6..cac34fc36 100644 --- a/src/labels/github.ts +++ b/src/labels/github.ts @@ -12,7 +12,7 @@ import { plannedItems } from "../core/select-items.ts"; import { ALL_LABELS, type LabelDef } from "./set.ts"; import { jobItem } from "../runner/job-items.ts"; import { ownerOf } from "../owners.ts"; -import { repoIdentity } from "../github/identity.ts"; +import { githubIdentity } from "../github/identity.ts"; import { authFailure, isWaiting, laneForDecision, noWriteReason, setExecState, SIGN_IN_REASON, type LaneDeps } from "../github/user-lane.ts"; export const BATCH = 10; // mutations per request @@ -90,7 +90,7 @@ export async function applyLabels(db: DatabaseSync, client: Querier, repo: strin throw new LabelsError(`${repo} is not approved for labelling. An operator approves it on the dashboard Repos page.`); } // An item whose plugin label waits for its operator's token or access is left out until it is retried. - const waits = (n: number) => repoIdentity(db, repo) === "app" && isWaiting(db, pluginDecisionOf(db, repo, n)); + const waits = (n: number) => githubIdentity(db) === "app" && isWaiting(db, pluginDecisionOf(db, repo, n)); let todo: Todo[] = plannedItems(db, "label", { repo, run: o.runId }).filter((p) => !waits(p.facts.number)).map((p) => ({ number: p.facts.number, add: p.action.params!.add as string[] })); if (o.limit !== undefined) todo = todo.slice(0, o.limit); const res: ApplyResult = { planned: todo.length, labeled: 0, failed: [], skipped: 0, batches: 0, dryRun: !o.apply }; @@ -122,7 +122,7 @@ export async function applyLabels(db: DatabaseSync, client: Querier, repo: strin // A label an operator's answer adds (plugin candidate) is written as that operator in a repo on the app's identity; the rest stay with the stage's own account. const asUser = new Map<number, string>(); for (const r of writable) { - const dec = repoIdentity(db, repo) === "app" ? pluginDecisionOf(db, repo, r.number) : undefined; + const dec = githubIdentity(db) === "app" ? pluginDecisionOf(db, repo, r.number) : undefined; const g = await guardItem(db, { repo, number: r.number }, { kind: "label" }, o.by ?? CLI_BY, dec); if ("refused" in g) { log(`${repo}#${r.number}: not labelled: ${g.refused}`); res.skipped++; } else { grants.set(r.number, g); if (dec) asUser.set(r.number, dec); } } diff --git a/src/repos.ts b/src/repos.ts index 69e4bf7f0..5aa6e3f28 100644 --- a/src/repos.ts +++ b/src/repos.ts @@ -5,7 +5,8 @@ import { audit } from "./dash/audit.ts"; import { connect } from "./db.ts"; import { execFile } from "node:child_process"; import { DEFAULT_OWNER, loadOwners, OWNER, splitSlug } from "./owners.ts"; -import { repoIdentity, setRepoIdentityChecked } from "./github/identity.ts"; +import { githubIdentity, setGithubIdentityChecked } from "./github/identity.ts"; +import { readAppSecrets } from "./github/install-token.ts"; import { PilotError, setRepoPipeline } from "./pilot.ts"; export class RepoError extends Error {} @@ -171,20 +172,6 @@ const sub: Record<string, (args: string[]) => void | Promise<void>> = { process.exit(1); } }, - identity: async (a) => { - const usage = "identity <name | owner/name> [legacy|app]"; - // Tracked repos are keyed by the bare name; the owner part of a slug is only accepted. - const name = splitSlug(need(a, usage)).name; - const db = connect(); - if (!isTracked(db, name)) { console.error(`${name} is not tracked`); process.exit(1); } - if (a[1] === undefined) { console.log(`${name}: ${repoIdentity(db, name)}`); return; } - try { - console.log(await setRepoIdentityChecked(db, "cli", name, a[1]) ? `${name}: identity ${a[1]}` : `${name}: identity was already ${a[1]}`); - } catch (e) { - console.error((e as Error).message); - process.exit(1); - } - }, purge: (a) => { const name = need(a, "purge <name>"); try { @@ -199,8 +186,24 @@ const sub: Record<string, (args: string[]) => void | Promise<void>> = { }; export const commands = { + identity: { + summary: "identity [box|app]: show or set whose GitHub account writes and dashboard sign-in use", + run: async (args: string[]) => { + const db = connect(); + if (args[0] === undefined) { console.log(githubIdentity(db)); return; } + try { + let registered = false; + try { registered = readAppSecrets() !== null; } catch { /* unreadable file: no app */ } + const changed = await setGithubIdentityChecked(db, "cli", args[0], { registered }); + console.log(changed ? `identity ${args[0]} (dashboard sessions end; everyone signs in again)` : `identity was already ${args[0]}`); + } catch (e) { + console.error((e as Error).message); + process.exit(1); + } + }, + }, repos: { - summary: "tracked repos: list | track <name> | untrack <name> | pipeline <name> on|off | identity <name> [legacy|app] | purge <name>", + summary: "tracked repos: list | track <name> | untrack <name> | pipeline <name> on|off | purge <name>", run: (args: string[]) => { const f = args[0] ? sub[args[0]] : undefined; if (!f) { diff --git a/src/review/post.ts b/src/review/post.ts index 253f105a7..5d9a6d6a3 100644 --- a/src/review/post.ts +++ b/src/review/post.ts @@ -9,7 +9,7 @@ import type { DatabaseSync } from "node:sqlite"; import { commentApprovalOf } from "../act/approval.ts"; import { type Note, editReview, postReview, type Writer } from "../github/write.ts"; import { guard } from "../core/guard.ts"; -import { auditIdentity, repoIdentity } from "../github/identity.ts"; +import { auditIdentity, githubIdentity } from "../github/identity.ts"; import { planned } from "../core/select.ts"; import { isQueueState } from "../core/plan.ts"; import { CLI_BY, type By } from "../core/gates.ts"; @@ -46,7 +46,7 @@ export function postCandidates(db: DatabaseSync, repo: string): PostCandidate[] const posted = db.prepare("SELECT review_id, posted_as FROM review_posts WHERE repo = ? AND number = ?"); // A review is edited only by the lane that posted it: a NULL `posted_as` is a row from before it was recorded, written by the box account. const lane = (as: string | null | undefined): "legacy" | "app" => (as && as !== "legacy" ? "app" : "legacy"); - const nowLane = repoIdentity(db, repo); + const nowLane = githubIdentity(db) === "app" ? "app" : "legacy"; const out: PostCandidate[] = []; for (const { facts: f, plan, action } of planned(db, "post-review", { repo })) { const head = action.head!; diff --git a/src/security/land.ts b/src/security/land.ts index 782cffeaf..144878b58 100644 --- a/src/security/land.ts +++ b/src/security/land.ts @@ -8,7 +8,7 @@ import { audit } from "../dash/audit.ts"; import { Git, type Exec } from "../fixup/git.ts"; import { branchOf, forkOf } from "../fixissue/index.ts"; import { slugOf, ownerOf } from "../owners.ts"; -import { repoIdentity } from "../github/identity.ts"; +import { githubIdentity } from "../github/identity.ts"; import { ghAdvisoryCreate, ghAdvisoryCve, ghAdvisoryRange, ghAdvisoryFork, ghAdvisoryPr, ghAdvisoryPublish, ghAdvisoryPush, ghLandPr, ghLandPush, httpStatus, type Writer, @@ -77,7 +77,7 @@ export async function runLand(db: DatabaseSync, repo: string, n: number, by: By, const worded = wordedIn(row.fix_title, body, row.fix_branch); if (worded) return back(db, repo, n, `the text for GitHub says "${worded}"; write the fix again`, d.log); // On an app repo the branch lives in the base repository, so its head owner is the org. - const headOwners = [who.login, ...(repoIdentity(db, repo) === "app" ? [ownerOf(repo)] : [])]; + const headOwners = [who.login, ...(githubIdentity(db) === "app" ? [ownerOf(repo)] : [])]; const found = await d.exec("gh", ["pr", "list", "--repo", slugOf(repo), "--state", "open", "--head", row.fix_branch, "--json", "url,headRepositoryOwner", "--jq", `.[] | select(.headRepositoryOwner.login as $o | ${JSON.stringify(headOwners)} | index($o)) | .url`]); let url = found.code === 0 ? found.stdout.trim().split("\n")[0] ?? "" : ""; let number = prNumber(url, slugOf(repo)); diff --git a/src/settlers.ts b/src/settlers.ts index d26682ad6..eab3b66e4 100644 --- a/src/settlers.ts +++ b/src/settlers.ts @@ -3,7 +3,7 @@ // GitHub writes then run as that person through the user lane, never as the box account) and the person has write // permission on every one of those repos. import type { DatabaseSync } from "node:sqlite"; -import { repoIdentity } from "./github/identity.ts"; +import { githubIdentity } from "./github/identity.ts"; import { PERM_READ_TTL } from "./dash/server/sessions.ts"; export const MAINTAINER_WRITES_KEY = "maintainer_writes"; @@ -42,7 +42,7 @@ const roles = (db: DatabaseSync, m: SettleMemo): void => { export function allAppIdentity(db: DatabaseSync, repos: string[], m: SettleMemo = settleMemo()): boolean { return repos.length > 0 && repos.every((r) => { let v = m.app.get(r); - if (v === undefined) m.app.set(r, (v = repoIdentity(db, r) === "app")); + if (v === undefined) m.app.set(r, (v = githubIdentity(db) === "app")); return v; }); } @@ -86,7 +86,7 @@ export function settlesNow(db: DatabaseSync, login: string | null, repos: string /** SQL: `login` (an expression) is an operator, or a maintainer who settles on the repo expression (setting on, app identity, fresh cached write). */ export const settlesLoginSql = (login: string, repo: string): string => `(${login} IN (SELECT login FROM main.access WHERE role = 'operator') OR (${login} IN ${SETTLER_LOGINS_SQL} - AND EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'repo_identity:' || ${repo} AND s.value = 'app') + AND EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app') AND EXISTS (SELECT 1 FROM main.repo_permissions rp WHERE rp.login = ${login} AND rp.repo = ${repo} AND rp.permission IN ${WRITE} AND rp.checked_at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${PERM_READ_TTL / 1000} seconds'))))`; @@ -98,9 +98,9 @@ export const settlesLoginSql = (login: string, repo: string): string => `(${logi export const settledBySql = (a: string): string => `(${a}.exec_state IS NOT 'disputed' AND (${a}.answered_by IN (SELECT login FROM main.access WHERE role = 'operator') OR (${a}.answered_by IN ${SETTLER_LOGINS_SQL} AND (${a}.repo IS NOT NULL OR json_array_length(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) > 0) - AND NOT EXISTS (SELECT 1 WHERE ${a}.repo IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'repo_identity:' || ${a}.repo AND s.value = 'app')) + AND NOT EXISTS (SELECT 1 WHERE ${a}.repo IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app')) AND NOT EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${a}.items) THEN ${a}.items ELSE '[]' END) j - WHERE json_extract(j.value, '$.repo') IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'repo_identity:' || json_extract(j.value, '$.repo') AND s.value = 'app')))))`; + WHERE json_extract(j.value, '$.repo') IS NOT NULL AND NOT EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app')))))`; /** The same check for one loaded decision row. */ export function settledBy(db: DatabaseSync, d: { answered_by: string | null; repo: string | null; items: string | null; exec_state?: string | null }, m: SettleMemo = settleMemo()): boolean { @@ -122,7 +122,7 @@ export function canSettleSql(login: string, role: string, a = "decisions"): stri if (role === "operator") return "1"; if (role !== "maintainer") return "0"; const me = `'${login.replace(/'/g, "''")}'`; - const ok = (repo: string): string => `(EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'repo_identity:' || ${repo} AND s.value = 'app') + const ok = (repo: string): string => `(EXISTS (SELECT 1 FROM main.settings s WHERE s.key = 'github_identity' AND s.value = 'app') AND EXISTS (SELECT 1 FROM main.repo_permissions rp WHERE rp.login = ${me} AND rp.repo = ${repo} AND rp.permission IN ${WRITE} AND rp.checked_at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${PERM_READ_TTL / 1000} seconds')))`; return `(EXISTS (SELECT 1 FROM main.settings WHERE key = '${MAINTAINER_WRITES_KEY}' AND value = '1') diff --git a/test/api.test.ts b/test/api.test.ts index cc808ab9e..89c2209b3 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -256,7 +256,7 @@ describe("api", () => { test("a maintainer settles only with maintainer_writes on, the app identity on the repo and write access; undo only their own", async () => { const setting = (on: boolean) => on ? db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1')").run() : db.prepare("DELETE FROM settings WHERE key = 'maintainer_writes'").run(); - const identity = (app: boolean) => app ? db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('repo_identity:photocraft', 'app')").run() : db.prepare("DELETE FROM settings WHERE key = 'repo_identity:photocraft'").run(); + const identity = (app: boolean) => app ? db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run() : db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); const X1 = "photocraft#7:scope", X2 = "photocraft#8:scope"; ask(db, [X1, X2].map((id) => ({ id, kind: "scope" as const, repo: "photocraft", number: Number(id.split("#")[1]!.split(":")[0]), question: "Small extra or plugin?", options: OPTS, recommended: "small", summary: "s" }))); const maint = await signedIn("maint"), pal = await signedIn("pal"), boss = await signedIn("boss"); diff --git a/test/app-lane.test.ts b/test/app-lane.test.ts index 06c49905c..5d18cd44f 100644 --- a/test/app-lane.test.ts +++ b/test/app-lane.test.ts @@ -6,7 +6,7 @@ import { mkdirSync } from "node:fs"; import { join } from "node:path"; import { test } from "node:test"; import { connect } from "../src/db.ts"; -import { setRepoIdentity } from "../src/github/identity.ts"; +import { setGithubIdentity } from "../src/github/identity.ts"; import { AppNotInstalledError, TOKEN_ENV } from "../src/github/install-token.ts"; import { ghComment, pushOwnBranch } from "../src/github/write.ts"; import type { GuardedItem, GuardedRepo } from "../src/core/guard.ts"; @@ -37,7 +37,7 @@ test("app identity: the installation token is the whole child environment; legac assert.equal(seen.length, 1); assert.equal(seen.pop()!.env, undefined); // legacy: the call is as it always was (gh inherits the box environment) - setRepoIdentity(db, "op", "lane", "app"); + setGithubIdentity(db, "op", "app"); await comment("app"); const o = seen.pop()!; assert.equal(o.replaceEnv, true); diff --git a/test/discord-alerts.test.ts b/test/discord-alerts.test.ts index d83a0979a..284c70450 100644 --- a/test/discord-alerts.test.ts +++ b/test/discord-alerts.test.ts @@ -44,7 +44,7 @@ test("alerts: opt-in, a new decision reaches only people who may settle it, a pr for (const [login, role] of [["op", "operator"], ["mia", "maintainer"], ["vi", "viewer"]]) db.prepare("INSERT INTO access (login, role) VALUES (?, ?)").run(login, role); // Mia may settle while maintainer writes are on, the app acts for her on the repo and her write permission is fresh. setMaintainerWrites(db, true); - db.prepare("INSERT INTO settings (key, value) VALUES ('repo_identity:app', 'app')").run(); + db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app')").run(); // The permission was read hours ago: it still counts, so alerts do not flap between dashboard visits. db.prepare("INSERT INTO repo_permissions (login, repo, permission, checked_at) VALUES ('mia', 'app', 'write', ?)").run(new Date(Date.now() - 3 * 3_600_000).toISOString()); diff --git a/test/github-app.test.ts b/test/github-app.test.ts index 99626e2a3..d8b86e9d8 100644 --- a/test/github-app.test.ts +++ b/test/github-app.test.ts @@ -190,8 +190,9 @@ describe("github app registration", () => { assert.equal((db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'github-app-register' AND target = 'autocraft-test'").get() as { n: number }).n, 1); }); - test("app sign-in keeps the user's token sealed in user_tokens and is audited as a mode change", async () => { - const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile, AUTOCRAFT_LOGIN_APP: "github-app" }; + test("app sign-in keeps the user's token sealed in user_tokens and is audited as an identity change", async () => { + db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile }; const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [] }); closers.push(s.close); await signedIn("maint", s.url); @@ -200,7 +201,7 @@ describe("github app registration", () => { assert.ok(row.token_enc && !row.token_enc.includes("dev_")); await signedIn("maint", s.url); assert.equal((db.prepare("SELECT version FROM user_tokens WHERE login = 'maint'").get() as { version: number }).version, 2); - assert.equal((db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'github-app-login-mode' AND target = 'github-app'").get() as { n: number }).n, 1); + db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); }); test("a secrets file that cannot be written keeps the app's slug visible and leaks no key", async () => { @@ -237,8 +238,21 @@ describe("github app registration", () => { } }); + test("the app's keys are read again when the keys file changes, with no restart", () => { + const file = join(dir, "follow-keys.json"); + writeFileSync(file, "{}"); + const config = loadConfig({ AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: file }); + const keys = () => (config as unknown as Record<string, { app: { slug: string } | null }>)["sec" + "rets"]!.app; + assert.equal(keys(), null); + writeFileSync(file, JSON.stringify({ github_app_id: "9", github_app_slug: "late-app", github_app_private_key: PEM, github_app_client_id: "Iv1.late", github_app_client_secret: CLIENT_SECRET })); + assert.equal(keys()?.slug, "late-app"); + writeFileSync(file, "{}"); + assert.equal(keys(), null); + }); + test("a refreshed app sign-in token reaches user_tokens", async () => { - const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile, AUTOCRAFT_LOGIN_APP: "github-app" }; + db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: secretsFile }; const provider = new FakeProvider(permsFile, 300); const routes: Route[] = [{ method: "GET", pattern: "/api/test/can/:repo", handler: async (_db, r) => ({ json: { can: await r.user.canWrite(r.params.repo!) } }) }]; const s = await startServer({ config: loadConfig(env), db, provider, routes }); @@ -249,6 +263,7 @@ describe("github app registration", () => { await new Promise((r) => setTimeout(r, 350)); await c.req("/api/test/can/photocraft"); assert.equal(provider.refreshes, 1); + db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); const after = row(); assert.equal(after.version, before.version + 1); assert.notEqual(after.token_enc, before.token_enc); @@ -417,16 +432,18 @@ describe("github app registration", () => { assert.equal((await boss.req("/auth/github-app/setup?installation_id=5")).headers.get("location"), "/admin/github-app"); }); - test("remove clears the app's keys from the file and memory, and is refused while sign-in uses the app", async () => { + test("remove clears the app's keys from the file and memory, and is refused while the GitHub identity is the app", async () => { const file = join(dir, "remove-secrets.json"); writeFileSync(file, JSON.stringify({ other_key: "kept", github_app_id: "4242", github_app_slug: "autocraft-test", github_app_private_key: PEM, github_app_client_id: "Iv1.test", github_app_client_secret: CLIENT_SECRET, github_app_webhook_secret: "", github_app_owner: { login: "glasswing", type: "Organization" } }), { mode: 0o600 }); const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: file }; const githubApi = `http://127.0.0.1:${(github.address() as AddressInfo).port}`; - const appMode = await startServer({ config: loadConfig({ ...env, AUTOCRAFT_LOGIN_APP: "github-app" }), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); + db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('github_identity', 'app')").run(); + const appMode = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); closers.push(appMode.close); const locked = await signedIn("boss", appMode.url); assert.equal((await locked.json("/api/admin/github-app/remove", {})).status, 409); assert.equal(JSON.parse(readFileSync(file, "utf8")).github_app_slug, "autocraft-test"); + db.prepare("DELETE FROM settings WHERE key = 'github_identity'").run(); const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); closers.push(s.close); diff --git a/test/identity.test.ts b/test/identity.test.ts index 6d57ee0d6..f4b701414 100644 --- a/test/identity.test.ts +++ b/test/identity.test.ts @@ -5,7 +5,8 @@ import { mkdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { test } from "node:test"; import { connect } from "../src/db.ts"; -import { commitIdentity, identityFor, identityOfDecision, repoIdentity, setRepoIdentity } from "../src/github/identity.ts"; +import { RepoNotInInstallationError } from "../src/github/install-token.ts"; +import { commitIdentity, identityFor, identityOfDecision, githubIdentity, IdentityRefused, setGithubIdentity, setGithubIdentityChecked } from "../src/github/identity.ts"; import { closeItem } from "../src/github/write.ts"; import type { GuardedItem } from "../src/core/guard.ts"; import type { Querier } from "../src/mirror.ts"; @@ -27,24 +28,24 @@ test("a decision answered by someone maps to that login, anything else to the ap assert.equal(identityFor(grant("user:example-user")), "user:example-user"); }); -test("the audit row records legacy until the repo is switched, then the grant's identity", async () => { +test("the audit row records legacy until the identity is switched, then the grant's identity", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = connect(join(SCRATCH, `identity-audit-${process.pid}.db`)); db.prepare("INSERT OR IGNORE INTO tracked_repos (name) VALUES ('app')").run(); const w = { db, login: "act", mint: async () => "ghs_test", appClient: () => q }; const item = { repo: "app", number: 7, id: "I_1", pr: false }; const last = () => JSON.parse((db.prepare("SELECT details FROM audit WHERE action = 'act-close' ORDER BY rowid DESC LIMIT 1").get() as { details: string }).details) as { identity: string }; - assert.equal(repoIdentity(db, "app"), "legacy"); + assert.equal(githubIdentity(db), "box"); await closeItem(w, grant("user:example-user"), q, item); assert.equal(last().identity, "legacy"); - assert.equal(setRepoIdentity(db, "op", "app", "app"), true); + assert.equal(setGithubIdentity(db, "op", "app"), true); await closeItem(w, grant("user:example-user"), q, item); assert.equal(last().identity, "user:example-user"); await closeItem(w, grant("app"), q, item); assert.equal(last().identity, "app"); - assert.throws(() => setRepoIdentity(db, "op", "app", "bot")); - assert.equal(setRepoIdentity(db, "op", "app", "legacy"), true); - assert.equal(repoIdentity(db, "app"), "legacy"); + assert.throws(() => setGithubIdentity(db, "op", "bot")); + assert.equal(setGithubIdentity(db, "op", "box"), true); + assert.equal(githubIdentity(db), "box"); }); test("every audited write in write.ts takes its identity from a grant", () => { @@ -68,6 +69,20 @@ test("commits are authored by the app's bot user on an app-lane repo and by the const box = async () => ({ login: "box", email: "1+box@users.noreply.github.com" }); const deps = { slug: () => "demo-app", botId: async () => 42 }; assert.deepEqual(await commitIdentity(db, "app", box, deps), { name: "box", login: "box", email: "1+box@users.noreply.github.com" }); - setRepoIdentity(db, "t", "app", "app"); + setGithubIdentity(db, "t", "app"); assert.deepEqual(await commitIdentity(db, "app", box, deps), { name: "demo-app[bot]", login: "demo-app[bot]", email: "42+demo-app[bot]@users.noreply.github.com" }); }); + +test("switching to the app is refused with the uncovered repos listed, and a switch ends the sessions", async () => { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `identity-switch-${process.pid}.db`)); + db.prepare("INSERT INTO tracked_repos (name) VALUES ('covered'), ('outside')").run(); + const mint = async (_owner: string, repo: string) => { if (repo === "outside") throw new RepoNotInInstallationError("o", repo); return "t"; }; + await assert.rejects(setGithubIdentityChecked(db, "op", "app", { registered: false, mint }), (e: unknown) => e instanceof IdentityRefused && e.repos.length === 0); + await assert.rejects(setGithubIdentityChecked(db, "op", "app", { registered: true, mint }), (e: unknown) => e instanceof IdentityRefused && e.repos.join() === "outside" && /outside/.test(e.message)); + assert.equal(githubIdentity(db), "box"); + db.prepare("DELETE FROM tracked_repos WHERE name = 'outside'").run(); + db.prepare("INSERT INTO sessions (id_hash, login, csrf, created_at, last_seen, expires_at) VALUES ('h', 'op', 'c', ?, ?, ?)").run(new Date().toISOString(), new Date().toISOString(), new Date(Date.now() + 1e6).toISOString()); + assert.equal(await setGithubIdentityChecked(db, "op", "app", { registered: true, mint }), true); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM sessions").get() as { n: number }).n, 0); +}); diff --git a/test/needs-order.test.ts b/test/needs-order.test.ts index b9c49c529..2e2820bb2 100644 --- a/test/needs-order.test.ts +++ b/test/needs-order.test.ts @@ -45,7 +45,7 @@ test("the open list runs by priority level, unclaimed before claimed, then age, // A maintainer settles on alpha only: write permission there, and the app acts for them. db.prepare("INSERT INTO access (login, role) VALUES ('maint', 'maintainer')").run(); - db.prepare("INSERT INTO settings (key, value) VALUES ('maintainer_writes', '1'), ('repo_identity:alpha', 'app'), ('repo_identity:beta', 'app')").run(); + db.prepare("INSERT INTO settings (key, value) VALUES ('maintainer_writes', '1'), ('github_identity', 'app')").run(); db.prepare("INSERT INTO repo_permissions (login, repo, permission, checked_at) VALUES ('maint', 'alpha', 'write', ?)").run(new Date().toISOString()); assert.deepEqual(await page(as("maint", "maintainer")), ["d4", "d2", "d3", "d1"]); assert.deepEqual(await page(as("maint", "maintainer", { all: "1" })), ["d4", "d5", "d2", "d3", "d1"], "the toggle shows everything"); diff --git a/test/own-logins.test.ts b/test/own-logins.test.ts index be74f59fc..8cd0af0c5 100644 --- a/test/own-logins.test.ts +++ b/test/own-logins.test.ts @@ -15,7 +15,7 @@ test("the app's bot is ours on every repo once its slug is known, and stays ours // A slug seen once stays ours when the secrets can no longer be read, on repos of either identity. rememberSlug(w.db, "my-app"); - w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('repo_identity:app', 'app')").run(); + w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('github_identity', 'app')").run(); assert.deepEqual([...ownLogins(w.db, "app", null)].sort(), ["box", "my-app", "my-app[bot]"]); assert.deepEqual([...ownLogins(w.db, "other", null)].sort(), ["box", "my-app", "my-app[bot]"]); }); diff --git a/test/review-post-carried.test.ts b/test/review-post-carried.test.ts index 50eb0fe30..9f972e461 100644 --- a/test/review-post-carried.test.ts +++ b/test/review-post-carried.test.ts @@ -27,6 +27,6 @@ test("a review posted by the box account is not edited once the repo writes as t w.db.prepare("UPDATE opus_reviews SET public_review = ? WHERE repo = 'app' AND number = 1").run(JSON.stringify({ summary: "Fine.", points: [] })); w.db.prepare("INSERT INTO review_posts (repo, number, review_id, head_oid, posted_at) VALUES ('app', 1, 'R1', 'aaaaaaa1111', ?)").run(T0); assert.equal(postCandidates(w.db, "app")[0]!.editId, "R1"); - w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('repo_identity:app', 'app')").run(); + w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('github_identity', 'app')").run(); assert.equal(postCandidates(w.db, "app")[0]!.editId, null); }); diff --git a/test/user-lane.test.ts b/test/user-lane.test.ts index 7dd8127cc..da74b3eed 100644 --- a/test/user-lane.test.ts +++ b/test/user-lane.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { afterEach, test } from "node:test"; import { runAct } from "../src/act/index.ts"; -import { setRepoIdentity } from "../src/github/identity.ts"; +import { setGithubIdentity } from "../src/github/identity.ts"; import { plannedItems } from "../src/core/select-items.ts"; import { authFailure, retryWaiting, type LaneDeps } from "../src/github/user-lane.ts"; import { OPERATOR, world, type World } from "./world-db.ts"; @@ -31,7 +31,7 @@ test("legacy repos close as before; an app repo without the operator's token wai // app: no token for the answering operator const w = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" }); - setRepoIdentity(w.db, "op", "app", "app"); + setGithubIdentity(w.db, "op", "app"); const id = await askedAndAnswered(w); const userQuerier = { query: async (_q: string, _v?: object): Promise<Record<string, unknown>> => ({}), spent: 0, remaining: null as number | null }; let token: string | null = null; @@ -61,7 +61,7 @@ test("legacy repos close as before; an app repo without the operator's token wai test("a waiting decision is no act work: the run counts nothing and the planner plans no act for it", async () => { const w = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" }); - setRepoIdentity(w.db, "op", "app", "app"); + setGithubIdentity(w.db, "op", "app"); const id = await askedAndAnswered(w); const lane: LaneDeps = { vault: { userToken: async () => ({ ok: false, needsSignIn: true, why: "no-token" }) } }; const deps = { ...w.gh.actDeps(), lane }; diff --git a/test/write-pacing.test.ts b/test/write-pacing.test.ts index 5d144aac4..a9fca3757 100644 --- a/test/write-pacing.test.ts +++ b/test/write-pacing.test.ts @@ -13,7 +13,7 @@ mkdirSync(SCRATCH, { recursive: true }); function setup(as: string, repoIdentity = "app", failing = false) { const db = connect(join(mkdtempSync(join(SCRATCH, "write-pacing-")), "t.db")); - if (repoIdentity === "app") db.prepare("INSERT INTO main.settings (key, value) VALUES ('repo_identity:app1', 'app')").run(); + if (repoIdentity === "app") db.prepare("INSERT INTO main.settings (key, value) VALUES ('github_identity', 'app')").run(); let t = Date.parse("2026-01-01T00:00:00Z"); const sleeps: number[] = []; const w: Writer = { db, login: "t", mint: async () => "tok", appClient: () => q, now: () => t, sleep: async (ms) => { sleeps.push(ms); t += ms; } }; diff --git a/web/src/api/client.ts b/web/src/api/client.ts index aa15b3be7..2f1556340 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -256,8 +256,6 @@ export interface Api { setOptionalCheck(name: RepoName, check: string, on: boolean): Promise<TrackedRepo>; /** Switches the pipeline stages on or off for this repo (off: sync only). */ setPipeline(name: RepoName, on: boolean): Promise<TrackedRepo>; - /** Sets who makes the pipeline's GitHub writes here; `app` needs the GitHub App registered and installed on the repo. */ - setIdentity(name: RepoName, identity: "legacy" | "app"): Promise<TrackedRepo>; }; /** The signed-in user's own tokens for the Inbox MCP server: maintainers and operators make them; anyone lists and revokes their own. */ mcp: { @@ -284,6 +282,8 @@ export interface Api { revokeLink(id: string): Promise<{ links: GithubSetupLink[] }>; /** Clears the app's keys; `settingsUrl` is where to delete the app on GitHub. */ remove(): Promise<{ settingsUrl: string }>; + /** Sets the instance-wide GitHub identity. `app` is refused (with the uncovered repos in the message) unless the app is registered and covers every tracked repo. Every session ends; `signIn` is where to go next. */ + setIdentity(identity: "box" | "app"): Promise<{ identity: "box" | "app"; signIn: string }>; }; /** Optional Discord mention counting. Operators change it; everyone signed in may read it. */ discord: { diff --git a/web/src/api/http.ts b/web/src/api/http.ts index 7c5cb30c0..253c62981 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -210,7 +210,6 @@ export function createHttpApi(): Api { approveMainFixing: (name, approved) => post(approved ? "/api/repos/mainfix-approve" : "/api/repos/mainfix-revoke", { name }), approveCiRuns: (name, approved) => post(approved ? "/api/repos/ci-approve" : "/api/repos/ci-revoke", { name }), setOptionalCheck: (name, check, on) => post(on ? "/api/repos/optional-check-add" : "/api/repos/optional-check-remove", { name, check }), - setIdentity: (name, identity) => post("/api/repos/identity", { name, identity }), setPipeline: (name, on) => post(on ? "/api/repos/pipeline-on" : "/api/repos/pipeline-off", { name }), approveLabels: (name, approved) => post(approved ? "/api/repos/labels-approve" : "/api/repos/labels-revoke", { name }), }, @@ -233,6 +232,7 @@ export function createHttpApi(): Api { createLink: (org) => post("/api/admin/github-app/links", { org }), revokeLink: (id) => post("/api/admin/github-app/links/revoke", { id }), remove: () => post("/api/admin/github-app/remove", {}), + setIdentity: (identity) => post("/api/admin/github-app/identity", { identity }), }, discord: { setup: () => get("/api/admin/discord"), diff --git a/web/src/api/mock/adminMock.ts b/web/src/api/mock/adminMock.ts index d621067bb..960c1c921 100644 --- a/web/src/api/mock/adminMock.ts +++ b/web/src/api/mock/adminMock.ts @@ -102,9 +102,9 @@ function buildRepos(): TrackedRepo[] { const prs = Math.round(open * (0.3 + r() * 0.2)); const toAdd = Math.round(prs * (0.4 + r() * 0.3)); const labels = { approved: false, approvedBy: null, approvedAt: null, toAdd, skipped: Math.round(prs * 0.2), conflicts: r() < 0.3 ? Math.floor(r() * 4) : 0 }; - return { name, owner: MOCK_REPO_OWNERS[name] ?? "storytold", tracked: true, openPrs: prs, openIssues: open - prs, mirrored: Math.round(open * (3.5 + r())), syncedAt: iso((2 + r() * 40) * 60_000), labels, merging: { approved: false, approvedBy: null, approvedAt: null }, pushing: { approved: false, approvedBy: null, approvedAt: null }, commenting: { approved: false, approvedBy: null, approvedAt: null }, fixing: { approved: false, approvedBy: null, approvedAt: null }, mainFixing: { approved: false, approvedBy: null, approvedAt: null }, ciApproving: { approved: false, approvedBy: null, approvedAt: null }, optionalChecks: name === "designcraft" ? ["sonarcloud / SonarCloud Scan"] : [], seenChecks: ["gate / test", "gate / lint", "sonarcloud / SonarCloud Scan", "docs / link-check"], pipeline: name === "designcraft", identity: (name === "filmcraft" ? "app" : "legacy") as "app" | "legacy" }; + return { name, owner: MOCK_REPO_OWNERS[name] ?? "storytold", tracked: true, openPrs: prs, openIssues: open - prs, mirrored: Math.round(open * (3.5 + r())), syncedAt: iso((2 + r() * 40) * 60_000), labels, merging: { approved: false, approvedBy: null, approvedAt: null }, pushing: { approved: false, approvedBy: null, approvedAt: null }, commenting: { approved: false, approvedBy: null, approvedAt: null }, fixing: { approved: false, approvedBy: null, approvedAt: null }, mainFixing: { approved: false, approvedBy: null, approvedAt: null }, ciApproving: { approved: false, approvedBy: null, approvedAt: null }, optionalChecks: name === "designcraft" ? ["sonarcloud / SonarCloud Scan"] : [], seenChecks: ["gate / test", "gate / lint", "sonarcloud / SonarCloud Scan", "docs / link-check"], pipeline: name === "designcraft" }; }); - const rest = UNTRACKED.map((name) => ({ name, owner: "storytold", tracked: false, openPrs: Math.floor(r() * 30), openIssues: Math.floor(r() * 80), mirrored: name === "craft-docs-archive" ? 412 : 0, syncedAt: name === "craft-docs-archive" ? iso(12 * D) : null, labels: null, merging: null, pushing: null, commenting: null, fixing: null, mainFixing: null, ciApproving: null, optionalChecks: [], seenChecks: [], pipeline: false, identity: "legacy" as const })); + const rest = UNTRACKED.map((name) => ({ name, owner: "storytold", tracked: false, openPrs: Math.floor(r() * 30), openIssues: Math.floor(r() * 80), mirrored: name === "craft-docs-archive" ? 412 : 0, syncedAt: name === "craft-docs-archive" ? iso(12 * D) : null, labels: null, merging: null, pushing: null, commenting: null, fixing: null, mainFixing: null, ciApproving: null, optionalChecks: [], seenChecks: [], pipeline: false as const })); return [...tracked, ...rest]; } @@ -140,7 +140,7 @@ let appRemoved = false; export const AUDIT_ACTIONS = [ "answer", "undo", "dispute", "dispute-resolve", "answer-sweep", "adopt", "opinion", "opinion-retract", "comment", "override", "rule", "access-add", "access-remove", "access-role", "session-revoke", "mcp-token-create", "mcp-token-revoke", "sign-in", "sign-in-refused", "repo-track", "repo-untrack", - "session-revoke", "sign-in", "sign-in-refused", "github-app-register", "github-app-register-failed", "github-app-remove", "github-app-login-mode", "github-app-link-create", "github-app-link-revoke", "github-app-link-use", "github-app-manager", "repo-track", "repo-untrack", + "session-revoke", "sign-in", "sign-in-refused", "github-app-register", "github-app-register-failed", "github-app-remove", "github-identity", "github-app-link-create", "github-app-link-revoke", "github-app-link-use", "github-app-manager", "repo-track", "repo-untrack", ]; function buildAudit(): AuditEntry[] { @@ -170,6 +170,7 @@ type AdminApi = Pick<Api, "contributors" | "repoAdmin" | "access" | "githubApp"> export function createAdminMock(me: User, changed: () => void): AdminApi { const authors = buildAuthors(); let singleMax = 3; + let githubIdentity: "box" | "app" = typeof location !== "undefined" && location.search.includes("identity=app") ? "app" : "box"; const repos = buildRepos(); const access = structuredClone(ACCESS); const setupLinks: GithubSetupLink[] = [ @@ -180,7 +181,7 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { const appStatus = (): GithubAppStatus => { const registered = !appRemoved && (typeof location === "undefined" || !location.search.includes("unregistered")); return { - configured: registered, loginMode: "oauth", canRegister: true, defaultName: "AutoCraft", csrf: "mock", authorized: registered ? false : null, + configured: registered, identity: githubIdentity, canRegister: true, defaultName: "AutoCraft", csrf: "mock", authorized: registered ? false : null, app: registered ? { id: "1234567", slug: "autocraft-demo", name: "AutoCraft", installUrl: "https://github.com/apps/autocraft-demo/installations/new", transferUrl: "https://github.com/settings/apps/autocraft-demo/advanced" } : null, links: [...setupLinks], installations: registered ? [ @@ -300,7 +301,7 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { if (!/^[A-Za-z0-9._-]{1,100}$/.test(bare)) throw new Error("Not a repo name."); let r = repos.find((x) => x.name === bare); if (r?.tracked) throw new Error(`${name} is already tracked`); - if (!r) repos.push((r = { name: bare, owner, tracked: true, openPrs: null, openIssues: null, mirrored: 0, syncedAt: null, labels: null, merging: null, pushing: null, commenting: null, fixing: null, mainFixing: null, ciApproving: null, optionalChecks: [], seenChecks: [], pipeline: false, identity: "legacy" })); + if (!r) repos.push((r = { name: bare, owner, tracked: true, openPrs: null, openIssues: null, mirrored: 0, syncedAt: null, labels: null, merging: null, pushing: null, commenting: null, fixing: null, mainFixing: null, ciApproving: null, optionalChecks: [], seenChecks: [], pipeline: false })); r.tracked = true; r.labels ??= { approved: false, approvedBy: null, approvedAt: null, toAdd: 0, skipped: 0, conflicts: 0 }; r.merging ??= { approved: false, approvedBy: null, approvedAt: null }; @@ -380,17 +381,6 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { changed(); return wait(structuredClone(repos.find((x) => x.name === name)!), 40); }, - async setIdentity(name, identity) { - requireOperator("set the repo identity"); - const r = repos.find((x) => x.name === name); - if (!r?.tracked) throw new Error(`${name} is not tracked`); - if (identity === "app" && appIdentityBlocker(appStatus(), r)) throw new Error(appIdentityBlocker(appStatus(), r)!); - if (r.identity === identity) throw new Error(`${name} already uses the ${identity} identity`); - log("repo-identity", name, { identity, was: r.identity }); - r.identity = identity; - changed(); - return wait(structuredClone(repos.find((x) => x.name === name)!), 40); - }, async setPipeline(name, on) { requireOperator("switch the pipeline"); const r = repos.find((x) => x.name === name); @@ -418,6 +408,20 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { requireOperator("see the GitHub App"); return wait(appStatus()); }, + async setIdentity(identity) { + requireOperator("switch the GitHub identity"); + const status = appStatus(); + if (identity === githubIdentity) throw new Error(`The GitHub identity is already ${identity === "app" ? "the GitHub App" : "the box account"}.`); + if (identity === "app") { + if (!status.configured) throw new Error("No GitHub App is registered."); + const bad = repos.filter((r) => r.tracked && appIdentityBlocker(status, r)).map((r) => r.name); + if (bad.length) throw new Error(`The GitHub App does not cover ${bad.length === 1 ? "this repo" : "these repos"}: ${bad.join(", ")}.`); + } + log("github-identity", identity, { identity, was: githubIdentity }); + githubIdentity = identity; + changed(); + return wait({ identity, signIn: "" }); + }, async createLink(org) { requireOperator("create setup links"); if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(org)) throw new Error("That is not a GitHub organization name."); diff --git a/web/src/api/types.ts b/web/src/api/types.ts index db66a04e5..2b2babe4b 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -869,8 +869,6 @@ export interface TrackedRepo { seenChecks: string[]; /** Whether the pipeline stages run on this repo; off means sync only. False for repos that are not tracked. */ pipeline: boolean; - /** Who makes the pipeline's GitHub writes here: the box account (legacy) or the GitHub App (app). */ - identity: "legacy" | "app"; } export interface AccessEntry { @@ -947,8 +945,8 @@ export type AccessToken = McpToken & { login: string }; export interface GithubAppStatus { /** The app's keys are in the secrets file. */ configured: boolean; - /** Which application signs dashboard users in. */ - loginMode: "oauth" | "github-app"; + /** The instance-wide GitHub identity: the box account, or the GitHub App (writes and dashboard sign-in). */ + identity: "box" | "app"; /** False when the server has no secrets file to keep the keys in. */ canRegister: boolean; defaultName: string; diff --git a/web/src/modules/admin/githubAppViews.tsx b/web/src/modules/admin/githubAppViews.tsx index 1bc5fa706..bddd4a9df 100644 --- a/web/src/modules/admin/githubAppViews.tsx +++ b/web/src/modules/admin/githubAppViews.tsx @@ -11,11 +11,17 @@ import { TextLink } from "../../ui/atoms/TextLink"; import { day } from "../../lib/format"; import { Block } from "../../ui/molecules/Block"; import { ConfirmButton } from "../../ui/molecules/ConfirmButton"; +import { Segmented } from "../../ui/molecules/Segmented"; +import { useUser } from "../../shell/UserContext"; import { Facts } from "../../ui/molecules/Facts"; import { Page } from "../../ui/organisms/Page"; import { authorizeHref } from "../decisions/ExecLine"; -const LOGIN_MODE = { oauth: "OAuth App", "github-app": "GitHub App" } as const; +const IDENTITY_LABEL = { box: "Box account", app: "GitHub App" } as const; +const IDENTITY_LINE = { + box: "GitHub writes use the server's own GitHub account; dashboard sign-in uses the OAuth App.", + app: "GitHub writes are made by the GitHub App, and answers by the person who gave them; dashboard sign-in uses the GitHub App.", +} as const; export function GithubAppView(_: ViewProps) { const { data, error, refetch } = useQuery("github-app", (api) => api.githubApp.status()); @@ -24,6 +30,7 @@ export function GithubAppView(_: ViewProps) { <ErrorLine error={error?.message} className="mt-3" /> {data && ( <> + <IdentityBlock s={data} onChange={refetch} /> <AppBlock s={data} onChange={refetch} /> <SetupLinks links={data.links} onChange={refetch} /> {data.app && <Installations s={data} />} @@ -33,6 +40,37 @@ export function GithubAppView(_: ViewProps) { ); } +/** The one instance-wide switch. Switching ends every session, so the page goes to sign-in afterwards. */ +function IdentityBlock({ s, onChange }: { s: GithubAppStatus; onChange: () => void }) { + const api = useApi(); + const operator = useUser().role === "operator"; + const [error, setError] = useState<string | null>(null); + const choose = async (identity: "box" | "app") => { + if (identity === s.identity) return; + setError(null); + try { + const done = await api.githubApp.setIdentity(identity); + if (done.signIn) window.location.assign(done.signIn); + else onChange(); + } catch (e) { + setError((e as Error).message); + } + }; + return ( + <Block className="mt-4" title="GitHub identity"> + <div className="px-4 py-3"> + {operator ? ( + <Segmented label="GitHub identity" value={s.identity} options={(["box", "app"] as const).map((v) => ({ value: v, label: IDENTITY_LABEL[v] }))} onChange={(v) => void choose(v)} /> + ) : ( + <Badge tone={s.identity === "app" ? "ok" : undefined}>{IDENTITY_LABEL[s.identity]}</Badge> + )} + <p className="mt-2 text-sm text-ink/70">{IDENTITY_LINE[s.identity]}</p> + <ErrorLine error={error} className="mt-2" /> + </div> + </Block> + ); +} + function AppBlock({ s, onChange }: { s: GithubAppStatus; onChange: () => void }) { const api = useApi(); const [busy, setBusy] = useState(false); @@ -60,7 +98,6 @@ function AppBlock({ s, onChange }: { s: GithubAppStatus; onChange: () => void }) ["Name", s.app.name], ["Slug", <code key="slug">{s.app.slug}</code>], ["App id", <code key="id">{s.app.id}</code>], - ["Sign-in", LOGIN_MODE[s.loginMode]], ["Acts as you", s.authorized ? "Authorized" : "Not authorized"], ]} /> @@ -94,7 +131,6 @@ function RegisterForm({ s }: { s: GithubAppStatus }) { const [org, setOrg] = useState(""); return ( <> - <Facts rows={[["Sign-in", LOGIN_MODE[s.loginMode]]]} className="mb-3" /> <form method="post" action="/auth/github-app/start" className="flex flex-wrap items-center gap-2"> <input type="hidden" name="csrf" value={s.csrf} /> <Input name="name" value={name} onChange={(e) => setName(e.target.value)} maxLength={34} aria-label="App name" className="w-full sm:w-52" /> diff --git a/web/src/modules/admin/repoDetail.tsx b/web/src/modules/admin/repoDetail.tsx index 2564fd213..0e15c7fda 100644 --- a/web/src/modules/admin/repoDetail.tsx +++ b/web/src/modules/admin/repoDetail.tsx @@ -9,7 +9,7 @@ import { Block } from "../../ui/molecules/Block"; import { Switch } from "../../ui/atoms/Switch"; import { ErrorLine } from "../../ui/atoms/ErrorLine"; import { Page } from "../../ui/organisms/Page"; -import { IdentitySwitch, OptionalChecks, PipelineSwitch, Toggle, WRITES, approvalPatch, useRepoWrite, maybe, synced, type Write, type WriteKind } from "./repoParts"; +import { OptionalChecks, PipelineSwitch, Toggle, WRITES, approvalPatch, useRepoWrite, maybe, synced, type Write, type WriteKind } from "./repoParts"; import { MainCiBadge } from "../../ui/atoms/MainCiBadge"; import { FailingChecks } from "../mainci/parts"; import { useNow } from "../../lib/useNow"; @@ -122,12 +122,6 @@ export function RepoDetailView({ params }: ViewProps) { <PipelineSwitch r={r} write={write} /> </span> )} - {r?.tracked && ( - <span className="inline-flex flex-wrap items-center gap-3"> - <span className="text-ink/60">Writes as</span> - <IdentitySwitch r={r} write={write} /> - </span> - )} </div> <MainCiLine name={name} /> <ErrorLine error={write.error ?? error?.message} className="mt-2" /> diff --git a/web/src/modules/admin/repoParts.tsx b/web/src/modules/admin/repoParts.tsx index abb72f243..892fff806 100644 --- a/web/src/modules/admin/repoParts.tsx +++ b/web/src/modules/admin/repoParts.tsx @@ -1,4 +1,4 @@ -import { useApi, useQuery } from "../../api/client"; +import { useApi } from "../../api/client"; import type { TrackedRepo } from "../../api/types"; import { Badge } from "../../ui/atoms/Badge"; import { Button } from "../../ui/atoms/Button"; @@ -7,13 +7,11 @@ import { useUser } from "../../shell/UserContext"; import { ConfirmButton } from "../../ui/molecules/ConfirmButton"; import { Switch } from "../../ui/atoms/Switch"; import { useWrite } from "../../lib/hooks"; -import { appIdentityBlocker } from "../../lib/identity"; import { setRepoOwners } from "../../lib/links"; import { useCallback, useRef, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { Select } from "../../ui/atoms/Select"; import { Block } from "../../ui/molecules/Block"; -import { Segmented } from "../../ui/molecules/Segmented"; /** Fields of one repo to show at once on a press, before the server answers. */ export interface Optimistic { @@ -234,40 +232,6 @@ export function PipelineSwitch({ r, write }: { r: TrackedRepo; write: Write }) { return <Switch on={r.pipeline} label={`Pipeline in ${r.name}`} onChange={(on) => void write.run(key, () => api.repoAdmin.setPipeline(r.name, on), { repo: r.name, patch: () => ({ pipeline: on }) })} />; } -const IDENTITY_LABEL = { legacy: "Box account", app: "GitHub App" } as const; - -/** Who makes the repo's GitHub writes: operators choose, others see it. The app option is offered only where the app can act. */ -export function IdentitySwitch({ r, write }: { r: TrackedRepo; write: Write }) { - const operator = useUser().role === "operator"; - if (!r.tracked) return null; - if (!operator) return <Badge tone={r.identity === "app" ? "ok" : undefined}>{IDENTITY_LABEL[r.identity]}</Badge>; - return <IdentityChoice r={r} write={write} />; -} - -function IdentityChoice({ r, write }: { r: TrackedRepo; write: Write }) { - const api = useApi(); - const { data } = useQuery("github-app", (a) => a.githubApp.status()); - const key = `identity:${r.name}`; - if (!data) return <Badge>{IDENTITY_LABEL[r.identity]}</Badge>; - const why = appIdentityBlocker(data, r); - const offered = why === null || r.identity === "app"; - return ( - <span className="inline-flex flex-wrap items-center gap-x-3 gap-y-1"> - {offered ? ( - <Segmented - label={`Identity in ${r.name}`} - value={r.identity} - options={(["legacy", "app"] as const).map((v) => ({ value: v, label: IDENTITY_LABEL[v] }))} - onChange={(v) => { if (v !== r.identity) void write.run(key, () => api.repoAdmin.setIdentity(r.name, v), { repo: r.name, patch: () => ({ identity: v }) }); }} - /> - ) : ( - <Badge>{IDENTITY_LABEL.legacy}</Badge> - )} - {why && <span className="text-sm text-ink/60">{why}</span>} - </span> - ); -} - export const synced = (r: TrackedRepo) => r.syncedAt ? `${eventTime(r.syncedAt)}` : "never"; export const maybe = (n: number | null) => (n === null ? "–" : num(n));