| 1 | import type { Env } from "../env.js"; |
| 2 | import { hmacSha256, matchesAnyKey, signingSecrets } from "../lib/crypto.js"; |
| 3 | import type { Account, Directory } from "../lib/directory.js"; |
| 4 | import { HttpError, b64url, fromB64url, now } from "../lib/util.js"; |
| 5 | import { GitHubApiError, GitHubAppClient, githubApp, type GitHubInstallation } from "./github.js"; |
| 6 | import type { RunnerJobRow } from "./service.js"; |
| 7 | |
| 8 | /** |
| 9 | * Linking a GitHub App installation to the Diffinery account that pays for its jobs. Whoever links one |
| 10 | * must manage that account (themselves, or an organization they own or administer) and, as GitHub |
| 11 | * tells the app when they authorize it, be able to manage the installation on GitHub: anyone else could |
| 12 | * otherwise spend their own minutes on another's jobs, read which jobs a private repository runs, or |
| 13 | * unlink them. |
| 14 | * |
| 15 | * The flow (web/github-runners.tsx): Install on GitHub carries a signed `state` naming the person and the |
| 16 | * paying account; GitHub returns to the setup URL with the installation id, the state and, with "Request |
| 17 | * user authorization (OAuth) during installation" on, a code. Without a code the person is sent to authorize |
| 18 | * the app first. The code becomes a user token, used once to list the installations they can manage. Link |
| 19 | * existing installations authorizes the app and lists those installations; the person picks one and who pays. |
| 20 | */ |
| 21 | |
| 22 | /** Where GitHub sends people back to: the app's setup URL and its callback URL. */ |
| 23 | export const SETUP_PATH = "/settings/github-runners/setup"; |
| 24 | /** How long a state or a proof is good for. */ |
| 25 | const TTL_SECONDS = 3600; |
| 26 | |
| 27 | /** What a state or proof says: who started, which account pays, and (once known) the installation. */ |
| 28 | interface Claims { |
| 29 | /** "state" for a flow under way, "proof" once GitHub said the person manages installation i. */ |
| 30 | k: "state" | "proof"; |
| 31 | u: string; |
| 32 | /** The paying account a state was started for. */ |
| 33 | a?: string; |
| 34 | i?: number; |
| 35 | login?: string; |
| 36 | type?: string; |
| 37 | x: number; |
| 38 | } |
| 39 | |
| 40 | export interface LinkedInstallation { |
| 41 | id: number; |
| 42 | account_id: string; |
| 43 | github_login: string; |
| 44 | github_type: string; |
| 45 | linked_by: string; |
| 46 | linked_at: string; |
| 47 | suspended_at: string | null; |
| 48 | } |
| 49 | |
| 50 | export type SetupResult = { linked: LinkedInstallation } | { redirect: string } | { choose: Array<GitHubInstallation & { proof: string; linkedTo: string | null }>; payer: Account }; |
| 51 | |
| 52 | export class GitHubRunnerLinks { |
| 53 | readonly client: GitHubAppClient | null; |
| 54 | |
| 55 | constructor( |
| 56 | private readonly env: Env, |
| 57 | private readonly dir: Directory, |
| 58 | fetcher?: typeof fetch, |
| 59 | ) { |
| 60 | const app = githubApp(env); |
| 61 | this.client = app ? new GitHubAppClient(app, fetcher) : null; |
| 62 | } |
| 63 | |
| 64 | get enabled(): boolean { |
| 65 | return !!this.client && !!this.env.GITHUB_RUNNERS; |
| 66 | } |
| 67 | |
| 68 | private gh(): GitHubAppClient { |
| 69 | if (!this.enabled) throw new HttpError(404, "GitHub runners are off: this Diffinery has no GitHub App"); |
| 70 | return this.client!; |
| 71 | } |
| 72 | |
| 73 | private get redirectUri(): string { |
| 74 | return `${this.env.PUBLIC_URL}${SETUP_PATH}`; |
| 75 | } |
| 76 | |
| 77 | private secrets(): string[] { |
| 78 | return signingSecrets(this.env, this.env.DEV_AUTH ? "dev" : null, "MASTER_KEY is not set"); |
| 79 | } |
| 80 | |
| 81 | private async mac(secret: string, payload: string): Promise<string> { |
| 82 | return b64url(await hmacSha256(secret, `github-runners:${payload}`)); |
| 83 | } |
| 84 | |
| 85 | private async sign(c: Omit<Claims, "x">): Promise<string> { |
| 86 | const payload = b64url(new TextEncoder().encode(JSON.stringify({ ...c, x: Math.floor(Date.now() / 1000) + TTL_SECONDS }))); |
| 87 | return `${payload}.${await this.mac(this.secrets()[0]!, payload)}`; |
| 88 | } |
| 89 | |
| 90 | private async open(token: string, kind: Claims["k"], me: Account): Promise<Claims> { |
| 91 | const [payload, tag] = token.split("."); |
| 92 | if (!payload || !tag || !(await matchesAnyKey(this.secrets(), tag, (s) => this.mac(s, payload)))) throw new HttpError(422, "this link to GitHub is not valid; start again from Settings → GitHub runners"); |
| 93 | const c = JSON.parse(new TextDecoder().decode(fromB64url(payload))) as Claims; |
| 94 | if (c.k !== kind || c.u !== me.id) throw new HttpError(422, "this link to GitHub was made for someone else; start again from Settings → GitHub runners"); |
| 95 | if (c.x < Date.now() / 1000) throw new HttpError(422, "this link to GitHub has expired; start again from Settings → GitHub runners"); |
| 96 | return c; |
| 97 | } |
| 98 | |
| 99 | /** The accounts a person may make pay: themselves and the organizations they own or administer. */ |
| 100 | async payers(me: Account): Promise<Account[]> { |
| 101 | const orgs = (await this.dir.orgsFor(me.id)).filter((o) => o.role === "owner" || o.role === "admin"); |
| 102 | return [me, ...orgs]; |
| 103 | } |
| 104 | |
| 105 | private async payer(me: Account, accountId: string): Promise<Account> { |
| 106 | const a = (await this.payers(me)).find((p) => p.id === accountId); |
| 107 | if (!a) throw new HttpError(403, "you can link GitHub runners only to your own account or an organization you own or administer"); |
| 108 | return a; |
| 109 | } |
| 110 | |
| 111 | /** Install on GitHub: the app's install page, with a state naming who pays. */ |
| 112 | async installUrl(me: Account, accountId: string): Promise<string> { |
| 113 | const gh = this.gh(); |
| 114 | await this.payer(me, accountId); |
| 115 | return gh.installUrl(await this.sign({ k: "state", u: me.id, a: accountId })); |
| 116 | } |
| 117 | |
| 118 | /** Link an installation that already exists: authorize the app, then pick it. */ |
| 119 | async authorizeUrl(me: Account, accountId: string): Promise<string> { |
| 120 | const gh = this.gh(); |
| 121 | await this.payer(me, accountId); |
| 122 | return gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: accountId })); |
| 123 | } |
| 124 | |
| 125 | /** |
| 126 | * GitHub sent the person back (after installing, or after authorizing the app). A code is only used with a |
| 127 | * state this person started here (signed, bound to them): one that came without, or with someone else's, |
| 128 | * could be another GitHub user's, sent to make this person pay for that user's installation. |
| 129 | */ |
| 130 | async setup(me: Account, q: { installationId: number | null; code: string | null; state: string | null }): Promise<SetupResult> { |
| 131 | const gh = this.gh(); |
| 132 | // Installed or configured from GitHub itself: authorize, then pick the installation and who pays. |
| 133 | if (!q.state) return { redirect: gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: me.id })) }; |
| 134 | const claims = await this.open(q.state, "state", me); |
| 135 | const payer = await this.payer(me, claims.a ?? me.id); |
| 136 | const installationId = claims.i ?? q.installationId ?? null; |
| 137 | if (!q.code) { |
| 138 | if (!installationId) throw new HttpError(422, "GitHub sent no installation; start again from Settings → GitHub runners"); |
| 139 | return { redirect: gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: payer.id, i: installationId })) }; |
| 140 | } |
| 141 | let mine: GitHubInstallation[]; |
| 142 | try { |
| 143 | mine = await gh.userInstallations(await gh.userToken(q.code, this.redirectUri)); |
| 144 | } catch (e) { |
| 145 | throw new HttpError(e instanceof GitHubApiError && e.status < 500 ? 422 : 502, (e as Error).message); |
| 146 | } |
| 147 | if (installationId) { |
| 148 | const inst = mine.find((i) => i.id === installationId); |
| 149 | if (!inst) throw new HttpError(403, "your GitHub account can't manage that installation of the app; ask an owner of the GitHub organization to link it"); |
| 150 | return { linked: await this.save(me, payer, inst) }; |
| 151 | } |
| 152 | const linked = new Map<number, string>(); |
| 153 | if (mine.length) { |
| 154 | const rows = await this.env.DB.prepare(`SELECT g.id, a.login FROM github_installations g JOIN accounts a ON a.id = g.account_id WHERE g.id IN (${mine.map(() => "?").join(",")})`) |
| 155 | .bind(...mine.map((i) => i.id)) |
| 156 | .all<{ id: number; login: string }>(); |
| 157 | for (const r of rows.results) linked.set(r.id, r.login); |
| 158 | } |
| 159 | const choose = await Promise.all(mine.map(async (i) => ({ ...i, linkedTo: linked.get(i.id) ?? null, proof: await this.sign({ k: "proof", u: me.id, i: i.id, login: i.login, type: i.type }) }))); |
| 160 | return { choose, payer }; |
| 161 | } |
| 162 | |
| 163 | /** Links an installation the person picked (with the proof setup made that they manage it) to an account they pick. */ |
| 164 | async linkWithProof(me: Account, proof: string, accountId: string): Promise<LinkedInstallation> { |
| 165 | this.gh(); |
| 166 | const c = await this.open(proof, "proof", me); |
| 167 | return this.save(me, await this.payer(me, accountId), { id: c.i!, login: c.login ?? "", type: c.type ?? "User" }); |
| 168 | } |
| 169 | |
| 170 | private async save(me: Account, payer: Account, inst: GitHubInstallation): Promise<LinkedInstallation> { |
| 171 | const before = await this.env.DB.prepare("SELECT account_id FROM github_installations WHERE id = ?").bind(inst.id).first<{ account_id: string }>(); |
| 172 | await this.env.DB.prepare( |
| 173 | "INSERT INTO github_installations (id, account_id, github_login, github_type, linked_by, linked_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET account_id = excluded.account_id, github_login = excluded.github_login, github_type = excluded.github_type, linked_by = excluded.linked_by, linked_at = excluded.linked_at", |
| 174 | ) |
| 175 | .bind(inst.id, payer.id, inst.login, inst.type, me.id, now()) |
| 176 | .run(); |
| 177 | await this.dir.audit({ actorId: me.id, actorLogin: me.login, action: "github_runners.link", target: payer.login, detail: { installation: inst.id, github: inst.login, ...(before && before.account_id !== payer.id ? { from: before.account_id } : {}) } }); |
| 178 | return (await this.env.DB.prepare("SELECT * FROM github_installations WHERE id = ?").bind(inst.id).first<LinkedInstallation>())!; |
| 179 | } |
| 180 | |
| 181 | /** Unlinks an installation: its queued jobs get no runner; runners already started finish their jobs. */ |
| 182 | async unlink(me: Account, installationId: number): Promise<void> { |
| 183 | const row = await this.env.DB.prepare("SELECT * FROM github_installations WHERE id = ?").bind(installationId).first<LinkedInstallation>(); |
| 184 | if (!row) throw new HttpError(404, "that installation isn't linked"); |
| 185 | const payer = await this.payer(me, row.account_id); |
| 186 | await this.env.DB.prepare("DELETE FROM github_installations WHERE id = ?").bind(installationId).run(); |
| 187 | await this.env.DB.prepare("UPDATE github_runner_jobs SET status = 'skipped', message = 'The GitHub installation was unlinked', ended_at = ? WHERE installation_id = ? AND status = 'queued'").bind(now(), installationId).run(); |
| 188 | await this.dir.audit({ actorId: me.id, actorLogin: me.login, action: "github_runners.unlink", target: payer.login, detail: { installation: installationId, github: row.github_login } }); |
| 189 | } |
| 190 | |
| 191 | /** The person's paying accounts with their linked installations and recent runner jobs, for the settings page. */ |
| 192 | async overview(me: Account, jobs = 30): Promise<Array<{ account: Account; installations: LinkedInstallation[]; jobs: RunnerJobRow[] }>> { |
| 193 | const payers = await this.payers(me); |
| 194 | return Promise.all( |
| 195 | payers.map(async (account) => { |
| 196 | const [installations, recent] = await Promise.all([ |
| 197 | this.env.DB.prepare("SELECT * FROM github_installations WHERE account_id = ? ORDER BY github_login").bind(account.id).all<LinkedInstallation>(), |
| 198 | this.env.DB.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? ORDER BY created_at DESC LIMIT ?").bind(account.id, jobs).all<RunnerJobRow>(), |
| 199 | ]); |
| 200 | return { account, installations: installations.results, jobs: recent.results }; |
| 201 | }), |
| 202 | ); |
| 203 | } |
| 204 | } |