294 lines · 15.2 KBRaw
| 1 | import { SECRET_NAME, SecretBox, namespaceSecretScope, repoSecretScope, type SecretScope } from "@refs/ci"; |
| 2 | import { cancelRun, decideJob, onPullOpened, startManualRun, type CiEnv, type RunStatus } from "@refs/ci/control"; |
| 3 | import { now } from "../auth.ts"; |
| 4 | import type { CiEnvironment, CiRunDetail, CiRunSummary, CiSecret, CiSettings, NamespaceSecrets, RepoCi } from "../contract/ci.ts"; |
| 5 | import { invalid, ok, problem, raise } from "../outcomes.ts"; |
| 6 | import type { Policy } from "../policy.ts"; |
| 7 | import type { Namespace, RepoRecord } from "../repos.ts"; |
| 8 | import type { Deps } from "./context.ts"; |
| 9 | |
| 10 | const MAX_SECRET_BYTES = 48 * 1024; |
| 11 | const MAX_SECRETS = 100; |
| 12 | const MAX_WAIT_SECONDS = 30 * 24 * 60 * 60; |
| 13 | const MAX_PATTERNS = 50; |
| 14 | const ENVIRONMENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/i; |
| 15 | const PATTERN = /^[^\s~^:?\\[]{1,200}$/; |
| 16 | const RUN_LIMIT = 50; |
| 17 | |
| 18 | type RunRow = { |
| 19 | id: string; |
| 20 | sha: string; |
| 21 | ref: string; |
| 22 | trigger: CiRunSummary["trigger"]; |
| 23 | pull_number: number | null; |
| 24 | state: CiRunSummary["state"]; |
| 25 | trust: "trusted" | "untrusted"; |
| 26 | trust_reason: string; |
| 27 | actor_kind: CiRunSummary["actor"]["kind"]; |
| 28 | actor_name: string | null; |
| 29 | superseded_by: string | null; |
| 30 | created_at: number; |
| 31 | ended_at: number | null; |
| 32 | }; |
| 33 | |
| 34 | const SELECT_RUN = "SELECT r.*, u.name AS actor_name FROM ci_runs r LEFT JOIN users u ON u.id = r.actor_id"; |
| 35 | |
| 36 | function seconds(ms: number | null): number | null { |
| 37 | return ms === null ? null : Math.floor(ms / 1000); |
| 38 | } |
| 39 | |
| 40 | function toSummary(row: RunRow): CiRunSummary { |
| 41 | return { |
| 42 | id: row.id, |
| 43 | sha: row.sha, |
| 44 | branch: row.ref.replace(/^refs\/heads\//, ""), |
| 45 | trigger: row.trigger, |
| 46 | pull: row.pull_number, |
| 47 | state: row.state, |
| 48 | trusted: row.trust === "trusted", |
| 49 | trustReason: row.trust_reason, |
| 50 | actor: { kind: row.actor_kind, name: row.actor_name }, |
| 51 | supersededBy: row.superseded_by, |
| 52 | createdAt: seconds(row.created_at)!, |
| 53 | endedAt: seconds(row.ended_at), |
| 54 | }; |
| 55 | } |
| 56 | |
| 57 | function ciEnv(env: Env): CiEnv { |
| 58 | return env as unknown as CiEnv; |
| 59 | } |
| 60 | |
| 61 | /** Starts the pull request run of a newly opened pull request, after the response. A CI failure never fails the open. */ |
| 62 | export function startPullCi(deps: Deps, policy: Policy, record: RepoRecord, pull: { readonly number: number; readonly base: string; readonly head: string; readonly sha: string }): void { |
| 63 | const started = onPullOpened(ciEnv(deps.env), { repoId: record.id, namespaceId: record.namespace_id, repo: record.artifacts_name, ...pull, author: policy.actor.kind === "agent" ? "agent" : "human", actorId: policy.person?.id ?? null }); |
| 64 | deps.ctx.waitUntil(started.catch((error: unknown) => console.error(`CI start failed for pull ${pull.number} in repo ${record.id}`, error))); |
| 65 | } |
| 66 | |
| 67 | export function openRepoCi(env: Env, policy: Policy, record: RepoRecord): RepoCi { |
| 68 | const db = env.DB; |
| 69 | const writer = policy.canWriteRepo({ name: record.full_name, visibility: record.visibility, creatorId: record.creator_id }); |
| 70 | const person = policy.person; |
| 71 | const canApprove = writer && policy.actor.kind === "human"; |
| 72 | |
| 73 | async function runRow(id: string): Promise<RunRow> { |
| 74 | const row = await db.prepare(`${SELECT_RUN} WHERE r.id = ? AND r.repo_id = ?`).bind(id, record.id).first<RunRow>(); |
| 75 | return row ?? raise("not_found", `No run ${id} in ${record.full_name}.`); |
| 76 | } |
| 77 | |
| 78 | return { |
| 79 | canRun: writer, |
| 80 | canApprove, |
| 81 | |
| 82 | async runs(query = {}) { |
| 83 | const limit = Math.min(Math.max(query.limit ?? RUN_LIMIT, 1), RUN_LIMIT); |
| 84 | const statement = db |
| 85 | .prepare(`${SELECT_RUN} WHERE r.repo_id = ?1 AND (?2 IS NULL OR r.pull_number = ?2) AND (?3 IS NULL OR r.sha = ?3) ORDER BY r.created_at DESC LIMIT ?4`) |
| 86 | .bind(record.id, query.pull ?? null, query.sha ?? null, limit); |
| 87 | return (await statement.all<RunRow>()).results.map(toSummary); |
| 88 | }, |
| 89 | |
| 90 | async run(id) { |
| 91 | const row = await runRow(id); |
| 92 | const status: RunStatus = await env.RUN_HUB.getByName(id).status().catch(() => raise("not_found", `The record of run ${id} is gone.`)); |
| 93 | const detail: CiRunDetail = { |
| 94 | ...toSummary(row), |
| 95 | state: status.state, |
| 96 | jobs: status.jobs.map((job) => ({ name: job.name, state: job.state, reason: job.reason, environment: job.environment, image: job.image, steps: job.steps, exitCode: job.exitCode, failedStep: job.failedStep, startedAt: seconds(job.startedAt), endedAt: seconds(job.endedAt) })), |
| 97 | }; |
| 98 | return detail; |
| 99 | }, |
| 100 | |
| 101 | async logs(id, job) { |
| 102 | await runRow(id); |
| 103 | return env.RUN_HUB.getByName(id).logs(job); |
| 104 | }, |
| 105 | |
| 106 | async events(id) { |
| 107 | await runRow(id); |
| 108 | return env.RUN_HUB.getByName(id).fetch(new Request("https://run-hub/events")); |
| 109 | }, |
| 110 | |
| 111 | async start(branch) { |
| 112 | if (!writer || !person) return invalid("Only people and agents with write access can start a run."); |
| 113 | const result = await startManualRun(ciEnv(env), { repoId: record.id, namespaceId: record.namespace_id, repo: record.artifacts_name }, branch, person.id, policy.actor.kind === "human" ? "human" : "agent"); |
| 114 | switch (result.kind) { |
| 115 | case "started": |
| 116 | case "exists": |
| 117 | return ok({ runId: result.runId }); |
| 118 | case "no_branch": |
| 119 | return invalid(`No branch named "${branch}".`, "branch"); |
| 120 | case "no_config": |
| 121 | return invalid(`${branch} has no .refs/ci.yml.`, "branch"); |
| 122 | case "invalid": |
| 123 | return invalid(`.refs/ci.yml on ${branch} has problems: ${result.problems.map((found) => `${found.path ? `${found.path}: ` : ""}${found.message}`).join(" ")}`, "branch"); |
| 124 | case "not_triggered": |
| 125 | return invalid(result.reason, "branch"); |
| 126 | } |
| 127 | }, |
| 128 | |
| 129 | async decide(id, job, decision) { |
| 130 | if (!canApprove || !person) return invalid("Only a person with write access can approve or reject a job."); |
| 131 | await runRow(id); |
| 132 | return (await decideJob(ciEnv(env), id, job, decision, person)) ? ok() : invalid(`${job} is not waiting for approval.`); |
| 133 | }, |
| 134 | |
| 135 | async cancel(id) { |
| 136 | if (!writer) return invalid("Only people and agents with write access can cancel a run."); |
| 137 | const row = await runRow(id); |
| 138 | if (row.ended_at !== null) return ok(); |
| 139 | await cancelRun(ciEnv(env), id, `${person?.name ?? "Someone"} cancelled the run.`); |
| 140 | return ok(); |
| 141 | }, |
| 142 | }; |
| 143 | } |
| 144 | |
| 145 | async function sealer(env: Env): Promise<SecretBox | null> { |
| 146 | const key = ciEnv(env).CI_SECRETS_KEY; |
| 147 | return key ? SecretBox.fromBase64(key) : null; |
| 148 | } |
| 149 | |
| 150 | const NO_KEY = problem("unavailable", "CI secrets are not set up on this server yet. Ask the operator to set CI_SECRETS_KEY."); |
| 151 | |
| 152 | function secretError(name: string, value: string): string | undefined { |
| 153 | if (!SECRET_NAME.test(name)) return "Use capital letters, digits and _, and do not start with a digit."; |
| 154 | if (name.startsWith("REFS_") || name === "CI" || name === "PATH" || name === "HOME") return `${name} is a name that refs sets itself. Choose another name.`; |
| 155 | if (!value) return "Enter a value."; |
| 156 | if (new TextEncoder().encode(value).length > MAX_SECRET_BYTES) return `A secret is at most ${MAX_SECRET_BYTES / 1024} KB.`; |
| 157 | return undefined; |
| 158 | } |
| 159 | |
| 160 | async function sealedValues(env: Env, value: string, scope: SecretScope): Promise<{ ciphertext: string; wrappedKey: string } | null> { |
| 161 | const box = await sealer(env); |
| 162 | return box && box.seal(value, scope); |
| 163 | } |
| 164 | |
| 165 | function patternsError(patterns: readonly string[]): string | undefined { |
| 166 | if (patterns.length > MAX_PATTERNS) return `Use at most ${MAX_PATTERNS} branch patterns.`; |
| 167 | const bad = patterns.find((pattern) => !PATTERN.test(pattern)); |
| 168 | return bad === undefined ? undefined : `"${bad}" is not a branch pattern. Use a branch name, with * for one segment and ** for many.`; |
| 169 | } |
| 170 | |
| 171 | export function openCiSettings(env: Env, policy: Policy, record: RepoRecord): CiSettings { |
| 172 | const db = env.DB; |
| 173 | const human = () => { |
| 174 | if (policy.actor.kind !== "human") raise("not_found", "Only people can change CI settings."); |
| 175 | }; |
| 176 | const person = () => policy.person!.id; |
| 177 | const environmentExists = (name: string) => db.prepare("SELECT 1 FROM ci_environments WHERE repo_id = ? AND name = ?").bind(record.id, name).first(); |
| 178 | |
| 179 | return { |
| 180 | async secrets() { |
| 181 | const { results } = await db |
| 182 | .prepare("SELECT s.name, s.environment, s.updated_at, coalesce(u.name, 'someone') AS updated_by FROM ci_secrets s LEFT JOIN users u ON u.id = s.updated_by WHERE s.repo_id = ? ORDER BY s.environment, s.name") |
| 183 | .bind(record.id) |
| 184 | .all<{ name: string; environment: string; updated_at: number; updated_by: string }>(); |
| 185 | return results.map((row): CiSecret => ({ name: row.name, environment: row.environment || null, updatedAt: row.updated_at, updatedBy: row.updated_by })); |
| 186 | }, |
| 187 | |
| 188 | async setSecret({ name, value, environment }) { |
| 189 | human(); |
| 190 | const trimmed = name.trim().toUpperCase(); |
| 191 | const problemText = secretError(trimmed, value); |
| 192 | if (problemText) return invalid(problemText, problemText === "Enter a value." || problemText.startsWith("A secret is") ? "value" : "name"); |
| 193 | if (environment !== null && !(await environmentExists(environment))) return invalid(`No environment named "${environment}".`, "environment"); |
| 194 | const count = await db.prepare("SELECT count(*) AS n FROM ci_secrets WHERE repo_id = ? AND NOT (environment = ? AND name = ?)").bind(record.id, environment ?? "", trimmed).first<number>("n"); |
| 195 | if ((count ?? 0) >= MAX_SECRETS) return invalid(`A repository has at most ${MAX_SECRETS} secrets.`, "name"); |
| 196 | const sealed = await sealedValues(env, value, repoSecretScope(record.id, environment, trimmed)); |
| 197 | if (!sealed) return NO_KEY; |
| 198 | await db |
| 199 | .prepare("INSERT INTO ci_secrets (repo_id, environment, name, ciphertext, wrapped_key, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (repo_id, environment, name) DO UPDATE SET ciphertext = excluded.ciphertext, wrapped_key = excluded.wrapped_key, updated_by = excluded.updated_by, updated_at = excluded.updated_at") |
| 200 | .bind(record.id, environment ?? "", trimmed, sealed.ciphertext, sealed.wrappedKey, person(), now()) |
| 201 | .run(); |
| 202 | return ok(); |
| 203 | }, |
| 204 | |
| 205 | async deleteSecret(name, environment) { |
| 206 | human(); |
| 207 | await db.prepare("DELETE FROM ci_secrets WHERE repo_id = ? AND environment = ? AND name = ?").bind(record.id, environment ?? "", name).run(); |
| 208 | return ok(); |
| 209 | }, |
| 210 | |
| 211 | async environments() { |
| 212 | const { results } = await db |
| 213 | .prepare("SELECT e.name, e.requires_approval, e.wait_seconds, (SELECT json_group_array(pattern) FROM ci_environment_branches b WHERE b.repo_id = e.repo_id AND b.environment = e.name) AS branches FROM ci_environments e WHERE e.repo_id = ? ORDER BY e.name") |
| 214 | .bind(record.id) |
| 215 | .all<{ name: string; requires_approval: number; wait_seconds: number; branches: string }>(); |
| 216 | return results.map((row): CiEnvironment => ({ name: row.name, requiresApproval: row.requires_approval === 1, waitSeconds: row.wait_seconds, branches: JSON.parse(row.branches) as string[] })); |
| 217 | }, |
| 218 | |
| 219 | async saveEnvironment(input) { |
| 220 | human(); |
| 221 | const name = input.name.trim(); |
| 222 | if (!ENVIRONMENT_NAME.test(name)) return invalid("An environment name uses letters, digits, - and _, and is at most 64 characters.", "name"); |
| 223 | if (!Number.isInteger(input.waitSeconds) || input.waitSeconds < 0 || input.waitSeconds > MAX_WAIT_SECONDS) return invalid("The wait is a whole number of minutes, at most 30 days.", "wait"); |
| 224 | const branches = [...new Set(input.branches.map((pattern) => pattern.trim()).filter(Boolean))]; |
| 225 | const branchProblem = patternsError(branches); |
| 226 | if (branchProblem) return invalid(branchProblem, "branches"); |
| 227 | await db.batch([ |
| 228 | db.prepare("INSERT INTO ci_environments (repo_id, name, requires_approval, wait_seconds, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (repo_id, name) DO UPDATE SET requires_approval = excluded.requires_approval, wait_seconds = excluded.wait_seconds").bind(record.id, name, input.requiresApproval ? 1 : 0, input.waitSeconds, now()), |
| 229 | db.prepare("DELETE FROM ci_environment_branches WHERE repo_id = ? AND environment = ?").bind(record.id, name), |
| 230 | ...branches.map((pattern) => db.prepare("INSERT INTO ci_environment_branches (repo_id, environment, pattern) VALUES (?, ?, ?)").bind(record.id, name, pattern)), |
| 231 | ]); |
| 232 | return ok(); |
| 233 | }, |
| 234 | |
| 235 | async deleteEnvironment(name) { |
| 236 | human(); |
| 237 | await db.batch([ |
| 238 | db.prepare("DELETE FROM ci_secrets WHERE repo_id = ? AND environment = ?").bind(record.id, name), |
| 239 | db.prepare("DELETE FROM ci_environment_branches WHERE repo_id = ? AND environment = ?").bind(record.id, name), |
| 240 | db.prepare("DELETE FROM ci_environments WHERE repo_id = ? AND name = ?").bind(record.id, name), |
| 241 | ]); |
| 242 | return ok(); |
| 243 | }, |
| 244 | |
| 245 | async protectedBranches() { |
| 246 | const { results } = await db.prepare("SELECT pattern FROM ci_protected_branches WHERE repo_id = ? ORDER BY pattern").bind(record.id).all<{ pattern: string }>(); |
| 247 | return results.map((row) => row.pattern); |
| 248 | }, |
| 249 | |
| 250 | async setProtectedBranches(patterns) { |
| 251 | human(); |
| 252 | const cleaned = [...new Set(patterns.map((pattern) => pattern.trim()).filter(Boolean))]; |
| 253 | const patternProblem = patternsError(cleaned); |
| 254 | if (patternProblem) return invalid(patternProblem, "patterns"); |
| 255 | await db.batch([db.prepare("DELETE FROM ci_protected_branches WHERE repo_id = ?").bind(record.id), ...cleaned.map((pattern) => db.prepare("INSERT INTO ci_protected_branches (repo_id, pattern) VALUES (?, ?)").bind(record.id, pattern))]); |
| 256 | return ok(); |
| 257 | }, |
| 258 | }; |
| 259 | } |
| 260 | |
| 261 | export function openNamespaceSecrets(env: Env, policy: Policy, namespace: Namespace): NamespaceSecrets { |
| 262 | const db = env.DB; |
| 263 | return { |
| 264 | namespace: namespace.slug, |
| 265 | |
| 266 | async list() { |
| 267 | const { results } = await db |
| 268 | .prepare("SELECT s.name, s.updated_at, coalesce(u.name, 'someone') AS updated_by FROM ci_namespace_secrets s LEFT JOIN users u ON u.id = s.updated_by WHERE s.namespace_id = ? ORDER BY s.name") |
| 269 | .bind(namespace.id) |
| 270 | .all<{ name: string; updated_at: number; updated_by: string }>(); |
| 271 | return results.map((row): CiSecret => ({ name: row.name, environment: null, updatedAt: row.updated_at, updatedBy: row.updated_by })); |
| 272 | }, |
| 273 | |
| 274 | async setSecret({ name, value }) { |
| 275 | const trimmed = name.trim().toUpperCase(); |
| 276 | const problemText = secretError(trimmed, value); |
| 277 | if (problemText) return invalid(problemText, problemText === "Enter a value." || problemText.startsWith("A secret is") ? "value" : "name"); |
| 278 | const count = await db.prepare("SELECT count(*) AS n FROM ci_namespace_secrets WHERE namespace_id = ? AND name != ?").bind(namespace.id, trimmed).first<number>("n"); |
| 279 | if ((count ?? 0) >= MAX_SECRETS) return invalid(`A namespace has at most ${MAX_SECRETS} secrets.`, "name"); |
| 280 | const sealed = await sealedValues(env, value, namespaceSecretScope(namespace.id, trimmed)); |
| 281 | if (!sealed) return NO_KEY; |
| 282 | await db |
| 283 | .prepare("INSERT INTO ci_namespace_secrets (namespace_id, name, ciphertext, wrapped_key, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (namespace_id, name) DO UPDATE SET ciphertext = excluded.ciphertext, wrapped_key = excluded.wrapped_key, updated_by = excluded.updated_by, updated_at = excluded.updated_at") |
| 284 | .bind(namespace.id, trimmed, sealed.ciphertext, sealed.wrappedKey, policy.person!.id, now()) |
| 285 | .run(); |
| 286 | return ok(); |
| 287 | }, |
| 288 | |
| 289 | async deleteSecret(name) { |
| 290 | await db.prepare("DELETE FROM ci_namespace_secrets WHERE namespace_id = ? AND name = ?").bind(namespace.id, name).run(); |
| 291 | return ok(); |
| 292 | }, |
| 293 | }; |
| 294 | } |