diff --git a/README.md b/README.md index 916c05e8d..9fdc70e13 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,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. 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. With the app's webhooks on, anyone who may use Queue items on the merge queue page can add a pull request or issue to the merge queue from GitHub by commenting `@ merge queue` on it; the app answers in the thread (docs/operations.md, Webhooks). The same people can comment `@ autorepin ` on a pull request that pins another tracked repository's crates to an unmerged pull request: once that pull request is merged, AutoCraft pushes a commit that repins them to its merge commit, or with `via ` after it, to the first commit of that branch that contains it (docs/operations.md, Autorepin). +To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard stores the app's keys in the database, sealed with a key derived from the file's `session_key`; the file itself is only read. 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. With the app's webhooks on, anyone who may use Queue items on the merge queue page can add a pull request or issue to the merge queue from GitHub by commenting `@ merge queue` on it; the app answers in the thread (docs/operations.md, Webhooks). The same people can comment `@ autorepin ` on a pull request that pins another tracked repository's crates to an unmerged pull request: once that pull request is merged, AutoCraft pushes a commit that repins them to its merge commit, or with `via ` after it, to the first commit of that branch that contains it (docs/operations.md, Autorepin). | Variable | Meaning | |---|---| diff --git a/docs/dashboard-spec.md b/docs/dashboard-spec.md index b274fbad2..242521b2d 100644 --- a/docs/dashboard-spec.md +++ b/docs/dashboard-spec.md @@ -264,7 +264,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). 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. +- The GitHub App's keys (id, slug, private key, client id and secret, webhook secret, owner) are stored in the database (table `github_app`, one row), sealed with the token box derived from `session_key`, so every dashboard replica and the runner read the same keys without sharing a filesystem. Registering the app stores them; Remove clears them. A secrets file that still holds `github_app_*` keys is imported once, while no row exists; after that the file's app keys are ignored, except a non-empty `github_app_webhook_secret` for the same app id, which replaces the stored one at start. Each process reads the row again at most every 10 seconds, 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/operations.md b/docs/operations.md index ccaca3ad7..d9bd8635b 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -34,7 +34,7 @@ Each run stores `sync_points_last_run` (a full run: `sync_full_points_last_run`) The poll stays the backup and serves repos without the GitHub App. With webhooks on, a change reaches the dashboard in seconds instead of up to a minute. Setup, in the app's GitHub settings under General (an app manager does this): -- Webhook: Active. Webhook URL `/webhooks/github`, content type `application/json`, secret: the value of `github_app_webhook_secret` in the secrets file (GitHub returns it when the app is registered from the dashboard; if the key is empty, set a secret in the app's settings and store the same value as `github_app_webhook_secret` in the secrets file). The dashboard reads the secret at start, so restart it after the secret changes. +- Webhook: Active. Webhook URL `/webhooks/github`, content type `application/json`, secret: the one GitHub returned when the app was registered from the dashboard (stored with the app's keys in the database). If there is none, set a secret in the app's settings and put the same value as `github_app_webhook_secret` in the secrets file; the dashboard stores it for the registered app at its next start. - Permissions (Permissions & events): read access to Issues, Pull requests and Checks. The answer to a command in a comment (below) is a comment by the app under the app identity, which needs write access to Issues and Pull requests; an app registered from the dashboard has both (`appManifest` in `src/github/app.ts`). After raising a permission in the app's settings, the owner of each installation approves it there before it takes effect. - Subscribe to events: Issues, Issue comment, Pull request, Pull request review, Pull request review comment, Check suite. A check suite counts when its action is `completed`; a fork's pull request, which GitHub lists no pull requests for, is found through the event's head commit. - Check Recent Deliveries after saving: the `ping` delivery answers 200. @@ -65,7 +65,7 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick - The commit ("Repin to ", authored like the pipeline's other commits) changes only those manifests and the lockfile, and is pushed with a lease on the head it was made on (`pushRepin` in `src/github/write.ts`, audit action `autorepin-push`). A head that moved meanwhile, a failed lockfile task or a GitHub read that fails starts the autorepin over after a minute, at most 5 times; then it fails with the last reason. A reason AutoCraft did not word itself (git or database errors) is only logged; the comment then gives a fixed reason. - The outcome is one comment on the pull request naming the person who asked (audit action `autorepin-comment`): the commit and the files it changed, why it failed, or that the named pull request was closed without merging. A quiet pull request gets no comment. A pull request that itself closed or merged first drops its autorepins without a comment. The new head goes through Review and Verify like any new head. A merge pre-approved at the old head (`@ merge queue`, Queue items) carries on to the repinned head as it does across the pipeline's own base merge (`ownPush` in `src/preapproval/index.ts`): the row goes back to `review`, and the review, the pre-merge review and CI must be clean at the new head before the PR reaches the merge queue. As for a base merge, this holds until the row is `queued`: a pre-approval whose Merge answer is already written for the old head is cancelled by the repin, with the reason in the PR's thread, and a person queues the PR again. So a pull request that has both commands needs nobody between the dependency's merge and its own. -The app's slug is `github_app_slug` in the secrets file; without the app there are no commands. The **Issue comment** event must be subscribed (it is in the list above). +The app's slug is shown on the GitHub App page; without the app there are no commands. The **Issue comment** event must be subscribed (it is in the list above). Sync also stores the hashes the planner compares, on the item row: `embed_hash` (the embedded text, `src/embed/text.ts`) and `class_hash` with `class_scheme` (the classifier's input hash, `src/itemhash.ts`). `classify-new` and `embed` select changed items from these columns on covering indexes instead of hashing every body. The first `connect()` after an upgrade fills them for existing rows (about 6 s for 56,000 items). An edit of title, body or size outside sync clears the row's hashes, and the readers fill them again. @@ -87,7 +87,7 @@ The frontend is the React app in `web/`. Build it before serving: `pnpm -C web i | `AUTOCRAFT_DB_URL` | A `postgres://` URL: the database is Postgres instead of SQLite. Set it or `AUTOCRAFT_DB`, not both. The runner hands it to its worker threads and job processes. | | `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 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 reads, writes and dashboard sign-in use the box account or the GitHub App is one instance-wide setting (GitHub App page, or `autocraft-server identity [box|app]`); switching ends every dashboard session and takes effect in the runner and the dashboard at their next GitHub call, without a restart. Under `box`, every `gh` and `git` call uses the server user's own `gh` login. Under `app`, every read (GraphQL, REST, git fetch over HTTPS, the image proxy, repository checks when tracking) runs with an installation token of the owner it concerns (the first tracked repo's owner when a read names none) and never sees the box account's credentials; the `gh` login of the server user is not needed. A read for which no installation token can be minted fails with an error naming the owner. The GitHub rate figures shown on the Pipeline page and used by the sync's reserve are those of the token in use. Permission checks of a signed-in person use that person's own token in both modes. | +| `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. The file is only read, so it can be a read-only mount. Registering the GitHub App from the dashboard (GitHub App page, operators only) stores the app's keys in the database, sealed with a key derived from `session_key`. The GitHub App page's Remove button clears them (refused while the GitHub identity is the GitHub App) and links to the app's GitHub settings page, where the operator deletes the app. A secrets file from before that 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` is imported into the database once, at the first start that finds no stored app; after that those keys in the file are ignored, except `github_app_webhook_secret` (Webhooks above). Every process reads the stored keys again at most every 10 seconds, so registering or removing the app needs no restart. Whether GitHub reads, writes and dashboard sign-in use the box account or the GitHub App is one instance-wide setting (GitHub App page, or `autocraft-server identity [box|app]`); switching ends every dashboard session and takes effect in the runner and the dashboard at their next GitHub call, without a restart. Under `box`, every `gh` and `git` call uses the server user's own `gh` login. Under `app`, every read (GraphQL, REST, git fetch over HTTPS, the image proxy, repository checks when tracking) runs with an installation token of the owner it concerns (the first tracked repo's owner when a read names none) and never sees the box account's credentials; the `gh` login of the server user is not needed. A read for which no installation token can be minted fails with an error naming the owner. The GitHub rate figures shown on the Pipeline page and used by the sync's reserve are those of the token in use. Permission checks of a signed-in person use that person's own token in both modes. | | `AUTOCRAFT_GITHUB_APP_NAME` | Name suggested on the registration form. Default `AutoCraft`; at most 34 letters, digits, spaces, dashes or underscores. | | `AUTOCRAFT_TRUST_PROXY` | The number of trusted proxies in front of the server (0 to 9, default 0), for the client address of the rate limits. Each proxy is assumed to append the address it was reached from to `X-Forwarded-For`, so the client is that many entries from the end; with 0 the socket address counts. A proxy that replaces the header with a CDN's client-address header counts as one, and must then refuse connections that do not come from the CDN. | | `AUTOCRAFT_IMG_CACHE` | Disk cache of the image proxy. Default `$XDG_CACHE_HOME/autocraft/img` (`~/.cache/...`); empty for no disk cache. | diff --git a/src/dash/server/config.ts b/src/dash/server/config.ts index fc096502e..d3cb2cd07 100644 --- a/src/dash/server/config.ts +++ b/src/dash/server/config.ts @@ -1,4 +1,4 @@ -import { chmodSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { readFileSync, statSync } from "node:fs"; import { isIP } from "node:net"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -18,31 +18,6 @@ export type AppSecrets = { export type AppOwner = { login: string; type: "User" | "Organization" }; export type Secrets = { githubClientId: string; githubClientSecret: string; sessionKey: string; app: AppSecrets | null }; -/** - * 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); stamp = now; } catch { /* mid-write or unreadable: keep the last good value */ } - } - } - return cached; - }, - set(v: AppSecrets | null) { cached = v; stamp = stampOf(); }, - }); -} - function configuredDb(env: NodeJS.ProcessEnv): string { try { return dbTarget(env); @@ -63,7 +38,7 @@ export type Config = { trustProxy: number; // proxies in front of the server that append to X-Forwarded-For; 0: use the socket address imageCacheDir: string | null; // the image proxy's disk cache; null: none secrets: Secrets; - secretsFile: string | null; // where registration writes the app's secrets + secretsFile: string | null; // the secrets file; its GitHub App keys are imported into the database once (src/github/app-keys.ts) }; export const DEFAULT_WEB_DIST = fileURLToPath(new URL("../../../web/dist", import.meta.url)); @@ -142,78 +117,7 @@ export function appSecretsOf(raw: Record): AppSecrets | null { return { id, slug, privateKey, clientId, clientSecret, webhookSecret: opt("github_app_webhook_secret"), owner }; } -function readRawSecrets(path: string): Record { - try { - return JSON.parse(readFileSync(path, "utf8")) as Record; - } catch (e) { - if ((e as NodeJS.ErrnoException).code === "ENOENT") return {}; - throw new ConfigError("secrets file is not valid JSON"); - } -} - -/** A sibling of the target with a random name, created exclusively (`wx`) so it never follows or replaces an existing file. */ -function writeTemp(target: string, body: string): string { - const tmp = `${target}.${randomToken(6)}.tmp`; - try { - writeFileSync(tmp, body, { mode: 0o600, flag: "wx" }); - chmodSync(tmp, 0o600); - } catch (e) { - try { unlinkSync(tmp); } catch { /* not created */ } - throw e; - } - return tmp; -} - -/** The file a write must replace: the secrets file itself, or the file a symlink there points to. */ -function secretsTarget(path: string): string { - try { - return realpathSync(path); - } catch (e) { - if ((e as NodeJS.ErrnoException).code === "ENOENT") return path; - throw e; - } -} - -/** Throws unless a later `writeAppSecrets` can succeed: the file parses and a temporary file can be created beside it. */ -export function checkSecretsWritable(path: string): void { - readRawSecrets(path); - unlinkSync(writeTemp(secretsTarget(path), "")); -} - -/** - * Adds the app's keys to the secrets file through a temporary file in the same - * directory and a rename, mode 0600. Other keys stay as they are, and a - * symlinked secrets file stays a symlink. - */ -export function writeAppSecrets(path: string, app: AppSecrets): void { - const target = secretsTarget(path); - const next = { - ...readRawSecrets(target), - github_app_id: app.id, github_app_slug: app.slug, github_app_private_key: app.privateKey, - github_app_client_id: app.clientId, github_app_client_secret: app.clientSecret, github_app_webhook_secret: app.webhookSecret ?? "", - github_app_owner: app.owner, - }; - const tmp = writeTemp(target, `${JSON.stringify(next, null, 2)}\n`); - try { - renameSync(tmp, target); - } catch (e) { - try { unlinkSync(tmp); } catch { /* already gone */ } - throw e; - } -} - -/** Removes every `github_app_*` key from the file the same way: temporary file, rename, mode 0600. */ -export function removeAppSecrets(path: string): void { - const target = secretsTarget(path); - const next = Object.fromEntries(Object.entries(readRawSecrets(target)).filter(([k]) => !k.startsWith("github_app_"))); - const tmp = writeTemp(target, `${JSON.stringify(next, null, 2)}\n`); - try { - renameSync(tmp, target); - } catch (e) { - try { unlinkSync(tmp); } catch { /* already gone */ } - throw e; - } -} +let devSessionKey: string | undefined; export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const { host, port } = parseListen(envVar("LISTEN", env) ?? (envVar("DEV_AUTH", env) === "1" ? DEV_LISTEN : DEFAULT_LISTEN)); @@ -223,7 +127,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { if (devAuth) { if (!isLoopback(host)) throw new ConfigError("AUTOCRAFT_DEV_AUTH=1 is allowed only on a loopback listen address"); // Dev sessions don't survive a restart: the key lives only in this process. - secrets = { githubClientId: "dev", githubClientSecret: "dev", sessionKey: randomToken(), app: null }; + secrets = { githubClientId: "dev", githubClientSecret: "dev", sessionKey: (devSessionKey ??= randomToken()), app: null }; } else { secrets = readSecrets(envVar("SECRETS_FILE", env)); } @@ -231,13 +135,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { // A dev server reads the app's keys from a secrets file when one is given, so registration can be tried locally. if (devAuth && secretsFile) { let loose = false; - try { loose = (statSync(secretsFile).mode & 0o077) !== 0; } catch { /* no file yet */ } + try { loose = (statSync(secretsFile).mode & 0o077) !== 0; } catch { /* no file */ } if (loose) throw new ConfigError("secrets file is readable or writable by group or others; chmod 600 it"); - try { - secrets.app = appSecretsOf(JSON.parse(readFileSync(secretsFile, "utf8")) as Record); - } catch { /* no file yet: registration creates it */ } } - if (secretsFile) followAppSecrets(secrets, secretsFile); const rawBaseUrl = envVar("BASE_URL", env); if (rawBaseUrl) { let u: URL; diff --git a/src/dash/server/github-app.ts b/src/dash/server/github-app.ts index 888a38c9f..dbc692406 100644 --- a/src/dash/server/github-app.ts +++ b/src/dash/server/github-app.ts @@ -1,7 +1,8 @@ // The operator's GitHub App registration: the status the admin page reads, the // start page that posts the manifest to GitHub, and the callback that turns the -// returned code into the app's keys. The keys go to the secrets file only; no -// response, log line or audit row carries the private key or client secret. +// returned code into the app's keys. The keys are stored sealed in the database +// (src/github/app-keys.ts) only; no response, log line or audit row carries the +// private key or client secret. import type { IncomingMessage } from "node:http"; import type { GithubAppStatus } from "../../../web/src/api/types.ts"; import { audit } from "../audit.ts"; @@ -9,7 +10,8 @@ import type { Session } from "./sessions.ts"; import { AppError, APP_NAME, appManifest, appName, convertManifest, installUrl, installations, installationRepos, registrationUrl, settingsUrl, transferUrl, type AppDeps } from "../../github/app.ts"; import type { Res, Route } from "../types.ts"; import { envVar } from "../../env.ts"; -import { checkSecretsWritable, removeAppSecrets, writeAppSecrets, type Config } from "./config.ts"; +import type { Config } from "./config.ts"; +import { boundAppKeys } from "../../github/app-keys.ts"; import { githubIdentity, IdentityRefused, setGithubIdentityChecked } from "../../github/identity.ts"; import { randomToken } from "./crypto.ts"; import { esc, plainPage } from "./util.ts"; @@ -55,14 +57,9 @@ export function githubAppRoutes(config: Config, deps: AppDeps, mint?: (owner: st const app = config.secrets.app; if (!app) return { status: 409, json: { error: "No app is registered." } }; if (await 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); - } catch (e) { - console.error(`github-app remove: file not updated (${errorCode(e)})`); - return { status: 500, json: { error: `The file holding the app's keys could not be updated (${errorCode(e)}).` } }; - } - config.secrets.app = null; + const keys = boundAppKeys(config.secrets); + if (keys) await keys.clear(); + else config.secrets.app = null; await db.run(db.k.deleteFrom("github_app_states")); // The stored user tokens belong to the removed app. await db.run(db.k.deleteFrom("user_tokens")); @@ -89,7 +86,7 @@ export function githubAppRoutes(config: Config, deps: AppDeps, mint?: (owner: st export async function githubAppStatus(db: Db, config: Config, deps: AppDeps): Promise> { const app = config.secrets.app; const status: Omit = { - configured: !!app, identity: await githubIdentity(db), canRegister: !!config.secretsFile, + configured: !!app, identity: await githubIdentity(db), canRegister: !!boundAppKeys(config.secrets), defaultName: envVar("GITHUB_APP_NAME") ?? DEFAULT_APP_NAME, app: null, installations: [], links: await openLinks(db), error: null, }; if (!app) return status; @@ -117,16 +114,11 @@ const refuse = (nonce: string, status: number, text: string, to: { back: string; export async function startRegistration(db: Db, config: Config, req: IncomingMessage, form: URLSearchParams, nonce: string, session: Session): Promise { if (session.role !== "operator") return refuse(nonce, 403, "Only operators can register the GitHub App."); if (config.secrets.app) return refuse(nonce, 409, "An app is already registered."); - if (!config.secretsFile) return refuse(nonce, 409, "AUTOCRAFT_SECRETS_FILE is not set, so there is nowhere to keep the app's keys."); + if (!boundAppKeys(config.secrets)) return refuse(nonce, 409, "There is nowhere to keep the app's keys."); const name = (form.get("name") ?? "").trim() || envVar("GITHUB_APP_NAME") || DEFAULT_APP_NAME; const org = (form.get("org") ?? "").trim() || null; if (!APP_NAME.test(name)) return refuse(nonce, 400, "The app name must be 1 to 34 letters, digits, spaces, dashes or underscores."); if (org && !ORG.test(org)) return refuse(nonce, 400, "That is not a GitHub organization name."); - try { - checkSecretsWritable(config.secretsFile); - } catch (e) { - return refuse(nonce, 409, `The secrets file cannot be updated (${errorCode(e)}), so the app's keys could not be kept.`); - } const state = randomToken(24); await db.run(db.k.deleteFrom("github_app_states").where("created_at", "<=", new Date(Date.now() - STATE_TTL_MS).toISOString())); await db.run(db.k.insertInto("github_app_states").values({ state, login: session.login, session_hash: session.idHash, created_at: new Date().toISOString() })); @@ -169,15 +161,8 @@ export type Actor = { login: string; back: string; backLabel: string; redirect: */ export async function convertAndStore(db: Db, config: Config, deps: AppDeps, code: string, state: string, nonce: string, actor: Actor, stale: string): Promise { const refuseTo = (status: number, text: string): Res => refuse(nonce, status, text, actor); - if (config.secrets.app || !config.secretsFile || converting.has(config)) return refuseTo(409, "An app is already registered, or no secrets file is set."); - // Prove the file can take the keys before the state is consumed: GitHub's code works once, and a lost PEM leaves an app nobody holds keys for. - // GitHub has already created the app by now; a failed probe keeps the state and the unconverted code, so a reload recovers. - try { - checkSecretsWritable(config.secretsFile); - } catch (e) { - console.error(`github-app registration: secrets file not writable (${errorCode(e)})`); - return refuseTo(409, `The app exists on GitHub, but the secrets file cannot be updated (${errorCode(e)}). Fix the file and reload this page within an hour.`); - } + const keys = boundAppKeys(config.secrets); + if (config.secrets.app || !keys || converting.has(config)) return refuseTo(409, "An app is already registered, or there is nowhere to keep its keys."); if ((await db.run(db.k.deleteFrom("github_app_states").where("state", "=", state))).changes !== 1) return refuseTo(400, stale); converting.add(config); try { @@ -200,17 +185,16 @@ export async function convertAndStore(db: Db, config: Config, deps: AppDeps, cod } try { if (config.secrets.app) throw Object.assign(new Error("another app was registered meanwhile"), { code: "EEXIST" }); - writeAppSecrets(config.secretsFile, app); + await keys.save(app); } catch (e) { console.error(`github-app registration: app ${app.slug} exists on GitHub but its keys were not stored (${errorCode(e)})`); await audit(db, actor.login, "github-app-register-failed", app.slug, { id: app.id, code: errorCode(e) }); const link = settingsUrl(app.slug, app.owner); return { status: 500, - html: plainPage(nonce, "GitHub App", `

GitHub created the app ${esc(app.slug)}, but its keys could not be stored (${esc(errorCode(e))}). Delete the app on GitHub, fix the secrets file and start again.

${esc(link)}

${esc(actor.backLabel)}

`), + html: plainPage(nonce, "GitHub App", `

GitHub created the app ${esc(app.slug)}, but its keys could not be stored (${esc(errorCode(e))}). Delete the app on GitHub and start again.

${esc(link)}

${esc(actor.backLabel)}

`), }; } - config.secrets.app = app; await audit(db, actor.login, "github-app-register", app.slug, { id: app.id, name, owner: app.owner?.login ?? null, ...actor.details }); } finally { converting.delete(config); diff --git a/src/dash/server/github-setup.ts b/src/dash/server/github-setup.ts index 7afc59d23..686046755 100644 --- a/src/dash/server/github-setup.ts +++ b/src/dash/server/github-setup.ts @@ -3,6 +3,7 @@ // creates the GitHub App in the org, optionally makes the operator an app // manager, and installs the app. The owner's token lives in memory for this // flow only: never written to the database, a log line or an audit row. +import { boundAppKeys } from "../../github/app-keys.ts"; import type { IncomingMessage } from "node:http"; import type { GithubSetupLink } from "../../../web/src/api/types.ts"; import { audit } from "../audit.ts"; @@ -219,7 +220,7 @@ export class OrgSetup { const later = (label: string) => steps.push(`
  • ${esc(label)}
  • `); const managerLabel = `Make ${flow.operator} an app manager`; if (app) done("Create GitHub App"); - else if (!config.secretsFile) return message(nonce, 409, "AUTOCRAFT_SECRETS_FILE is not set, so there is nowhere to keep the app's keys."); + else if (!boundAppKeys(config.secrets)) return message(nonce, 409, "There is nowhere to keep the app's keys."); else { const name = envVar("GITHUB_APP_NAME") ?? DEFAULT_APP_NAME; const manifest = JSON.stringify(appManifest(name, publicBase(config, req))); diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 4cd130f1e..09a2787e2 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -1,5 +1,6 @@ // HTTP server: sign-in, sessions, CSRF, rate limits, security headers and // routing for the dashboard. Handlers only ever see authenticated requests. +import { AppKeys, bindSecrets, useAppKeys } from "../../github/app-keys.ts"; import { maintainerWritesOn } from "../../settlers.ts"; import { readFile, realpath } from "node:fs/promises"; import { isAbsolute, relative, resolve, sep } from "node:path"; @@ -235,6 +236,10 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { const resealed = await resealLegacyValues(db, box); const resealedTotal = Object.values(resealed).reduce((a, b) => a + b, 0); if (resealedTotal) console.log(`re-sealed ${resealedTotal} stored token values under the current key (${Object.entries(resealed).map(([t, n]) => `${t} ${n}`).join(", ")})`); + // The GitHub App's keys live in the database, imported once from the secrets file; `config.secrets.app` reads them. + const dbAppKeys = await new AppKeys(db, box, config.secretsFile).load(); + bindSecrets(config.secrets, dbAppKeys); + useAppKeys(dbAppKeys); // 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). // Read at each use: registering or removing the app takes effect without a restart. const appProviderNow = (): Provider | null => { diff --git a/src/db/types.ts b/src/db/types.ts index a32f4de97..69710011b 100644 --- a/src/db/types.ts +++ b/src/db/types.ts @@ -802,6 +802,14 @@ export interface FlowSummary { decisions_sig: string | null; } +export interface GithubApp { + id: Generated; + app_id: string | null; + slug: string | null; + keys_enc: string | null; + updated_at: string; +} + export interface GithubAppStates { state: string; login: string; @@ -2244,6 +2252,7 @@ export interface DB { fix_attempts: FixAttempts; fixups: Fixups; flow_summary: FlowSummary; + github_app: GithubApp; github_app_states: GithubAppStates; github_commands: GithubCommands; github_setup_links: GithubSetupLinks; @@ -2421,6 +2430,7 @@ export interface DB { "main.fix_attempts": FixAttempts; "main.fixups": Fixups; "main.flow_summary": FlowSummary; + "main.github_app": GithubApp; "main.github_app_states": GithubAppStates; "main.github_commands": GithubCommands; "main.github_setup_links": GithubSetupLinks; @@ -2602,6 +2612,7 @@ export const COLUMNS = { fix_attempts: ["repo", "number", "main_sha", "text_hash", "state", "round", "files", "crate", "crate_dir", "patch", "test_patch", "head_task_id", "base_task_id", "retries", "push_tries", "summary", "pr_url", "reason", "created_at", "updated_at", "size", "format_diff"], fixups: ["repo", "number", "from_head", "to_head", "state", "reason", "files", "attempt", "created_at", "source", "patch", "lint_task", "lint_round", "lint_state", "carry_decision", "operator_fix", "changes", "session"], flow_summary: ["repo", "counts", "counted_at", "stale", "decisions_sig"], + github_app: ["id", "app_id", "slug", "keys_enc", "updated_at"], github_app_states: ["state", "login", "session_hash", "created_at"], github_commands: ["comment_id", "repo", "number", "pr", "command", "weight", "login", "github_id", "created_at", "requested_at", "state", "result", "done_at", "tried_at", "retries", "allowed", "reply", "ref_repo", "ref_number", "ref_branch"], github_setup_links: ["id", "org", "created_by", "hash", "created_at", "expires_at", "revoked_at", "used_at", "used_by", "installation_id"], diff --git a/src/discord/file-issue.ts b/src/discord/file-issue.ts index a4441fc08..40a74e002 100644 --- a/src/discord/file-issue.ts +++ b/src/discord/file-issue.ts @@ -10,6 +10,7 @@ import { GitHubProvider, type Provider } from "../dash/server/provider.ts"; import { exec as defaultExec, type Exec } from "../fixup/git.ts"; import { createReporterIssue, IssueError, labelReporterIssue } from "../github/write.ts"; import { appChildEnv } from "../github/install-token.ts"; +import { openAppKeys } from "../github/app-keys.ts"; import { JEV_PROMPTS } from "../prompts/index.ts"; import { isPublicRepo } from "../public/status.ts"; import { jevJunk, junkBand, junkState, parseJunk, type JunkAsk } from "./junk-ask.ts"; @@ -100,10 +101,11 @@ async function junkCheck(db: Db, a: JunkAsk, judge: NonNullable { try { const s = readSecrets(envVar("SECRETS_FILE", env)); - return s.app ? { box: new TokenBox(s.sessionKey), provider: new GitHubProvider(s.app.clientId, s.app.clientSecret) } : null; + const app = (await openAppKeys(db, env))?.current() ?? null; + return app ? { box: new TokenBox(s.sessionKey), provider: new GitHubProvider(app.clientId, app.clientSecret) } : null; } catch { return null; } @@ -120,7 +122,7 @@ export async function fileIssue(deps: FileDeps, req: FileRequest, hooks: FileHoo if (!title || !body) return { status: "refused", reason: "The title and the description must not be empty." }; if (title.length > TITLE_MAX) return { status: "refused", reason: "The title is too long." }; - const keys = hooks.box && hooks.provider ? { box: hooks.box, provider: hooks.provider } : secretsOf(); + const keys = hooks.box && hooks.provider ? { box: hooks.box, provider: hooks.provider } : await secretsOf(db); const baseUrl = (hooks.baseUrl === undefined ? envVar("BASE_URL") ?? null : hooks.baseUrl)?.replace(/\/+$/, "") ?? null; if (!keys || !baseUrl) return { status: "refused", reason: "Filing from Discord is not set up." }; diff --git a/src/discord/index.ts b/src/discord/index.ts index 288986a81..bc4148944 100644 --- a/src/discord/index.ts +++ b/src/discord/index.ts @@ -2,6 +2,7 @@ // are set; the runner starts it next to the worker server. See docs/pipeline.md. import { loadConfig, type Config } from "../dash/server/config.ts"; import { TokenBox } from "../dash/server/crypto.ts"; +import { bindSecrets, processAppKeys } from "../github/app-keys.ts"; import { githubIdentity } from "../github/identity.ts"; import { providerFor } from "../dash/server/provider.ts"; import { userForLogin } from "../dash/server/sessions.ts"; @@ -82,6 +83,8 @@ export function dispatcher(db: Db, keys: DiscordKeys, interactions: Interactions function installDecisionAlerts(db: Db, keys: DiscordKeys, rest: RestClient, interactions: Interactions, signal: AbortSignal, log: (l: string) => void): void { 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 appKeys = processAppKeys(); + if (config && appKeys) bindSecrets(config.secrets, appKeys); const box = config ? new TokenBox(config.secrets.sessionKey) : null; const provider = config ? providerFor(config, async () => await githubIdentity(db)) : null; const alerts = new DecisionAlerts({ diff --git a/src/github/app-keys.ts b/src/github/app-keys.ts new file mode 100644 index 000000000..ea7700666 --- /dev/null +++ b/src/github/app-keys.ts @@ -0,0 +1,154 @@ +// The registered GitHub App's keys, kept in the database (table github_app, one row) sealed with the TokenBox every +// process derives from the secrets file's session_key, so the dashboard, its replicas and the runner read the same keys +// without sharing a filesystem. A secrets file's `github_app_*` keys are imported once, while no row exists: after that +// the row decides, and a removed app (keys_enc null) is not brought back from the file. +// +// Readers are synchronous (the slug and the minter's keys are read in many places), so each store keeps the last value +// it read and reads the row again, in the background, when that value is older than REREAD_MS. A change made through the +// store itself is visible at once; one made by another process within REREAD_MS. +import { readFileSync } from "node:fs"; +import { appSecretsOf, checkSecretsFileMode, readSecrets, type AppSecrets, type Secrets } from "../dash/server/config.ts"; +import { TokenBox } from "../dash/server/crypto.ts"; +import type { Db } from "../db/index.ts"; +import { envVar } from "../env.ts"; + +const AAD = "github_app:1"; +const REREAD_MS = 10_000; + +export class AppKeys { + #db: Db; + #box: TokenBox; + #file: string | null; + #app: AppSecrets | null = null; + #readAt = 0; + #reading: Promise | null = null; + + constructor(db: Db, box: TokenBox, file: string | null) { + this.#db = db; + this.#box = box; + this.#file = file; + } + + /** + * Imports the secrets file's keys when no row exists yet, then reads the row. A webhook secret set in the file for the + * stored app (same app id) replaces the stored one at start: GitHub returns none when webhooks are off at registration. + */ + async load(): Promise { + const file = this.#file ? fileKeys(this.#file) : null; + if (file && !await this.#db.get(this.#db.k.selectFrom("github_app").select("id").where("id", "=", 1))) { + await this.#db.run(this.#db.k.insertInto("github_app").values(this.#row(file)).onConflict((oc) => oc.column("id").doNothing())); + console.log(`imported the GitHub App ${file.slug} from the secrets file into the database`); + } + await this.#read(); + const app = this.#app; + if (file?.webhookSecret && app && app.id === file.id && app.webhookSecret !== file.webhookSecret) { + const next = { ...app, webhookSecret: file.webhookSecret }; + await this.#db.run(this.#db.k.updateTable("github_app").set({ keys_enc: this.#row(next).keys_enc, updated_at: new Date().toISOString() }).where("id", "=", 1)); + this.#set(next); + } + return this; + } + + /** The keys as last read; starts a background reread when they are older than REREAD_MS. */ + current(): AppSecrets | null { + if (Date.now() - this.#readAt > REREAD_MS && !this.#reading) { + this.#reading = this.#read().catch(() => { /* unreachable database: keep the last value */ }).finally(() => { this.#reading = null; }); + } + return this.#app; + } + + /** The keys read now, for callers that can wait (token minting after a registration elsewhere). */ + async fresh(): Promise { + await this.#read(); + return this.#app; + } + + /** Stores a newly registered app. Refuses (EEXIST) when another app is registered. */ + async save(app: AppSecrets): Promise { + const row = this.#row(app); + const r = await this.#db.run(this.#db.k.insertInto("github_app").values(row) + .onConflict((oc) => oc.column("id").doUpdateSet(row).where("github_app.keys_enc", "is", null))); + if (!r.changes) throw Object.assign(new Error("another app is registered"), { code: "EEXIST" }); + this.#set(app); + } + + /** Forgets the app's keys; the row stays, so the secrets file's keys are not imported again. */ + async clear(): Promise { + await this.#db.run(this.#db.k.insertInto("github_app").values({ id: 1, app_id: null, slug: null, keys_enc: null, updated_at: new Date().toISOString() }) + .onConflict((oc) => oc.column("id").doUpdateSet({ app_id: null, slug: null, keys_enc: null, updated_at: new Date().toISOString() }))); + this.#set(null); + } + + /** For tests and dev servers: the value readers see, without a database write. */ + set(app: AppSecrets | null): void { this.#set(app); } + + #set(app: AppSecrets | null): void { + this.#app = app; + this.#readAt = Date.now(); + } + + #row(app: AppSecrets) { + return { id: 1, app_id: app.id, slug: app.slug, keys_enc: this.#box.seal(JSON.stringify(app), AAD), updated_at: new Date().toISOString() }; + } + + async #read(): Promise { + const row = await this.#db.get(this.#db.k.selectFrom("github_app").select("keys_enc").where("id", "=", 1)); + const plain = row?.keys_enc ? this.#box.open(row.keys_enc, AAD) : null; + let app: AppSecrets | null = null; + try { app = plain ? (JSON.parse(plain) as AppSecrets) : null; } catch { /* unreadable: no app */ } + this.#set(app); + } +} + +/** The app's keys in a secrets file, for the one-time import; null when it has none or cannot be read. */ +function fileKeys(file: string): AppSecrets | null { + try { + checkSecretsFileMode(file); + return appSecretsOf(JSON.parse(readFileSync(file, "utf8")) as Record); + } catch { + return null; + } +} + +let processKeys: AppKeys | null = null; +let opening: Promise | null = null; + +/** Makes `keys` the store that readAppSecrets() and the minter read in this process. */ +export function useAppKeys(keys: AppKeys): void { + processKeys = keys; +} + +/** The process's store, if one is in use (the dashboard, the runner and the Discord bot set it at start). */ +export const processAppKeys = (): AppKeys | null => processKeys; + +/** + * The process's store, opened on `db` with the secrets file's session key when none is in use yet; null without a + * secrets file. CLI commands reach it through the minter and the vault. + */ +export function openAppKeys(db: Db | (() => Promise), env: NodeJS.ProcessEnv = process.env): Promise { + if (processKeys) return Promise.resolve(processKeys); + opening ??= (async () => { + const file = envVar("SECRETS_FILE", env); + if (!file) return null; + const { sessionKey } = readSecrets(file); + const keys = await new AppKeys(typeof db === "function" ? await db() : db, new TokenBox(sessionKey), file).load(); + processKeys ??= keys; + return processKeys; + })().finally(() => { opening = null; }); + return opening; +} + +const bound = new WeakMap(); + +/** The store `secrets` is bound to; null when its app keys come from the loaded file only. */ +export const boundAppKeys = (secrets: Secrets): AppKeys | null => bound.get(secrets) ?? null; + +/** Makes `secrets.app` read and set `keys` (the dashboard's configuration, read where the routes expect it). */ +export function bindSecrets(secrets: Secrets, keys: AppKeys): void { + bound.set(secrets, keys); + Object.defineProperty(secrets, "app", { + enumerable: true, configurable: true, + get: (): AppSecrets | null => keys.current(), + set: (v: AppSecrets | null) => keys.set(v), + }); +} diff --git a/src/github/install-token.ts b/src/github/install-token.ts index c437d0658..a69ff7c02 100644 --- a/src/github/install-token.ts +++ b/src/github/install-token.ts @@ -7,6 +7,7 @@ import { readFileSync } from "node:fs"; import type { AppSecrets } from "../dash/server/config.ts"; import { appSecretsOf, checkSecretsFileMode } from "../dash/server/config.ts"; import { envVar } from "../env.ts"; +import { openAppKeys, processAppKeys } from "./app-keys.ts"; import { AppError, appJwt, call, GITHUB_API, type AppDeps } from "./app.ts"; export class AppNotInstalledError extends Error { @@ -147,8 +148,13 @@ export class InstallTokenMinter { } } -/** The app's keys from the secrets file (the runner reads the same file as the dashboard); null when no app is registered. */ +/** + * The app's keys: from the process's store (src/github/app-keys.ts) when one is in use, otherwise from the secrets file + * (a command-line process that has not opened the store); null when no app is registered. + */ export function readAppSecrets(path = envVar("SECRETS_FILE")): AppSecrets | null { + const store = processAppKeys(); + if (store) return store.current(); if (!path) return null; checkSecretsFileMode(path); return appSecretsOf(JSON.parse(readFileSync(path, "utf8")) as Record); @@ -156,8 +162,9 @@ export function readAppSecrets(path = envVar("SECRETS_FILE")): AppSecrets | null let shared: { appId: string; minter: InstallTokenMinter } | null = null; /** The process-wide minter; throws when no app is registered. Its caches belong to one app: another app (or none) starts them afresh. */ -export function installationToken(owner: string, repo?: string, scope?: TokenScope): Promise { - const app = readAppSecrets(); +export async function installationToken(owner: string, repo?: string, scope?: TokenScope): Promise { + const store = processAppKeys() ?? await openAppKeys(async () => (await import("../db/open.ts")).openDb()).catch(() => null); + const app = store ? store.current() ?? await store.fresh() : readAppSecrets(); if (!app) { shared = null; throw new AppError("no GitHub App is registered"); } if (shared?.appId !== app.id) shared = { appId: app.id, minter: new InstallTokenMinter(() => readAppSecrets() ?? app) }; return shared.minter.token(owner, repo, scope); diff --git a/src/github/vault.ts b/src/github/vault.ts index 8cfa7f52f..ef3fa5f55 100644 --- a/src/github/vault.ts +++ b/src/github/vault.ts @@ -14,6 +14,7 @@ import { envVar } from "../env.ts"; import { TokenBox } from "../dash/server/crypto.ts"; import { resealLegacyValues } from "../dash/server/reseal.ts"; import { readSecrets } from "../dash/server/config.ts"; +import { openAppKeys } from "./app-keys.ts"; import { GitHubProvider, RevokeRefused, type Provider, type Tokens } from "../dash/server/provider.ts"; import { failUserTokens, readUserTokens, revocationAad, shareRefresh, swapUserTokens } from "../dash/server/user-tokens.ts"; import type { Db } from "../db/index.ts"; @@ -163,12 +164,17 @@ export class Vault { } } -/** The runner's vault: the app's client credentials and the session key from the secrets file, as the dashboard reads them. Null without the GitHub App secrets. */ +/** The runner's vault: the app's client credentials from the process's app-key store and the session key from the secrets file, as the dashboard reads them. Null without a registered app. */ export async function openVault(db: Db, env: NodeJS.ProcessEnv = process.env): Promise { const secrets = readSecrets(envVar("SECRETS_FILE", env)); - if (!secrets.app) return null; + const keys = await openAppKeys(db, env); + const app = keys?.current() ?? null; + if (!keys || !app) return null; const box = new TokenBox(secrets.sessionKey); // The runner may start before the dashboard has re-sealed values under the current key. await resealLegacyValues(db, box); - return new Vault(db, box, new GitHubProvider(secrets.app.clientId, secrets.app.clientSecret)); + return new Vault(db, box, () => { + const now = keys.current() ?? app; + return new GitHubProvider(now.clientId, now.clientSecret); + }); } diff --git a/src/runner/index.ts b/src/runner/index.ts index 6c1afe927..874983ced 100644 --- a/src/runner/index.ts +++ b/src/runner/index.ts @@ -23,6 +23,7 @@ import { dbReady, startHealthServer } from "../health.ts"; import { envVar } from "../env.ts"; import { startDiscord } from "../discord/index.ts"; import { openDb, setDbRole } from "../db/open.ts"; +import { openAppKeys } from "../github/app-keys.ts"; const USAGE = `usage: autocraft-server runner serve autocraft-server runner steps @@ -42,6 +43,8 @@ async function serve(): Promise { setDbRole("runner"); const db = await openDb(); await scopeToTracked(db); + // The GitHub App's keys, from the database (imported once from the secrets file). + await openAppKeys(db).catch((e: Error) => console.error(`runner: GitHub App keys not read: ${e.message}`)); // Once per database: open decisions' proposed cards become choices. Here rather than in db.ts migrations, which cannot import the decision modules. const conv = await convertOpenDecisionsOnce(db); if (conv) console.log(`runner: converted ${conv.converted} open decisions to choices (${conv.skipped} skipped, ${conv.stale} stale cards, ${conv.unconverted} cards matching no choice)`); @@ -121,6 +124,8 @@ async function enqueueCmd(args: string[]): Promise { } const db = await openDb(); await scopeToTracked(db); + // The GitHub App's keys, from the database (imported once from the secrets file). + await openAppKeys(db).catch((e: Error) => console.error(`runner: GitHub App keys not read: ${e.message}`)); try { const job = await enqueue(db, name, params, "cli"); console.log(`job ${job.id} queued: ${job.step} ${JSON.stringify(job.params)}`); diff --git a/src/schema.pg.sql b/src/schema.pg.sql index 0b26eec71..98d09a9e1 100644 --- a/src/schema.pg.sql +++ b/src/schema.pg.sql @@ -1,5 +1,5 @@ -- Generated by scripts/gen-pg-schema.ts from src/schema.sql and the added columns and indexes in src/db.ts. Do not edit. --- dialect: postgres; stamp: 4f8c71dac91c3abe +-- dialect: postgres; stamp: 538a82de573691a0 -- Identity columns start at 1: after a data copy, each identity sequence is set past the copied keys (setval). -- Compat functions: SQLite built-ins the queries use, with SQLite's results. -- char() has no equivalent: CHAR is a Postgres keyword, so no function can be called char(...); queries use a dialect helper. @@ -384,6 +384,13 @@ CREATE TABLE IF NOT EXISTS user_token_revocations ( aad text COLLATE "C", attempts bigint NOT NULL DEFAULT 0 ); +CREATE TABLE IF NOT EXISTS github_app ( + id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + app_id text COLLATE "C", + slug text COLLATE "C", + keys_enc text COLLATE "C", + updated_at text COLLATE "C" NOT NULL +); CREATE TABLE IF NOT EXISTS reporter_tokens ( reporter text COLLATE "C" PRIMARY KEY, github_id bigint NOT NULL, diff --git a/src/schema.sql b/src/schema.sql index e66f57a41..60c041fac 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -353,6 +353,16 @@ CREATE TABLE IF NOT EXISTS user_token_revocations ( attempts INTEGER NOT NULL DEFAULT 0 -- failed sweeps so far ); +-- The registered GitHub App (src/github/app-keys.ts): at most one row, id 1. keys_enc null: the app was removed, and a +-- secrets file's app keys are not imported again (they are imported only while no row exists). +CREATE TABLE IF NOT EXISTS github_app ( + id INTEGER PRIMARY KEY, + app_id TEXT, + slug TEXT, + keys_enc TEXT, -- sealed JSON of the app's keys (TokenBox, aad 'github_app:1') + updated_at TEXT NOT NULL +); + -- The GitHub App user token of a Discord reporter (src/discord/reporter.ts), keyed by the Discord user's keyed hash. Not a -- dashboard login: it grants no access, it only lets the bot file an issue as that GitHub account. CREATE TABLE IF NOT EXISTS reporter_tokens ( diff --git a/test/github-app.test.ts b/test/github-app.test.ts index e83f508f9..177240405 100644 --- a/test/github-app.test.ts +++ b/test/github-app.test.ts @@ -1,10 +1,10 @@ // GitHub App registration through the dashboard, with a fake GitHub for the -// manifest conversion: the keys land in the secrets file (mode 0600) and +// manifest conversion: the keys are stored sealed in the database and // nowhere else, the state nonce works once, only operators reach the page's // API, and app sign-in keeps the user's token sealed in user_tokens. import assert from "node:assert/strict"; import { generateKeyPairSync } from "node:crypto"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { join } from "node:path"; @@ -134,6 +134,11 @@ class Client { } } +/** Forgets the stored app, so the next server imports its own secrets file. */ +async function resetApp(): Promise { + await db.run(db.k.deleteFrom("github_app")); +} + async function signedIn(login: string, origin = base): Promise { const c = new Client(origin); const start = await c.req("/auth/signin?return_to=/"); @@ -153,7 +158,7 @@ describe("github app registration", () => { } }); - test("registration stores the keys 0600, returns none of them, and the state works once", async () => { + test("registration stores the keys sealed in the database, returns none of them, and the state works once", async () => { const boss = await signedIn("boss"); const before = (await (await boss.req("/api/admin/github-app")).json()) as { configured: boolean }; assert.equal(before.configured, false); @@ -168,12 +173,10 @@ describe("github app registration", () => { const done = await boss.req(`/auth/github-app/callback?code=good-code&state=${state}`); assert.equal(done.status, 303); assert.equal(done.headers.get("location"), "/admin/github-app"); - assert.equal(statSync(secretsFile).mode & 0o777, 0o600); - const stored = JSON.parse(readFileSync(secretsFile, "utf8")) as Record; - assert.equal(stored.github_app_slug, "autocraft-test"); - assert.equal(stored.github_app_private_key, PEM); - assert.equal(stored.github_app_client_secret, CLIENT_SECRET); - assert.deepEqual(stored.github_app_owner, { login: "glasswing", type: "Organization" }); + assert.ok(!existsSync(secretsFile), "registration writes no file"); + const row = (await db.get(db.k.selectFrom("github_app").select(["slug", "keys_enc"])))!; + assert.equal(row.slug, "autocraft-test"); + for (const secret of [PEM.slice(40, 80), CLIENT_SECRET, WEBHOOK_SECRET]) assert.ok(!row.keys_enc!.includes(secret)); const replay = await boss.req(`/auth/github-app/callback?code=good-code&state=${state}`); assert.equal(replay.status, 400); @@ -206,56 +209,38 @@ describe("github app registration", () => { assert.equal((await db.get(db.k.selectFrom("user_tokens").select("version").where("login", "=", "maint")))!.version, 2); }); - test("a secrets file that cannot be written keeps the app's slug visible and leaks no key", async () => { - const dir2 = join(dir, "readonly"); - mkdirSync(dir2); - const file2 = join(dir2, "secrets.json"); - const env = { AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile, AUTOCRAFT_SECRETS_FILE: file2 }; - const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi: `http://127.0.0.1:${(github.address() as AddressInfo).port}` }); - closers.push(s.close); - const boss = await signedIn("boss", s.url); - const start = async () => /settings\/apps\/new\?state=([A-Za-z0-9_-]+)/.exec(await (await boss.post("/auth/github-app/start", { csrf: await boss.csrf() })).text())![1]!; - const errors: string[] = []; - const log = console.error; - console.error = (...a: unknown[]) => void errors.push(a.join(" ")); - try { - // The directory turns read-only while GitHub converts the code: the probe passed, the write fails. - const state = await start(); - onConvert = () => chmodSync(dir2, 0o500); - const page = await (await boss.req(`/auth/github-app/callback?code=good-code&state=${state}`)).text(); - onConvert = () => {}; - assert.match(page, /autocraft-test/); - assert.match(page, /https:\/\/github\.com\/organizations\/glasswing\/settings\/apps\/autocraft-test/); - assert.match(page, /EACCES/); - // With the directory still read-only, a new registration stops before GitHub is asked. - const before = converted.length; - assert.equal((await boss.post("/auth/github-app/start", { csrf: await boss.csrf() })).status, 409); - assert.equal(converted.length, before); - const text = JSON.stringify(await db.all(db.k.selectFrom("audit").select(kx.cols("audit")))) + page + errors.join("\n"); - for (const secret of [PEM.slice(40, 80), CLIENT_SECRET, WEBHOOK_SECRET]) assert.ok(!text.includes(secret)); - assert.match(errors.join("\n"), /autocraft-test/); - } finally { - console.error = log; - chmodSync(dir2, 0o700); - } - }); + test("a secrets file's app keys are imported once, other processes see the stored keys, and a removed app stays removed", async () => { + const file = join(dir, "import-secrets.json"); + writeFileSync(file, JSON.stringify({ github_app_id: "9", github_app_slug: "file-app", github_app_private_key: PEM, github_app_client_id: "Iv1.file", github_app_client_secret: CLIENT_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 }; + await resetApp(); + const githubApi = `http://127.0.0.1:${(github.address() as AddressInfo).port}`; + const one = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); + closers.push(one.close); + const status = async (url: string) => (await (await (await signedIn("boss", url)).req("/api/admin/github-app")).json()) as { configured: boolean; app: { slug: string } | null }; + assert.equal((await status(one.url)).app?.slug, "file-app"); + assert.ok(!(await db.get(db.k.selectFrom("github_app").select("keys_enc")))!.keys_enc!.includes(CLIENT_SECRET)); - 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, "{}", { mode: 0o600 }); - 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)["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 }), { mode: 0o600 }); - assert.equal(keys()?.slug, "late-app"); - writeFileSync(file, "{}", { mode: 0o600 }); - assert.equal(keys(), null); + // A second dashboard (another replica) whose secrets file has no app keys reads them from the database. + const bare = join(dir, "import-bare.json"); + writeFileSync(bare, "{}", { mode: 0o600 }); + const two = await startServer({ config: loadConfig({ ...env, AUTOCRAFT_SECRETS_FILE: bare }), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); + closers.push(two.close); + assert.equal((await status(two.url)).app?.slug, "file-app"); + + // Removed through one dashboard, the app is not imported again from the file at the next start. + assert.equal((await (await signedIn("boss", one.url)).json("/api/admin/github-app/remove", {})).status, 200); + assert.equal(JSON.parse(readFileSync(file, "utf8")).github_app_slug, "file-app"); + const three = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); + closers.push(three.close); + assert.equal((await status(three.url)).configured, false); }); test("the identity route refuses with the uncovered repos listed, and a switch ends every session", async () => { const file = join(dir, "identity-secrets.json"); writeFileSync(file, JSON.stringify({ 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 }), { 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 }; + await resetApp(); const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [] }); closers.push(s.close); const boss = await signedIn("boss", s.url); @@ -297,6 +282,7 @@ describe("github app registration", () => { const file = join(dir, "setup-secrets.json"); writeFileSync(file, "{}", { 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 }; + await resetApp(); const s = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi: `http://127.0.0.1:${(github.address() as AddressInfo).port}` }); closers.push(s.close); const boss = await signedIn("boss", s.url); @@ -344,7 +330,7 @@ describe("github app registration", () => { assert.ok(state, "the manifest goes to the org"); assert.match(create.t, /"setup_url":"http:\/\/127\.0\.0\.1:\d+\/auth\/github-app\/setup"/); assert.equal((await owner.req(`/auth/github-app/callback?code=good-code&state=${state}`)).status, 303); - assert.equal(JSON.parse(readFileSync(file, "utf8")).github_app_slug, "autocraft-test"); + assert.equal((await db.get(db.k.selectFrom("github_app").select("slug")))!.slug, "autocraft-test"); // Organization roles answer 404 (Free plan): the page offers the settings link instead. const manage = await owner.post("/auth/setup/manager", {}); @@ -387,6 +373,7 @@ describe("github app registration", () => { const file = join(dir, "setup2-secrets.json"); writeFileSync(file, "{}", { 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 }; + await resetApp(); const provider = new FakeProvider(permsFile); const s = await startServer({ config: loadConfig(env), db, provider, routes: [], githubApi: `http://127.0.0.1:${(github.address() as AddressInfo).port}` }); closers.push(s.close); @@ -434,8 +421,7 @@ describe("github app registration", () => { // The owner's flow still works: create, then a 403 on the role list leaves the settings link and the Install step. assert.equal((await a.req(`/auth/github-app/callback?code=good-code&state=${stateA2}`)).status, 303); - const keys = JSON.parse(readFileSync(file, "utf8")) as Record; - assert.equal(keys.github_app_slug, "autocraft-test"); + assert.equal((await db.get(db.k.selectFrom("github_app").select("slug")))!.slug, "autocraft-test"); const pageB = await text(b, "/auth/setup"); assert.match(pageB, /Make boss an app manager/); rolesAnswer = 403; @@ -456,10 +442,11 @@ 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 the GitHub identity is the app", async () => { + test("remove clears the app's keys from the database 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 }; + await resetApp(); const githubApi = `http://127.0.0.1:${(github.address() as AddressInfo).port}`; await db.prepare("INSERT INTO settings (key, value) VALUES ('github_identity', 'app') ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(); const appMode = await startServer({ config: loadConfig(env), db, provider: new FakeProvider(permsFile), routes: [], githubApi }); @@ -478,8 +465,7 @@ describe("github app registration", () => { assert.equal(res.status, 200); const text = await res.text(); assert.deepEqual(JSON.parse(text), { settingsUrl: "https://github.com/organizations/glasswing/settings/apps/autocraft-test" }); - assert.deepEqual(JSON.parse(readFileSync(file, "utf8")), { other_key: "kept" }); - assert.equal(statSync(file).mode & 0o777, 0o600); + assert.equal((await db.get(db.k.selectFrom("github_app").select("keys_enc")))!.keys_enc, null); assert.equal((await (await boss.req("/api/admin/github-app")).json() as { configured: boolean }).configured, false); assert.equal((await db.get(db.k.selectFrom("github_app_states").select((eb) => eb.fn.countAll().as("n"))))!.n, 0); assert.equal((await db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'github-app-remove' AND target = 'autocraft-test'").get() as { n: number }).n, 1);