// Mock Gitea for tests: the API endpoints Peppa uses plus OAuth token exchange. Repos are // local bare git repositories, so clone/push against `clone_url` really works. // CI (PEP-57): pull requests, commit statuses, Actions secrets, runner tokens, webhooks // (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags. import { execFileSync } from "node:child_process"; import { createHmac } from "node:crypto"; import { mkdirSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { join } from "node:path"; interface MockRepo { id: number; owner: string; name: string; path: string; collaborators: Record; admins: Set; private: boolean; pulls: MockPull[]; statuses: Map>; secrets: Record; hooks: Array<{ id: number; url: string; secret: string; events: string[] }>; tags: Array<{ name: string; target: string }>; } export interface MockPull { number: number; head: string; base: string; title: string; body: string; state: "open" | "closed"; merged: boolean; mergeable: boolean; } export interface MockGiteaUser { id: number; login: string; token: string; orgs?: string[]; } export class MockGitea { readonly repos = new Map(); readonly users = new Map(); readonly oauthCodes = new Map(); // code → token readonly runnerTokens: Array<{ scope: string; token: string }> = []; private seq = 1; private server: Server | null = null; url = ""; private readonly dir: string; constructor(dir: string) { this.dir = dir; mkdirSync(dir, { recursive: true }); } async start(): Promise { this.server = createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { let r: { status: number; body?: unknown }; try { r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); } catch (e) { r = { status: 422, body: { message: `mock-gitea: ${(e as Error).message.split("\n")[0]}` } }; } res.writeHead(r.status, { "Content-Type": "application/json" }); res.end(r.body === undefined ? "" : JSON.stringify(r.body)); }); }); await new Promise((r) => this.server!.listen(0, "127.0.0.1", r)); this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; return this; } stop() { return new Promise((r) => this.server?.close(() => r()) ?? r()); } addUser(u: MockGiteaUser) { this.users.set(u.token, u); return u; } /** Creates a bare repo, optionally with an initial commit of `files`. */ addRepo(owner: string, name: string, opts: { admins?: string[]; files?: Record; private?: boolean } = {}): MockRepo { const path = join(this.dir, `${owner}-${name}-${this.seq}.git`); execFileSync("git", ["init", "-q", "--bare", "-b", "main", path]); if (opts.files) { const work = `${path}-work`; execFileSync("git", ["init", "-q", "-b", "main", work]); for (const [f, text] of Object.entries(opts.files)) { mkdirSync(join(work, f, ".."), { recursive: true }); execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text }); } execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm init && git push -q ${JSON.stringify(path)} main`]); } const repo: MockRepo = { id: this.seq++, owner, name, path, collaborators: {}, admins: new Set(opts.admins ?? [owner]), pulls: [], statuses: new Map(), secrets: {}, hooks: [], tags: [], private: opts.private ?? true, }; this.repos.set(`${owner}/${name}`, repo); return repo; } /** Files on the default branch of a repo (empty if no commits). */ files(owner: string, name: string): string[] { const r = this.repos.get(`${owner}/${name}`); if (!r || this.isEmpty(r)) return []; return execFileSync("git", ["--git-dir", r.path, "ls-tree", "-r", "--name-only", "main"], { encoding: "utf8" }).trim().split("\n"); } show(owner: string, name: string, file: string): string { const r = this.repos.get(`${owner}/${name}`)!; return execFileSync("git", ["--git-dir", r.path, "show", `main:${file}`], { encoding: "utf8" }); } repo(owner: string, name: string): MockRepo { const r = this.repos.get(`${owner}/${name}`); if (!r) throw new Error(`mock-gitea: no repo ${owner}/${name}`); return r; } /** SHA of a branch (or any rev) in the repo. */ sha(owner: string, name: string, rev: string): string { return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "rev-parse", rev], { encoding: "utf8" }).trim(); } /** Files on any rev. */ filesAt(owner: string, name: string, rev: string): string[] { return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "ls-tree", "-r", "--name-only", rev], { encoding: "utf8" }).trim().split("\n"); } /** Pushes `files` as a new commit on `branch` (created from main if missing); returns its SHA. */ commit(owner: string, name: string, branch: string, files: Record, message = "change"): string { const r = this.repo(owner, name); const work = `${r.path}-c${this.seq++}`; execFileSync("git", ["clone", "-q", r.path, work]); const has = execFileSync("git", ["-C", work, "ls-remote", "--heads", "origin", branch], { encoding: "utf8" }).trim(); execFileSync("git", ["-C", work, "checkout", "-q", "-B", branch, ...(has ? [`origin/${branch}`] : [])]); for (const [f, text] of Object.entries(files)) { mkdirSync(join(work, f, ".."), { recursive: true }); execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text }); } execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm ${JSON.stringify(message)} && git push -q origin ${branch}`]); return this.sha(owner, name, branch); } /** A PR from `head` into main, as an agent would open it. */ openPull(owner: string, name: string, head: string, title = head, body = ""): MockPull { const r = this.repo(owner, name); const pr: MockPull = { number: r.pulls.length + 1, head, base: "main", title, body, state: "open", merged: false, mergeable: true }; r.pulls.push(pr); return pr; } /** Records a commit status, like a CI job does. */ setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) { const r = this.repo(owner, name); const list = (r.statuses.get(sha) ?? []).filter((s) => s.context !== context); list.push({ context, status, ...extra }); r.statuses.set(sha, list); } /** Sends a webhook event to every hook of the repo subscribed to it; returns HTTP statuses. */ async deliver(owner: string, name: string, event: string, payload: object): Promise { const r = this.repo(owner, name); const out: number[] = []; for (const h of r.hooks.filter((h) => h.events.includes(event) || h.events.includes(event.split("_")[0]!))) { const body = JSON.stringify(payload); const res = await fetch(h.url, { method: "POST", headers: { "Content-Type": "application/json", "X-Gitea-Event": event, "X-Gitea-Signature": createHmac("sha256", h.secret).update(body).digest("hex") }, body, }); out.push(res.status); } return out; } pullJson(r: MockRepo, p: MockPull) { let sha = ""; try { sha = this.sha(r.owner, r.name, p.head); } catch {} return { number: p.number, state: p.state, title: p.title, body: p.body, html_url: `${this.url}/${r.owner}/${r.name}/pulls/${p.number}`, merged: p.merged, mergeable: p.mergeable, head: { ref: p.head, sha, repo: { full_name: `${r.owner}/${r.name}` } }, base: { ref: p.base }, }; } private combined(r: MockRepo, ref: string) { let sha = ref; try { sha = this.sha(r.owner, r.name, ref); } catch {} const statuses = r.statuses.get(sha) ?? []; const st = statuses.map((s) => s.status); const state = !st.length ? "" : st.some((s) => s === "failure" || s === "error") ? "failure" : st.some((s) => s === "pending") ? "pending" : "success"; return { state, sha, statuses }; } private merge(r: MockRepo, p: MockPull) { const g = (...a: string[]) => execFileSync("git", ["--git-dir", r.path, ...a], { encoding: "utf8" }).trim(); const head = g("rev-parse", p.head); const base = g("rev-parse", p.base); let isAncestor = true; try { g("merge-base", "--is-ancestor", base, head); } catch { isAncestor = false; } const target = isAncestor ? head : g("-c", "user.name=t", "-c", "user.email=t@t", "commit-tree", `${head}^{tree}`, "-p", base, "-p", head, "-m", `Merge pull request #${p.number}`); g("update-ref", `refs/heads/${p.base}`, target); p.merged = true; p.state = "closed"; } private isEmpty(r: MockRepo) { return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === ""; } private json(r: MockRepo, as: MockGiteaUser) { return { id: r.id, name: r.name, full_name: `${r.owner}/${r.name}`, owner: { login: r.owner }, empty: this.isEmpty(r), private: r.private, default_branch: "main", clone_url: r.path, html_url: `${this.url}/${r.owner}/${r.name}`, permissions: { admin: r.admins.has(as.login), push: true, pull: true }, }; } private handle(method: string, url: string, auth: string, body: Record): { status: number; body?: unknown } { const path = url.split("?")[0]!; if (method === "POST" && path === "/login/oauth/access_token") { const token = this.oauthCodes.get(String(body.code)); if (!token) return { status: 400, body: { error: "invalid_grant" } }; this.oauthCodes.delete(String(body.code)); return { status: 200, body: { access_token: token, refresh_token: `r-${token}`, expires_in: 3600 } }; } const me = this.users.get(auth.replace(/^token /, "")); if (!me) return { status: 401, body: { message: "unauthorized" } }; let m: RegExpMatchArray | null; if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } }; if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) }; if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) { return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } }; } if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) { const name = decodeURIComponent(m[1]!); const isOrg = [...this.users.values()].some((u) => u.orgs?.includes(name)); return isOrg ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } }; } if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; return { status: 200, body: Object.keys(r.collaborators).map((login, i) => ({ id: 3000 + i, login })) }; } if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)$/))) { const want = decodeURIComponent(m[1]!).toLowerCase(); const u = [...this.users.values()].find((x) => x.login.toLowerCase() === want); return u ? { status: 200, body: { id: u.id, login: u.login, full_name: u.login } } : { status: 404, body: { message: "user does not exist" } }; } if (method === "GET" && path === "/api/v1/user/actions/runners/registration-token") { const token = `mock-runner-token-${me.login}-${this.seq++}`; this.runnerTokens.push({ scope: `user:${me.login}`, token }); return { status: 200, body: { token } }; } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; const res = this.handleRepo(r, me, method, m[3]!, url, body); if (res) return res; } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 }; return { status: 200, body: this.json(r, me) }; } if (method === "POST" && (path === "/api/v1/user/repos" || (m = path.match(/^\/api\/v1\/orgs\/([^/]+)\/repos$/)))) { const owner = path === "/api/v1/user/repos" ? me.login : decodeURIComponent(m![1]!); if (this.repos.has(`${owner}/${body.name}`)) return { status: 409, body: { message: "repository already exists" } }; return { status: 201, body: this.json(this.addRepo(owner, String(body.name), { admins: [me.login], private: body.private !== false }), me) }; } if (method === "PUT" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } }; r.collaborators[decodeURIComponent(m[3]!)] = String(body.permission); return { status: 204 }; } if (method === "DELETE" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } }; delete r.collaborators[decodeURIComponent(m[3]!)]; return { status: 204 }; } return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } }; } private handleRepo(r: MockRepo, me: MockGiteaUser, method: string, sub: string, url: string, body: Record): { status: number; body?: unknown } | null { const isAdmin = r.admins.has(me.login); const canWrite = isAdmin || r.owner === me.login || r.collaborators[me.login] === "write" || r.collaborators[me.login] === "admin"; const q = new URLSearchParams(url.split("?")[1] ?? ""); let m: RegExpMatchArray | null = null; if (method === "GET" && sub === "actions/runners/registration-token") { if (!isAdmin) return { status: 403, body: { message: "forbidden" } }; const token = `mock-runner-token-${r.owner}-${r.name}-${this.seq++}`; this.runnerTokens.push({ scope: `repo:${r.owner}/${r.name}`, token }); return { status: 200, body: { token } }; } if (method === "PUT" && (m = sub.match(/^actions\/secrets\/([^/]+)$/))) { if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } }; r.secrets[decodeURIComponent(m[1]!)] = String(body.data); return { status: 201 }; } if (method === "GET" && sub === "hooks") return { status: 200, body: r.hooks.map((h) => ({ id: h.id, type: "gitea", active: true, events: h.events, config: { url: h.url, content_type: "json" } })) }; if ((method === "POST" && sub === "hooks") || (method === "PATCH" && (m = sub.match(/^hooks\/(\d+)$/)))) { if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } }; const cfg = body.config as { url: string; secret: string }; const events = body.events as string[]; let h = m ? r.hooks.find((x) => x.id === Number(m![1])) : undefined; if (h) Object.assign(h, { url: cfg.url, secret: cfg.secret, events }); else r.hooks.push((h = { id: this.seq++, url: cfg.url, secret: cfg.secret, events })); return { status: m ? 200 : 201, body: { id: h.id, type: "gitea", active: true, events, config: { url: h.url, content_type: "json" } } }; } if (method === "POST" && sub === "pulls") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; return { status: 201, body: this.pullJson(r, this.openPull(r.owner, r.name, String(body.head), String(body.title), String(body.body ?? ""))) }; } if (method === "GET" && sub === "pulls") { const state = q.get("state") ?? "open"; return { status: 200, body: r.pulls.filter((p) => state === "all" || p.state === state).map((p) => this.pullJson(r, p)) }; } if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge)?$/))) { const p = r.pulls.find((x) => x.number === Number(m![1])); if (!p) return { status: 404, body: { message: "pull not found" } }; if (method === "GET" && !m[2]) return { status: 200, body: this.pullJson(r, p) }; if (method === "GET" && m[2] === "/files") { const out = execFileSync("git", ["--git-dir", r.path, "diff", "--name-only", `${p.base}...${p.head}`], { encoding: "utf8" }).trim(); return { status: 200, body: out ? out.split("\n").map((filename) => ({ filename })) : [] }; } if (method === "POST" && m[2] === "/merge") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; if (p.merged) return { status: 405, body: { message: "already merged" } }; if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } }; if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } }; this.merge(r, p); return { status: 200 }; } } if (method === "POST" && (m = sub.match(/^statuses\/([0-9a-f]+)$/))) { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; this.setStatus(r.owner, r.name, m[1]!, String(body.context), String(body.state), { target_url: body.target_url as string, description: body.description as string }); return { status: 201, body: {} }; } if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) }; if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) { try { const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64" } }; } catch { return { status: 404, body: { message: "not found" } }; } } if (method === "POST" && sub === "tags") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; const target = this.sha(r.owner, r.name, String(body.target)); execFileSync("git", ["--git-dir", r.path, "tag", String(body.tag_name), target]); r.tags.push({ name: String(body.tag_name), target }); return { status: 201, body: { name: body.tag_name, commit: { sha: target } } }; } return null; } }