From de0547d8836eb976c4f4906bfa2d2fc8329aec2a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:24:55 +0000 Subject: [PATCH] Whitelist tiers, overrides and the pipeline's own tier belong to accounts and heads; removing an operator ends what acts as them - History counts per GitHub account: a PR row with an id counts for that id, an id-less row for the account the login is bound to, and for nobody while the login is unbound. The sync no longer binds a login that has id-less merged or closed PRs; the backfill binds it from the history's own author. A failed binding pass shows as the author-ids health warning. - An allow override stores the account it was given to (looked up when set) and counts only for it; a deny holds for any account under the login, in any letter case. The outside-author limits read the same per-account standing. - The pipeline's own Fix, main CI fix and security fix PRs keep their own tier only while the head is a commit the pipeline pushed to its own branch (own_commits), or reached from one only through its own later pushes; otherwise a person is asked. - Removing or demoting an operator revokes their org setup links, and a link works only while its creator is an operator. Removal drops Discord links and codes in any letter case. - Decision alerts to maintainers need a repo permission read within a day. - A cached author permission is not used for another account under the login, nor once its refresh has failed too often or for too long. - Pushes to new branches and new PRs need the grant of a step that opens the pipeline's own PRs; security fix writes carry their own grant kind. --- docs/dashboard-spec.md | 2 +- docs/operations.md | 1 + docs/pipeline.md | 4 +- src/access.ts | 17 ++++-- src/core/facts.ts | 15 ++++-- src/core/gates.ts | 7 ++- src/core/guard.ts | 6 +-- src/dash/api/admin.ts | 19 +++++-- src/dash/api/index.ts | 2 +- src/dash/server/github-setup.ts | 7 ++- src/db.ts | 14 +++++ src/discord/alerts.ts | 14 ++--- src/fixup/author-permission.ts | 36 ++++++++----- src/github/write.ts | 17 ++++-- src/health-checks.ts | 15 +++++- src/mirror.ts | 7 ++- src/outside.ts | 17 +++--- src/schema.sql | 10 ++++ src/security/land.ts | 8 +-- src/whitelist.ts | 94 +++++++++++++++++++++------------ test/app-lane.test.ts | 2 +- test/identity-sec3.test.ts | 85 +++++++++++++++++++++++++++++ test/merge-trust.test.ts | 4 +- test/world-db.ts | 12 +++-- 24 files changed, 313 insertions(+), 102 deletions(-) create mode 100644 test/identity-sec3.test.ts diff --git a/docs/dashboard-spec.md b/docs/dashboard-spec.md index d7b29556a..219051520 100644 --- a/docs/dashboard-spec.md +++ b/docs/dashboard-spec.md @@ -119,7 +119,7 @@ Title, link, author with tier, size, CI, mergeable state; the stage timeline; ev ### Contributors -Table: login, tier (whitelisted / not / override allow / override deny), merged PRs, closed unmerged, open, merge rate, last merge, repos. Filter by repo and tier; sort by any column. Allow / deny / clear buttons with an optional note. The whitelist rule (`settings.whitelist_min_merged`, `settings.whitelist_min_merge_rate`) shown and editable at the top. Notes on overrides are private. +Table: login, tier (whitelisted / not / override allow / override deny), merged PRs, closed unmerged, open, merge rate, last merge, repos. Filter by repo and tier; sort by any column. Allow / deny / clear buttons with an optional note. The whitelist rule (`settings.whitelist_min_merged`, `settings.whitelist_min_merge_rate`) shown and editable at the top. Notes on overrides are private. A tier belongs to a GitHub account, not to the login string, which can pass to another account: a PR counts for the account id it was opened by, and PRs mirrored without an id count for the account the login's oldest merged or closed PR was by (looked up once; until then they count for nobody). An allow is given to the account that holds the login when it is set; a deny holds for every account under the login, in any letter case. ### Classifiers diff --git a/docs/operations.md b/docs/operations.md index 56e7dd4e5..edaf3fc96 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -464,6 +464,7 @@ The dashboard computes the checks below from the database on each request; nothi | `sync-repos` (`sync-repo:` in the dashboard) | a tracked repo could not be read by the last sync (warn; fail when more than half of the tracked repos have an error, for example after a token lost access). The reason is `sync_repo_errors`: `not-found` (moved, renamed or deleted; the new name is shown when GitHub's REST endpoint redirects), `forbidden`, `transient` or `error` | | `accounts` | every enabled Claude account is paused or signed out (fail) | | `github-rate` | fewer than 500 (warn) or 100 (fail) GitHub points are left until the next reset | +| `author-ids` | the last pass that binds contributors' account ids failed (`author_ids_error`) and logins with merged or closed PRs are still unbound: their earlier PRs count toward no whitelist tier until a pass succeeds (warn) | A repo that fails is skipped for that run and the sync continues with the others; the run exits non-zero only when every repo it tried failed, or after three transient failures in a row or a rate-limit stop (a GitHub outage). A full re-sync keeps its cursor before the first failed repo. A repo is never untracked automatically: untrack it or track it under its new name, and its warning goes with the next successful read (a not-found record also clears when the org listing shows the repo again). diff --git a/docs/pipeline.md b/docs/pipeline.md index 4479bbffa..e90369ef5 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -281,7 +281,7 @@ A PR we want (final review take, or take-fix once its listed fixes are pushed or 3. The clean commit goes to the pipeline account's fork on `autocraft/main-ci--` (`pushBranch`, fork found or created as for Fix issues). A PR "Fix main CI: " is opened against the default branch with `ghOpenPr`: the body names the failing check with its run link, the culprit commit (and its PR when the message names one) and the patched files, and starts with the AI note (Sonnet). The row becomes `pr-opened` with `pr_number` and `pr_url`. Approval and the red head are read again right before the push. 4. `fix-failed` (reason on the row) records any other end: no patch, a refusal, an Opus rejection, a failed push. The Main CI page shows "needs a person" and nothing retries it. -The PR is one of our own Fix PRs: the merge queue counts `main_fixes.pr_number` PRs by the pipeline account as whitelisted like Fix issues PRs, and they still need green CI and the Opus review. Only such a PR (branch prefix `autocraft/main-ci-`, by the pipeline account, in `main_fixes`) is merged singly and not held while main is red; the branch name alone does not count. +The PR is one of our own Fix PRs: the merge queue counts `main_fixes.pr_number` PRs by the pipeline account as whitelisted like Fix issues PRs while the head is a commit the pipeline pushed (or reached from one only through its own fix-ups, conflict merges and CI fixes), and they still need green CI and the Opus review. Only such a PR (branch prefix `autocraft/main-ci-`, by the pipeline account, in `main_fixes`) is merged singly and not held while main is red; the branch name alone does not count. A head the reader finds nothing to act on (no failed check run, or only optional checks failed) gets one `nothing-to-do` row. `GET /api/main-ci` carries each repo's row as `autocraft` ("rerunning failed jobs", "asked an operator", "needs a fix", "checking a fix", "opened fix PR #N", "needs a person", "nothing to do: infra", or null). `autocraft main-fix --repo R --apply` runs the step by hand. @@ -522,7 +522,7 @@ Untrusted code (a PR's build and tests) never runs where the GitHub token or a C - **Scope calls**: is this in scope, closer to the reference app, a plug-in rather than core? - **Reference behaviour** that public sources don't settle. -- **Merges outside the rule** (see Merge queue). Contributors shows who is on the whitelist and why. The pipeline's own account counts as whitelisted for the Fix PRs it opened from issues (S or M bugfix after Verify can merge by the rule); an operator's deny still wins. +- **Merges outside the rule** (see Merge queue). Contributors shows who is on the whitelist and why. The pipeline's own account counts as whitelisted for the Fix PRs it opened from issues (S or M bugfix after Verify can merge by the rule) while the head is the pipeline's own work: a commit someone else pushed to the branch gets a Merge? question. An operator's deny still wins. - **Closing a PR** the review says to close. - **A label** where Jev and Haiku disagree outside the scope labels: the Work queue says "Referee: waiting for Sonnet", then "Referee: waiting for Opus" when Sonnet was unsure, and links to the Items list of disagreements. When Opus is unsure too, the label stands and the item is asked as a scope question. - **Duplicate?** answers: an open one holds the item out of Review, Verify, Fix and the merge queue (Work queue: "Held"). diff --git a/src/access.ts b/src/access.ts index 4b8b742a1..2476fedcc 100644 --- a/src/access.ts +++ b/src/access.ts @@ -45,6 +45,12 @@ function endSessions(db: DatabaseSync, login: string): number { return Number(db.prepare("DELETE FROM sessions WHERE login = ?").run(login).changes); } +/** Org setup links are an operator's: they end when their creator stops being one (the link flow also checks the creator's role). */ +function endSetupLinks(db: DatabaseSync, login: string): number { + return Number(db.prepare("UPDATE github_setup_links SET revoked_at = ? WHERE created_by = ? COLLATE NOCASE AND revoked_at IS NULL AND used_at IS NULL") + .run(new Date().toISOString(), login).changes); +} + function tx(db: DatabaseSync, f: () => T): T { db.exec("BEGIN IMMEDIATE"); try { @@ -89,9 +95,11 @@ export function removeLogin(db: DatabaseSync, by: string, login: string, opts: A // 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); // A linked Discord account acts as the login (presses, alerts); the delete trigger takes the alert opt-ins with the links. - const discordLinks = Number(db.prepare("DELETE FROM discord_links WHERE login = ?").run(login).changes); - db.prepare("DELETE FROM discord_link_codes WHERE login = ?").run(login); - audit(db, by, "access-remove", row.login, { role: row.role, sessions, ...(mcpTokens ? { mcpTokens } : {}), ...(userTokens ? { userTokens } : {}), ...(discordLinks ? { discordLinks } : {}) }); + // Matched in any letter case: the access list is, and the removal may name the login in another case than the link stores. + const discordLinks = Number(db.prepare("DELETE FROM discord_links WHERE login = ? COLLATE NOCASE").run(row.login).changes); + db.prepare("DELETE FROM discord_link_codes WHERE login = ? COLLATE NOCASE").run(row.login); + const setupLinks = endSetupLinks(db, row.login); + audit(db, by, "access-remove", row.login, { role: row.role, sessions, ...(mcpTokens ? { mcpTokens } : {}), ...(userTokens ? { userTokens } : {}), ...(discordLinks ? { discordLinks } : {}), ...(setupLinks ? { setupLinks } : {}) }); }); } @@ -110,7 +118,8 @@ export function setRole(db: DatabaseSync, by: string, login: string, role: Role, const answerTokens = RANK[role] < RANK[row.role] ? endAnswerTokens(db, login) : 0; // 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 } : {}) }); + const setupLinks = role === "operator" ? 0 : endSetupLinks(db, row.login); + audit(db, by, "access-role", row.login, { from: row.role, to: role, sessions, ...(answerTokens ? { answerTokens } : {}), ...(userTokens ? { userTokens } : {}), ...(setupLinks ? { setupLinks } : {}) }); return true; }); } diff --git a/src/core/facts.ts b/src/core/facts.ts index 84b708af9..30728b9cc 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -213,6 +213,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const openQuestion = db.prepare(OPEN_QUESTION_SQL); const answeredAfter = db.prepare(`SELECT 1 FROM decisions WHERE id = ? AND kind = 'merge' AND answer = 'merge' AND answered_at > ? AND ${settledBySql("decisions")}`); const pushChain = pushChainOf(db); + const ownHead = ownHeadOf(db); const unsureAt = db.prepare(UNSURE_AT_SQL); const reviewRows = db.prepare("SELECT author, author_association AS association, review_state AS state, created_at AS at FROM comments WHERE repo = ? AND number = ? AND kind = 'review'"); const batchTip = db.prepare(`SELECT a.runs, a.approved, a.reread, a.failed, a.cross_repo FROM merge_batches b @@ -377,8 +378,9 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] } } base.tier = (r.author ? tiers.get(tierKey({ login: r.author, id: r.author_id })) : undefined) ?? "not"; - // The pipeline's own Fix PRs count as whitelisted; an operator's deny still wins. - if (base.tier === "not" && r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref)) base.tier = "whitelisted"; + // The pipeline's own Fix PRs count as whitelisted at a head the pipeline itself pushed (others may push to the branch); an operator's deny still wins. + const ownHere = !!r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref) && !!head && ownHead(r.repo, r.number, head); + if (base.tier === "not" && ownHere) base.tier = "whitelisted"; const last = merges.get(r.repo, r.number, r.r_head) as { outcome: string; reason: string | null; ci: string | null; mergeable: string | null; at: string; refusals: number } | undefined; // An operator's Retry after a refusal asks for another try now, without waiting for CI or the mergeable state to change. @@ -432,7 +434,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] base.batch = inBatch.get(`${ref}@${r.r_head}`) ?? null; if (r.base_ref && r.state === "OPEN") base.stackedOn = (stackedOnQ.get(r.repo, r.base_ref, `${slugOf(r.repo)}`.toLowerCase(), r.number) as { number: number } | undefined)?.number ?? null; base.baseOffDefault = !!r.base_ref && !!rf.defaultBranch && r.base_ref !== rf.defaultBranch; - base.mainFix = !!r.head_ref?.startsWith(MAIN_FIX_BRANCH_PREFIX) && !!r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref); + base.mainFix = !!r.head_ref?.startsWith(MAIN_FIX_BRANCH_PREFIX) && ownHere; const gate = gates.get(ref); const { why, live } = changesRequestedWhy(gate, r.updated_at, reviewRows.all(r.repo, r.number) as ReviewFact[], r.review_decision); if (gate && gate.failures >= GATE_FAILURES) base.gateFailureNote = failureNote(gate.failures); @@ -463,6 +465,13 @@ export function pushChainOf(db: DatabaseSync): (repo: string, number: number, he }; } +/** Returns a function telling whether a PR's head is the pipeline's own work: a commit it pushed to its own branch, or one reached from such a commit only through its own later pushes. */ +export function ownHeadOf(db: DatabaseSync): (repo: string, number: number, head: string) => boolean { + const chain = pushChainOf(db); + const pushed = db.prepare("SELECT 1 FROM main.own_commits WHERE repo = ? AND sha = ?"); + return (repo, number, head) => chain(repo, number, head).some((h) => !!pushed.get(repo, h)); +} + /** True when any stored Opus review at the head (the current row or an overwritten one in the history) was a take or take-fix with sure = 0. */ export function headWasUnsure(db: DatabaseSync, repo: string, number: number, head: string): boolean { return !!db.prepare(UNSURE_AT_SQL).get(repo, number, head); diff --git a/src/core/gates.ts b/src/core/gates.ts index 1849ba7b4..9cd2a5111 100644 --- a/src/core/gates.ts +++ b/src/core/gates.ts @@ -18,9 +18,12 @@ const WHAT: Record = { merge: "Merges", push: "Pushes", commen export type RepoApprovals = Record & { pipelineOn: boolean }; /** Why a write needing `need` is refused, or null. A write with no approval need (`need` null) is gated by the switch only. */ -export function gateRepo(a: RepoApprovals, need: Approval | null, by: By, repo: string): string | null { +/** What a repo-level write needs: a repo approval, `security` for a security fix's writes (approved per finding, no repo approval), or null for none. */ +export type RepoNeed = Approval | "security" | null; + +export function gateRepo(a: RepoApprovals, need: RepoNeed, by: By, repo: string): string | null { if (by === "pipeline" && !a.pipelineOn) return "The pipeline is off"; - return need === null || a[need] ? null : `${WHAT[need]} in ${repo} are not approved`; + return need === null || need === "security" || a[need] ? null : `${WHAT[need]} in ${repo} are not approved`; } /** The approval an action's GitHub write needs, or null for an action that writes nothing there. */ diff --git a/src/core/guard.ts b/src/core/guard.ts index c6579308c..affe46323 100644 --- a/src/core/guard.ts +++ b/src/core/guard.ts @@ -15,7 +15,7 @@ import { mainFixApprovalOf } from "../mainfix/approval.ts"; import { mergeApprovalOf } from "../merge/approval.ts"; import { ciApprovalOf } from "../merge/ci-approval.ts"; import { decideItem } from "./decide-item.ts"; -import { gateRepo, gates, type Approval, type By, type Want } from "./gates.ts"; +import { gateRepo, gates, type By, type RepoNeed, 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"; @@ -28,7 +28,7 @@ export type Guarded = { readonly [guarded]: t /** 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; 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; readonly as: Identity }; +export type GuardedRepo = { readonly [guarded]: true; readonly scope: "repo"; readonly need: RepoNeed; 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 }; @@ -150,7 +150,7 @@ export function repoApprovals(db: DatabaseSync, repo: string): Parameters { requireOperator(req, "change the whitelist"); const login = req.params.login!; const b = body(req); const status = b.status; if (status !== "allow" && status !== "deny" && status !== null) throw new HttpError(400, "status must be allow, deny or null"); + if (!OVERRIDE_LOGIN.test(login)) throw new HttpError(400, `not a GitHub login: ${login}`); // Without a note field the override keeps the note it has. - const kept = () => (db.prepare("SELECT note FROM whitelist_overrides WHERE login = ?").get(login) as { note: string | null } | undefined)?.note ?? null; + const kept = () => (db.prepare("SELECT note FROM whitelist_overrides WHERE login = ? COLLATE NOCASE").get(login) as { note: string | null } | undefined)?.note ?? null; const note = status === null ? null : b.note === undefined ? kept() : text(b.note, NOTE_MAX, "note"); + // An allow belongs to the account that holds the login now; a deny holds for any account, so it does not wait for GitHub. + let id: number | null = null; + if (status !== null) { + try { + id = await lookup(login); + } catch { + if (status === "allow") throw new HttpError(502, "GitHub could not be reached to look up that login. Try again."); + } + if (id === null && status === "allow") throw new HttpError(400, `${login} is not a GitHub user`); + } try { - setOverride(db, login, status, note, req.user.login); + setOverride(db, login, status, note, req.user.login, id); clearContributorCache(db); } catch (e) { throw new HttpError(400, (e as Error).message); diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index a08a7731e..113ce7e27 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -450,7 +450,7 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { get("/api/contributors", adm.listContributors), get("/api/contributors/rule-preview", adm.previewRule), post("/api/contributors/rule", adm.saveRule), - post("/api/contributors/:login/override", adm.override), + post("/api/contributors/:login/override", (db, req) => adm.override(db, req, opts.githubUserId ?? githubUserId)), get("/api/repos/all", adm.allRepos), post("/api/repos/track", (db, req) => adm.track(db, req, true)), post("/api/repos/untrack", (db, req) => adm.track(db, req, false)), diff --git a/src/dash/server/github-setup.ts b/src/dash/server/github-setup.ts index 5d927531b..7ede5e974 100644 --- a/src/dash/server/github-setup.ts +++ b/src/dash/server/github-setup.ts @@ -49,13 +49,16 @@ export function revokeLink(db: DatabaseSync, operator: string, id: string): bool /** Links that can still be used, newest first. */ export function openLinks(db: DatabaseSync): GithubSetupLink[] { - const rows = db.prepare("SELECT id, org, created_by, created_at, expires_at FROM github_setup_links WHERE revoked_at IS NULL AND used_at IS NULL AND expires_at > ? ORDER BY created_at DESC") + const rows = db.prepare(`SELECT id, org, created_by, created_at, expires_at FROM github_setup_links WHERE revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${BY_OPERATOR} ORDER BY created_at DESC`) .all(new Date().toISOString()) as LinkRow[]; return rows.map((l) => ({ id: l.id, org: l.org, createdBy: l.created_by, createdAt: l.created_at, expiresAt: l.expires_at })); } +/** A link works only while its creator is an operator on the access list. */ +const BY_OPERATOR = "EXISTS (SELECT 1 FROM access a WHERE a.login = github_setup_links.created_by COLLATE NOCASE AND a.role = 'operator')"; + const openLink = (db: DatabaseSync, where: "id" | "hash", value: string): LinkRow | null => - (db.prepare(`SELECT * FROM github_setup_links WHERE ${where} = ? AND revoked_at IS NULL AND used_at IS NULL AND expires_at > ?`).get(value, new Date().toISOString()) as LinkRow | undefined) ?? null; + (db.prepare(`SELECT * FROM github_setup_links WHERE ${where} = ? AND revoked_at IS NULL AND used_at IS NULL AND expires_at > ? AND ${BY_OPERATOR}`).get(value, new Date().toISOString()) as LinkRow | undefined) ?? null; // ---- The visitor's flow ----------------------------------------------------- diff --git a/src/db.ts b/src/db.ts index 74405a2e0..cb29e0af1 100644 --- a/src/db.ts +++ b/src/db.ts @@ -171,6 +171,10 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [ ["items", "author_type", "TEXT"], // GitHub's numeric id of the author's account; a login string can pass to another account, the id cannot. ["items", "author_id", "INTEGER"], + // The GitHub account an allow override was given to: it counts for that account only, not for a later holder of the login. + ["whitelist_overrides", "github_id", "INTEGER"], + // The account a cached author permission was read for: another account under the login is read again. + ["author_permissions", "author_id", "INTEGER"], // The commenter's association with the repository (OWNER, MEMBER, ...). ["comments", "author_association", "TEXT"], // 1 when the body names the pipeline login (@login); set when the comment is written, backfilled by migrateValues. @@ -245,6 +249,16 @@ const MIGRATION_VERSION = 16; // Rows written before their column existed. function backfill(db: DatabaseSync): void { + // Commits the pipeline pushed to its own branches before own_commits existed, from their audit rows (the repo is the target's prefix). + db.exec(`INSERT OR IGNORE INTO main.own_commits (repo, sha, action, at) + SELECT CASE WHEN instr(target, '#') > 0 THEN substr(target, 1, instr(target, '#') - 1) ELSE substr(target, 1, instr(target, ':') - 1) END, + json_extract(details, '$.commit'), action, at FROM main.audit + WHERE action IN ('fixissue-push', 'main-fix-push', 'security-land-push', 'security-advisory-push', 'batch-push') + AND json_valid(details) AND json_extract(details, '$.commit') IS NOT NULL AND json_extract(details, '$.state') = 'done' + AND (instr(target, '#') > 0 OR instr(target, ':') > 0)`); + // Overrides given before their account was stored belong to the account the login's history is bound to; without one an allow counts for nobody. + db.exec(`UPDATE main.whitelist_overrides SET github_id = (SELECT a.id FROM main.author_ids a WHERE a.login = whitelist_overrides.login COLLATE NOCASE AND a.id > 0) + WHERE github_id IS NULL`); // Repos whose work rows outlive their tracking: the list is maintained by a trigger from here on. db.exec(`INSERT OR IGNORE INTO main.ever_tracked_repos (name) SELECT name FROM main.tracked_repos diff --git a/src/discord/alerts.ts b/src/discord/alerts.ts index 15613dee8..4f71441a3 100644 --- a/src/discord/alerts.ts +++ b/src/discord/alerts.ts @@ -57,16 +57,18 @@ const roleOf = (db: DatabaseSync, login: string): Role | null => { return r === "operator" || r === "maintainer" || r === "viewer" ? r : null; }; -/** The same rule as the dashboard's: an operator, or a maintainer while maintainer_writes is on, with write permission where the app acts for them. Read from cached permissions. */ +/** How old a maintainer's cached repo permission may be for alerts: longer than the dashboard's, so a message does not flap between visits. */ +export const RECEIVE_PERMISSION_TTL_MS = 24 * 3600_000; + /** - * Who receives and keeps alerts: an operator, or a maintainer while maintainer_writes is on, the app acts for them on every repo and their last - * known permission on each is write or better. The permission has no age limit here (the cache is refreshed only by dashboard visits, and a - * message must not flap); a press checks it live. + * Who receives and keeps alerts: an operator, or a maintainer while maintainer_writes is on, the app acts for them on every repo and their + * permission on each, read by a dashboard visit within RECEIVE_PERMISSION_TTL_MS, is write or better. A press checks it live. */ -export function mayReceive(db: DatabaseSync, login: string, role: Role, repos: string[]): boolean { +export function mayReceive(db: DatabaseSync, login: string, role: Role, repos: string[], now: number = Date.now()): boolean { if (role === "operator") return true; if (role !== "maintainer" || !maintainerWritesOn(db) || !allAppIdentity(db, repos)) return false; - return repos.every((r) => !!db.prepare("SELECT 1 FROM main.repo_permissions WHERE login = ? AND repo = ? AND permission IN ('write', 'maintain', 'admin')").get(login, r)); + const since = new Date(now - RECEIVE_PERMISSION_TTL_MS).toISOString(); + return repos.every((r) => !!db.prepare("SELECT 1 FROM main.repo_permissions WHERE login = ? AND repo = ? AND permission IN ('write', 'maintain', 'admin') AND checked_at > ?").get(login, r, since)); } export function mayAlert(db: DatabaseSync, login: string): boolean { diff --git a/src/fixup/author-permission.ts b/src/fixup/author-permission.ts index c935637fc..ab1e38299 100644 --- a/src/fixup/author-permission.ts +++ b/src/fixup/author-permission.ts @@ -13,9 +13,9 @@ const KNOWN = new Set(["admin", "maintain", "write", "triage", "read", "none"]); /** "yes" and "no" are known; "unknown" means the permission has not been read yet (a missing entry). */ export type AuthorWrite = "yes" | "no" | "unknown"; -type Row = { author: string | null; author_type: string | null }; +type Row = { author: string | null; author_type: string | null; author_id: number | null }; const authorOf = (db: DatabaseSync, repo: string, number: number): Row | undefined => - db.prepare("SELECT author, author_type FROM items WHERE repo = ? AND number = ?").get(repo, number) as Row | undefined; + db.prepare("SELECT author, author_type, author_id FROM items WHERE repo = ? AND number = ?").get(repo, number) as Row | undefined; /** The pipeline's own account and bots write to the repository by construction. */ function writesByRole(db: DatabaseSync, r: Row): boolean { @@ -24,23 +24,31 @@ function writesByRole(db: DatabaseSync, r: Row): boolean { return !!me && !!r.author && me.toLowerCase() === r.author.toLowerCase(); } -type Cached = { permission: string | null; checked_at: string | null; failures: number; first_failure_at: string | null }; -const cached = (db: DatabaseSync, repo: string, login: string): Cached | undefined => - db.prepare("SELECT permission, checked_at, failures, first_failure_at FROM main.author_permissions WHERE login = ? AND repo = ?").get(login, repo) as Cached | undefined; +type Cached = { permission: string | null; checked_at: string | null; failures: number; first_failure_at: string | null; author_id: number | null }; +/** The cached entry of the PR's author; a permission read for another account under the login counts as never read. */ +const cached = (db: DatabaseSync, repo: string, r: Row & { author: string }): Cached | undefined => { + const c = db.prepare("SELECT permission, checked_at, failures, first_failure_at, author_id FROM main.author_permissions WHERE login = ? AND repo = ?").get(r.author, repo) as Cached | undefined; + return c && c.permission && c.author_id !== null && r.author_id !== null && c.author_id !== r.author_id ? { ...c, permission: null, checked_at: null } : c; +}; +const old = (at: string | null): boolean => !at || Date.now() - Date.parse(at) > AUTHOR_PERMISSION_TTL_MS; +/** The reads have failed too often or for too long. */ +const gaveUp = (c: Cached): boolean => c.failures >= AUTHOR_READ_FAILURES || (!!c.first_failure_at && old(c.first_failure_at)); /** After this many failed reads, or this long since the first, an author never read counts as unable to write. */ export const AUTHOR_READ_FAILURES = 3; -/** Database only: whether the PR's author can write to the repository, as last read (a stale entry still counts until it is refreshed). */ +/** + * Database only: whether the PR's author can write to the repository, as last read. A stale entry still counts until it is refreshed, + * but not once its refresh has failed too often or for too long. + */ export function authorWrites(db: DatabaseSync, repo: string, number: number): AuthorWrite { const r = authorOf(db, repo, number); if (!r?.author) return "no"; if (writesByRole(db, r)) return "yes"; - const c = cached(db, repo, r.author); - if (c?.permission) return WRITE.has(c.permission) ? "yes" : "no"; + const c = cached(db, repo, { ...r, author: r.author }); + if (c?.permission) return old(c.checked_at) && gaveUp(c) ? "no" : WRITE.has(c.permission) ? "yes" : "no"; // Never read: waiting, until the reads have failed too often or for too long; then the PR gets the normal cannot-push hold. - const gaveUp = !!c && (c.failures >= AUTHOR_READ_FAILURES || (!!c.first_failure_at && Date.now() - Date.parse(c.first_failure_at) > AUTHOR_PERMISSION_TTL_MS)); - return gaveUp ? "no" : "unknown"; + return c && gaveUp(c) ? "no" : "unknown"; } export type PermissionReader = (repo: string, login: string) => Promise; @@ -64,12 +72,12 @@ export async function ensureAuthorWrites(db: DatabaseSync, repo: string, number: const r = authorOf(db, repo, number); if (!r?.author) return "no"; if (!writesByRole(db, r)) { - const c = cached(db, repo, r.author); - if (!c?.permission || !c.checked_at || Date.now() - Date.parse(c.checked_at) > AUTHOR_PERMISSION_TTL_MS) { + const c = cached(db, repo, { ...r, author: r.author }); + if (!c?.permission || old(c.checked_at)) { const now = new Date().toISOString(); const p = await read(repo, r.author).catch(() => null); - if (p) db.prepare(`INSERT INTO main.author_permissions (login, repo, permission, checked_at, failures, first_failure_at) VALUES (?, ?, ?, ?, 0, NULL) - ON CONFLICT (login, repo) DO UPDATE SET permission = excluded.permission, checked_at = excluded.checked_at, failures = 0, first_failure_at = NULL`).run(r.author, repo, p, now); + if (p) db.prepare(`INSERT INTO main.author_permissions (login, repo, permission, checked_at, failures, first_failure_at, author_id) VALUES (?, ?, ?, ?, 0, NULL, ?) + ON CONFLICT (login, repo) DO UPDATE SET permission = excluded.permission, checked_at = excluded.checked_at, failures = 0, first_failure_at = NULL, author_id = excluded.author_id`).run(r.author, repo, p, now, r.author_id); else db.prepare(`INSERT INTO main.author_permissions (login, repo, failures, first_failure_at) VALUES (?, ?, 1, ?) ON CONFLICT (login, repo) DO UPDATE SET failures = failures + 1, first_failure_at = COALESCE(first_failure_at, excluded.first_failure_at)`).run(r.author, repo, now); } diff --git a/src/github/write.ts b/src/github/write.ts index 88563dc18..b8e987417 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -42,6 +42,13 @@ 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}`}`); } +/** A push to the pipeline's own branch and a new PR are made only under the grants of the steps that open the pipeline's own PRs. */ +function opensOwnPr(g: Grant, repo: string): void { + covers(g, repo); + const ok = g.scope === "item" ? g.action.kind === "fixissue-collect" : g.need === "main-fix" || g.need === "merge" || g.need === "security"; + if (!ok) throw new Error(`a ${g.scope === "item" ? `${g.action.kind} grant` : `grant for ${g.need ?? "no approval"}`} does not allow a push to a new branch or a new pull request`); +} + /** * 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. @@ -461,7 +468,7 @@ 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); + opensOwnPr(g, o.repo); exec = laneExec(w, g, exec); const body = withNote(note, o.body); return viaGh(w, idOf(w, g), exec, action, o.target, { ...details, text: body }, @@ -598,10 +605,14 @@ export function pushBranch(w: Writer, git: Pick, action: string, g: /** 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 = {}, /** The push needs the box account whatever the repo's identity (an advisory's private fork, which the app cannot reach). */ asBox = false): Promise { - covers(g, o.repo); + opensOwnPr(g, o.repo); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9._-]+$/.test(o.remote) || o.branch.startsWith("-") || !/^[0-9a-f]{40,64}$/.test(o.sha)) throw new Error("the push target is not a repository and branch"); // 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, g, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details, { repo: o.repo, number: null }, asBox); + 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 }, asBox).then((r) => { + // Without this row the pipeline's own PR at this commit is not counted as its own (a person is asked), so a failed write only holds it. + if (r.code === 0) try { w.db.prepare("INSERT OR IGNORE INTO main.own_commits (repo, sha, action, at) VALUES (?, ?, ?, ?)").run(o.repo, o.sha, action, new Date().toISOString()); } catch (e) { console.error(`own commit not recorded: ${oneLine(String((e as Error).message ?? e))}`); } + return r; + }); } 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 }, asBox = false): Promise { diff --git a/src/health-checks.ts b/src/health-checks.ts index 5fd98dc75..37f95a92c 100644 --- a/src/health-checks.ts +++ b/src/health-checks.ts @@ -12,6 +12,7 @@ import { storedLiveness } from "./liveness.ts"; import { coverageSnapshot, githubIdentity } from "./github/identity.ts"; import { readAppSecrets } from "./github/install-token.ts"; import { PROBE_HEADERS } from "./health.ts"; +import { unboundLogins } from "./author-ids.ts"; /** Thresholds, in one place. */ export const THRESHOLDS = { @@ -186,6 +187,18 @@ function appIdentityChecks({ db, probe }: CheckCtx): Check[] { return [ok("app-keys", "/admin/github-app"), { id: "app-coverage", state: "warn", text, brief: "The GitHub App does not cover every tracked repo", since: null, count: uncovered.length, to: "/admin/github-app" }]; } +/** The last pass that binds contributors' account ids failed: the earlier PRs of the logins it did not bind count toward no tier until a pass succeeds. */ +function authorIdsCheck({ db }: CheckCtx): Check[] { + const err = (db.prepare("SELECT value FROM settings WHERE key = 'author_ids_error'").get() as { value: string } | undefined)?.value; + if (!err) return [ok("author-ids", "/contributors")]; + const n = unboundLogins(db).length; + if (!n) return [ok("author-ids", "/contributors")]; + const at = err.split(" ")[0] ?? null; + return [{ id: "author-ids", state: "warn", count: n, since: at, to: "/contributors", + text: `Contributor account ids could not be read (${err.slice(at ? at.length + 1 : 0).trim() || "error"}): the earlier PRs of ${n} login${n === 1 ? "" : "s"} count toward no whitelist tier until the next sync reads them`, + brief: "Some contributors' whitelist history cannot be read" }]; +} + /** The outside-author surge breaker (src/outside.ts) while it is tripped; an operator resumes it on the Pipeline page. */ function outsideSurgeCheck({ db }: CheckCtx): Check[] { const t = db.prepare("SELECT reason, tripped_at FROM stage_trips WHERE stage = 'outside-surge' AND active = 1").get() as { reason: string; tripped_at: string } | undefined; @@ -195,7 +208,7 @@ function outsideSurgeCheck({ db }: CheckCtx): Check[] { } /** Every check, in the order the lists show them. */ -const SOURCES: ((ctx: CheckCtx) => Check[])[] = [runnerCheck, workerChecks, queueCheck, syncCheck, syncRepoChecks, accountsCheck, rateCheck, deadlineChecks, livenessCheck, appIdentityChecks, outsideSurgeCheck]; +const SOURCES: ((ctx: CheckCtx) => Check[])[] = [runnerCheck, workerChecks, queueCheck, syncCheck, syncRepoChecks, accountsCheck, rateCheck, deadlineChecks, livenessCheck, appIdentityChecks, authorIdsCheck, outsideSurgeCheck]; export function computeChecks(db: DatabaseSync, nowMs: number = Date.now(), probe = false): Check[] { return SOURCES.flatMap((f) => f({ db, nowMs, probe })); diff --git a/src/mirror.ts b/src/mirror.ts index 00050e1fa..a1926a8ef 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -330,8 +330,10 @@ function writePage(db: DatabaseSync, repo: string, kind: Kind, detail: Detail, n const insert = db.prepare(`INSERT INTO main.items (${COLUMNS.join(",")}) VALUES (${COLUMNS.map((c) => `:${c}`).join(",")}) ON CONFLICT (repo, number) DO UPDATE SET ${COLUMNS.filter((c) => c !== "repo" && c !== "number").map((c) => c === "mergeable" ? `mergeable=${KEEP_KNOWN_MERGEABLE("items")}` : `${c}=excluded.${c}`).join(",")}`); const stored = db.prepare(`SELECT ${COLUMNS.join(",")} FROM items WHERE repo=? AND number=?`); - // The first account seen under a login string owns it for the whitelist; a later account with the same login does not inherit its history. - const bindId = db.prepare("INSERT OR IGNORE INTO main.author_ids (login, id) VALUES (?, ?)"); + // The account seen under a login string owns its id-less history for the whitelist; a later account with the same login does not inherit it. + // A login with merged or closed PRs mirrored without an id is left to the backfill, which binds the author of that history, not the login's current holder. + const bindId = db.prepare(`INSERT OR IGNORE INTO main.author_ids (login, id) SELECT ?1, ?2 + WHERE NOT EXISTS (SELECT 1 FROM main.items WHERE author = ?1 AND kind = 'pr' AND state IN ('MERGED','CLOSED') AND author_id IS NULL)`); const del = db.prepare("DELETE FROM main.comments WHERE repo=? AND number=?"); const insComment = db.prepare(`INSERT INTO main.comments (repo, number, id, kind, author, created_at, body, review_state, commit_oid, counted, author_association, mentions_pipeline, url) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT (id) DO UPDATE SET repo=excluded.repo, number=excluded.number, kind=excluded.kind, author=excluded.author, created_at=excluded.created_at, @@ -917,6 +919,7 @@ export async function runSync(db: DatabaseSync, client: Querier, opts: SyncOpts, const bound = await backfillAuthorIds(db, client); if (bound) console.log(`bound ${bound} author account id${bound === 1 ? "" : "s"}`); setSetting(db, "author_ids_backfilled", iso(new Date())); + db.prepare("DELETE FROM main.settings WHERE key = 'author_ids_error'").run(); } catch (e) { const msg = String((e as Error)?.message ?? e).slice(0, 200); console.log(`author ids: ${msg}`); diff --git a/src/outside.ts b/src/outside.ts index fdcab6700..d4eb19de9 100644 --- a/src/outside.ts +++ b/src/outside.ts @@ -62,7 +62,7 @@ export function setOutsideLimits(db: DatabaseSync, by: string, input: unknown): return next; } -type Row = { repo: string; number: number; kind: string; author: string; state: string; created_at: string; author_association: string | null; author_type: string | null }; +type Row = { repo: string; number: number; kind: string; author: string; author_id: number | null; state: string; created_at: string; author_association: string | null; author_type: string | null }; export type Hold = { repo: string; number: number; author: string; kind: "pr" | "issue"; reason: "limit" | "surge" }; const INSIDE_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]); @@ -114,16 +114,17 @@ export function refreshOutsideHolds(db: DatabaseSync, now: number = Date.now()): // Only items in scope for model work count: repos with the pipeline on, and not fast-tracked. const scope = pipelineRepos(db); const fast = new Set((db.prepare("SELECT repo, number FROM main.fast_track").all() as { repo: string; number: number }[]).map((r) => `${r.repo}#${r.number}`)); - const rows = (db.prepare("SELECT repo, number, kind, author, state, created_at, author_association, author_type FROM items WHERE created_at >= ? AND author IS NOT NULL") + const rows = (db.prepare("SELECT repo, number, kind, author, author_id, state, created_at, author_association, author_type FROM items WHERE created_at >= ? AND author IS NOT NULL") .all(new Date(from).toISOString()) as Row[]).filter((r) => scope.has(r.repo) && !fast.has(`${r.repo}#${r.number}`)); backfillAdmitted(db, new Date(from).toISOString(), now); const admitted = new Set((db.prepare("SELECT repo, number FROM main.outside_admitted").all() as { repo: string; number: number }[]).map((r) => `${r.repo}#${r.number}`)); const inside = insiders(db); const memo = new Map(); - const whitelisted = (login: string): boolean => { - const k = login.toLowerCase(); + // Whitelisting belongs to the author's account, not to the login string. + const whitelisted = (r: Row): boolean => { + const k = `${r.author.toLowerCase()}|${r.author_id ?? ""}`; let v = memo.get(k); - if (v === undefined) { v = isWhitelisted(db, login).ok; memo.set(k, v); } + if (v === undefined) { v = isWhitelisted(db, r.author, r.author_id).ok; memo.set(k, v); } return v; }; const cheap = rows.filter((r) => isOutsideAuthor(db, r, inside)); @@ -133,7 +134,7 @@ export function refreshOutsideHolds(db: DatabaseSync, now: number = Date.now()): const since = Math.max(now - HOUR_MS, Date.parse(sinceOf(db, OUTSIDE_SURGE)) || 0); const recent = cheap.filter((r) => Date.parse(r.created_at) > since); // The whitelist is read only when the cheap count already passes the threshold. - const real = recent.length > lim.surgePerHour ? recent.filter((r) => !whitelisted(r.author)) : []; + const real = recent.length > lim.surgePerHour ? recent.filter((r) => !whitelisted(r)) : []; if (real.length > lim.surgePerHour) { const byAuthor = new Map(); for (const r of real) byAuthor.set(r.author, (byAuthor.get(r.author) ?? 0) + 1); @@ -144,7 +145,7 @@ export function refreshOutsideHolds(db: DatabaseSync, now: number = Date.now()): } const groups = new Map(); for (const r of cheap) { - const k = `${r.author.toLowerCase()}|${r.kind}`; + const k = `${r.author.toLowerCase()}|${r.author_id ?? ""}|${r.kind}`; (groups.get(k) ?? groups.set(k, []).get(k)!).push(r); } for (const rs of groups.values()) { @@ -155,7 +156,7 @@ export function refreshOutsideHolds(db: DatabaseSync, now: number = Date.now()): const overLimit = limit > 0 && win.length > limit; const inSurge = surgeFrom !== null && rs.some((r) => Date.parse(r.created_at) >= surgeFrom); if (!overLimit && !inSurge) continue; - if (whitelisted(rs[0]!.author)) continue; + if (whitelisted(rs[0]!)) continue; // An admitted item (planned without a hold once, or with pipeline work already) is never held again. const free = (r: Row) => r.state !== "OPEN" || released.has(`${r.repo}#${r.number}`) || admitted.has(`${r.repo}#${r.number}`); for (const r of rs) if (!free(r) && surgeFrom !== null && Date.parse(r.created_at) >= surgeFrom) holds.push({ repo: r.repo, number: r.number, author: r.author, kind, reason: "surge" }); diff --git a/src/schema.sql b/src/schema.sql index 53fee2c46..bb082a513 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -1513,6 +1513,16 @@ CREATE TABLE IF NOT EXISTS model_checks ( CREATE INDEX IF NOT EXISTS model_checks_item ON model_checks(repo, number, id); CREATE INDEX IF NOT EXISTS model_checks_median ON model_checks(repo, command, id); +-- Commits the pipeline pushed to a branch of its own (pushOwnBranch: the first commit of a Fix, main CI fix or security fix PR, a batch tip). +-- The pipeline's own PR keeps its own tier only at such a head, or one reached from it through our own later pushes (pushChainOf). +CREATE TABLE IF NOT EXISTS own_commits ( + repo TEXT NOT NULL, + sha TEXT NOT NULL, + action TEXT NOT NULL, + at TEXT NOT NULL, + PRIMARY KEY (repo, sha) +); + -- Every push of ours to a PR branch (fix-up, conflict merge, CI fix, fix-issue PR) and what it did to the PR's required checks. -- before_res / after_res: green | red | pending | none | unknown (required checks only; optional ones are ignored). A branch created -- by the push has no earlier head: it counts as green before. outcome stays NULL until the checks at to_oid are final; diff --git a/src/security/land.ts b/src/security/land.ts index 902a19840..c743ac2f3 100644 --- a/src/security/land.ts +++ b/src/security/land.ts @@ -69,7 +69,7 @@ export async function runLand(db: DatabaseSync, repo: string, n: number, by: By, if (!row.fix_commit || !row.fix_title || !row.fix_summary || !row.fix_branch) return back(db, repo, n, "the finding has no fix to land", d.log); const git = new Git(d.exec, d.root, repo); if (!(await haveCommit(git, row))) return back(db, repo, n, "the fix commit is gone from the local cache; write the fix again", d.log); - const g = guardRepo(db, repo, null, by); + const g = guardRepo(db, repo, "security", by); if ("refused" in g) return back(db, repo, n, g.refused, d.log); const who = await d.who(); const base = branchOf(db, repo); @@ -182,7 +182,7 @@ export async function runAdvisory(db: DatabaseSync, repo: string, n: number, by: if (!row.fix_commit || !row.fix_title || !row.fix_summary || !row.fix_branch) return back(db, repo, n, "the finding has no fix to land", d.log); const git = new Git(d.exec, d.root, repo); if (!(await haveCommit(git, row))) return back(db, repo, n, "the fix commit is gone from the local cache; write the fix again", d.log); - const g = guardRepo(db, repo, null, by); + const g = guardRepo(db, repo, "security", by); if ("refused" in g) return back(db, repo, n, g.refused, d.log); const set: Record = {}; let ghsa = row.ghsa_id; @@ -254,7 +254,7 @@ export async function runPublish(db: DatabaseSync, repo: string, n: number, by: const key = findingKey(repo, n); const w: Writer = { db, login: ACTOR }; const note = (why: string): string => { db.prepare("UPDATE security_findings SET note = ?, updated_at = ? WHERE repo = ? AND number = ?").run(oneLine(why, 400), new Date().toISOString(), repo, n); return `finding ${n}: ${oneLine(why, 120)}`; }; - const g = guardRepo(db, repo, null, by); + const g = guardRepo(db, repo, "security", by); if ("refused" in g) return note(g.refused); let ghsa = row.ghsa_id; if (!ghsa) { @@ -331,7 +331,7 @@ export async function pollLanding(db: DatabaseSync, d: Pick `${a.login}\0${a.id ?? ""}`; +type Standing = { merged: number; closed: number; override: "allow" | "deny" | null }; + /** - * Tiers of the given authors, from one stats query. A login string can pass to another GitHub account: when the account id differs - * from the one first seen under the login, the history and an allow override are not this account's, so the tier is "not" (a deny still holds). + * The history and override that count for each author account. A login string can pass to another GitHub account, so history is + * counted per account: a PR row with an id counts for that id, a row without one (mirrored before ids were stored) for the account + * the login is bound to (author_ids), and for nobody while the login is unbound. An author with no id stands for the bound account. + * An allow override counts only for the account it was given to; a deny holds for every account under the login. */ -export function tiersOf(db: DatabaseSync, authors: AuthorRef[]): Map { - const out = new Map(); +function standings(db: DatabaseSync, authors: AuthorRef[]): Map { + const out = new Map(); if (!authors.length) return out; const logins = [...new Set(authors.map((a) => a.login))]; - const rule = getRule(db); const marks = logins.map(() => "?").join(","); - const stats = new Map((db.prepare(`${STATS_SQL} AND author IN (${marks}) GROUP BY author`).all(...logins) as { login: string; merged: number; closed: number }[]).map((r) => [r.login, r])); - const over = new Map((db.prepare(`SELECT login, status FROM whitelist_overrides WHERE login IN (${marks})`).all(...logins) as { login: string; status: string }[]).map((r) => [r.login, r.status])); + const rows = new Map(); + for (const r of db.prepare(`SELECT author AS login, author_id AS id, SUM(state = 'MERGED') AS merged, SUM(state = 'CLOSED') AS closed + FROM items WHERE kind = 'pr' AND author IN (${marks}) GROUP BY author, author_id`).all(...logins) as { login: string; id: number | null; merged: number; closed: number }[]) { + (rows.get(r.login) ?? rows.set(r.login, []).get(r.login)!).push(r); + } + const over = new Map((db.prepare(`SELECT login, status, github_id FROM whitelist_overrides WHERE login COLLATE NOCASE IN (${marks})`).all(...logins) as { login: string; status: string; github_id: number | null }[]) + .map((r) => [r.login.toLowerCase(), r])); const bound = new Map((db.prepare(`SELECT login, id FROM author_ids WHERE login IN (${marks})`).all(...logins) as { login: string; id: number }[]).map((r) => [r.login, r.id])); for (const a of authors) { const owner = bound.get(a.login); - const other = a.id !== null && owner !== undefined && owner !== a.id; - const s = other ? undefined : stats.get(a.login); - const o = over.get(a.login) ?? null; - out.set(tierKey(a), tierOf(s?.merged ?? 0, s?.closed ?? 0, other && o === "allow" ? null : o, rule)); + const account = a.id ?? owner ?? null; + let merged = 0, closed = 0; + if (account !== null) for (const r of rows.get(a.login) ?? []) if (r.id === account || (r.id === null && owner === account)) { merged += r.merged; closed += r.closed; } + const o = over.get(a.login.toLowerCase()); + const override = o?.status === "deny" ? "deny" : o?.status === "allow" && account !== null && o.github_id === account ? "allow" : null; + out.set(tierKey(a), { merged, closed, override }); } return out; } +/** Tiers of the given authors, from one stats query (see standings: history and an allow count only for their own account). */ +export function tiersOf(db: DatabaseSync, authors: AuthorRef[]): Map { + const rule = getRule(db); + return new Map([...standings(db, authors)].map(([k, s]) => [k, tierOf(s.merged, s.closed, s.override, rule)])); +} + // SQL expression for the tier, given columns merged, closed, override and // bound parameters :min_merged, :min_rate. export const TIER_SQL = `CASE @@ -106,39 +123,45 @@ export function contributors(db: DatabaseSync, opts: { repo?: string; login?: st j AS ( SELECT r.author AS login, COALESCE(s.merged,0) AS merged, COALESCE(s.closed,0) AS closed, COALESCE(s.open,0) AS open, s.last_merge, r.repos, o.status AS override, o.note, o.by AS override_by, o.at AS override_at - FROM r LEFT JOIN s ON s.login = r.author LEFT JOIN whitelist_overrides o ON o.login = r.author + FROM r LEFT JOIN s ON s.login = r.author LEFT JOIN whitelist_overrides o ON o.login = r.author COLLATE NOCASE UNION ALL SELECT o.login, 0, 0, 0, NULL, '', o.status, o.note, o.by, o.at FROM whitelist_overrides o - WHERE NOT EXISTS (SELECT 1 FROM items i WHERE i.kind = 'pr' AND i.author = o.login) ${opts.repo ? "AND 0" : ""} ${opts.login ? "AND o.login = :login" : ""} + WHERE NOT EXISTS (SELECT 1 FROM items i WHERE i.kind = 'pr' AND i.author = o.login COLLATE NOCASE) ${opts.repo ? "AND 0" : ""} ${opts.login ? "AND o.login = :login" : ""} ) SELECT j.*, ${TIER_SQL} AS tier FROM j`).all(params) as Omit[]; return rows.map((r) => ({ ...r, rate: r.merged + r.closed > 0 ? r.merged / (r.merged + r.closed) : null })); } -export function isWhitelisted(db: DatabaseSync, login: string): { ok: boolean; reason: string } { +/** Whether the author account is whitelisted (by history or an allow override), with the facts; `id` null stands for the login's bound account. */ +export function isWhitelisted(db: DatabaseSync, login: string, id: number | null): { ok: boolean; reason: string } { const rule = getRule(db); - const o = db.prepare("SELECT status FROM whitelist_overrides WHERE login = ?").get(login) as { status: string } | undefined; - if (o?.status === "allow") return { ok: true, reason: "override: allow" }; - if (o?.status === "deny") return { ok: false, reason: "override: deny" }; - const s = db.prepare(`${STATS_SQL} AND author = ?`).get(login) as { merged: number | null; closed: number | null }; - const merged = s.merged ?? 0; - const closed = s.closed ?? 0; - const rate = merged + closed > 0 ? merged / (merged + closed) : 0; - const ok = tierOf(merged, closed, null, rule) === "whitelisted"; - const facts = `${merged} merged, merge rate ${Math.round(rate * 100)}%; rule: ≥ ${rule.minMerged} merged and ≥ ${Math.round(rule.minRate * 100)}%`; + const s = standings(db, [{ login, id }]).get(tierKey({ login, id }))!; + if (s.override === "allow") return { ok: true, reason: "override: allow" }; + if (s.override === "deny") return { ok: false, reason: "override: deny" }; + const rate = s.merged + s.closed > 0 ? s.merged / (s.merged + s.closed) : 0; + const ok = tierOf(s.merged, s.closed, null, rule) === "whitelisted"; + const facts = `${s.merged} merged, merge rate ${Math.round(rate * 100)}%; rule: ≥ ${rule.minMerged} merged and ≥ ${Math.round(rule.minRate * 100)}%`; return { ok, reason: facts }; } -export function setOverride(db: DatabaseSync, login: string, status: "allow" | "deny" | null, note: string | null, by: string): void { - if (!/^[A-Za-z0-9-]{1,39}(\[bot\])?$/.test(login)) throw new Error(`not a GitHub login: ${login}`); +export const OVERRIDE_LOGIN = /^[A-Za-z0-9-]{1,39}(\[bot\])?$/; + +/** + * Sets or clears the override of a login. `githubId` is the account the login names now (looked up by the caller): an allow + * counts only for that account, so it needs one; a deny holds for any account under the login. + */ +export function setOverride(db: DatabaseSync, login: string, status: "allow" | "deny" | null, note: string | null, by: string, githubId: number | null = null): void { + if (!OVERRIDE_LOGIN.test(login)) throw new Error(`not a GitHub login: ${login}`); + if (status === "allow" && githubId === null) throw new Error(`${login} is not a GitHub user`); if (status === null) { - db.prepare("DELETE FROM whitelist_overrides WHERE login = ?").run(login); + db.prepare("DELETE FROM whitelist_overrides WHERE login = ? COLLATE NOCASE").run(login); } else { - db.prepare("INSERT OR REPLACE INTO whitelist_overrides (login, status, note, by, at) VALUES (?, ?, ?, ?, ?)") - .run(login, status, note || null, by, new Date().toISOString()); + db.prepare("DELETE FROM whitelist_overrides WHERE login = ? COLLATE NOCASE AND login <> ?").run(login, login); + db.prepare("INSERT OR REPLACE INTO whitelist_overrides (login, status, note, by, at, github_id) VALUES (?, ?, ?, ?, ?, ?)") + .run(login, status, note || null, by, new Date().toISOString(), githubId); } // The note is private: the audit row records only that one was given. - audit(db, by, "override", login, { status: status ?? "clear", note: note ? true : undefined }); + audit(db, by, "override", login, { status: status ?? "clear", note: note ? true : undefined, githubId: githubId ?? undefined }); } function flag(args: string[], name: string): string | undefined { @@ -165,7 +188,7 @@ function show(args: string[]): void { if (!login) throw new Error("usage: whitelist show "); const db = connect(); const c = contributors(db, { login })[0]; - const w = isWhitelisted(db, login); + const w = isWhitelisted(db, login, null); if (!c) { console.log(`${login}: no PRs in the mirror; ${w.ok ? "allowed" : "not allowed"} (${w.reason})`); return; @@ -175,11 +198,12 @@ function show(args: string[]): void { } function override(status: "allow" | "deny" | null) { - return (args: string[]): void => { + return async (args: string[]): Promise => { const note = flag(args, "--note") ?? null; const login = args[0]; if (!login) throw new Error(`usage: whitelist ${status ?? "clear"} ${status ? " [--note TEXT]" : ""}`); - setOverride(connect(), login, status, note, "cli"); + const id = status === "allow" ? await githubUserId(login) : status === "deny" ? await githubUserId(login).catch(() => null) : null; + setOverride(connect(), login, status, note, "cli", id); console.log(`${login}: ${status ?? "override cleared"}`); }; } @@ -196,21 +220,21 @@ function rule(args: string[]): void { console.log(`whitelisted: at least ${now.minMerged} merged PRs and a merge rate of at least ${now.minRate}`); } -const SUB: Record void> = { +const SUB: Record void | Promise> = { list, show, allow: override("allow"), deny: override("deny"), clear: override(null), rule, }; export const commands = { whitelist: { summary: "contributor whitelist: list [--tier T] [--repo R] | show LOGIN | allow|deny LOGIN [--note T] | clear LOGIN | rule [--min-merged N] [--min-rate R]", - run(args: string[]): void { + async run(args: string[]): Promise { const [sub, ...rest] = args; const fn = sub ? SUB[sub] : undefined; if (!fn) { console.log(`usage: autocraft whitelist ${Object.keys(SUB).join("|")} ...`); process.exit(sub ? 1 : 0); } - fn(rest); + await fn(rest); }, }, }; diff --git a/test/app-lane.test.ts b/test/app-lane.test.ts index c6a029255..22b8c248c 100644 --- a/test/app-lane.test.ts +++ b/test/app-lane.test.ts @@ -16,7 +16,7 @@ import { SCRATCH } from "./scratch.ts"; const BOX = "ghp_box_account_token"; const APP = "ghs_installation_token"; const item = (as: string): GuardedItem => ({ scope: "item", action: { kind: "act" }, repo: "lane", number: 7, as }) as unknown as GuardedItem; -const repoGrant = { scope: "repo", need: null, repo: "lane", as: "app" } as unknown as GuardedRepo; +const repoGrant = { scope: "repo", need: "merge", repo: "lane", as: "app" } as unknown as GuardedRepo; const note = { by: "fixed" } as never; test("app identity: the installation token is the whole child environment; legacy and user grants are untouched", async () => { diff --git a/test/identity-sec3.test.ts b/test/identity-sec3.test.ts new file mode 100644 index 000000000..aec441e74 --- /dev/null +++ b/test/identity-sec3.test.ts @@ -0,0 +1,85 @@ +// A whitelist tier belongs to a GitHub account and the pipeline's own tier to heads it pushed; removing an operator ends what acts as them. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, test } from "node:test"; +import { addLogin, removeLogin, setRole } from "../src/access.ts"; +import { backfillAuthorIds } from "../src/author-ids.ts"; +import { loadPrFact } from "../src/core/facts.ts"; +import { connect } from "../src/db.ts"; +import { createLink, openLinks } from "../src/dash/server/github-setup.ts"; +import { writeItemNode } from "../src/mirror.ts"; +import { isWhitelisted, setOverride, tierKey, tiersOf } from "../src/whitelist.ts"; +import { SCRATCH } from "./scratch.ts"; +import { T0, world, type World } from "./world-db.ts"; + +let current: World | null = null; +afterEach(() => current?.close()); + +const fresh = () => { + mkdirSync(SCRATCH, { recursive: true }); + return connect(join(mkdtempSync(join(SCRATCH, "identity-")), "m.db")); +}; +const issue = (number: number, login: string, id: number) => ({ + __typename: "Issue", number, state: "OPEN", title: "t", body: "", url: `https://github.com/storytold/r/issues/${number}`, + author: { __typename: "User", login, databaseId: id }, authorAssociation: "NONE", createdAt: T0, updatedAt: T0, closedAt: null, stateReason: null, repository: { name: "r", owner: { login: "storytold" } }, +}); + +test("history and an allow count only for their own account, and the pipeline's own PR only at a head it pushed", async () => { + const db = fresh(); + const tier = (login: string, id: number | null) => tiersOf(db, [{ login, id }]).get(tierKey({ login, id })); + const ins = db.prepare("INSERT INTO items (repo, number, kind, state, title, author, created_at, merged_at) VALUES ('r', ?, 'pr', 'MERGED', 't', ?, '2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z')"); + for (let i = 1; i <= 6; i++) ins.run(i, "old-dev"); + // A new holder of the login writes an issue before the history is bound: no binding, and no tier for anyone while unbound. + writeItemNode(db, "r", issue(50, "old-dev", 999)); + assert.deepEqual(db.prepare("SELECT id FROM author_ids WHERE login = 'old-dev'").all(), []); + assert.equal(tier("old-dev", 999), "not"); + const client = { spent: 0, remaining: null, async query() { return { p0: { pullRequest: { author: { __typename: "User", databaseId: 42 } } } }; } }; + await backfillAuthorIds(db, client); + assert.equal(tier("old-dev", 42), "whitelisted"); + assert.equal(tier("old-dev", 999), "not"); + assert.equal(isWhitelisted(db, "old-dev", 999).ok, false); + // An allow given to account 42 under "alice" does not pass to account 999 under the same login; a deny holds in any letter case. + setOverride(db, "alice", "allow", null, "op", 42); + writeItemNode(db, "r", issue(51, "alice", 999)); + assert.equal(tier("alice", 999), "not"); + assert.equal(tier("alice", 42), "allow"); + assert.equal(isWhitelisted(db, "alice", 999).ok, false); + setOverride(db, "Old-Dev", "deny", null, "op", 42); + assert.equal(tier("old-dev", 42), "deny"); + + const w = (current = world().repo()); + w.db.prepare("INSERT INTO settings (key, value) VALUES ('pipeline_login', 'pipeline-bot')").run(); + w.pr(9, { author: "pipeline-bot", head: "a".repeat(40) }).review(9, { verdict: "take", head: "a".repeat(40) }); + w.db.prepare("INSERT INTO fix_attempts (repo, number, main_sha, text_hash, state, created_at, updated_at, pr_url) VALUES ('app', 3, 'm', 'h', 'pr-opened', ?, ?, 'https://github.com/storytold/app/pull/9')").run(T0, T0); + const prTier = () => loadPrFact(w.db, "app", 9)?.tier; + assert.equal(prTier(), "not", "no record that the pipeline pushed this head"); + w.db.prepare("INSERT INTO own_commits (repo, sha, action, at) VALUES ('app', ?, 'fixissue-push', ?)").run("a".repeat(40), T0); + assert.equal(prTier(), "whitelisted"); + w.synced(9, "b".repeat(40)); + assert.equal(prTier(), "not", "someone else pushed to the branch"); + w.db.prepare("INSERT INTO fixups (repo, number, from_head, to_head, state, attempt, created_at) VALUES ('app', 9, ?, ?, 'pushed', 1, ?)").run("a".repeat(40), "c".repeat(40), T0); + w.synced(9, "c".repeat(40)); + assert.equal(prTier(), "whitelisted", "our own fix-up of our commit"); +}); + +test("removing or demoting an operator in any letter case ends their Discord link and their org setup links", () => { + const db = fresh(); + addLogin(db, "cli", "Owner", "operator", null); + addLogin(db, "cli", "Bob", "operator", null); + addLogin(db, "cli", "Ann", "operator", null); + db.prepare("INSERT INTO discord_links (user_hash, login, linked_at) VALUES ('u1', 'Bob', ?)").run(T0); + db.prepare("INSERT INTO discord_link_codes (code_hash, login, expires_at) VALUES ('c1', 'Bob', '2099-01-01T00:00:00Z')").run(); + createLink(db, "Bob", "real-org"); + createLink(db, "Ann", "real-org"); + createLink(db, "Owner", "real-org"); + assert.equal(openLinks(db).length, 3); + removeLogin(db, "cli", "bob"); + setRole(db, "cli", "ann", "viewer"); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM discord_links").get() as { n: number }).n, 0); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM discord_link_codes").get() as { n: number }).n, 0); + assert.deepEqual(openLinks(db).map((l) => l.createdBy), ["Owner"]); + // A link whose creator lost the role by any other path stops working too. + db.prepare("UPDATE access SET role = 'maintainer' WHERE login = 'Owner'").run(); + assert.deepEqual(openLinks(db), []); +}); diff --git a/test/merge-trust.test.ts b/test/merge-trust.test.ts index 82751c8b4..c0172daba 100644 --- a/test/merge-trust.test.ts +++ b/test/merge-trust.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { afterEach, test } from "node:test"; import { advancePreapprovals, preapprovalOf } from "../src/preapproval/index.ts"; -import { OPERATOR, T0, world, type World } from "./world-db.ts"; +import { OPERATOR, REGULAR_ID, T0, world, type World } from "./world-db.ts"; let current: World | null = null; afterEach(() => current?.close()); @@ -24,7 +24,7 @@ test("a Merge answer carries across a base merge that left the diff unchanged, n test("code carried from a closed duplicate by an author who is not whitelisted needs a Merge answer at the head", () => { const w = (current = world().repo().pr(5).review(5, { verdict: "take" }).verified(5).premerge(5, "clean").pr(6).pr(7, { author: "regular" }).review(7, { verdict: "take" }).verified(7).premerge(7, "clean")); w.db.prepare("UPDATE items SET state = 'CLOSED', author = ? WHERE number = 6").run("stranger"); - w.db.prepare("INSERT INTO items (repo, number, kind, state, title, author, created_at, updated_at) VALUES ('app', 8, 'pr', 'CLOSED', 'PR 8', 'regular', ?, ?)").run(T0, T0); + w.db.prepare("INSERT INTO items (repo, number, kind, state, title, author, author_id, created_at, updated_at) VALUES ('app', 8, 'pr', 'CLOSED', 'PR 8', 'regular', ?, ?, ?)").run(REGULAR_ID, T0, T0); const carry = (kept: number, closed: number) => { const id = `app:dupegroup:${kept}`; w.db.prepare("INSERT INTO dupe_carries (decision_id, repo, number, state, outcome, updated_at) VALUES (?, 'app', ?, 'done', 'pushed', ?)").run(id, kept, T0); diff --git a/test/world-db.ts b/test/world-db.ts index 947ee6bd1..70026e96c 100644 --- a/test/world-db.ts +++ b/test/world-db.ts @@ -42,7 +42,10 @@ type Live = { head: string; state: string; mergeable: string; ci: string; author mkdirSync(SCRATCH, { recursive: true }); export const tmpdir = (name: string): string => mkdtempSync(join(SCRATCH, `${name}-`)); -export type PrOpts = { author?: string; lines?: number; label?: string; head?: string; mergeable?: string; ci?: "success" | "failure" | "pending"; canModify?: boolean; flags?: string[] }; +/** `authorId`: the author's GitHub account id (default: the allowed "regular" account for "regular", none for others). */ +export type PrOpts = { author?: string; authorId?: number | null; lines?: number; label?: string; head?: string; mergeable?: string; ci?: "success" | "failure" | "pending"; canModify?: boolean; flags?: string[] }; +/** The GitHub account of the allowed author "regular". */ +export const REGULAR_ID = 7; export type ReviewOpts = { verdict?: "take" | "take-fix" | "hold" | "close"; head?: string; sure?: boolean; fixes?: { file: string; change: string }[]; reason?: string }; export type IssueOpts = { label?: string; flags?: string[]; title?: string; body?: string; impact?: string }; @@ -152,7 +155,7 @@ export function world() { db.prepare("UPDATE tracked_repos SET pipeline = 1 WHERE name = 'app'").run(); db.prepare("INSERT OR IGNORE INTO repos (name, visibility, default_branch) VALUES ('app', 'public', 'main')").run(); db.prepare("INSERT OR IGNORE INTO access (login, role) VALUES (?, 'operator')").run(OPERATOR); - db.prepare("INSERT OR IGNORE INTO whitelist_overrides (login, status, by, at) VALUES ('regular', 'allow', ?, ?)").run(OPERATOR, T0); + db.prepare("INSERT OR IGNORE INTO whitelist_overrides (login, status, by, at, github_id) VALUES ('regular', 'allow', ?, ?, ?)").run(OPERATOR, T0, REGULAR_ID); const on = (k: string) => !off.includes(k as never); setMergeApproval(db, OPERATOR, "app", on("merge")); setPushApproval(db, OPERATOR, "app", on("push")); @@ -171,8 +174,9 @@ export function world() { /** An open PR with its classification and its checks at its head. */ pr(n: number, o: PrOpts = {}) { const head = o.head ?? `sha${n}`; - db.prepare(`INSERT INTO items (repo, number, kind, state, title, author, additions, deletions, head_oid, head_ref, created_at, updated_at) - VALUES ('app', ?, 'pr', 'OPEN', ?, ?, ?, 0, ?, ?, ?, ?)`).run(n, `PR ${n}`, o.author ?? "regular", o.lines ?? 20, head, `fix-${n}`, T0, T0); + const author = o.author ?? "regular"; + db.prepare(`INSERT INTO items (repo, number, kind, state, title, author, author_id, additions, deletions, head_oid, head_ref, created_at, updated_at) + VALUES ('app', ?, 'pr', 'OPEN', ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(n, `PR ${n}`, author, o.authorId !== undefined ? o.authorId : author === "regular" ? REGULAR_ID : null, o.lines ?? 20, head, `fix-${n}`, T0, T0); db.prepare(`INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, flags, probs) VALUES ('app', ?, 'jev', 'r1', ?, ?, ?, '{"top":0.95}')`) .run(n, T0, o.label ?? "bugfix", JSON.stringify(o.flags ?? [])); db.prepare(`INSERT INTO pr_checks (repo, number, head_oid, state, is_draft, overall, checks, mergeable, maintainer_can_modify, fetched_at)