import { SECRET_NAME, SecretBox, namespaceSecretScope, repoSecretScope, type SecretScope } from "@refs/ci"; import { cancelRun, decideJob, onPullOpened, startManualRun, type CiEnv, type RunStatus } from "@refs/ci/control"; import { now } from "../auth.ts"; import type { CiEnvironment, CiRunDetail, CiRunSummary, CiSecret, CiSettings, NamespaceSecrets, RepoCi } from "../contract/ci.ts"; import { invalid, ok, problem, raise } from "../outcomes.ts"; import type { Policy } from "../policy.ts"; import type { Namespace, RepoRecord } from "../repos.ts"; import type { Deps } from "./context.ts"; const MAX_SECRET_BYTES = 48 * 1024; const MAX_SECRETS = 100; const MAX_WAIT_SECONDS = 30 * 24 * 60 * 60; const MAX_PATTERNS = 50; const ENVIRONMENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/i; const PATTERN = /^[^\s~^:?\\[]{1,200}$/; const RUN_LIMIT = 50; type RunRow = { id: string; sha: string; ref: string; trigger: CiRunSummary["trigger"]; pull_number: number | null; state: CiRunSummary["state"]; trust: "trusted" | "untrusted"; trust_reason: string; actor_kind: CiRunSummary["actor"]["kind"]; actor_name: string | null; superseded_by: string | null; created_at: number; ended_at: number | null; }; const SELECT_RUN = "SELECT r.*, u.name AS actor_name FROM ci_runs r LEFT JOIN users u ON u.id = r.actor_id"; function seconds(ms: number | null): number | null { return ms === null ? null : Math.floor(ms / 1000); } function toSummary(row: RunRow): CiRunSummary { return { id: row.id, sha: row.sha, branch: row.ref.replace(/^refs\/heads\//, ""), trigger: row.trigger, pull: row.pull_number, state: row.state, trusted: row.trust === "trusted", trustReason: row.trust_reason, actor: { kind: row.actor_kind, name: row.actor_name }, supersededBy: row.superseded_by, createdAt: seconds(row.created_at)!, endedAt: seconds(row.ended_at), }; } function ciEnv(env: Env): CiEnv { return env as unknown as CiEnv; } /** Starts the pull request run of a newly opened pull request, after the response. A CI failure never fails the open. */ export function startPullCi(deps: Deps, policy: Policy, record: RepoRecord, pull: { readonly number: number; readonly base: string; readonly head: string; readonly sha: string }): void { 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 }); deps.ctx.waitUntil(started.catch((error: unknown) => console.error(`CI start failed for pull ${pull.number} in repo ${record.id}`, error))); } export function openRepoCi(env: Env, policy: Policy, record: RepoRecord): RepoCi { const db = env.DB; const writer = policy.canWriteRepo({ name: record.full_name, visibility: record.visibility, creatorId: record.creator_id }); const person = policy.person; const canApprove = writer && policy.actor.kind === "human"; async function runRow(id: string): Promise { const row = await db.prepare(`${SELECT_RUN} WHERE r.id = ? AND r.repo_id = ?`).bind(id, record.id).first(); return row ?? raise("not_found", `No run ${id} in ${record.full_name}.`); } return { canRun: writer, canApprove, async runs(query = {}) { const limit = Math.min(Math.max(query.limit ?? RUN_LIMIT, 1), RUN_LIMIT); const statement = db .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`) .bind(record.id, query.pull ?? null, query.sha ?? null, limit); return (await statement.all()).results.map(toSummary); }, async run(id) { const row = await runRow(id); const status: RunStatus = await env.RUN_HUB.getByName(id).status().catch(() => raise("not_found", `The record of run ${id} is gone.`)); const detail: CiRunDetail = { ...toSummary(row), state: status.state, 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) })), }; return detail; }, async logs(id, job) { await runRow(id); return env.RUN_HUB.getByName(id).logs(job); }, async events(id) { await runRow(id); return env.RUN_HUB.getByName(id).fetch(new Request("https://run-hub/events")); }, async start(branch) { if (!writer || !person) return invalid("Only people and agents with write access can start a run."); 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"); switch (result.kind) { case "started": case "exists": return ok({ runId: result.runId }); case "no_branch": return invalid(`No branch named "${branch}".`, "branch"); case "no_config": return invalid(`${branch} has no .refs/ci.yml.`, "branch"); case "invalid": return invalid(`.refs/ci.yml on ${branch} has problems: ${result.problems.map((found) => `${found.path ? `${found.path}: ` : ""}${found.message}`).join(" ")}`, "branch"); case "not_triggered": return invalid(result.reason, "branch"); } }, async decide(id, job, decision) { if (!canApprove || !person) return invalid("Only a person with write access can approve or reject a job."); await runRow(id); return (await decideJob(ciEnv(env), id, job, decision, person)) ? ok() : invalid(`${job} is not waiting for approval.`); }, async cancel(id) { if (!writer) return invalid("Only people and agents with write access can cancel a run."); const row = await runRow(id); if (row.ended_at !== null) return ok(); await cancelRun(ciEnv(env), id, `${person?.name ?? "Someone"} cancelled the run.`); return ok(); }, }; } async function sealer(env: Env): Promise { const key = ciEnv(env).CI_SECRETS_KEY; return key ? SecretBox.fromBase64(key) : null; } const NO_KEY = problem("unavailable", "CI secrets are not set up on this server yet. Ask the operator to set CI_SECRETS_KEY."); function secretError(name: string, value: string): string | undefined { if (!SECRET_NAME.test(name)) return "Use capital letters, digits and _, and do not start with a digit."; if (name.startsWith("REFS_") || name === "CI" || name === "PATH" || name === "HOME") return `${name} is a name that refs sets itself. Choose another name.`; if (!value) return "Enter a value."; if (new TextEncoder().encode(value).length > MAX_SECRET_BYTES) return `A secret is at most ${MAX_SECRET_BYTES / 1024} KB.`; return undefined; } async function sealedValues(env: Env, value: string, scope: SecretScope): Promise<{ ciphertext: string; wrappedKey: string } | null> { const box = await sealer(env); return box && box.seal(value, scope); } function patternsError(patterns: readonly string[]): string | undefined { if (patterns.length > MAX_PATTERNS) return `Use at most ${MAX_PATTERNS} branch patterns.`; const bad = patterns.find((pattern) => !PATTERN.test(pattern)); return bad === undefined ? undefined : `"${bad}" is not a branch pattern. Use a branch name, with * for one segment and ** for many.`; } export function openCiSettings(env: Env, policy: Policy, record: RepoRecord): CiSettings { const db = env.DB; const human = () => { if (policy.actor.kind !== "human") raise("not_found", "Only people can change CI settings."); }; const person = () => policy.person!.id; const environmentExists = (name: string) => db.prepare("SELECT 1 FROM ci_environments WHERE repo_id = ? AND name = ?").bind(record.id, name).first(); return { async secrets() { const { results } = await db .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") .bind(record.id) .all<{ name: string; environment: string; updated_at: number; updated_by: string }>(); return results.map((row): CiSecret => ({ name: row.name, environment: row.environment || null, updatedAt: row.updated_at, updatedBy: row.updated_by })); }, async setSecret({ name, value, environment }) { human(); const trimmed = name.trim().toUpperCase(); const problemText = secretError(trimmed, value); if (problemText) return invalid(problemText, problemText === "Enter a value." || problemText.startsWith("A secret is") ? "value" : "name"); if (environment !== null && !(await environmentExists(environment))) return invalid(`No environment named "${environment}".`, "environment"); 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("n"); if ((count ?? 0) >= MAX_SECRETS) return invalid(`A repository has at most ${MAX_SECRETS} secrets.`, "name"); const sealed = await sealedValues(env, value, repoSecretScope(record.id, environment, trimmed)); if (!sealed) return NO_KEY; await db .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") .bind(record.id, environment ?? "", trimmed, sealed.ciphertext, sealed.wrappedKey, person(), now()) .run(); return ok(); }, async deleteSecret(name, environment) { human(); await db.prepare("DELETE FROM ci_secrets WHERE repo_id = ? AND environment = ? AND name = ?").bind(record.id, environment ?? "", name).run(); return ok(); }, async environments() { const { results } = await db .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") .bind(record.id) .all<{ name: string; requires_approval: number; wait_seconds: number; branches: string }>(); return results.map((row): CiEnvironment => ({ name: row.name, requiresApproval: row.requires_approval === 1, waitSeconds: row.wait_seconds, branches: JSON.parse(row.branches) as string[] })); }, async saveEnvironment(input) { human(); const name = input.name.trim(); if (!ENVIRONMENT_NAME.test(name)) return invalid("An environment name uses letters, digits, - and _, and is at most 64 characters.", "name"); 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"); const branches = [...new Set(input.branches.map((pattern) => pattern.trim()).filter(Boolean))]; const branchProblem = patternsError(branches); if (branchProblem) return invalid(branchProblem, "branches"); await db.batch([ 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()), db.prepare("DELETE FROM ci_environment_branches WHERE repo_id = ? AND environment = ?").bind(record.id, name), ...branches.map((pattern) => db.prepare("INSERT INTO ci_environment_branches (repo_id, environment, pattern) VALUES (?, ?, ?)").bind(record.id, name, pattern)), ]); return ok(); }, async deleteEnvironment(name) { human(); await db.batch([ db.prepare("DELETE FROM ci_secrets WHERE repo_id = ? AND environment = ?").bind(record.id, name), db.prepare("DELETE FROM ci_environment_branches WHERE repo_id = ? AND environment = ?").bind(record.id, name), db.prepare("DELETE FROM ci_environments WHERE repo_id = ? AND name = ?").bind(record.id, name), ]); return ok(); }, async protectedBranches() { const { results } = await db.prepare("SELECT pattern FROM ci_protected_branches WHERE repo_id = ? ORDER BY pattern").bind(record.id).all<{ pattern: string }>(); return results.map((row) => row.pattern); }, async setProtectedBranches(patterns) { human(); const cleaned = [...new Set(patterns.map((pattern) => pattern.trim()).filter(Boolean))]; const patternProblem = patternsError(cleaned); if (patternProblem) return invalid(patternProblem, "patterns"); 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))]); return ok(); }, }; } export function openNamespaceSecrets(env: Env, policy: Policy, namespace: Namespace): NamespaceSecrets { const db = env.DB; return { namespace: namespace.slug, async list() { const { results } = await db .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") .bind(namespace.id) .all<{ name: string; updated_at: number; updated_by: string }>(); return results.map((row): CiSecret => ({ name: row.name, environment: null, updatedAt: row.updated_at, updatedBy: row.updated_by })); }, async setSecret({ name, value }) { const trimmed = name.trim().toUpperCase(); const problemText = secretError(trimmed, value); if (problemText) return invalid(problemText, problemText === "Enter a value." || problemText.startsWith("A secret is") ? "value" : "name"); const count = await db.prepare("SELECT count(*) AS n FROM ci_namespace_secrets WHERE namespace_id = ? AND name != ?").bind(namespace.id, trimmed).first("n"); if ((count ?? 0) >= MAX_SECRETS) return invalid(`A namespace has at most ${MAX_SECRETS} secrets.`, "name"); const sealed = await sealedValues(env, value, namespaceSecretScope(namespace.id, trimmed)); if (!sealed) return NO_KEY; await db .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") .bind(namespace.id, trimmed, sealed.ciphertext, sealed.wrappedKey, policy.person!.id, now()) .run(); return ok(); }, async deleteSecret(name) { await db.prepare("DELETE FROM ci_namespace_secrets WHERE namespace_id = ? AND name = ?").bind(namespace.id, name).run(); return ok(); }, }; }