From 223ef9f84f70c07f93e8a2289a8310f7970756c2 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 19:04:34 +0000 Subject: [PATCH] =?UTF-8?q?PEP-280:=20=D1=82=D0=B5=D1=81=D1=82=20=E2=80=94?= =?UTF-8?q?=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=20=D0=BA=D0=BB=D0=BE=D0=BD?= =?UTF-8?q?=D0=B8=D1=80=D1=83=D0=B5=D1=82=20=D0=B8=20=D0=BF=D1=83=D1=88?= =?UTF-8?q?=D0=B8=D1=82=20=D0=B7=D0=B0=D0=BA=D1=80=D1=8B=D1=82=D1=8B=D0=B9?= =?UTF-8?q?=20=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8?= =?UTF-8?q?=D0=B9=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20=D1=80=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../pep-280-private-by-default/tasks.md | 2 +- packages/testkit/test/private-repo.test.ts | 147 ++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 packages/testkit/test/private-repo.test.ts diff --git a/openspec/changes/pep-280-private-by-default/tasks.md b/openspec/changes/pep-280-private-by-default/tasks.md index b34b60d5..adb3aec7 100644 --- a/openspec/changes/pep-280-private-by-default/tasks.md +++ b/openspec/changes/pep-280-private-by-default/tasks.md @@ -11,7 +11,7 @@ ## 3. Агенты с закрытым репозиторием -- [ ] 3.1 Тест: клон и push закрытого репозитория через git-прокси релея; без токена бота — отказ +- [x] 3.1 Тест: клон и push закрытого репозитория через git-прокси релея; без токена бота — отказ ## 4. Завершение diff --git a/packages/testkit/test/private-repo.test.ts b/packages/testkit/test/private-repo.test.ts new file mode 100644 index 00000000..e9f57661 --- /dev/null +++ b/packages/testkit/test/private-repo.test.ts @@ -0,0 +1,147 @@ +// 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))); + }); +});