import { env } from "cloudflare:workers"; import { batch, first, run, stmt } from "../db"; import { randomToken, sha256Hex } from "../crypto"; import { credentialFromRequest } from "../auth"; import { publicUrl } from "../events/emit"; import { allows, restrictPermissions } from "./permissions"; import type { TokenPermissions } from "./permissions"; import { isUntrustedRun } from "./jobs"; import type { JobExecution } from "./jobs"; import type { Permission } from "~/lib/types"; export const JOB_TOKEN_PREFIX = "gitfor_job"; const TOKEN_GRACE_MS = 10 * 60 * 1000; const MARKER_TTL_MS = 24 * 60 * 60 * 1000; export type JobTokenRow = { token_hash: string; job_id: string; repo_id: string; permissions: string; expires_at: number; }; export type JobTokenAccess = { jobId: string; repoId: string; permissions: TokenPermissions }; /** Mints the job's `GITHUB_TOKEN` equivalent; it is revoked when the job completes and expires after its timeout. */ export async function mintJobToken(execution: JobExecution): Promise { const token = randomToken(JOB_TOKEN_PREFIX); const forked = isUntrustedRun(execution); const permissions = forked ? restrictPermissions(execution.spec.permissions) : execution.spec.permissions; await run( "INSERT INTO job_tokens (token_hash, job_id, repo_id, permissions, expires_at) VALUES (?, ?, ?, ?, ?)", await sha256Hex(token), execution.job.id, execution.repo.id, JSON.stringify(permissions), Date.now() + execution.spec.timeoutMinutes * 60 * 1000 + TOKEN_GRACE_MS, ); return token; } export async function jobTokenAccess(request: Request): Promise { const credential = credentialFromRequest(request); if (!credential?.startsWith(`${JOB_TOKEN_PREFIX}_`)) return null; const row = await first("SELECT * FROM job_tokens WHERE token_hash = ?", await sha256Hex(credential)); if (!row || row.expires_at < Date.now()) return null; return { jobId: row.job_id, repoId: row.repo_id, permissions: JSON.parse(row.permissions) }; } /** Repository permission a job token grants for git and the API: only on its own repo, via `contents`. */ export function jobTokenRepoPermission(access: JobTokenAccess, repoId: string): Permission { if (access.repoId !== repoId) return "none"; if (allows(access.permissions, "contents", "write")) return "write"; return allows(access.permissions, "contents", "read") ? "read" : "none"; } /** Environment for a job's runner process: forge API endpoint, job token and the OIDC request pair. */ export function jobTokenEnv(token: string, permissions: TokenPermissions): Record { const vars: Record = { GITFOR_API_URL: env.PUBLIC_URL.replace(/\/$/, ""), GITFOR_JOB_TOKEN: token }; if (allows(permissions, "id-token", "write")) { vars.ACTIONS_ID_TOKEN_REQUEST_URL = publicUrl("/api/actions/oidc/token?api-version=1"); vars.ACTIONS_ID_TOKEN_REQUEST_TOKEN = token; } return vars; } /** Pushes made with a job token don't trigger workflows (as on GitHub), which prevents CI feedback loops. */ export async function markJobTokenPush(repoId: string, shas: string[]): Promise { const now = Date.now(); await batch( shas.map((sha) => stmt("INSERT OR IGNORE INTO job_token_pushes (repo_id, sha, created_at) VALUES (?, ?, ?)", repoId, sha, now), ), ); } export async function isJobTokenPush(repoId: string, sha: string): Promise { return (await first("SELECT 1 AS ok FROM job_token_pushes WHERE repo_id = ? AND sha = ?", repoId, sha)) !== null; } export async function purgeExpiredJobTokens(): Promise { const now = Date.now(); await run("DELETE FROM job_tokens WHERE expires_at < ?", now); await run("DELETE FROM job_token_pushes WHERE created_at < ?", now - MARKER_TTL_MS); await run("DELETE FROM workflow_event_receipts WHERE created_at < ?", now - MARKER_TTL_MS); }