From e6e38b2563dff0438e7bf0d288ba4e88f4fdf58c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:21:13 +0000 Subject: [PATCH] GitHub App: user-token vault (CAS refresh, shared refresh pair, removal revokes) and identity map on grants and audit rows --- src/access.ts | 9 ++- src/core/guard.ts | 19 +++--- src/dash/api/admin.ts | 5 +- src/dash/server/index.ts | 3 + src/dash/server/provider.ts | 20 +++++- src/dash/server/sessions.ts | 18 ++++-- src/dash/server/user-tokens.ts | 69 ++++++++++++++++++--- src/github/identity.ts | 47 ++++++++++++++ src/github/vault.ts | 109 +++++++++++++++++++++++++++++++++ src/github/write.ts | 83 ++++++++++++++----------- src/merge/index.ts | 2 +- src/schema.sql | 9 ++- test/github-app.test.ts | 2 +- test/guarded.ts | 4 +- test/identity.test.ts | 62 +++++++++++++++++++ test/vault.test.ts | 77 +++++++++++++++++++++++ 16 files changed, 471 insertions(+), 67 deletions(-) create mode 100644 src/github/identity.ts create mode 100644 src/github/vault.ts create mode 100644 test/identity.test.ts create mode 100644 test/vault.test.ts diff --git a/src/access.ts b/src/access.ts index 1e523309..50b669a8 100644 --- a/src/access.ts +++ b/src/access.ts @@ -5,6 +5,7 @@ import { connect } from "./db.ts"; import { audit } from "./dash/audit.ts"; import type { Role } from "./dash/types.ts"; import { endAnswerTokens, endTokens } from "./dash/mcp/tokens.ts"; +import { dropUserTokens } from "./dash/server/user-tokens.ts"; export type AccessRow = { login: string; role: Role; added_by: string | null; added_at: string | null; note: string | null }; @@ -83,7 +84,9 @@ export function removeLogin(db: DatabaseSync, by: string, login: string, opts: A const sessions = endSessions(db, login); // Re-adding the login later must not bring its old agent tokens back. const mcpTokens = endTokens(db, login); - audit(db, by, "access-remove", row.login, { role: row.role, sessions, ...(mcpTokens ? { mcpTokens } : {}) }); + // The GitHub App user token goes with the login; its grant is revoked at GitHub later (the vault's sweep). + const userTokens = dropUserTokens(db, row.login); + audit(db, by, "access-remove", row.login, { role: row.role, sessions, ...(mcpTokens ? { mcpTokens } : {}), ...(userTokens ? { userTokens } : {}) }); }); } @@ -98,7 +101,9 @@ export function setRole(db: DatabaseSync, by: string, login: string, role: Role, const sessions = endSessions(db, login); // An answering token must not outlive the operator role: it would work again if the login is promoted again. const answerTokens = row.role === "operator" ? endAnswerTokens(db, login) : 0; - audit(db, by, "access-role", row.login, { from: row.role, to: role, sessions, ...(answerTokens ? { answerTokens } : {}) }); + // A role change ends the sessions, so the login's GitHub App user token goes too and the next sign-in makes a new one. + const userTokens = dropUserTokens(db, row.login); + audit(db, by, "access-role", row.login, { from: row.role, to: role, sessions, ...(answerTokens ? { answerTokens } : {}), ...(userTokens ? { userTokens } : {}) }); return true; }); } diff --git a/src/core/guard.ts b/src/core/guard.ts index 1023b894..9c3a87d9 100644 --- a/src/core/guard.ts +++ b/src/core/guard.ts @@ -18,22 +18,23 @@ import { decideItem } from "./decide-item.ts"; import { gateRepo, gates, type Approval, type By, type Want } from "./gates.ts"; import { loadItemFact } from "./issue-facts.ts"; import type { ActionKind, PrFacts } from "./plan.ts"; +import { identityOfDecision, type Identity } from "../github/identity.ts"; declare const guarded: unique symbol; /** What the guard let through: the action (its kind is part of the type, so a write takes only the grants made for it), the reviewed head it holds at, and the PR. Only `guard` makes one. */ -export type Guarded = { readonly [guarded]: true; readonly scope: "pr"; readonly action: Want; readonly head: string; readonly repo: string; readonly number: number }; +export type Guarded = { readonly [guarded]: true; readonly scope: "pr"; readonly action: Want; readonly head: string; readonly repo: string; readonly number: number; /** Who the write is made as, once its repo leaves the box account (src/github/identity.ts). */ readonly as: Identity }; /** What the guard let through for an issue or PR in its item steps (labels, act, fix issue). Only `guardItem` makes one. */ -export type GuardedItem = { readonly [guarded]: true; readonly scope: "item"; readonly action: ItemWant; readonly repo: string; readonly number: number }; +export type GuardedItem = { readonly [guarded]: true; readonly scope: "item"; readonly action: ItemWant; readonly repo: string; readonly number: number; readonly as: Identity }; /** What the guard let through for a repo-level write (a label set, a fork, an issue, a batch branch): the approval and the global switch held. Only `guardRepo` makes one. */ -export type GuardedRepo = { readonly [guarded]: true; readonly scope: "repo"; readonly need: Approval | null; readonly repo: string }; +export type GuardedRepo = { readonly [guarded]: true; readonly scope: "repo"; readonly need: Approval | null; readonly repo: string; readonly as: Identity }; /** What an item or repo write accepts. A PR grant is left out: no caller writes with one, and a merge or CI grant must not type-check there. */ export type Grant = GuardedItem | GuardedRepo; export type Refused = { refused: string }; /** An item action to guard: the Plan must hold the kind with the bucket, decision and source given. */ export type ItemWant = Want & { decisionId?: string; source?: string }; /** The action to guard: `head` is the head the caller reviewed or worked on. `batch`: a member of a merge batch, which is in its batch state, not ready. */ -export type Ask = Want & { head: string; batch?: boolean; /** Fix-up: the Plan action's source (review, premerge or carry). */ source?: string }; +export type Ask = Want & { head: string; batch?: boolean; /** Fix-up: the Plan action's source (review, premerge or carry). */ source?: string; /** The answered decision this merge or push carries out: the answering operator is the identity. */ decisionId?: string }; export type Ref = { repo: string; number: number }; export type LiveRead = { state: "OPEN" | "MERGED" | "CLOSED"; head: string; draft: boolean; mergeable: string }; @@ -55,7 +56,7 @@ const needsLive = (a: Want): boolean => a.kind === "merge" || (a.kind === "fixup" && a.bucket === "fix") || (a.kind === "conflict" && a.bucket === "merge") || (a.kind === "cifix" && (a.bucket === "work" || a.bucket === "collect" || a.bucket === "ask")) || a.kind === "lint"; -const make = (ref: Ref, a: Want, head: string): Guarded => ({ scope: "pr", action: a, head, repo: ref.repo, number: ref.number }) as unknown as Guarded; +const make = (ref: Ref, a: Want, head: string, as: Identity = "app"): Guarded => ({ scope: "pr", action: a, head, repo: ref.repo, number: ref.number, as }) as unknown as Guarded; async function check(db: DatabaseSync, ref: Ref, a: Ask, by: By, live?: Live): Promise<{ f: PrFacts } | Refused> { const name = `${ref.repo}#${ref.number}`; @@ -92,7 +93,7 @@ async function check(db: DatabaseSync, ref: Ref, a: Ask, by: By, live?: Live): P export async function guard(db: DatabaseSync, ref: Ref, action: Ask, by: By, live?: Live): Promise | Refused> { const r = await check(db, ref, action, by, live); if ("refused" in r) return r; - return make(ref, action, action.head); + return make(ref, action, action.head, identityOfDecision(db, action.decisionId)); } /** @@ -133,7 +134,7 @@ export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by const now = plan.actions.map((x) => x.kind + (typeof x.params?.bucket === "string" ? `:${x.params.bucket}` : "")).join(", ") || "none"; return { refused: `${name}: the plan no longer has ${action.kind}${action.bucket ? `:${action.bucket}` : ""} (state ${plan.state}, actions: ${now})` }; } - return { scope: "item", action, repo: ref.repo, number: ref.number } as unknown as GuardedItem; + return { scope: "item", action, repo: ref.repo, number: ref.number, as: identityOfDecision(db, action.decisionId) } as unknown as GuardedItem; } /** The approvals of a repo and the global switch, read now. */ @@ -146,7 +147,7 @@ export function repoApprovals(db: DatabaseSync, repo: string): Parameters {}); } // Dev auth lets anyone who reaches the port sign in as any login, so // a request that came through a proxy or under a public name is refused. diff --git a/src/dash/server/provider.ts b/src/dash/server/provider.ts index 63294679..e8865534 100644 --- a/src/dash/server/provider.ts +++ b/src/dash/server/provider.ts @@ -32,6 +32,8 @@ export interface Provider { identity(access: string): Promise; /** Revokes a token at the provider; callers ignore failures. */ revoke(access: string): Promise; + /** Revokes the whole authorization behind a token: every token of that user for this app dies with it. Callers ignore failures. */ + revokeGrant(access: string): Promise; // "unauthorized": the access token is expired or revoked. Throws on a // transport failure, so a GitHub outage isn't cached as "none". permission(access: string, repo: string): Promise; @@ -84,8 +86,14 @@ export class GitHubProvider implements Provider { // A rejected code or refresh token answers 200 with an `error` field. return tokensFrom((await r.json()) as Record); } - async revoke(access: string): Promise { - await fetch(`https://api.github.com/applications/${encodeURIComponent(this.#id)}/token`, { + revoke(access: string): Promise { + return this.#deleteApplication("token", access); + } + revokeGrant(access: string): Promise { + return this.#deleteApplication("grant", access); + } + async #deleteApplication(what: "token" | "grant", access: string): Promise { + await fetch(`https://api.github.com/applications/${encodeURIComponent(this.#id)}/${what}`, { method: "DELETE", headers: { authorization: `Basic ${Buffer.from(`${this.#id}:${this.#secret}`).toString("base64")}`, accept: "application/vnd.github+json", @@ -174,6 +182,14 @@ export class FakeProvider implements Provider { this.#access.delete(access); this.revoked.push(access); } + revokedGrants: string[] = []; + async revokeGrant(access: string): Promise { + this.revokedGrants.push(access); + const t = this.#access.get(access); + if (!t) return; + for (const [a, v] of this.#access) if (v.login === t.login) this.#access.delete(a); + for (const [r, l] of this.#refresh) if (l === t.login) this.#refresh.delete(r); + } async refresh(refreshToken: string): Promise { const login = this.#refresh.get(refreshToken); this.#refresh.delete(refreshToken); diff --git a/src/dash/server/sessions.ts b/src/dash/server/sessions.ts index 2edc267f..35cbbb34 100644 --- a/src/dash/server/sessions.ts +++ b/src/dash/server/sessions.ts @@ -1,7 +1,7 @@ import type { DatabaseSync } from "node:sqlite"; import type { Role, User } from "../types.ts"; import { randomToken, sha256hex, type TokenBox } from "./crypto.ts"; -import { updateUserTokens } from "./user-tokens.ts"; +import { shareRefresh } from "./user-tokens.ts"; import { REPO_NAME, WRITE_PERMISSIONS, type Provider, type Tokens } from "./provider.ts"; const DAY = 86_400_000; @@ -114,10 +114,20 @@ async function accessToken(db: DatabaseSync, box: TokenBox, provider: Provider, console.error(`token refresh: ${(e as Error).message}`); return undefined; } - if (!next) return end(); + if (!next) { + // The vault (another process) may have used this single-use refresh token first and stored the new pair here. + for (let i = 0; i < 4; i++) { + const again = db.prepare("SELECT token_enc FROM sessions WHERE id_hash = ?").get(idHash) as { token_enc: string | null } | undefined; + const shared = again ? openTokens(box, again.token_enc, idHash) : null; + if (shared && shared.refresh !== t.refresh) return shared.access; + if (!mirror) break; + await new Promise((r) => setTimeout(r, 300)); + } + return end(); + } db.prepare("UPDATE sessions SET token_enc = ? WHERE id_hash = ?").run(sealTokens(box, next, idHash), idHash); - // The old refresh token is dead now, so user_tokens must hold the new pair too. - if (mirror) updateUserTokens(db, box, row.login, next); + // The old refresh token is dead now, so every other copy of it (user_tokens, sessions of the same sign-in) takes the new pair. + if (mirror) shareRefresh(db, box, row.login, t.refresh, next); return next.access; })().finally(() => refreshing.delete(idHash)); refreshing.set(idHash, p); diff --git a/src/dash/server/user-tokens.ts b/src/dash/server/user-tokens.ts index a0343f3a..e7eeadb9 100644 --- a/src/dash/server/user-tokens.ts +++ b/src/dash/server/user-tokens.ts @@ -1,8 +1,8 @@ // user_tokens: the GitHub App user token of each login, written at every // sign-in while AUTOCRAFT_LOGIN_APP=github-app. It holds the sealed JSON of -// the whole token set, like sessions.token_enc, but is keyed by login so a later -// step can act for a login without a live session. Refresh, revocation and the -// vault around it come later. +// the whole token set, like sessions.token_enc, but is keyed by login so the +// act stage can act for a login without a live session. The vault +// (src/github/vault.ts) refreshes it. import type { DatabaseSync } from "node:sqlite"; import type { TokenBox } from "./crypto.ts"; import type { Tokens } from "./provider.ts"; @@ -26,8 +26,63 @@ export function loadUserTokens(db: DatabaseSync, box: TokenBox, login: string): } } -/** Stores the pair a refresh returned (GitHub invalidates the old refresh token), if the login has a row. */ -export function updateUserTokens(db: DatabaseSync, box: TokenBox, login: string, tokens: Tokens): void { - db.prepare("UPDATE user_tokens SET token_enc = ?, version = version + 1, updated_at = ?, status = 'ok' WHERE login = ?") - .run(box.seal(JSON.stringify(tokens), aad(login)), new Date().toISOString(), login); +type Row = { token_enc: string; version: number; status: string }; + +/** The login's row with its opened tokens, whatever its status (null tokens: unreadable). */ +export function readUserTokens(db: DatabaseSync, box: TokenBox, login: string): { tokens: Tokens | null; version: number; status: string } | null { + const row = db.prepare("SELECT token_enc, version, status FROM user_tokens WHERE login = ?").get(login) as Row | undefined; + if (!row) return null; + const plain = box.open(row.token_enc, aad(login)); + let tokens: Tokens | null = null; + try { + tokens = plain ? (JSON.parse(plain) as Tokens) : null; + } catch { /* unreadable: the caller treats it as no token */ } + return { tokens, version: Number(row.version), status: row.status }; +} + +/** + * Stores a refreshed pair if the row still has `version` (compare-and-swap: a refresh in another process or a new + * sign-in may have written first). Returns false when it lost. + */ +export function swapUserTokens(db: DatabaseSync, box: TokenBox, login: string, version: number, tokens: Tokens): boolean { + return Number(db.prepare("UPDATE user_tokens SET token_enc = ?, version = version + 1, updated_at = ?, status = 'ok' WHERE login = ? AND version = ? AND status = 'ok'") + .run(box.seal(JSON.stringify(tokens), aad(login)), new Date().toISOString(), login, version).changes) > 0; +} + +/** Marks the row as needing a new sign-in, if it still has `version`. Returns false when it lost. */ +export function failUserTokens(db: DatabaseSync, login: string, version: number): boolean { + return Number(db.prepare("UPDATE user_tokens SET status = 'refresh-failed', version = version + 1, updated_at = ? WHERE login = ? AND version = ? AND status = 'ok'") + .run(new Date().toISOString(), login, version).changes) > 0; +} + +/** + * Deletes the login's row (a removed login, a revoked session or a demotion) and queues its grant for revocation at + * GitHub; the dashboard's vault does that later and ignores failures. Returns whether a row existed. + */ +export function dropUserTokens(db: DatabaseSync, login: string): boolean { + const row = db.prepare("DELETE FROM user_tokens WHERE login = ? RETURNING token_enc").get(login) as { token_enc: string } | undefined; + if (!row) return false; + db.prepare("INSERT INTO user_token_revocations (login, token_enc, queued_at) VALUES (?, ?, ?)").run(login, row.token_enc, new Date().toISOString()); + return true; +} + +export const revocationAad = aad; + +/** + * A refresh consumed `oldRefresh` (GitHub refresh tokens are single use), so every stored copy of that token set must + * take the new pair: the login's user_tokens row and each of its sessions that holds the same refresh token. Copies + * with another refresh token come from another sign-in and are left alone. The sessions keep running. + */ +export function shareRefresh(db: DatabaseSync, box: TokenBox, login: string, oldRefresh: string, next: Tokens): void { + const u = readUserTokens(db, box, login); + if (u?.status === "ok" && u.tokens?.refresh === oldRefresh) swapUserTokens(db, box, login, u.version, next); + const sessions = db.prepare("SELECT id_hash, token_enc FROM sessions WHERE login = ? AND token_enc IS NOT NULL").all(login) as { id_hash: string; token_enc: string }[]; + for (const s of sessions) { + const plain = box.open(s.token_enc, s.id_hash); + let t: Tokens | null = null; + try { + t = plain ? (JSON.parse(plain) as Tokens) : null; + } catch { /* unreadable: leave it */ } + if (t?.refresh === oldRefresh) db.prepare("UPDATE sessions SET token_enc = ? WHERE id_hash = ? AND token_enc = ?").run(box.seal(JSON.stringify(next), s.id_hash), s.id_hash, s.token_enc); + } } diff --git a/src/github/identity.ts b/src/github/identity.ts new file mode 100644 index 00000000..99d580d7 --- /dev/null +++ b/src/github/identity.ts @@ -0,0 +1,47 @@ +// Who a GitHub write is made as. A grant carries `as`, decided where the guard makes it: +// - a decision answered by an operator gives `user:` (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. +import type { DatabaseSync } from "node:sqlite"; +import { audit } from "../dash/audit.ts"; +import type { Grant, Guarded } from "../core/guard.ts"; + +export type Identity = "app" | `user:${string}`; +export type RepoIdentity = "legacy" | "app"; +export const REPO_IDENTITIES: readonly RepoIdentity[] = ["legacy", "app"]; + +const key = (repo: string): string => `repo_identity:${repo}`; + +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"; +} + +/** 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); + 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 }); + return true; +} + +/** The identity a write made for `decisionId` has: the login that answered it, or the app (no decision, not answered yet). */ +export function identityOfDecision(db: DatabaseSync, decisionId: string | undefined): Identity { + if (decisionId === undefined) return "app"; + const row = db.prepare("SELECT answered_by FROM decisions WHERE id = ? AND answer IS NOT NULL").get(decisionId) as { answered_by: string | null } | undefined; + return row?.answered_by ? `user:${row.answered_by}` : "app"; +} + +/** 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. */ +export function auditIdentity(db: DatabaseSync, g: Guarded | Grant): "legacy" | Identity { + return repoIdentity(db, g.repo) === "legacy" ? "legacy" : identityFor(g); +} diff --git a/src/github/vault.ts b/src/github/vault.ts new file mode 100644 index 00000000..cc71dd18 --- /dev/null +++ b/src/github/vault.ts @@ -0,0 +1,109 @@ +// The user-token vault: a usable GitHub App access token for a login, for the dashboard and the runner process alike +// (both open the same database and derive the same TokenBox from the secrets file's session_key). +// +// Refresh protocol. GitHub refresh tokens are single use, and the token set lives in several copies: the login's +// user_tokens row and each session from the same sign-in. Any process may refresh: +// 1. read the row and its `version`; a fresh access token is returned as is; +// 2. otherwise call the refresh endpoint with the row's refresh token; +// 3. store the new pair only if `version` is unchanged (compare-and-swap), then copy it into every other stored +// copy of the old refresh token (sessions keep running, see shareRefresh); +// 4. a refresh the endpoint rejects may mean another process used the token first: reread a few times, and only +// when the row stays unchanged mark it `refresh-failed`, also by compare-and-swap. +// There is never a fallback to another identity: a final failure answers "needs sign-in". +import type { DatabaseSync } from "node:sqlite"; +import { envVar } from "../env.ts"; +import { TokenBox } from "../dash/server/crypto.ts"; +import { readSecrets } from "../dash/server/config.ts"; +import { GitHubProvider, type Provider, type Tokens } from "../dash/server/provider.ts"; +import { failUserTokens, readUserTokens, revocationAad, shareRefresh, swapUserTokens } from "../dash/server/user-tokens.ts"; + +export type NeedsSignIn = { ok: false; needsSignIn: true; why: "no-token" | "refresh-failed" | "expired" }; +/** A transient failure (GitHub unreachable): try again later, the token set is untouched. */ +export type Unavailable = { ok: false; needsSignIn: false }; +export type UserTokenResult = { ok: true; access: string } | NeedsSignIn | Unavailable; + +const EXPIRY_MARGIN = 60_000; +const REREADS = 4; + +export class Vault { + #db: DatabaseSync; + #box: TokenBox; + #provider: Provider; + #inflight = new Map>(); + /** Pause between rereads after a rejected refresh; tests set it to 0. */ + waitMs = 300; + + constructor(db: DatabaseSync, box: TokenBox, provider: Provider) { + this.#db = db; + this.#box = box; + this.#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). */ + userToken(login: string, rejected?: string): Promise { + const key = login.toLowerCase(); + let p = this.#inflight.get(key); + if (!p) { + p = this.#obtain(login, rejected).finally(() => this.#inflight.delete(key)); + this.#inflight.set(key, p); + } + return p; + } + + async #obtain(login: string, rejected: string | undefined): Promise { + for (let attempt = 0; attempt < REREADS; attempt++) { + const row = readUserTokens(this.#db, this.#box, login); + if (!row?.tokens) return { ok: false, needsSignIn: true, why: "no-token" }; + if (row.status !== "ok") return { ok: false, needsSignIn: true, why: "refresh-failed" }; + const t = row.tokens; + if (t.access !== rejected && (t.expiresAt === null || t.expiresAt - EXPIRY_MARGIN > Date.now())) return { ok: true, access: t.access }; + if (!t.refresh || (t.refreshExpiresAt !== null && t.refreshExpiresAt <= Date.now())) { + failUserTokens(this.#db, login, row.version); + return { ok: false, needsSignIn: true, why: "expired" }; + } + let next: Tokens | null; + try { + next = await this.#provider.refresh(t.refresh); + } catch (e) { + console.error(`user token refresh: ${(e as Error).message}`); + return { ok: false, needsSignIn: false }; + } + if (next) { + if (swapUserTokens(this.#db, this.#box, login, row.version, next)) { + shareRefresh(this.#db, this.#box, login, t.refresh, next); + return { ok: true, access: next.access }; + } + // Another writer stored a pair first; its pair is the one to use. + continue; + } + // Rejected: either the refresh token is dead, or another process just used it and is about to store the new pair. + if (this.waitMs) await new Promise((r) => setTimeout(r, this.waitMs)); + const again = readUserTokens(this.#db, this.#box, login); + if (again && again.version !== row.version) continue; + if (attempt < REREADS - 1 && this.waitMs) continue; + if (failUserTokens(this.#db, login, row.version)) return { ok: false, needsSignIn: true, why: "refresh-failed" }; + } + return { ok: false, needsSignIn: true, why: "refresh-failed" }; + } + + /** Revokes the grants of removed rows (user_tokens deleted with a removed login, revoked session or demotion). Failures are ignored. */ + async sweepRevocations(): Promise { + const rows = this.#db.prepare("SELECT id, login, token_enc FROM user_token_revocations ORDER BY id").all() as { id: number; login: string; token_enc: string }[]; + for (const r of rows) { + this.#db.prepare("DELETE FROM user_token_revocations WHERE id = ?").run(r.id); + try { + const plain = this.#box.open(r.token_enc, revocationAad(r.login)); + const t = plain ? (JSON.parse(plain) as Tokens) : null; + if (t) await this.#provider.revokeGrant(t.access); + } catch { /* best effort */ } + } + return rows.length; + } +} + +/** 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. */ +export function openVault(db: DatabaseSync, env: NodeJS.ProcessEnv = process.env): Vault | null { + const secrets = readSecrets(envVar("SECRETS_FILE", env)); + if (!secrets.app) return null; + return new Vault(db, new TokenBox(secrets.sessionKey), new GitHubProvider(secrets.app.clientId, secrets.app.clientSecret)); +} diff --git a/src/github/write.ts b/src/github/write.ts index d27a990d..26bbe2f7 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -8,6 +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 } 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"; @@ -39,6 +40,12 @@ function covers(g: Guarded | Grant, repo: string, number?: number): void { if (g.repo !== repo || (number !== undefined && "number" in g && g.number !== number)) throw new Error(`the guard covers ${g.repo}${"number" in g ? `#${g.number}` : ""}, not ${repo}${number === undefined ? "" : `#${number}`}`); } +/** + * Who a write is made as, for the audit row's `identity`: `legacy` while the grant's repo is on the box account, else + * the grant's identity (src/github/identity.ts). Every write takes it from its grant, so none goes unmapped. + */ +const idOf = (w: Writer, g: Guarded | Grant): string => auditIdentity(w.db, g); + /** Adds the row before the write, so a crash during the call leaves a "started" row: an unknown outcome. */ function begin(w: Writer, action: string, target: string, details: Details): number { const r = w.db.prepare("INSERT INTO audit (at, login, action, target, details) VALUES (?, ?, ?, ?, ?)") @@ -52,7 +59,8 @@ function finish(w: Writer, id: number, details: Details, error?: string): void { } /** Records the row first, runs the write, then marks the row done with `view`'s extra details or failed with the error. */ -async function recorded(w: Writer, action: string, target: string, details: Details, f: () => Promise, view?: (r: T) => Details, failure?: (r: T) => string | null): Promise { +async function recorded(w: Writer, identity: string, action: string, target: string, details0: Details, f: () => Promise, view?: (r: T) => Details, failure?: (r: T) => string | null): Promise { + const details = { ...details0, identity }; const id = begin(w, action, target, details); let r: T; try { @@ -110,7 +118,7 @@ export type ItemRef = { repo: string; number: number; id: string }; export async function commentOn(w: Writer, g: Grant, q: Querier, action: string, item: ItemRef, note: Note, text: string, details: Details = {}): Promise { covers(g, item.repo, item.number); const body = withNote(note, text); - const r = await recorded(w, action, refOf(item.repo, item.number), { ...details, text: body }, + const r = await recorded(w, idOf(w, g), action, refOf(item.repo, item.number), { ...details, text: body }, () => q.query(ADD_COMMENT, { id: item.id, body }) as Promise<{ addComment?: { commentEdge?: { node?: { url?: string } } } }>, (x) => ({ url: x.addComment?.commentEdge?.node?.url ?? undefined })); return r.addComment?.commentEdge?.node?.url ?? ""; @@ -119,35 +127,35 @@ export async function commentOn(w: Writer, g: Grant, q: Querier, action: string, export async function closeItem(w: Writer, g: Grant, q: Querier, item: ItemRef & { pr: boolean }, details: Details = {}, reason?: "COMPLETED" | "NOT_PLANNED"): Promise { covers(g, item.repo, item.number); // GitHub has a state reason for issues only. - await recorded(w, "act-close", refOf(item.repo, item.number), reason && !item.pr ? { ...details, reason } : details, + await recorded(w, idOf(w, g), "act-close", refOf(item.repo, item.number), reason && !item.pr ? { ...details, reason } : details, () => (item.pr ? q.query(CLOSE_PR, { id: item.id }) : reason ? q.query(CLOSE_ISSUE_AS, { id: item.id, reason }) : q.query(CLOSE_ISSUE, { id: item.id }))); } export async function assignTo(w: Writer, g: Grant, q: Querier, item: ItemRef, user: { id: string; login: string }, details: Details = {}): Promise { covers(g, item.repo, item.number); - await recorded(w, "assign", refOf(item.repo, item.number), { ...details, assignee: user.login }, () => q.query(ASSIGN, { id: item.id, user: user.id })); + await recorded(w, idOf(w, g), "assign", refOf(item.repo, item.number), { ...details, assignee: user.login }, () => q.query(ASSIGN, { id: item.id, user: user.id })); } export async function unassignFrom(w: Writer, g: Grant, q: Querier, item: ItemRef, user: { id: string; login: string }, details: Details = {}): Promise { covers(g, item.repo, item.number); - await recorded(w, "unassign", refOf(item.repo, item.number), { ...details, assignee: user.login }, () => q.query(UNASSIGN, { id: item.id, user: user.id })); + await recorded(w, idOf(w, g), "unassign", refOf(item.repo, item.number), { ...details, assignee: user.login }, () => q.query(UNASSIGN, { id: item.id, user: user.id })); } export async function reopenItem(w: Writer, g: Grant, q: Querier, item: ItemRef & { pr: boolean }, details: Details = {}): Promise { covers(g, item.repo, item.number); - await recorded(w, "act-reopen", refOf(item.repo, item.number), details, () => q.query(item.pr ? REOPEN_PR : REOPEN_ISSUE, { id: item.id })); + await recorded(w, idOf(w, g), "act-reopen", refOf(item.repo, item.number), details, () => q.query(item.pr ? REOPEN_PR : REOPEN_ISSUE, { id: item.id })); } export async function removeLabel(w: Writer, g: Grant, q: Querier, item: ItemRef, label: { id: string; name: string }, details: Details = {}): Promise { covers(g, item.repo, item.number); - await recorded(w, "act-unlabel", refOf(item.repo, item.number), { ...details, label: label.name }, () => q.query(REMOVE_LABEL, { id: item.id, label: label.id })); + await recorded(w, idOf(w, g), "act-unlabel", refOf(item.repo, item.number), { ...details, label: label.name }, () => q.query(REMOVE_LABEL, { id: item.id, label: label.id })); } /** Moves an issue to another repository of the organisation (`to.id` is its node id). The grant `gTo` must cover the target repo; returns the issue's new URL. */ export async function transferIssue(w: Writer, g: Grant, gTo: Grant, q: Querier, item: ItemRef, to: { repo: string; id: string }, details: Details = {}): Promise { covers(g, item.repo, item.number); covers(gTo, to.repo); - const r = await recorded(w, "act-transfer", refOf(item.repo, item.number), { ...details, to: to.repo }, + const r = await recorded(w, idOf(w, g), "act-transfer", refOf(item.repo, item.number), { ...details, to: to.repo }, () => q.query(TRANSFER_ISSUE, { id: item.id, repo: to.id }) as Promise<{ transferIssue?: { issue?: { url?: string } } }>, (x) => ({ url: x.transferIssue?.issue?.url ?? undefined })); return r.transferIssue?.issue?.url ?? ""; @@ -156,14 +164,14 @@ export async function transferIssue(w: Writer, g: Grant, gTo: Grant, q: Querier, /** Requests reviews from users (added to the reviewers already requested). */ export async function requestReviewers(w: Writer, g: Grant, q: Querier, item: ItemRef, users: { id: string; login: string }[], details: Details = {}): Promise { covers(g, item.repo, item.number); - await recorded(w, "act-request-reviewers", refOf(item.repo, item.number), { ...details, reviewers: users.map((u) => u.login) }, + await recorded(w, idOf(w, g), "act-request-reviewers", refOf(item.repo, item.number), { ...details, reviewers: users.map((u) => u.login) }, () => q.query(REQUEST_REVIEWS, { id: item.id, users: users.map((u) => u.id) })); } /** Posts a review as a plain comment review on the commit; returns the review id (null when GitHub returned none). */ export async function postReview(w: Writer, q: Querier, g: Guarded<"post-review">, nodeId: string, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); - const r = await recorded(w, "review-post", refOf(g.repo, g.number), { ...details, head: g.head }, + const r = await recorded(w, idOf(w, g), "review-post", refOf(g.repo, g.number), { ...details, head: g.head }, () => q.query(ADD_REVIEW, { pr: nodeId, oid: g.head, body }) as Promise<{ addPullRequestReview?: { pullRequestReview?: { id?: string } | null } | null }>, (x) => ({ review: x.addPullRequestReview?.pullRequestReview?.id ?? undefined }), (x) => (x.addPullRequestReview?.pullRequestReview?.id ? null : "GitHub returned no review")); @@ -172,12 +180,12 @@ export async function postReview(w: Writer, q: Querier, g: Guarded<"post-review" export async function editReview(w: Writer, q: Querier, g: Guarded<"post-review">, reviewId: string, note: Note, text: string, details: Details = {}): Promise { const body = withNote(note, text); - await recorded(w, "review-edit", refOf(g.repo, g.number), { ...details, head: g.head, review: reviewId }, () => q.query(EDIT_REVIEW, { id: reviewId, body })); + await recorded(w, idOf(w, g), "review-edit", refOf(g.repo, g.number), { ...details, head: g.head, review: reviewId }, () => q.query(EDIT_REVIEW, { id: reviewId, body })); } export async function createLabel(w: Writer, g: GuardedRepo, q: Querier, repo: string, repoId: string, label: { name: string; color: string; description: string }, retry: Retry = direct, details: Details = {}): Promise { covers(g, repo); - await recorded(w, "label-create", repo, { ...details, name: label.name }, () => retry(() => q.query(CREATE_LABEL, { input: { repositoryId: repoId, ...label } }))); + await recorded(w, idOf(w, g), "label-create", repo, { ...details, name: label.name }, () => retry(() => q.query(CREATE_LABEL, { input: { repositoryId: repoId, ...label } }))); } export type LabelWrite = { number: number; id: string; labelIds: string[]; names: string[]; /** The guard that let this item's labels through (an item grant, or the repo grant of a conversation card). */ g: GuardedItem | GuardedRepo }; @@ -187,7 +195,7 @@ export async function addLabels(w: Writer, q: Querier, repo: string, items: Labe const vars: Record = {}; for (const it of items) covers(it.g, repo, it.number); items.forEach((it, k) => { vars[`i${k}`] = it.id; vars[`l${k}`] = it.labelIds; }); - const det = (it: LabelWrite): Details => ({ ...details, labels: it.names }); + const det = (it: LabelWrite): Details => ({ ...details, labels: it.names, identity: idOf(w, it.g) }); const ids = items.map((it) => begin(w, "labels-apply", refOf(repo, it.number), det(it))); let d: Record | null; try { @@ -211,8 +219,8 @@ export async function addLabels(w: Writer, q: Querier, repo: string, items: Labe const GH_URL = /https:\/\/github\.com\/\S+/; -async function viaGh(w: Writer, exec: Exec, action: string, target: string, details: Details, args: string[], input?: string): Promise { - return recorded(w, action, target, details, () => exec("gh", args, input === undefined ? undefined : { input }), +async function viaGh(w: Writer, identity: string, exec: Exec, action: string, target: string, details: Details, args: string[], input?: string): Promise { + return recorded(w, identity, action, target, details, () => exec("gh", args, input === undefined ? undefined : { input }), (r) => ({ url: r.stdout.match(GH_URL)?.[0] }), (r) => (r.code === 0 ? null : oneLine(r.stderr || r.stdout) || `exit code ${r.code}`)); } @@ -226,7 +234,7 @@ export function ghAskComment(w: Writer, exec: Exec, action: string, g: Guarded { covers(g, o.repo, o.number); const body = withNote(note, text); - return viaGh(w, exec, action, refOf(o.repo, o.number), { ...details, text: body }, + return viaGh(w, idOf(w, g), exec, action, refOf(o.repo, o.number), { ...details, text: body }, [o.pr ? "pr" : "issue", "comment", String(o.number), "--repo", `${slugOf(o.repo)}`, "--body-file", "-"], body); } @@ -234,7 +242,7 @@ export function ghComment(w: Writer, g: CommentGrant, exec: Exec, action: string export function ghEditComment(w: Writer, g: CommentGrant, exec: Exec, action: string, o: { repo: string; number: number; commentId: string }, note: Note, text: string, details: Details = {}): Promise { covers(g, o.repo, o.number); const body = withNote(note, text); - return viaGh(w, exec, action, refOf(o.repo, o.number), { ...details, text: body, comment: o.commentId }, + return viaGh(w, idOf(w, g), exec, action, refOf(o.repo, o.number), { ...details, text: body, comment: o.commentId }, ["api", "-X", "PATCH", `repos/${slugOf(o.repo)}/issues/comments/${o.commentId}`, "-F", "body=@-"], body); } @@ -247,7 +255,7 @@ export function ghDeleteComment(w: Writer, g: CommentGrant, exec: Exec, action: const path = `repos/${slugOf(o.repo)}/issues/comments/${o.commentId}`; const gone = (r: ExecResult): boolean => r.code !== 0 && /404|not found/i.test(`${r.stderr} ${r.stdout}`); const goneResult: ExecResult = { code: 0, stdout: "gone", stderr: "" }; - return recorded(w, action, refOf(o.repo, o.number), { ...details, comment: o.commentId }, + return recorded(w, idOf(w, g), action, refOf(o.repo, o.number), { ...details, comment: o.commentId }, async () => { const author = await exec("gh", ["api", path, "--jq", ".user.login"]); if (gone(author)) return goneResult; @@ -263,21 +271,21 @@ export function ghDeleteComment(w: Writer, g: CommentGrant, exec: Exec, action: export function ghOpenPr(w: Writer, g: Grant, exec: Exec, action: string, o: { repo: string; target: string; base: string; head: string; title: string; body: string }, note: Note, details: Details = {}): Promise { covers(g, o.repo); const body = withNote(note, o.body); - return viaGh(w, exec, action, o.target, { ...details, text: body }, + return viaGh(w, idOf(w, g), exec, action, o.target, { ...details, text: body }, ["pr", "create", "--repo", `${slugOf(o.repo)}`, "--base", o.base, "--head", o.head, "--title", o.title, "--body-file", "-"], body); } export function ghClosePr(w: Writer, g: Grant, exec: Exec, o: { repo: string; number: number }, note: Note, text: string, details: Details = {}): Promise { covers(g, o.repo, o.number); const comment = withNote(note, text); - return viaGh(w, exec, "batch-pr-close", refOf(o.repo, o.number), { ...details, text: comment }, + return viaGh(w, idOf(w, g), exec, "batch-pr-close", refOf(o.repo, o.number), { ...details, text: comment }, ["pr", "close", String(o.number), "--repo", `${slugOf(o.repo)}`, "--comment", comment]); } /** Creates the pipeline account's fork of `repo` when it has none. */ export function ghFork(w: Writer, g: GuardedRepo, exec: Exec, repo: string, details: Details = {}): Promise { covers(g, repo); - return viaGh(w, exec, "fork-create", repo, details, ["repo", "fork", `${slugOf(repo)}`, "--clone=false"]); + return viaGh(w, idOf(w, g), exec, "fork-create", repo, details, ["repo", "fork", `${slugOf(repo)}`, "--clone=false"]); } /** `clear`: GitHub refused the request, so no issue can exist. Otherwise the outcome is unknown (a timeout, a lost response, a success without a URL). */ @@ -298,7 +306,7 @@ export async function createIssue(w: Writer, g: Grant, exec: Exec, o: { repo: st const body = withNote(note, o.body); let r: ExecResult; try { - r = await viaGh(w, exec, o.action ?? "postmerge-file", o.target, { ...details, title: o.title, text: body }, + r = await viaGh(w, idOf(w, g), exec, o.action ?? "postmerge-file", o.target, { ...details, title: o.title, text: body }, ["issue", "create", "--repo", `${slugOf(o.repo)}`, "--title", o.title, "--body-file", "-"], body); } catch (e) { // exec rejects only when the command could not be started. @@ -312,20 +320,20 @@ export async function createIssue(w: Writer, g: Grant, exec: Exec, o: { repo: st /** Approves one Actions run that waits for a maintainer's approval (a run from an outside contributor's PR). */ export function ghApproveRun(w: Writer, exec: Exec, g: Guarded<"approve-ci">, runId: number, details: Details = {}): Promise { - return viaGh(w, exec, "ci-run-approve", refOf(g.repo, g.number), { ...details, run: runId }, + return viaGh(w, idOf(w, g), exec, "ci-run-approve", refOf(g.repo, g.number), { ...details, run: runId }, ["api", "-X", "POST", `repos/${slugOf(g.repo)}/actions/runs/${runId}/approve`]); } /** Reruns the failed jobs of one Actions run of a PR's head commit. */ export function ghRerunFailed(w: Writer, exec: Exec, g: Guarded<"cifix">, runId: number, details: Details = {}): Promise { - return viaGh(w, exec, "ci-rerun", refOf(g.repo, g.number), { ...details, run: runId }, + return viaGh(w, idOf(w, g), exec, "ci-rerun", refOf(g.repo, g.number), { ...details, run: runId }, ["run", "rerun", String(runId), "--failed", "--repo", `${slugOf(g.repo)}`]); } /** Reruns the failed jobs of one Actions run on a default-branch head. It belongs to no item: the audit target names the repo and the commit. */ export function ghRerunMainFailed(w: Writer, g: GuardedRepo, exec: Exec, o: { repo: string; head: string; runId: number }, details: Details = {}): Promise { covers(g, o.repo); - return viaGh(w, exec, "ci-rerun", `${o.repo}:${o.head.slice(0, 8)}`, { ...details, run: o.runId }, + return viaGh(w, idOf(w, g), exec, "ci-rerun", `${o.repo}:${o.head.slice(0, 8)}`, { ...details, run: o.runId }, ["run", "rerun", String(o.runId), "--failed", "--repo", `${slugOf(o.repo)}`]); } @@ -335,18 +343,18 @@ export function ghRerunMainFailed(w: Writer, g: GuardedRepo, exec: Exec, o: { re export function pushBranch(w: Writer, git: Pick, action: string, g: Guarded, o: { remote: string; branch: string; sha: string }, details: Details = {}): Promise { const b = g.action.bucket; if ((g.action.kind === "fixup" && b === "ask") || (g.action.kind === "cifix" && b === "rerun")) throw new Error(`a ${g.action.kind}:${b} grant does not allow a push`); - return pushed(w, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details, { repo: g.repo, number: g.number }); + return pushed(w, g, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details, { repo: g.repo, number: g.number }); } /** Pushes `sha` to `branch` of the pipeline's own fork, replacing the branch. */ export function pushOwnBranch(w: Writer, g: Grant, git: Pick, action: string, o: { repo: string; number?: number; remote: string; branch: string; sha: string }, details: Details = {}): Promise { covers(g, o.repo); // A new branch has no PR yet: its outcome is matched to the PR by commit once the PR's checks arrive. - return pushed(w, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details, { repo: o.repo, number: null }); + return pushed(w, g, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details, { repo: o.repo, number: null }); } -async function pushed(w: Writer, git: Pick, action: string, target: string, o: { remote: string; branch: string; sha: string }, lease: string, details: Details, pr: { repo: string; number: number | null }): Promise { - const r = await recorded(w, action, target, { ...details, branch: o.branch, remote: o.remote, commit: o.sha }, +async function pushed(w: Writer, g: Guarded | Grant, git: Pick, action: string, target: string, o: { remote: string; branch: string; sha: string }, lease: string, details: Details, pr: { repo: string; number: number | null }): Promise { + const r = await recorded(w, idOf(w, g), action, target, { ...details, branch: o.branch, remote: o.remote, commit: o.sha }, () => git.git(["push", "--quiet", lease, `https://github.com/${o.remote}.git`, `${o.sha}:refs/heads/${o.branch}`]), undefined, (r) => (r.code === 0 ? null : oneLine(r.stderr) || `exit code ${r.code}`)); @@ -398,7 +406,7 @@ export async function ghAdvisoryCreate(w: Writer, g: Grant, exec: Exec, o: { rep covers(g, o.repo); const body = json({ summary: o.summary, description: o.description, severity: o.severity, vulnerabilities: [{ package: { ecosystem: "other", name: o.repo }, vulnerable_version_range: null, patched_versions: null }] }); let ghsa: string | null = null; - const result = await recorded(w, "security-advisory", o.key, { repo: o.repo }, + const result = await recorded(w, idOf(w, g), "security-advisory", o.key, { repo: o.repo }, () => exec("gh", ["api", "-X", "POST", `repos/${slugOf(o.repo)}/security-advisories`, "--input", "-", "--jq", ".ghsa_id"], { input: body }), (r) => { ghsa = r.stdout.trim() || null; return { ghsa: ghsa ?? undefined }; }, (r) => (r.code === 0 && r.stdout.trim() ? null : oneLine(r.stderr || r.stdout) || `exit code ${r.code}`)); @@ -409,7 +417,7 @@ export async function ghAdvisoryCreate(w: Writer, g: Grant, exec: Exec, o: { rep export async function ghAdvisoryFork(w: Writer, g: Grant, exec: Exec, o: { repo: string; key: string; ghsa: string }): Promise<{ fork: string | null; result: ExecResult }> { covers(g, o.repo); let fork: string | null = null; - const result = await recorded(w, "security-advisory-fork", o.key, { repo: o.repo, ghsa: o.ghsa }, + const result = await recorded(w, idOf(w, g), "security-advisory-fork", o.key, { repo: o.repo, ghsa: o.ghsa }, () => exec("gh", ["api", "-X", "POST", `repos/${slugOf(o.repo)}/security-advisories/${o.ghsa}/forks`, "--jq", ".full_name"]), (r) => { fork = r.stdout.trim() || null; return { fork: fork ?? undefined }; }, (r) => (r.code === 0 && r.stdout.trim() ? null : oneLine(r.stderr || r.stdout) || `exit code ${r.code}`)); @@ -424,21 +432,21 @@ export function ghAdvisoryPush(w: Writer, g: Grant, git: Pick, o: { /** Opens the fix pull request inside the private fork. */ export function ghAdvisoryPr(w: Writer, g: Grant, exec: Exec, o: { repo: string; key: string; fork: string; base: string; head: string; title: string; body: string }): Promise { covers(g, o.repo); - return viaGh(w, exec, "security-advisory-pr", o.key, { repo: o.repo, fork: o.fork }, + return viaGh(w, idOf(w, g), exec, "security-advisory-pr", o.key, { repo: o.repo, fork: o.fork }, ["pr", "create", "--repo", o.fork, "--base", o.base, "--head", o.head, "--title", o.title, "--body-file", "-"], o.body); } /** Publishes the draft advisory; a published advisory deletes its private fork. */ export function ghAdvisoryPublish(w: Writer, g: Grant, exec: Exec, o: { repo: string; key: string; ghsa: string }): Promise { covers(g, o.repo); - return viaGh(w, exec, "security-publish", o.key, { repo: o.repo, ghsa: o.ghsa }, + return viaGh(w, idOf(w, g), exec, "security-publish", o.key, { repo: o.repo, ghsa: o.ghsa }, ["api", "-X", "PATCH", `repos/${slugOf(o.repo)}/security-advisories/${o.ghsa}`, "--input", "-"], json({ state: "published" })); } /** Requests a CVE for the advisory (public repositories only). */ export function ghAdvisoryCve(w: Writer, g: Grant, exec: Exec, o: { repo: string; key: string; ghsa: string }): Promise { covers(g, o.repo); - return viaGh(w, exec, "security-cve", o.key, { repo: o.repo, ghsa: o.ghsa }, ["api", "-X", "POST", `repos/${slugOf(o.repo)}/security-advisories/${o.ghsa}/cve`]); + return viaGh(w, idOf(w, g), exec, "security-cve", o.key, { repo: o.repo, ghsa: o.ghsa }, ["api", "-X", "POST", `repos/${slugOf(o.repo)}/security-advisories/${o.ghsa}/cve`]); } // ---- merges --------------------------------------------------------------------- @@ -457,7 +465,7 @@ export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string const args = [`${slugOf(g.repo)}`, String(g.number), `--${o.method}`, ...(o.extra ?? []), "--head", g.head]; const repo = g.repo; const method: string = o.method; - const base = { ...details, method }; + const base = { ...details, method, identity: idOf(w, g) }; const target = refOf(repo, g.number); const id = begin(w, "merge", target, base); let r: CommandResult; @@ -496,7 +504,8 @@ export async function ghMergePr(gh: (args: string[]) => Promise, repo: s export function cliMergeRecorder(repoSlug: string, pr: string, method: string, head: string): () => (error?: string) => void { return () => { const w: Writer = { db: connect(), login: "cli" }; - const details = { method: method.slice(2), head }; + // The command line runs as the box account whatever the repo's setting. + const details = { method: method.slice(2), head, identity: "legacy" }; const id = begin(w, "merge", `${repoName(repoSlug)}#${Number(pr)}`, details); return (error) => { try { @@ -516,6 +525,6 @@ export function cliMergeRecorder(repoSlug: string, pr: string, method: string, h * call and nowhere else: the audit row names the org, user and role. */ export function grantOrgRole(w: Writer, o: { org: string; user: string; role: { id: number; name: string }; token: string; apiBase?: string }): Promise { - return recorded(w, "github-app-manager", o.org, { user: o.user, role: o.role.name, roleId: o.role.id }, + return recorded(w, `user:${w.login}`, "github-app-manager", o.org, { user: o.user, role: o.role.name, roleId: o.role.id }, () => call(o.apiBase ?? GITHUB_API, `/orgs/${encodeURIComponent(o.org)}/organization-roles/users/${encodeURIComponent(o.user)}/${o.role.id}`, o.token, "PUT").then(() => undefined)); } diff --git a/src/merge/index.ts b/src/merge/index.ts index 9600e187..c8db1982 100644 --- a/src/merge/index.ts +++ b/src/merge/index.ts @@ -354,7 +354,7 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line const method = methodOf(info); // A hold may have been set during the calls above. if (mergeHeld(db, repo, e.number)) { log(` ${refOf(e)}: merge held meanwhile; skipped`); summary.attempted.pop(); continue; } - const g = await guard(db, { repo, number: e.number }, { kind: "merge", head: e.head }, params.by ?? CLI_BY, liveOf(db, d.querier)); + const g = await guard(db, { repo, number: e.number }, { kind: "merge", head: e.head, ...(e.path === "operator" ? { decisionId: e.decisionId ?? undefined } : {}) }, params.by ?? CLI_BY, liveOf(db, d.querier)); if ("refused" in g) { // Not recorded as a merge attempt: the PR is tried again once the reason is gone. summary.refused.push({ ref: refOf(e), reason: g.refused }); diff --git a/src/schema.sql b/src/schema.sql index cb106ba2..523b9a2d 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -235,7 +235,14 @@ CREATE TABLE IF NOT EXISTS user_tokens ( token_enc TEXT NOT NULL, -- sealed JSON of the whole token set (access, refresh, expiry times), like sessions.token_enc version INTEGER NOT NULL DEFAULT 1, -- compare-and-swap counter for refreshes updated_at TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'ok' -- ok; later steps add refresh-failed and revoked + status TEXT NOT NULL DEFAULT 'ok' -- ok; refresh-failed: the refresh token is dead or expired, the login must sign in again +); +-- Sealed token sets of removed user_tokens rows, waiting for the dashboard to revoke their grant at GitHub (best effort, then deleted). +CREATE TABLE IF NOT EXISTS user_token_revocations ( + id INTEGER PRIMARY KEY, + login TEXT NOT NULL, + token_enc TEXT NOT NULL, -- sealed like user_tokens.token_enc + queued_at TEXT NOT NULL ); -- One row per started GitHub App registration: the manifest flow's single-use state nonce. diff --git a/test/github-app.test.ts b/test/github-app.test.ts index 01a45ca3..99626e2a 100644 --- a/test/github-app.test.ts +++ b/test/github-app.test.ts @@ -333,7 +333,7 @@ describe("github app registration", () => { assert.equal((await second.post("/auth/setup/manager", {})).status, 303); assert.deepEqual(rolePuts, ["/orgs/glasswing/organization-roles/users/boss/8140"]); const row = db.prepare("SELECT details FROM audit WHERE action = 'github-app-manager'").get() as { details: string }; - assert.deepEqual(JSON.parse(row.details), { user: "boss", role: "GitHub App Manager", roleId: 8140, state: "done" }); + assert.deepEqual(JSON.parse(row.details), { user: "boss", role: "GitHub App Manager", roleId: 8140, identity: "user:alice", state: "done" }); const id = (db.prepare("SELECT id FROM github_setup_links WHERE hash = ?").get(sha256hex(path2.split("/").pop()!)) as { id: string }).id; assert.equal((await boss.json("/api/admin/github-app/links/revoke", { id })).status, 200); assert.equal((await get(new Client(s.url), path2)).r.status, 410); diff --git a/test/guarded.ts b/test/guarded.ts index e497ecb4..9d67403c 100644 --- a/test/guarded.ts +++ b/test/guarded.ts @@ -3,7 +3,7 @@ import type { Guarded, GuardedRepo } from "../src/core/guard.ts"; import type { Want } from "../src/core/gates.ts"; import type { ActionKind } from "../src/core/plan.ts"; -export const guarded = (repo: string, number: number, head: string, action: Want = { kind: "merge" } as Want): Guarded => ({ repo, number, head, action }) as unknown as Guarded; +export const guarded = (repo: string, number: number, head: string, action: Want = { kind: "merge" } as Want): Guarded => ({ repo, number, head, action, as: "app" }) as unknown as Guarded; /** A repo-level grant without running the guard. */ -export const G = (repo: string): GuardedRepo => ({ scope: "repo", need: null, repo }) as unknown as GuardedRepo; +export const G = (repo: string): GuardedRepo => ({ scope: "repo", need: null, repo, as: "app" }) as unknown as GuardedRepo; diff --git a/test/identity.test.ts b/test/identity.test.ts new file mode 100644 index 00000000..4a1b2760 --- /dev/null +++ b/test/identity.test.ts @@ -0,0 +1,62 @@ +// The identity map: which identity a grant carries, what the audit row records per repo setting, and that no write +// function in src/github/write.ts records a row without one. +import assert from "node:assert/strict"; +import { mkdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import { connect } from "../src/db.ts"; +import { identityFor, identityOfDecision, repoIdentity, setRepoIdentity } 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"; +import { SCRATCH } from "./scratch.ts"; + +const grant = (as: string): GuardedItem => ({ scope: "item", action: { kind: "act" }, repo: "app", number: 7, as }) as unknown as GuardedItem; +const q: Querier = { query: async () => ({}) } as unknown as Querier; + +test("a decision answered by someone maps to that login, anything else to the app", () => { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `identity-${process.pid}.db`)); + const ins = db.prepare("INSERT INTO decisions (id, kind, question, options, asked_at, answer, answered_by) VALUES (?, 'close', 'q', '[]', 't', ?, ?)"); + ins.run("d1", "yes", "example-user"); + ins.run("d2", null, "example-user"); + assert.equal(identityOfDecision(db, "d1"), "user:example-user"); + assert.equal(identityOfDecision(db, "d2"), "app"); + assert.equal(identityOfDecision(db, "missing"), "app"); + assert.equal(identityOfDecision(db, undefined), "app"); + 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 () => { + 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" }; + 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"); + await closeItem(w, grant("user:example-user"), q, item); + assert.equal(last().identity, "legacy"); + assert.equal(setRepoIdentity(db, "op", "app", "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"); +}); + +test("every audited write in write.ts takes its identity from a grant", () => { + const src = readFileSync(new URL("../src/github/write.ts", import.meta.url), "utf8"); + const calls = src.split("\n").filter((l) => /\b(recorded|viaGh)\(w, /.test(l) && !/function /.test(l)); + assert.ok(calls.length >= 25, `found ${calls.length} audited calls`); + for (const l of calls) assert.match(l, /\b(recorded|viaGh)\(w, (idOf\(w, g\)|identity|`user:\$\{w\.login\}`), /, l.trim().slice(0, 80)); + // The rows started with begin() directly (labels, merge, command-line merge) carry the identity in their details. + const begins = src.split("\n").filter((l) => /\bbegin\(w, /.test(l) && !/function /.test(l)); + assert.equal(begins.length, 4); + for (const l of begins) assert.match(l, /begin\(w, (action, target, details|"labels-apply", .*det\(it\)|"merge", target, base|"merge", .*details)\)/); + assert.match(src, /identity: idOf\(w, it\.g\)/); + assert.match(src, /base = \{ \.\.\.details, method, identity: idOf\(w, g\) \}/); + assert.match(src, /identity: "legacy"/); +}); diff --git a/test/vault.test.ts b/test/vault.test.ts new file mode 100644 index 00000000..db63a84b --- /dev/null +++ b/test/vault.test.ts @@ -0,0 +1,77 @@ +// The user-token vault: a refresh race between two processes, a final refresh failure, and removal. +import assert from "node:assert/strict"; +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import { addLogin, removeLogin } from "../src/access.ts"; +import { connect } from "../src/db.ts"; +import { pkceChallenge, TokenBox } from "../src/dash/server/crypto.ts"; +import { FakeProvider, type Tokens } from "../src/dash/server/provider.ts"; +import { createSession, openTokens } from "../src/dash/server/sessions.ts"; +import { saveUserTokens } from "../src/dash/server/user-tokens.ts"; +import { Vault } from "../src/github/vault.ts"; +import { SCRATCH } from "./scratch.ts"; + +const REDIRECT = "http://localhost/cb"; + +function setup(name: string) { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `${name}-${process.pid}.db`)); + const box = new TokenBox("test-session-key-test-session-key-0"); + const provider = new FakeProvider(null); + const signIn = async (login: string, ttlMs: number): Promise => { + provider.tokenTtlMs = ttlMs; + const t = (await provider.exchange(provider.issueCode(login, pkceChallenge("v"), REDIRECT), "v", REDIRECT))!; + provider.tokenTtlMs = 8 * 3_600_000; + saveUserTokens(db, box, login, 1, t); + return t; + }; + return { db, box, provider, signIn }; +} + +test("two vaults refreshing one expired token end with one refresh and the same pair, and the session keeps running", async () => { + const { db, box, provider, signIn } = setup("vault-race"); + const old = await signIn("example-user", -1000); + const sid = createSession(db, box, "example-user", old, undefined); + const a = new Vault(db, box, provider); + const b = new Vault(db, box, provider); + a.waitMs = b.waitMs = 0; + const [ra, rb] = await Promise.all([a.userToken("example-user"), b.userToken("example-user")]); + assert.ok(ra.ok && rb.ok); + assert.equal(provider.refreshes, 1); + assert.equal(ra.access, rb.access); + assert.notEqual(ra.access, old.access); + // The session held the same refresh token, so it took the new pair instead of being left with a dead one. + const s = db.prepare("SELECT id_hash, token_enc FROM sessions").get() as { id_hash: string; token_enc: string }; + assert.equal(openTokens(box, s.token_enc, s.id_hash)?.access, ra.access); + assert.ok(sid); +}); + +test("a refresh GitHub rejects marks the row and answers needs-sign-in, never another identity", async () => { + const { db, box, provider, signIn } = setup("vault-fail"); + await signIn("example-user", -1000); + provider.rejectRefresh = true; + const v = new Vault(db, box, provider); + v.waitMs = 0; + assert.deepEqual(await v.userToken("example-user"), { ok: false, needsSignIn: true, why: "refresh-failed" }); + assert.equal((db.prepare("SELECT status FROM user_tokens").get() as { status: string }).status, "refresh-failed"); + provider.rejectRefresh = false; + assert.equal((await v.userToken("example-user")).ok, false); + assert.equal(provider.refreshes, 0); + assert.deepEqual(await v.userToken("nobody"), { ok: false, needsSignIn: true, why: "no-token" }); + // Signing in again makes the token usable. + await signIn("example-user", 8 * 3_600_000); + assert.equal((await v.userToken("example-user")).ok, true); +}); + +test("removing a login deletes its token row and the sweep revokes the grant at the provider", async () => { + const { db, box, provider, signIn } = setup("vault-remove"); + addLogin(db, "op", "example-user", "viewer", null); + const t = await signIn("example-user", 8 * 3_600_000); + removeLogin(db, "op", "example-user"); + assert.equal(db.prepare("SELECT 1 FROM user_tokens").get(), undefined); + const v = new Vault(db, box, provider); + assert.equal(await v.sweepRevocations(), 1); + assert.deepEqual(provider.revokedGrants, [t.access]); + assert.equal(db.prepare("SELECT 1 FROM user_token_revocations").get(), undefined); +});