// PEP-280: new projects are private — the agent in a container still clones and pushes the // project's repo through the relay's git proxy (the bot's token is added by FORGE), while the // same repo is refused to anyone asking without credentials. import assert from "node:assert/strict"; import { execFile, execFileSync, spawn } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { promisify } from "node:util"; import { after, before, describe, test } from "node:test"; import { core, db, runner, teardown } from "./helpers.ts"; const TMP = join(process.env.PEPPA_HOME!, "..", "pep280"); const GIT_ROOT = join(TMP, "git"); const BOT_TOKEN = "mock-gitea-bot-token-280"; const run = promisify(execFile); let gitServer: Server; let relay: Server; let relayUrl = ""; let gitUrl = ""; const asked: Array<{ path: string; auth: string; status: number }> = []; /** * Smart-HTTP git (git http-backend) standing in for Gitea with a private repo: without the bot's * token — 401 like Gitea asks for credentials, with it — served. */ function serveGit(): Promise { const server = createServer((req, res) => { const url = new URL(req.url!, "http://x"); const auth = String(req.headers.authorization ?? ""); if (auth !== `token ${BOT_TOKEN}`) { asked.push({ path: url.pathname, auth, status: 401 }); res.writeHead(401, { "WWW-Authenticate": 'Basic realm="Gitea"' }); return void res.end("Unauthorized\n"); } asked.push({ path: url.pathname, auth, status: 200 }); const cgi = spawn("git", ["http-backend"], { env: { ...process.env, GIT_PROJECT_ROOT: GIT_ROOT, GIT_HTTP_EXPORT_ALL: "1", REQUEST_METHOD: req.method!, PATH_INFO: decodeURIComponent(url.pathname), QUERY_STRING: url.search.slice(1), CONTENT_TYPE: String(req.headers["content-type"] ?? ""), HTTP_CONTENT_ENCODING: String(req.headers["content-encoding"] ?? ""), GIT_PROTOCOL: String(req.headers["git-protocol"] ?? ""), REMOTE_USER: "peppa-bot", }, }); req.pipe(cgi.stdin); let buf = Buffer.alloc(0); let headersDone = false; cgi.stdout.on("data", (d: Buffer) => { if (headersDone) return void res.write(d); buf = Buffer.concat([buf, d]); const i = buf.indexOf("\r\n\r\n"); if (i < 0) return; headersDone = true; let status = 200; for (const line of buf.subarray(0, i).toString().split("\r\n")) { const [k, ...v] = line.split(":"); if (k!.toLowerCase() === "status") status = Number(v.join(":").trim().split(" ")[0]); else res.setHeader(k!, v.join(":").trim()); } res.statusCode = status; res.write(buf.subarray(i + 4)); }); cgi.on("close", () => res.end()); }); return new Promise((r) => server.listen(0, "127.0.0.1", () => r(server))); } function bareRepo(owner: string, slug: string) { const work = join(TMP, "seed", slug); mkdirSync(work, { recursive: true }); writeFileSync(join(work, "README.md"), `# ${slug}\n`); const g = (...a: string[]) => execFileSync("git", a, { cwd: work, stdio: "ignore" }); g("init", "-q", "-b", "main"); g("add", "."); g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init"); mkdirSync(join(GIT_ROOT, owner), { recursive: true }); const bare = join(GIT_ROOT, owner, `${slug}.git`); execFileSync("git", ["clone", "-q", "--bare", work, bare]); execFileSync("git", ["config", "http.receivepack", "true"], { cwd: bare }); return bare; } let saved: Record = {}; before(async () => { process.env.PEPPA_SECRET = "mock-secret-for-tests"; mkdirSync(GIT_ROOT, { recursive: true }); gitServer = await serveGit(); gitUrl = `http://127.0.0.1:${(gitServer.address() as AddressInfo).port}`; saved = { GITEA_URL: process.env.GITEA_URL, GITEA_TOKEN: process.env.GITEA_TOKEN }; process.env.GITEA_URL = gitUrl; process.env.GITEA_TOKEN = BOT_TOKEN; relay = await runner.serveAgentRelay(db, 0); relayUrl = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`; }); after(async () => { relay?.close(); gitServer?.close(); for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v; await teardown(); }); /** git with no credentials of its own (no helpers, no prompts), env like the container's. */ const git = (cwd: string, env: Record, ...a: string[]) => run("git", ["-c", "credential.helper=", ...a], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false", ...env } }); describe("PEP-280: закрытый репозиторий и агент", () => { test("Без релея закрытый код не отдаётся", async () => { bareRepo("test", "pay"); const dir = join(TMP, "anon"); await assert.rejects(git(TMP, {}, "clone", "-q", `${gitUrl}/test/pay.git`, dir), /Authentication failed|could not read Username|401/); assert.ok(asked.length > 0 && asked.every((a) => a.status === 401)); }); test("Клон и push через релей", async () => { const p = await core.createProject(db, { slug: "pay", key: "PAY", name: "Pay", giteaOwner: "test", giteaRepo: "pay", workspacePath: join(TMP, "ws") }); const task = await core.createTask(db, { projectId: p.id, title: "Private repo", description: "t" }); const s = await core.createSession(db, { projectId: p.id, taskId: task.task.id }); const token = core.agentRelayToken(s.id, s.generation); // The container's git setup: GITEA_URL rewritten to the relay, the run's token as a header. const env = runner.gitRelayEnv(relayUrl, token); assert.ok(Object.keys(env).length > 0); asked.length = 0; const dir = join(TMP, "agent-clone"); await git(TMP, env, "clone", "-q", `${gitUrl}/test/pay.git`, dir); writeFileSync(join(dir, "agent.txt"), "from the agent\n"); await git(dir, env, "add", "agent.txt"); await git(dir, env, "commit", "-q", "-m", "PAY-1: agent commit"); await git(dir, env, "push", "-q", "origin", "HEAD:task/pay-1"); const log = execFileSync("git", ["log", "--format=%s", "task/pay-1"], { cwd: join(GIT_ROOT, "test", "pay.git"), encoding: "utf8" }); assert.match(log, /PAY-1: agent commit/); // Every request reached Gitea with the bot's token — the agent never had it. assert.ok(asked.length > 0); assert.ok(asked.every((a) => a.status === 200 && a.auth === `token ${BOT_TOKEN}`), JSON.stringify(asked)); assert.ok(!Object.values(env).some((v) => v.includes(BOT_TOKEN))); }); });