Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

1812 lines · 126.0 KBRaw History
1// End-to-end security checks of the GitHub-compatible REST API, against a real
2// `wrangler dev` Worker with real (seeded) accounts, tokens and sessions.
3//
4// pnpm --filter @diffinery/app e2e
5//
6// Covers: search only shows what the caller may read (pending, disabled and
7// orphaned-agent callers see nothing); agents can't turn a failing required
8// check green; deployments verify every context; agents can't manage
9// environments or dismiss reviews; secrets default environments to protected
10// branches; locked conversations and archived repositories refuse changes;
11// draft releases stay off readers' live sockets; unsafe tree names, tree bombs,
12// long search queries and percent signs in label names. Anonymous callers and
13// read-scoped tokens can't write; agents can't change secrets or variables;
14// merges honour linear history, need an explicit admin bypass, and drafts can
15// be marked ready; the exact branch protection rule wins over a pattern.
16// Push protection also covers commits made without git (web editor, REST, MCP).
17// Repository-limited tokens can't mint wider ones; settings changed through the
18// API are audited; readers' labels and assignees are dropped. Repository
19// transfers keep a repository's data and leave redirects (web, REST, git, MCP,
20// images) that only readers can follow; emptied organizations can be deleted.
21// Agents land changes on protected branches only through auto-merge (or the
22// merge queue) where a person allowed it and a required check gates it, never by bypass.
23import { spawn, spawnSync, execFileSync } from "node:child_process";
24import { createHash, randomBytes } from "node:crypto";
25import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
26import { gzipSync } from "node:zlib";
27import { tmpdir } from "node:os";
28import { join, dirname, resolve } from "node:path";
29import { fileURLToPath } from "node:url";
30import { createServer } from "node:net";
31import { test, before, after } from "node:test";
32import assert from "node:assert/strict";
33
34const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
35const work = mkdtempSync(join(tmpdir(), "diffinery-security-"));
36let base;
37let dev;
38let devLog = "";
39
40const hash = (s) => createHash("sha256").update(s).digest("hex");
41const tok = (name) => `dfy_${name}_${randomBytes(12).toString("hex")}`;
42const T = { olive: tok("olive"), bot: tok("bot"), rita: tok("rita"), dora: tok("dora"), orphan: tok("orphan"), reader: tok("reader"), ritaAdmin: tok("ritaAdmin"), milo: tok("milo"), sam: tok("sam"), helper: tok("helper") };
43const S = { penny: `penny-session-${randomBytes(12).toString("hex")}`, dora: `dora-session-${randomBytes(12).toString("hex")}`, olive: `olive-session-${randomBytes(12).toString("hex")}`, sam: `sam-session-${randomBytes(12).toString("hex")}` };
44const OWNER = "olive";
45
46const freePort = () =>
47 new Promise((res) => {
48 const s = createServer();
49 s.listen(0, "127.0.0.1", () => {
50 const { port } = s.address();
51 s.close(() => res(port));
52 });
53 });
54
55const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
56async function until(what, fn, timeoutMs = 60_000) {
57 const end = Date.now() + timeoutMs;
58 while (Date.now() < end) {
59 const v = await fn();
60 if (v) return v;
61 await sleep(300);
62 }
63 assert.fail(`timed out waiting for ${what}\n--- wrangler log tail ---\n${devLog.slice(-4000)}`);
64}
65
66/** Call the REST API as a token (`as`), a session cookie (`{ cookie }`) or anonymously (null). */
67async function api(method, path, body, as = T.olive) {
68 const headers = { "content-type": "application/json" };
69 if (typeof as === "string") headers.authorization = `Bearer ${as}`;
70 else if (as?.cookie) headers.cookie = `__Host-dfy_session=${as.cookie}`;
71 const send = () => fetch(`${base}/api/v3${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
72 // wrangler dev closes idle keep-alive connections (the audit checks pause for seconds), so a reused one can be gone.
73 const res = await send().catch((e) => (e.cause?.code === "UND_ERR_SOCKET" ? send() : Promise.reject(e)));
74 const text = await res.text();
75 let json = null;
76 try {
77 json = text ? JSON.parse(text) : null;
78 } catch {
79 json = text;
80 }
81 return { status: res.status, json };
82}
83async function ok(method, path, body, as) {
84 const r = await api(method, path, body, as);
85 assert.ok(r.status >= 200 && r.status < 300, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
86 return r.json;
87}
88async function status(expected, method, path, body, as) {
89 const r = await api(method, path, body, as);
90 assert.equal(r.status, expected, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
91 return r.json;
92}
93const b64 = (s) => Buffer.from(s).toString("base64");
94
95before(async () => {
96 const port = await freePort();
97 base = `http://127.0.0.1:${port}`;
98 const persist = join(work, "state");
99 const wrangler = (...args) => execFileSync("pnpm", ["exec", "wrangler", ...args], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } });
100 wrangler("d1", "migrations", "apply", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist);
101 const at = new Date().toISOString();
102 const later = new Date(Date.now() + 30 * 86400_000).toISOString();
103 const account = (id, login, kind, status, owner = null) => `INSERT INTO accounts (id, login, kind, name, status, owner_id, created_at) VALUES ('${id}', '${login}', '${kind}', '${login}', '${status}', ${owner ? `'${owner}'` : "NULL"}, '${at}')`;
104 const token = (id, account, t, scopes) => `INSERT INTO tokens (id, account_id, name, token_hash, prefix, scopes, expires_at, created_at) VALUES ('${id}', '${account}', 'e2e', '${hash(t)}', '${t.slice(0, 10)}', '${JSON.stringify(scopes)}', '${later}', '${at}')`;
105 const session = (id, account, cookie) => `INSERT INTO sessions (id, account_id, method, created_at, last_seen_at, expires_at) VALUES ('${hash(cookie)}', '${account}', 'passkey', '${at}', '${at}', '${later}')`;
106 wrangler(
107 "d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--command",
108 [
109 account("u-olive", "olive", "user", "active"),
110 account("a-bot", "olive-bot", "agent", "active", "u-olive"),
111 account("u-rita", "rita", "user", "active"),
112 account("u-penny", "penny", "user", "pending"),
113 account("u-dora", "dora", "user", "disabled"),
114 account("u-gone", "gone", "user", "disabled"),
115 account("a-orphan", "gone-bot", "agent", "active", "u-gone"),
116 token("t1", "u-olive", T.olive, ["admin"]),
117 token("t2", "a-bot", T.bot, ["admin"]),
118 token("t3", "u-rita", T.rita, ["write"]),
119 token("t4", "u-dora", T.dora, ["write"]),
120 token("t5", "a-orphan", T.orphan, ["write"]),
121 account("o-guild", "guild", "org", "active"),
122 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-guild', 'u-olive', 'owner', '${at}'), ('o-guild', 'u-rita', 'admin', '${at}')`,
123 token("t6", "u-olive", T.reader, ["read"]),
124 token("t7", "u-rita", T.ritaAdmin, ["admin"]),
125 account("u-milo", "milo", "user", "active"),
126 token("t8", "u-milo", T.milo, ["admin"]),
127 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-guild', 'u-milo', 'member', '${at}')`,
128 session("s1", "u-penny", S.penny),
129 session("s2", "u-dora", S.dora),
130 session("s3", "u-olive", S.olive),
131 account("o-shop", "shop", "org", "active"),
132 account("u-sam", "sam", "user", "active"),
133 token("t9", "u-sam", T.sam, ["admin"]),
134 account("a-helper", "olive-helper", "agent", "active", "u-olive"),
135 token("t10", "a-helper", T.helper, ["write"]),
136 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-shop', 'u-olive', 'owner', '${at}'), ('o-shop', 'u-sam', 'member', '${at}')`,
137 session("s4", "u-sam", S.sam),
138 "UPDATE accounts SET email = 'sam@example.com' WHERE id = 'u-sam'",
139 ].join("; "),
140 );
141 dev = spawn(
142 "pnpm",
143 ["exec", "wrangler", "dev", "-e", "dev", "--ip", "127.0.0.1", "--port", String(port), "--inspector-port", String(await freePort()), "--persist-to", persist, "--var", `PUBLIC_URL:${base}`, "--var", "DEV_AUTH:", "--var", `MASTER_KEY:${randomBytes(32).toString("base64")}`, "--show-interactive-dev-session=false"],
144 { cwd: APP, env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" }, stdio: ["ignore", "pipe", "pipe"], detached: true },
145 );
146 dev.stdout.on("data", (d) => (devLog += d));
147 dev.stderr.on("data", (d) => (devLog += d));
148 await until(
149 "wrangler dev",
150 async () => {
151 try {
152 return (await fetch(`${base}/healthz`)).ok;
153 } catch {
154 return false;
155 }
156 },
157 120_000,
158 );
159});
160
161after(() => {
162 if (dev?.pid) {
163 try {
164 process.kill(-dev.pid, "SIGTERM");
165 } catch {}
166 }
167 if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true });
168});
169
170/** A private repository owned by olive with one commit on main. */
171async function repoWithReadme(name, extra = {}) {
172 await ok("POST", "/user/repos", { name, ...extra });
173 const put = await ok("PUT", `/repos/${OWNER}/${name}/contents/README.md`, { message: "init", content: b64(`# ${name}\n`) });
174 return put.commit.sha;
175}
176
177test("security: search, required checks, environments, reviews, locks, archives, drafts and tree names", async () => {
178 // ------------------------------------------------------------ setup: a private repo the agent and rita can use
179 const R = `/repos/${OWNER}/guarded`;
180 const mainSha = await repoWithReadme("guarded");
181 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
182 await status(204, "PUT", `${R}/collaborators/rita`, { permission: "read" });
183 await status(204, "PUT", `${R}/collaborators/gone-bot`, { permission: "write" });
184 const issue = await ok("POST", `${R}/issues`, { title: "needle in a haystack" });
185
186 // ------------------------------------------------------------ search only shows what the caller may read
187 const found = await ok("GET", "/search/issues?q=needle");
188 assert.equal(found.total_count, 1);
189 assert.equal(found.items[0].number, issue.number);
190 assert.equal((await ok("GET", "/search/issues?q=needle", undefined, T.rita)).total_count, 1);
191 for (const [who, as] of [
192 ["pending account (session)", { cookie: S.penny }],
193 ["disabled account (session)", { cookie: S.dora }],
194 ["agent of a disabled owner", T.orphan],
195 ["anonymous", null],
196 ]) {
197 const r = await api("GET", "/search/issues?q=needle", undefined, as);
198 assert.equal(r.status, 200, `${who}: ${JSON.stringify(r.json)}`);
199 assert.equal(r.json.total_count, 0, `${who} must not find private issues`);
200 const repos = await ok("GET", "/search/repositories?q=guarded", undefined, as);
201 assert.equal(repos.total_count, 0, `${who} must not find private repos`);
202 }
203 await status(401, "GET", "/search/issues?q=needle", undefined, T.dora);
204 await status(404, "GET", R, undefined, T.orphan);
205 // Search input is bounded.
206 await status(422, "GET", `/search/issues?q=${"x".repeat(300)}`);
207 await status(422, "GET", "/search/issues");
208
209 // ------------------------------------------------------------ required checks: an agent can't turn its failing PR green
210 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
211 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-change", sha: mainSha }, T.bot);
212 const change = await ok("PUT", `${R}/contents/change.txt`, { message: "agent change", content: b64("hi\n"), branch: "agent-change" }, T.bot);
213 const head = change.commit.sha;
214 const pr = await ok("POST", `${R}/pulls`, { title: "Agent change", head: "agent-change", base: "main" }, T.bot);
215 await ok("POST", `${R}/pulls/${pr.number}/reviews`, { event: "APPROVE", body: "fine by me" });
216 const failing = await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "failure" });
217 assert.equal(typeof failing.id, "number");
218 const mergeState = async () =>
219 until("mergeability", async () => {
220 const p = await ok("GET", `${R}/pulls/${pr.number}`);
221 return typeof p.mergeable === "boolean" ? p.mergeable_state : null;
222 });
223 assert.equal(await mergeState(), "blocked");
224 // 1. PATCH someone else's check run.
225 await status(403, "PATCH", `${R}/check-runs/${failing.id}`, { conclusion: "success" }, T.bot);
226 // 2. A green commit status with the same name.
227 await ok("POST", `${R}/statuses/${head}`, { state: "success", context: "ci" }, T.bot);
228 assert.equal(await mergeState(), "blocked");
229 // 3. A green check run of its own with the same name.
230 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" }, T.bot);
231 assert.equal(await mergeState(), "blocked");
232
233 // ------------------------------------------------------------ deployments verify every context unless told otherwise
234 await status(409, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging" });
235 await status(201, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging", required_contexts: [] });
236 await status(409, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging", required_contexts: ["ci"] });
237
238 // The real reporter fixes its check: now the PR is mergeable and deployable.
239 await ok("PATCH", `${R}/check-runs/${failing.id}`, { conclusion: "success" });
240 assert.equal(await mergeState(), "clean");
241 await status(201, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging" });
242
243 // ------------------------------------------------------------ review dismissal: maintainers only, never the author or an agent
244 const reviews = await ok("GET", `${R}/pulls/${pr.number}/reviews`);
245 const approval = reviews.find((r) => r.state === "APPROVED");
246 await status(403, "PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "nope" }, T.bot);
247 await status(403, "PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "nope" }, T.rita);
248 const dismissed = await ok("PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "stale" });
249 assert.equal(dismissed.state, "DISMISSED");
250
251 // ------------------------------------------------------------ environments: admins who are people, not agents
252 await status(403, "PUT", `${R}/environments/production`, {}, T.bot);
253 await ok("PUT", `${R}/environments/production`, { deployment_branch_policy: { protected_branches: false, custom_branch_policies: true } });
254 await status(403, "POST", `${R}/environments/production/deployment-branch-policies`, { name: "v*", type: "tag" }, T.bot);
255 const policy = await ok("POST", `${R}/environments/production/deployment-branch-policies`, { name: "release/*", type: "branch" });
256 await status(403, "DELETE", `${R}/environments/production/deployment-branch-policies/${policy.id}`, undefined, T.bot);
257 await status(403, "DELETE", `${R}/environments/production`, undefined, T.bot);
258 await status(403, "PUT", `${R}/environments/production/secrets/TOKEN`, { value: "s3cret" }, T.bot);
259 // The first secret limits an environment without rules to protected branches.
260 await ok("PUT", `${R}/environments/vault`, {});
261 assert.equal((await ok("GET", `${R}/environments/vault`)).deployment_branch_policy, null);
262 await status(201, "PUT", `${R}/environments/vault/secrets/API_KEY`, { value: "s3cret" });
263 const vault = await ok("GET", `${R}/environments/vault`);
264 assert.equal(vault.deployment_branch_policy?.protected_branches, true);
265 assert.ok(!JSON.stringify(vault).includes("s3cret"));
266
267 // ------------------------------------------------------------ locked conversations
268 await status(204, "PUT", `${R}/issues/${pr.number}/lock`, { lock_reason: "resolved" });
269 await status(403, "POST", `${R}/pulls/${pr.number}/comments`, { body: "late", commit_id: head, path: "change.txt", line: 1, side: "RIGHT" }, T.rita);
270 await status(403, "POST", `${R}/issues/${pr.number}/reactions`, { content: "+1" }, T.rita);
271 await status(201, "POST", `${R}/issues/${issue.number}/reactions`, { content: "+1" }, T.rita);
272
273 // ------------------------------------------------------------ unsafe tree entry names, on every write path
274 for (const path of [".git/config", ".GIT/hooks/pre-commit", "x/.git./config", "git~1/config", "a\\b", "x/../y"]) {
275 await status(422, "POST", `${R}/git/trees`, { tree: [{ path, mode: "100644", type: "blob", content: "x" }] });
276 }
277 for (const path of [".Git/hooks/post-checkout", "git~1/HEAD", "sub/.git/config"]) {
278 await status(422, "PUT", `${R}/contents/${path}`, { message: "bad", content: b64("x") });
279 }
280
281 // ------------------------------------------------------------ a tree bomb can't blow up archives or languages
282 const leaf = await ok("POST", `${R}/git/trees`, { tree: [{ path: "a.js", mode: "100644", type: "blob", content: "x" }] });
283 const wide = await ok("POST", `${R}/git/trees`, { tree: Array.from({ length: 400 }, (_, i) => ({ path: `d${i}`, mode: "040000", type: "tree", sha: leaf.sha })) });
284 const bomb = await ok("POST", `${R}/git/trees`, { tree: Array.from({ length: 400 }, (_, i) => ({ path: `e${i}`, mode: "040000", type: "tree", sha: wide.sha })) });
285 const bombCommit = await ok("POST", `${R}/git/commits`, { message: "bomb", tree: bomb.sha, parents: [mainSha] });
286 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/bomb", sha: bombCommit.sha });
287 const zip = await fetch(`${base}/api/v3${R}/zipball/bomb`, { headers: { authorization: `Bearer ${T.olive}` }, redirect: "manual" });
288 assert.equal(zip.status, 413, await zip.text());
289 await status(200, "GET", `${R}/languages`);
290
291 // ------------------------------------------------------------ labels with a percent sign (no double decoding)
292 await ok("POST", `${R}/labels`, { name: "50%", color: "ff0000" });
293 assert.equal((await ok("GET", `${R}/labels/50%25`)).name, "50%");
294 assert.equal((await ok("PATCH", `${R}/labels/50%25`, { description: "half" })).description, "half");
295 await ok("POST", `${R}/issues/${issue.number}/labels`, { labels: ["50%"] });
296 await ok("DELETE", `${R}/issues/${issue.number}/labels/50%25`);
297 await status(204, "DELETE", `${R}/labels/50%25`);
298
299 // ------------------------------------------------------------ archived repositories are read-only for everyone
300 const A = `/repos/${OWNER}/attic`;
301 await repoWithReadme("attic");
302 const old = await ok("POST", `${A}/issues`, { title: "old" });
303 assert.equal((await ok("PATCH", A, { archived: true })).archived, true);
304 await status(403, "POST", `${A}/issues/${old.number}/reactions`, { content: "heart" });
305 await status(403, "PUT", `${A}/environments/production`, {});
306 await status(403, "POST", `${A}/releases`, { tag_name: "v1" });
307 await status(200, "GET", `${A}/labels`);
308 // Every write is refused, issue and admin routes alike...
309 await status(403, "POST", `${A}/issues`, { title: "new" });
310 await status(403, "POST", `${A}/issues/${old.number}/comments`, { body: "late" });
311 await status(403, "PATCH", `${A}/issues/${old.number}`, { title: "renamed" });
312 await status(403, "PUT", `${A}/branches/main/protection`, { required_status_checks: null, enforce_admins: false, required_pull_request_reviews: null, restrictions: null });
313 await status(403, "PUT", `${A}/collaborators/rita`, { permission: "push" });
314 await status(403, "PUT", `${A}/actions/secrets/TOKEN`, { value: "s3cret" });
315 await status(403, "POST", `${A}/actions/variables`, { name: "X", value: "1" });
316 await status(403, "POST", `${A}/hooks`, { config: { url: "https://example.com/hook" } });
317 const mcp = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${T.bot}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "create_issue", arguments: { owner: OWNER, repo: "attic", title: "via mcp" } } }) });
318 assert.equal((await mcp.json()).result.isError, true);
319 // ...but reads, watching and unarchiving still work.
320 await status(200, "GET", `${A}/actions/secrets`);
321 await status(200, "PUT", `${A}/subscription`, { subscribed: true });
322 assert.equal((await ok("PATCH", A, { archived: false })).archived, false);
323 await status(201, "POST", `${A}/issues`, { title: "after unarchiving" });
324
325 // ------------------------------------------------------------ renaming a variable onto an existing name is a conflict
326 for (const n of ["ONE", "TWO"]) await status(201, "POST", `${A}/actions/variables`, { name: n, value: n });
327 await status(409, "PATCH", `${A}/actions/variables/ONE`, { name: "two" });
328 assert.equal((await ok("GET", `${A}/actions/variables/TWO`)).value, "TWO");
329 await ok("PUT", `${A}/environments/Staging`, {});
330 for (const n of ["ONE", "TWO"]) await status(201, "POST", `${A}/environments/Staging/variables`, { name: n, value: n });
331 await status(409, "PATCH", `${A}/environments/Staging/variables/ONE`, { name: "TWO" });
332
333 // ------------------------------------------------------------ deployments: environment names ignore case; only older ones go inactive
334 const dep = async (environment) => (await ok("POST", `${A}/deployments`, { ref: "main", environment, required_contexts: [] })).id;
335 const latest = async (id) => (await ok("GET", `${A}/deployments/${id}/statuses`))[0].state;
336 const d1 = await dep("staging");
337 await ok("POST", `${A}/deployments/${d1}/statuses`, { state: "success" });
338 const d2 = await dep("STAGING");
339 assert.equal((await ok("GET", `${A}/deployments/${d2}`)).environment, "Staging");
340 await ok("POST", `${A}/deployments/${d2}/statuses`, { state: "success" });
341 assert.equal(await latest(d1), "inactive");
342 await ok("POST", `${A}/deployments/${d1}/statuses`, { state: "success" });
343 assert.equal(await latest(d2), "success", "a newer deployment stays active");
344 assert.equal((await ok("GET", `${A}/deployments?environment=staging`)).length, 2);
345
346 // ------------------------------------------------------------ private: false makes a repository public
347 await repoWithReadme("flip");
348 const flipped = await ok("PATCH", `/repos/${OWNER}/flip`, { private: false });
349 assert.equal(flipped.private, false);
350 assert.equal(flipped.visibility, "public");
351 await status(200, "GET", `/repos/${OWNER}/flip`, undefined, null);
352 await status(422, "PATCH", `/repos/${OWNER}/flip`, { visibility: "secret" });
353
354 // ------------------------------------------------------------ draft releases never reach readers' live pages
355 const ws = new WebSocket(`${base.replace("http", "ws")}/${OWNER}/flip/live?topics=repo,releases`);
356 const seen = [];
357 ws.addEventListener("message", (e) => seen.push(String(e.data)));
358 await new Promise((res, rej) => {
359 ws.addEventListener("open", res);
360 ws.addEventListener("error", rej);
361 });
362 const draft = await ok("POST", `/repos/${OWNER}/flip/releases`, { tag_name: "v0.9", name: "Secret plans", body: "draft notes", draft: true });
363 // Live messages only say what kind of thing changed: nothing for the draft, then the published release.
364 const releases = () => seen.filter((m) => JSON.parse(m).data?.type === "release");
365 await sleep(700);
366 assert.equal(releases().length, 0, seen.join("\n"));
367 await ok("POST", `/repos/${OWNER}/flip/releases`, { tag_name: "v1.0", name: "Public release" });
368 await until("the published release event", async () => releases().length > 0);
369 ws.close();
370 assert.ok(!seen.some((m) => m.includes("Secret plans") || m.includes("Public release") || m.includes(`"id":${draft.id}`)), `release details leaked: ${seen.join("\n")}`);
371});
372
373test("security: organization admins can't hand out ownership", async () => {
374 // rita is an admin of guild, olive its owner. Invitations need an admin-scoped token.
375 await status(403, "POST", "/orgs/guild/invitations", { email: "helper@example.com", role: "member" }, T.rita);
376 await status(403, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "owner" }, T.ritaAdmin);
377 await status(422, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "superuser" }, T.ritaAdmin);
378 await status(201, "POST", "/orgs/guild/invitations", { email: "helper@example.com", role: "admin" }, T.ritaAdmin);
379 await status(201, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "owner" }, T.olive);
380});
381
382/** Open a pull request from a new branch with one changed file. */
383async function pullFrom(R, base, branch, opts = {}) {
384 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: base });
385 await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
386 return ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main", ...opts });
387}
388
389test("security: anonymous writes, token scopes, agent secrets, merge rules and drafts", async () => {
390 const R = `/repos/${OWNER}/commons`;
391 const mainSha = await repoWithReadme("commons", { visibility: "public" });
392 const issue = await ok("POST", `${R}/issues`, { title: "public issue" });
393
394 // ------------------------------------------------------------ unknown API paths answer like GitHub, in JSON
395 const missing = await status(404, "GET", "/no/such/endpoint");
396 assert.equal(missing.message, "Not Found");
397
398 // ------------------------------------------------------------ anonymous callers read public repos but never write
399 await status(200, "GET", `${R}/issues/${issue.number}`, undefined, null);
400 await status(401, "POST", `${R}/issues`, { title: "spam" }, null);
401 await status(401, "POST", `${R}/issues/${issue.number}/comments`, { body: "spam" }, null);
402 await status(401, "POST", `${R}/issues/${issue.number}/reactions`, { content: "+1" }, null);
403 await status(401, "PUT", `${R}/subscription`, { subscribed: true }, null);
404 // ...while anonymous git fetches (a POST) keep working.
405 const clone = join(work, "commons-anon");
406 execFileSync("git", ["-c", "protocol.version=2", "clone", "-q", `${base}/${OWNER}/commons.git`, clone], { stdio: "pipe" });
407
408 // ------------------------------------------------------------ read-scoped tokens only read
409 await status(200, "GET", R, undefined, T.reader);
410 await status(403, "POST", `${R}/issues`, { title: "nope" }, T.reader);
411 await status(403, "POST", `${R}/issues/${issue.number}/comments`, { body: "nope" }, T.reader);
412 await status(403, "POST", "/user/orgs", { login: "reader-org" }, T.reader);
413 await status(403, "POST", "/user/repos", { name: "reader-repo" }, T.reader);
414 await status(403, "POST", "/diffinery/agents", { login: "reader-bot" }, T.reader);
415 await status(403, "POST", "/diffinery/tokens", { name: "escalate", scopes: ["admin"] }, T.reader);
416 await status(403, "PUT", "/notifications", {}, T.reader);
417 // Token scopes are checked on the server.
418 await status(422, "POST", "/diffinery/tokens", { name: "bad", scopes: ["root"] }, { cookie: S.olive });
419 await status(422, "POST", "/diffinery/tokens", { name: "bad", scopes: [] }, { cookie: S.olive });
420 await status(422, "POST", "/diffinery/agents/olive-bot/tokens", { scopes: ["superuser"] }, { cookie: S.olive });
421 const minted = await ok("POST", "/diffinery/tokens", { name: "fine", scopes: ["read", "read"] }, { cookie: S.olive });
422 assert.ok(minted.token);
423 assert.deepEqual((await ok("GET", "/diffinery/tokens")).find((t) => t.id === minted.id).scopes, ["read"]);
424
425 // ------------------------------------------------------------ admin-role agents can't change secrets or variables
426 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
427 await status(204, "PUT", `${R}/actions/secrets/TOKEN`, { value: "s3cret" });
428 await status(204, "PUT", `${R}/actions/variables/REGION`, { value: "eu" });
429 await status(403, "DELETE", `${R}/actions/secrets/TOKEN`, undefined, T.bot);
430 await status(403, "PUT", `${R}/actions/variables/REGION`, { value: "attacker" }, T.bot);
431 await status(403, "DELETE", `${R}/actions/variables/REGION`, undefined, T.bot);
432 await status(403, "POST", `${R}/actions/variables`, { name: "NEW", value: "x" }, T.bot);
433 await status(403, "PATCH", `${R}/actions/variables/REGION`, { value: "attacker" }, T.bot);
434 assert.equal((await ok("GET", `${R}/actions/variables/REGION`)).value, "eu");
435
436 // ------------------------------------------------------------ the exact rule wins over a wildcard, whatever their order
437 await ok("PUT", `${R}/branches/${encodeURIComponent("*")}/protection`, { requireLinearHistory: true, requiredApprovals: 2 });
438 await ok("PUT", `${R}/branches/main/protection`, { requireLinearHistory: true });
439 const linear = await pullFrom(R, mainSha, "linear");
440 // A merge commit breaks linear history, through the API as through the queue.
441 const refused = await status(405, "PUT", `${R}/pulls/${linear.number}/merge`, { merge_method: "merge" });
442 assert.match(refused.message, /linear history/);
443 const squashed = await ok("PUT", `${R}/pulls/${linear.number}/merge`, { merge_method: "squash" });
444 assert.equal(squashed.merged, true);
445
446 // ------------------------------------------------------------ admins bypass unmet rules only when they ask to
447 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1 });
448 const head = (await ok("GET", `${R}/branches/main`)).commit.sha;
449 const unreviewed = await pullFrom(R, head, "unreviewed");
450 const blocked = await status(405, "PUT", `${R}/pulls/${unreviewed.number}/merge`, { merge_method: "squash" });
451 assert.match(blocked.message, /approving review/);
452 assert.match(blocked.message, /bypass_rules/);
453 assert.equal((await ok("PUT", `${R}/pulls/${unreviewed.number}/merge`, { merge_method: "squash", bypass_rules: true })).merged, true);
454
455 // ------------------------------------------------------------ drafts can be marked ready for review
456 await status(204, "DELETE", `${R}/branches/main/protection`);
457 await status(204, "DELETE", `${R}/branches/${encodeURIComponent("*")}/protection`);
458 const head2 = (await ok("GET", `${R}/branches/main`)).commit.sha;
459 const draft = await pullFrom(R, head2, "wip", { draft: true });
460 assert.equal(draft.draft, true);
461 await status(405, "PUT", `${R}/pulls/${draft.number}/merge`, { merge_method: "squash" });
462 await status(403, "PATCH", `${R}/pulls/${draft.number}`, { draft: false }, T.rita);
463 const ready = await ok("PATCH", `${R}/pulls/${draft.number}`, { draft: false });
464 assert.equal(ready.draft, false);
465 const events = await ok("GET", `${R}/issues/${draft.number}/events`);
466 assert.ok(events.some((e) => e.event === "ready_for_review"), JSON.stringify(events));
467 assert.equal((await ok("PUT", `${R}/pulls/${draft.number}/merge`, { merge_method: "squash" })).merged, true);
468});
469
470test("security: push protection covers commits made without git", async () => {
471 const R = `/repos/${OWNER}/leaky`;
472 const mainSha = await repoWithReadme("leaky");
473 // Built at run time so this file holds no credential-shaped string.
474 const leak = `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n`;
475 const files = [{ path: "config.env", content: leak }];
476 const head = async () => (await ok("GET", `${R}/branches/main`)).commit.sha;
477
478 // ------------------------------------------------------------ REST: the contents API and the multi-file commits API
479 const viaContents = await status(422, "PUT", `${R}/contents/config.env`, { message: "leak", content: b64(leak) });
480 assert.match(viaContents.message, /push protection.*AWS access key/);
481 const viaCommits = await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files });
482 assert.match(viaCommits.message, /push protection.*AWS access key.*config\.env/);
483 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "k.env", encoding: "base64", content: b64(leak) }] });
484 // Agents can't bypass, even with a reason; a human admin can, and it's on the record.
485 const agentTry = await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files, allow_secrets: "please" }, T.bot);
486 assert.match(agentTry.message, /people, not agents/);
487 assert.equal(await head(), mainSha);
488
489 // ------------------------------------------------------------ MCP commit_files
490 const rpc = async (method, params) => {
491 const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${T.bot}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
492 assert.equal(r.status, 200);
493 return (await r.json()).result;
494 };
495 const viaMcp = await rpc("tools/call", { name: "commit_files", arguments: { owner: OWNER, repo: "leaky", branch: "agent-leak", create_branch_from: "main", message: "leak", files } });
496 assert.equal(viaMcp.isError, true, JSON.stringify(viaMcp));
497 assert.match(JSON.stringify(viaMcp), /push protection/);
498 await status(404, "GET", `${R}/branches/agent-leak`);
499
500 // ------------------------------------------------------------ the web editor
501 const cookie = `__Host-dfy_session=${S.olive}`;
502 const page = await fetch(`${base}/${OWNER}/leaky/new/main`, { headers: { cookie } });
503 assert.equal(page.status, 200);
504 const csrf = /name="_csrf" value="([^"]+)"/.exec(await page.text())?.[1];
505 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
506 assert.ok(csrf && csrfCookie);
507 const form = new URLSearchParams({ _csrf: csrf, path: "config.env", content: leak, message: "leak", description: "", choice: "direct", new_branch: "", head: mainSha });
508 const posted = await fetch(`${base}/${OWNER}/leaky/new/main`, { method: "POST", body: form, redirect: "manual", headers: { cookie: `${cookie}; dfy_csrf=${csrfCookie}`, "sec-fetch-site": "same-origin" } });
509 assert.equal(posted.status, 422);
510 assert.match(await posted.text(), /push protection/);
511 assert.equal(await head(), mainSha);
512
513 // ------------------------------------------------------------ an admin's explicit bypass goes through
514 const bypassed = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "test fixture", files, allow_secrets: "fake key used by this test" });
515 assert.notEqual(bypassed.sha, mainSha);
516});
517
518/** Audit entries recorded so far, read straight from the local D1 database. The running dev server can hold its lock, so a busy database is retried. */
519function auditLog(action) {
520 for (let attempt = 1; ; attempt++) {
521 try {
522 return readAuditLog(action);
523 } catch (e) {
524 if (attempt >= 10 || !/SQLITE_BUSY|database is locked/.test(String(e.stderr ?? e.message))) throw e;
525 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300 * attempt);
526 }
527 }
528}
529
530function readAuditLog(action) {
531 const out = execFileSync("pnpm", ["exec", "wrangler", "d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", join(work, "state"), "--json", "--command", `SELECT actor_login, action, target, detail FROM audit_log WHERE action = '${action}'`], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } });
532 return JSON.parse(out.toString())[0].results;
533}
534
535test("security: limited tokens, invisible repositories, readers' labels and the audit trail", async () => {
536 await repoWithReadme("limits");
537 // ------------------------------------------------------------ a token limited to some repositories can't mint one that isn't
538 const limited = (await ok("POST", "/diffinery/tokens", { name: "limited", scopes: ["admin"], repositories: [`${OWNER}/limits`] }, { cookie: S.olive })).token;
539 await status(403, "POST", "/diffinery/tokens", { name: "wider", scopes: ["admin"] }, limited);
540 // ------------------------------------------------------------ private repositories you can't see stay unknown
541 await ok("POST", "/user/repos", { name: "hidden", private: true }, T.rita);
542 await status(422, "POST", "/diffinery/tokens", { name: "peek", repositories: ["rita/hidden"] }, { cookie: S.olive });
543 await status(404, "POST", "/repos/rita/hidden/issues", { title: "hi" }, T.reader);
544 // An anonymous push is asked for credentials (git only sends them after a 401), even to a public repository.
545 await ok("PATCH", `/repos/${OWNER}/limits`, { visibility: "public" });
546 const push = await fetch(`${base}/${OWNER}/limits.git/info/refs?service=git-receive-pack`);
547 assert.equal(push.status, 401);
548 assert.match(push.headers.get("www-authenticate") ?? "", /Basic/);
549 assert.equal((await fetch(`${base}/${OWNER}/limits.git/info/refs?service=git-receive-pack`, { headers: { authorization: `Basic ${Buffer.from(`x:${T.olive}`).toString("base64")}` } })).status, 200);
550
551 // ------------------------------------------------------------ labels and assignees from readers are dropped, as on GitHub
552 const R = `/repos/${OWNER}/limits`;
553 await ok("POST", `${R}/labels`, { name: "bug", color: "ff0000" });
554 const fromReader = await ok("POST", `${R}/issues`, { title: "from a reader", labels: ["bug"], assignees: [OWNER] }, T.rita);
555 assert.deepEqual([fromReader.labels.length, fromReader.assignees.length], [0, 0]);
556 const fromAdmin = await ok("POST", `${R}/issues`, { title: "from the owner", labels: ["bug"] });
557 assert.equal(fromAdmin.labels[0].name, "bug");
558 // Editing their own issue doesn't let them in either.
559 const milestone = await status(201, "POST", `${R}/milestones`, { title: "v1" });
560 const edited = await ok("PATCH", `${R}/issues/${fromReader.number}`, { title: "edited by its author", labels: ["bug"], assignees: [OWNER], milestone: milestone.number }, T.rita);
561 assert.equal(edited.title, "edited by its author");
562 assert.deepEqual([edited.labels.length, edited.assignees.length, edited.milestone], [0, 0, null]);
563
564 // ------------------------------------------------------------ settings changed through the API are on the record
565 await status(204, "PUT", `${R}/collaborators/rita`, { permission: "push" });
566 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1 });
567 await status(204, "PUT", `${R}/actions/secrets/TOKEN`, { value: "s3cret" });
568 await status(201, "POST", `${R}/actions/variables`, { name: "MODE", value: "x" });
569 await status(201, "POST", `${R}/hooks`, { config: { url: "https://example.com/hook" } });
570 await until("audit entries", async () => {
571 const want = ["repo.update", "repo.collaborator.set", "repo.protection.set", "repo.secret.set", "repo.variable.set", "repo.webhook.create"];
572 return want.every((a) => auditLog(a).some((e) => e.target === `${OWNER}/limits` && JSON.parse(e.detail).via === "api"));
573 });
574 const leak = auditLog("api.blocked_secret").find((e) => e.target === `${OWNER}/leaky`);
575 assert.equal(leak?.actor_login, OWNER, "blocked API writes are audited against the caller");
576});
577
578test("security: organization pictures are the owners' to change, and invitations aren't sent twice", async () => {
579 // rita is an admin of guild: like its name, the picture is for owners (the settings page agrees).
580 const denied = await status(403, "DELETE", "/orgs/guild/avatar", undefined, T.ritaAdmin);
581 assert.match(denied.message, /only organization owners/);
582 await status(200, "DELETE", "/orgs/guild/avatar", undefined, T.olive);
583
584 // A second invitation to the same address, in any letter case, is refused.
585 await status(201, "POST", "/orgs/guild/invitations", { email: "twice@example.com" }, T.olive);
586 const again = await status(422, "POST", "/orgs/guild/invitations", { email: "Twice@Example.COM" }, T.olive);
587 assert.match(again.message, /already has a pending invitation/);
588});
589
590test("security: organization members get the base permission, which only owners change", async () => {
591 const can = async (path, as) => {
592 const { admin, push, pull } = (await ok("GET", path, undefined, as)).permissions;
593 return { admin, push, pull };
594 };
595 // New organizations start at read (guild's is unset, which also means read).
596 await ok("POST", "/user/orgs", { login: "fresh-org" });
597 assert.equal((await ok("GET", "/orgs/fresh-org")).default_repository_permission, "read");
598 assert.equal((await ok("GET", "/orgs/guild", undefined, T.milo)).default_repository_permission, "read");
599 await ok("POST", "/orgs/guild/repos", { name: "vault", private: true });
600 assert.deepEqual(await can("/repos/guild/vault", T.milo), { admin: false, push: false, pull: true });
601
602 // Only owners change it, to one of none, read, write or admin.
603 await status(403, "PATCH", "/orgs/guild", { default_repository_permission: "write" }, T.ritaAdmin);
604 await status(403, "PATCH", "/orgs/guild", { default_repository_permission: "write" }, T.milo);
605 await status(422, "PATCH", "/orgs/guild", { default_repository_permission: "maintain" });
606 assert.equal((await ok("PATCH", "/orgs/guild", { default_repository_permission: "write" })).default_repository_permission, "write");
607 assert.deepEqual(await can("/repos/guild/vault", T.milo), { admin: false, push: true, pull: true });
608
609 // With none, members don't see private repositories they weren't given; admins still administer them.
610 await ok("PATCH", "/orgs/guild", { default_repository_permission: "none" });
611 await status(404, "GET", "/repos/guild/vault", undefined, T.milo);
612 assert.ok(!(await ok("GET", "/orgs/guild/repos", undefined, T.milo)).some((r) => r.name === "vault"));
613 assert.deepEqual(await can("/repos/guild/vault", T.ritaAdmin), { admin: true, push: true, pull: true });
614
615 // A member administers the repositories they create, whatever the base permission.
616 await ok("POST", "/orgs/guild/repos", { name: "milo-tools", private: true }, T.milo);
617 assert.deepEqual(await can("/repos/guild/milo-tools", T.milo), { admin: true, push: true, pull: true });
618 await ok("PATCH", "/orgs/guild", { default_repository_permission: "read" });
619});
620
621/** A web form post as olive (signed in by session), with the CSRF pair taken from `page`. */
622const oliveSubmits = (page, action, fields) => submitsAs(S.olive, page, action, fields);
623
624/** A web form post signed in with `session`, with the CSRF pair taken from `page`. */
625async function submitsAs(session, page, action, fields) {
626 const cookie = `__Host-dfy_session=${session}`;
627 const res = await fetch(`${base}${page}`, { headers: { cookie } });
628 const csrf = /name="_csrf" value="([^"]+)"/.exec(await res.text())?.[1];
629 const pair = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1];
630 assert.ok(csrf && pair, `no CSRF pair on ${page} (${res.status})`);
631 const r = await fetch(`${base}${action}`, { method: "POST", body: new URLSearchParams({ _csrf: csrf, ...fields }), redirect: "manual", headers: { cookie: `${cookie}; dfy_csrf=${pair}`, "sec-fetch-site": "same-origin" } });
632 return { status: r.status, flash: decodeURIComponent(decodeURIComponent(r.headers.get("set-cookie") ?? "")), text: await r.text() };
633}
634
635/** Call an MCP tool with a token. */
636async function mcpTool(as, name, args) {
637 const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${as}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) });
638 const { result } = await r.json();
639 return { isError: result.isError, text: result.content[0].text, data: result.structuredContent };
640}
641
642test("security: leaving an organization takes its repository access along", async () => {
643 // sam, a member of shop, creates a repository (and so administers it) and is given write on another,
644 // as is the agent he works with.
645 await ok("PATCH", "/orgs/shop", { default_repository_permission: "none" });
646 await ok("POST", "/orgs/shop/repos", { name: "sam-lab", private: true }, T.sam);
647 await ok("POST", "/orgs/shop/repos", { name: "tools", private: true });
648 const helper = (await ok("POST", "/diffinery/agents", { login: "sam-helper" }, { cookie: S.sam })).agent.login;
649 await status(204, "PUT", "/repos/shop/tools/collaborators/sam", { permission: "write" });
650 await status(204, "PUT", `/repos/shop/tools/collaborators/${helper}`, { permission: "write" });
651 assert.equal((await ok("GET", "/repos/shop/sam-lab", undefined, T.sam)).permissions.admin, true);
652 assert.equal((await ok("GET", "/repos/shop/tools", undefined, T.sam)).permissions.push, true);
653
654 // Removing him from the organization removes those grants, his agent's included.
655 const removed = await oliveSubmits("/shop?tab=people", "/shop/-/org/members", { login: "sam", role: "remove" });
656 assert.equal(removed.status, 303, removed.flash);
657 assert.doesNotMatch(removed.flash, /error/i);
658 await status(404, "GET", "/repos/shop/sam-lab", undefined, T.sam);
659 await status(404, "GET", "/repos/shop/tools", undefined, T.sam);
660 const logins = async (repo) => (await ok("GET", `/repos/shop/${repo}/collaborators`)).map((u) => u.login);
661 assert.ok(!(await logins("sam-lab")).includes("sam"));
662 assert.deepEqual((await logins("tools")).filter((l) => l === "sam" || l === helper), []);
663});
664
665test("security: organization settings are checked before anything is saved, and agents see the base permission", async () => {
666 // A non-string name is a 422, not a crash; a bad base permission doesn't let the rename through.
667 const bad = await status(422, "PATCH", "/orgs/guild", { name: 123 });
668 assert.match(bad.message, /name must be a string/);
669 await status(422, "PATCH", "/orgs/guild", { name: "Halfway", default_repository_permission: "superuser" });
670 assert.equal((await ok("GET", "/orgs/guild")).name, "guild");
671 // The settings form does the same.
672 const form = await oliveSubmits("/guild?tab=settings", "/guild/-/org/settings", { login: "guild", name: "Halfway", base_role: "superuser" });
673 assert.match(form.flash, /base permission must be/);
674 assert.equal((await ok("GET", "/orgs/guild")).name, "guild");
675 const saved = await oliveSubmits("/guild?tab=settings", "/guild/-/org/settings", { login: "guild", name: "The Guild", base_role: "read" });
676 assert.match(saved.flash, /Organization updated/);
677 assert.equal((await ok("GET", "/orgs/guild")).name, "The Guild");
678
679 // olive-bot works for an owner of guild: it sees the base permission, in the API and over MCP.
680 assert.equal((await ok("GET", "/orgs/guild", undefined, T.bot)).default_repository_permission, "read");
681 const org = await mcpTool(T.bot, "get_organization", { org: "guild" });
682 assert.equal(org.isError, false, org.text);
683 assert.equal(org.data.default_repository_permission, "read");
684 // Outsiders don't.
685 assert.equal((await mcpTool(T.sam, "get_organization", { org: "guild" })).data.default_repository_permission, undefined);
686 assert.equal((await ok("GET", "/orgs/guild", undefined, T.sam)).default_repository_permission, undefined);
687
688 // Deleting an organization secret that doesn't exist is a 404 and leaves no audit entry.
689 await status(404, "DELETE", "/orgs/guild/actions/secrets/NEVER_SET");
690 await status(204, "PUT", "/orgs/guild/actions/secrets/DEPLOY_KEY", { value: "k" });
691 await status(204, "DELETE", "/orgs/guild/actions/secrets/DEPLOY_KEY");
692 await until("the secret's audit entry", async () => auditLog("org.secret.delete").some((e) => JSON.parse(e.detail).name === "DEPLOY_KEY"));
693 assert.ok(!auditLog("org.secret.delete").some((e) => JSON.parse(e.detail).name === "NEVER_SET"));
694});
695
696/** A request that doesn't follow redirects: as a token, or as olive's browser session (`{ cookie: true }`). */
697async function manual(method, url, { as = T.olive, body } = {}) {
698 const headers = { "content-type": "application/json" };
699 if (typeof as === "string") headers.authorization = `Bearer ${as}`;
700 else if (as?.cookie) headers.cookie = `__Host-dfy_session=${S.olive}`;
701 const res = await fetch(url.startsWith("http") ? url : `${base}${url}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual" });
702 const text = await res.text();
703 let json = null;
704 try {
705 json = text ? JSON.parse(text) : null;
706 } catch {}
707 return { status: res.status, location: res.headers.get("location"), json, text };
708}
709
710/** Runs git, returning its stderr; fails the test when git fails. */
711function gitRun(args, cwd) {
712 const r = spawnSync("git", ["-c", "protocol.version=2", "-c", "user.name=e2e", "-c", "user.email=e2e@example.com", ...args], { cwd, encoding: "utf8" });
713 assert.equal(r.status, 0, `git ${args.join(" ")} failed:\n${r.stderr}`);
714 return r.stderr;
715}
716
717/** Uploads a blob, then a one-layer manifest tagged `tag`, through the registry API. */
718async function pushTinyImage(name, tag, as) {
719 const auth = { authorization: `Basic ${Buffer.from(`anyone:${as}`).toString("base64")}` };
720 const digest = (b) => `sha256:${createHash("sha256").update(b).digest("hex")}`;
721 const blob = async (bytes) => {
722 const r = await fetch(`${base}/v2/${name}/blobs/uploads/?digest=${digest(bytes)}`, { method: "POST", body: bytes, headers: { ...auth, "content-type": "application/octet-stream" } });
723 assert.equal(r.status, 201, await r.text());
724 return { digest: digest(bytes), size: bytes.length };
725 };
726 const layer = randomBytes(256);
727 const config = Buffer.from(JSON.stringify({ architecture: "amd64", os: "linux", rootfs: { type: "layers", diff_ids: [digest(layer)] } }));
728 const manifest = JSON.stringify({ schemaVersion: 2, mediaType: "application/vnd.oci.image.manifest.v1+json", config: { mediaType: "application/vnd.oci.image.config.v1+json", ...(await blob(config)) }, layers: [{ mediaType: "application/vnd.oci.image.layer.v1.tar+gzip", ...(await blob(layer)) }] });
729 const r = await fetch(`${base}/v2/${name}/manifests/${tag}`, { method: "PUT", body: manifest, headers: { ...auth, "content-type": "application/vnd.oci.image.manifest.v1+json" } });
730 assert.equal(r.status, 201, await r.text());
731}
732const pullManifest = (name, tag, as) => fetch(`${base}/v2/${name}/manifests/${tag}`, { headers: { authorization: `Basic ${Buffer.from(`anyone:${as}`).toString("base64")}`, accept: "application/vnd.oci.image.manifest.v1+json" } }).then(async (r) => ({ status: r.status, json: await r.json().catch(() => null) }));
733
734test("security: a transferred repository keeps its data, and its old name redirects only for readers", async () => {
735 // Two organizations olive owns, like moving everything from codician-team to codician. sam is a
736 // member of the old one, which gives members no access by default.
737 await ok("POST", "/user/orgs", { login: "team-old" });
738 await ok("POST", "/user/orgs", { login: "team-new" });
739 await ok("PATCH", "/orgs/team-old", { default_repository_permission: "none" });
740 assert.equal((await oliveSubmits("/team-old?tab=people", "/team-old/-/org/people", { who: "sam", role: "member" })).status, 303);
741
742 // ------------------------------------------------------------ a private repository with history, an issue, a secret, a variable and an image
743 await repoWithReadme("moving");
744 const R = `/repos/${OWNER}/moving`;
745 const issue = await ok("POST", `${R}/issues`, { title: "survives the move" });
746 await status(204, "PUT", `${R}/actions/secrets/DEPLOY_KEY`, { value: "s3cret" });
747 await status(204, "PUT", `${R}/actions/variables/REGION`, { value: "eu" });
748 await status(204, "PUT", `${R}/collaborators/rita`, { permission: "read" });
749 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
750 const repoId = (await ok("GET", R)).id;
751 await pushTinyImage(`${OWNER}/moving`, "v1", T.olive);
752
753 // ------------------------------------------------------------ who may transfer
754 // Agents never, whatever their role; readers and read-scoped tokens need admin; a missing body field is a 422.
755 assert.match((await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.bot)).message, /agents/);
756 await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.rita);
757 await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.reader);
758 await status(404, "POST", `${R}/transfer`, { new_owner: "sam" }, T.sam);
759 await status(422, "POST", `${R}/transfer`, {});
760 await status(422, "POST", `${R}/transfer`, { new_owner: "nobody-here" });
761 // Only to your own account or an organization you own or administer.
762 assert.match((await status(403, "POST", `${R}/transfer`, { new_owner: "sam" })).message, /your own account/);
763 await ok("POST", "/user/repos", { name: "scratch" }, T.sam);
764 await status(403, "POST", "/repos/sam/scratch/transfer", { new_owner: "guild" }, T.sam);
765 // Not onto a name the target already uses.
766 await ok("POST", "/orgs/team-old/repos", { name: "clash", private: true });
767 assert.match((await status(422, "POST", `${R}/transfer`, { new_owner: "team-old", new_name: "clash" })).message, /already has a repository named clash/);
768
769 // ------------------------------------------------------------ user to organization
770 const moved = await status(202, "POST", `${R}/transfer`, { new_owner: "team-old" });
771 assert.equal(moved.full_name, "team-old/moving");
772 assert.equal(moved.owner.login, "team-old");
773 assert.equal(moved.id, repoId);
774 const N = "/repos/team-old/moving";
775
776 // Everything stayed: issues, secrets, variables and direct collaborators.
777 assert.equal((await ok("GET", `${N}/issues/${issue.number}`)).title, "survives the move");
778 assert.ok((await ok("GET", `${N}/actions/secrets`)).secrets.some((s) => s.name === "DEPLOY_KEY"));
779 assert.ok((await ok("GET", `${N}/actions/variables`)).variables.some((v) => v.name === "REGION" && v.value === "eu"));
780 assert.ok((await ok("GET", `${N}/collaborators`)).some((u) => u.login === "rita"), "a user-to-org transfer keeps direct collaborators");
781 assert.equal((await ok("GET", N, undefined, T.rita)).permissions.pull, true);
782
783 // ------------------------------------------------------------ REST: 301 for reads, 307 for the rest, like GitHub
784 const get = await manual("GET", `/api/v3${R}/issues?state=all`);
785 assert.equal(get.status, 301);
786 assert.equal(get.location, `${base}/api/v3${N}/issues?state=all`);
787 assert.equal(get.json.url, get.location);
788 const post = await manual("POST", `/api/v3${R}/issues`, { body: { title: "via the old name" } });
789 assert.equal(post.status, 307);
790 assert.equal(post.location, `${base}/api/v3${N}/issues`);
791 // A client that follows the redirect (fetch, Octokit) keeps working, writes included.
792 assert.equal((await status(201, "POST", `${R}/issues`, { title: "followed" })).title, "followed");
793 assert.equal((await manual("GET", `/api/v3${R}`, { as: T.rita })).location, `${base}/api/v3${N}`);
794 // Someone who can't read the repository learns nothing: the same 404 (or 401) as for a name that never existed.
795 await status(404, "GET", R, undefined, T.sam);
796 await status(404, "GET", `${R}/issues`, undefined, T.sam);
797 await status(404, "POST", `${R}/issues`, { title: "probe" }, T.sam);
798 await status(404, "GET", R, undefined, null);
799 assert.deepEqual(await api("GET", R, undefined, T.sam), await api("GET", `/repos/${OWNER}/never-existed`, undefined, T.sam));
800
801 // ------------------------------------------------------------ web pages: 301 to the same page, query kept
802 const page = await manual("GET", `/${OWNER}/moving/issues?state=closed`, { as: { cookie: true } });
803 assert.equal(page.status, 301);
804 assert.equal(page.location, `${base}/team-old/moving/issues?state=closed`);
805 assert.equal((await manual("GET", `/${OWNER}/moving/blob/main/README.md`, { as: { cookie: true } })).location, `${base}/team-old/moving/blob/main/README.md`);
806
807 // ------------------------------------------------------------ git: clone and push through the old URL
808 const authed = (path) => base.replace("://", `://x:${T.olive}@`) + path;
809 const clone = join(work, "moving-old-url");
810 // Served under the old name, as GitHub does (a redirect would make git drop the token in the URL).
811 gitRun(["clone", "-q", authed(`/${OWNER}/moving.git`), clone]);
812 gitRun(["commit", "-q", "--allow-empty", "-m", "pushed through the old URL"], clone);
813 const pushed = gitRun(["push", "origin", "HEAD:main"], clone);
814 assert.match(pushed, /This repository moved\. Please use the new location:\s+remote:\s+\S+\/team-old\/moving\.git/);
815 const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: clone, encoding: "utf8" }).trim();
816 assert.equal((await ok("GET", `${N}/branches/main`)).commit.sha, head);
817 gitRun(["fetch", "-q", "origin"], clone);
818 const reader = spawnSync("git", ["-c", "protocol.version=2", "ls-remote", base.replace("://", `://x:${T.sam}@`) + `/${OWNER}/moving.git`], { encoding: "utf8" });
819 assert.notEqual(reader.status, 0, "someone without access can't clone through the old URL");
820 assert.doesNotMatch(reader.stderr, /team-old/);
821
822 // ------------------------------------------------------------ MCP tools take the old owner/name
823 const file = await mcpTool(T.olive, "get_file", { owner: OWNER, repo: "moving", path: "README.md" });
824 assert.equal(file.isError, false, file.text);
825 assert.match(file.data.content, /# moving/);
826 const hidden = await mcpTool(T.sam, "get_file", { owner: OWNER, repo: "moving", path: "README.md" });
827 assert.equal(hidden.isError, true);
828 assert.doesNotMatch(hidden.text, /team-old/);
829
830 // ------------------------------------------------------------ the image moved with it, and its old name resolves
831 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
832 assert.equal((await pullManifest(`${OWNER}/moving`, "v1", T.olive)).status, 200);
833 const probe = await pullManifest(`${OWNER}/moving`, "v1", T.sam);
834 assert.equal(probe.status, 404);
835 assert.doesNotMatch(JSON.stringify(probe.json), /team-old/);
836
837 // ------------------------------------------------------------ an organization that owns repositories can't be deleted
838 await status(204, "PUT", `${N}/collaborators/sam`, { permission: "write" });
839 assert.equal((await ok("GET", N, undefined, T.sam)).permissions.push, true);
840 await status(204, "DELETE", "/repos/team-old/clash");
841 const refused = await status(422, "DELETE", "/orgs/team-old");
842 assert.match(refused.message, /team-old still owns 1 repository; transfer or delete it/);
843 await status(403, "DELETE", "/orgs/team-old", undefined, T.sam);
844
845 // ------------------------------------------------------------ organization to organization, renamed on the way
846 const again = await status(202, "POST", `${N}/transfer`, { new_owner: "team-new", new_name: "moved" });
847 assert.equal(again.full_name, "team-new/moved");
848 const M = "/repos/team-new/moved";
849 // Grants that came with team-old go (sam is its member); outside collaborators stay.
850 const logins = (await ok("GET", `${M}/collaborators`)).map((u) => u.login);
851 assert.ok(logins.includes("rita") && !logins.includes("sam"), JSON.stringify(logins));
852 await status(404, "GET", M, undefined, T.sam);
853 await status(404, "GET", N, undefined, T.sam);
854 // Both old names lead here.
855 assert.equal((await manual("GET", `/api/v3${R}`)).location, `${base}/api/v3${M}`);
856 assert.equal((await manual("GET", `/api/v3${N}/pulls`)).location, `${base}/api/v3${M}/pulls`);
857 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
858
859 // ------------------------------------------------------------ a new repository at an old name takes over for good
860 await ok("POST", "/user/repos", { name: "moving" });
861 const fresh = await ok("GET", R);
862 assert.notEqual(fresh.id, repoId);
863 assert.equal(fresh.full_name, `${OWNER}/moving`);
864 // ...and so does its own image name: the moved image no longer answers there.
865 assert.equal((await pullManifest(`${OWNER}/moving`, "v1", T.olive)).status, 404);
866 assert.equal((await pullManifest("team-new/moving", "v1", T.olive)).status, 200);
867 // Deleting it doesn't bring the redirect back.
868 await status(204, "DELETE", R);
869 await status(404, "GET", R);
870
871 // ------------------------------------------------------------ the emptied organization can now be deleted; its old URLs keep working
872 await status(202, "DELETE", "/orgs/team-old");
873 await status(404, "GET", "/orgs/team-old");
874 assert.equal((await manual("GET", `/api/v3${N}`)).location, `${base}/api/v3${M}`);
875 assert.equal((await manual("GET", "/team-old/moving", { as: { cookie: true } })).location, `${base}/team-new/moved`);
876 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
877
878 // ------------------------------------------------------------ renames leave redirects too, and refuse a taken name
879 await ok("POST", "/orgs/team-new/repos", { name: "taken", private: true });
880 await status(422, "PATCH", M, { name: "taken" });
881 assert.equal((await ok("PATCH", M, { name: "settled" })).full_name, "team-new/settled");
882 assert.equal((await manual("GET", `/api/v3${M}`)).location, `${base}/api/v3/repos/team-new/settled`);
883
884 // ------------------------------------------------------------ the web form: a Kumo picker, a typed confirmation, CSRF
885 const settings = await fetch(`${base}/team-new/settled/settings`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } }).then((r) => r.text());
886 assert.match(settings, /Transfer ownership/);
887 assert.match(settings, /data-k="select"[^>]*new_owner/);
888 assert.doesNotMatch(settings, /<select/);
889 const wrong = await oliveSubmits("/team-new/settled/settings", "/team-new/settled/settings/transfer", { new_owner: "olive", new_name: "web-moved", confirm: "settled" });
890 assert.match(wrong.flash, /type team-new\/settled to confirm/);
891 const viaWeb = await oliveSubmits("/team-new/settled/settings", "/team-new/settled/settings/transfer", { new_owner: "olive", new_name: "web-moved", confirm: "team-new/settled" });
892 assert.equal(viaWeb.status, 303, viaWeb.flash);
893 assert.match(viaWeb.flash, /Transferred team-new\/settled to olive\/web-moved/);
894 assert.equal((await ok("GET", `/repos/${OWNER}/web-moved`)).id, repoId);
895 assert.equal((await ok("GET", `/repos/${OWNER}/web-moved/issues/${issue.number}`)).title, "survives the move");
896
897 // ------------------------------------------------------------ audited, with from and to
898 await until("transfer audit entries", async () => auditLog("repo.transfer").length >= 3);
899 const trail = auditLog("repo.transfer").map((e) => JSON.parse(e.detail));
900 assert.ok(trail.some((d) => d.from === `${OWNER}/moving` && d.to === "team-old/moving"), JSON.stringify(trail));
901 assert.ok(trail.some((d) => d.from === "team-old/moving" && d.to === "team-new/moved"));
902 assert.ok(trail.some((d) => d.from === "team-new/settled" && d.to === `${OWNER}/web-moved`));
903});
904
905test("security: agents land changes on protected branches only through auto-merge a person allowed, gated by CI", async () => {
906 const R = `/repos/${OWNER}/landing`;
907 await repoWithReadme("landing");
908 // A workflow on pushes to main shows who the merge's own runs act as (no runner ever takes its job).
909 const workflow = "on:\n push:\n branches: [main]\njobs:\n note:\n runs-on: [self-hosted, nobody]\n steps:\n - run: echo merged\n";
910 const mainSha = (await ok("PUT", `${R}/contents/.github/workflows/after-merge.yml`, { message: "after-merge workflow", content: b64(workflow) })).commit.sha;
911 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
912 await status(204, "PUT", `${R}/collaborators/olive-helper`, { permission: "write" });
913 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
914 /** A fresh clone of the repository, to read raw commits. */
915 const clone = () => {
916 const dir = mkdtempSync(join(work, "landing-"));
917 execFileSync("git", ["-c", `http.extraHeader=Authorization: Bearer ${T.olive}`, "clone", "-q", `${base}/${OWNER}/landing.git`, dir], { stdio: "pipe" });
918 return dir;
919 };
920 /** A pull request the agent opens from a new branch off `from`. */
921 const agentPull = async (branch, base = "main", from = mainSha, path = `${branch}.txt`) => {
922 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from }, T.bot);
923 const put = await ok("PUT", `${R}/contents/${path}`, { message: `agent: ${branch}`, content: b64(`${branch}\n`), branch }, T.bot);
924 const pr = await ok("POST", `${R}/pulls`, { title: `Agent ${branch}`, head: branch, base }, T.bot);
925 return { number: pr.number, head: put.commit.sha };
926 };
927
928 // ------------------------------------------------------------ refused unless a person allowed it, and CI gates it
929 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
930 const one = await agentPull("agent-one");
931 const off = await status(403, "PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
932 assert.match(off.message, /allowAgentAutoMerge/);
933 // The agent can't turn the setting on for itself, nor can its helper.
934 for (const as of [T.bot, T.helper]) await status(403, "PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true }, as);
935 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, allowAgentAutoMerge: true });
936 const unchecked = await status(422, "PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
937 assert.match(unchecked.message, /required status checks/);
938 await status(422, "PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"], allowAgentAutoMerge: "yes" });
939 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true });
940 // A change to the workflows that gate it needs a person.
941 const wf = await agentPull("agent-workflow", "main", mainSha, ".github/workflows/ci.yml");
942 assert.match((await status(422, "PUT", `${R}/pulls/${wf.number}/auto-merge`, {}, T.bot)).message, /workflow file/);
943
944 // ------------------------------------------------------------ with both, it merges by itself once the check passes, not before
945 const enabled = await ok("PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
946 assert.equal(enabled.state, "enabled");
947 assert.deepEqual([enabled.auto_merge.enabled_by.login, enabled.auto_merge.merge_method], ["olive-bot", "squash"]);
948 assert.equal((await pull(one.number)).auto_merge.enabled_by.login, "olive-bot");
949 // A direct merge is still the agent's to ask for and be refused, bypass flags or not.
950 for (const extra of [{}, { bypass_rules: true }, { bypass_merge_queue: true }]) {
951 assert.match((await status(405, "PUT", `${R}/pulls/${one.number}/merge`, { merge_method: "squash", ...extra }, T.bot)).message, /agents may not merge/);
952 }
953 // Approvals from agents don't count.
954 await ok("POST", `${R}/pulls/${one.number}/reviews`, { event: "APPROVE", body: "lgtm" }, T.helper);
955 const run = await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: one.head, status: "in_progress" });
956 let p = await pull(one.number);
957 assert.equal(p.approvals, 0);
958 assert.ok(p.merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(p.merge_blockers));
959 // A person approves; the required check is still running, so nothing merges yet.
960 await ok("POST", `${R}/pulls/${one.number}/reviews`, { event: "APPROVE", body: "ship it" });
961 await sleep(1500);
962 p = await pull(one.number);
963 assert.equal(p.merged, false);
964 assert.deepEqual(p.merge_blockers, ["required check 'ci' is in_progress"]);
965 assert.ok(p.auto_merge);
966 // The check passes: Diffinery merges, as the agent, and main moves to that commit.
967 await ok("PATCH", `${R}/check-runs/${run.id}`, { status: "completed", conclusion: "success" });
968 const merged = await until("auto-merge", async () => {
969 const x = await pull(one.number);
970 return x.merged ? x : null;
971 });
972 assert.equal(merged.merged_by.login, "olive-bot");
973 assert.equal(merged.auto_merge, null);
974 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, merged.merge_commit_sha);
975 // The merge commit says who it acts for, and the workflows it triggers run as the agent's.
976 assert.match(execFileSync("git", ["cat-file", "commit", merged.merge_commit_sha], { cwd: clone(), encoding: "utf8" }), /^diffinery-agent olive-bot on-behalf-of olive$/m);
977 const after = await until("the merge's push run", async () => (await ok("GET", `${R}/actions/runs?event=push`)).workflow_runs.find((r) => r.head_sha === merged.merge_commit_sha));
978 assert.equal(after.actor.login, "olive-bot");
979
980 // ------------------------------------------------------------ an approval counts only for the commit it approved
981 const three = await agentPull("agent-three", "main", merged.merge_commit_sha);
982 await ok("POST", `${R}/pulls/${three.number}/reviews`, { event: "APPROVE" });
983 const later = await ok("PUT", `${R}/contents/agent-three-later.txt`, { message: "after the approval", content: b64("later\n"), branch: "agent-three" }, T.bot);
984 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: later.commit.sha, status: "completed", conclusion: "success" });
985 assert.equal((await ok("PUT", `${R}/pulls/${three.number}/auto-merge`, {}, T.bot)).state, "enabled");
986 await sleep(1500);
987 assert.equal((await pull(three.number)).merged, false, "the person approved an older commit");
988 await ok("POST", `${R}/pulls/${three.number}/reviews`, { event: "APPROVE", body: "the new commit too" });
989 await until("merged after the fresh approval", async () => (await pull(three.number)).merged);
990
991 // ------------------------------------------------------------ a push by someone else cancels it; the agent's own doesn't
992 const two = await agentPull("agent-two");
993 await ok("POST", `${R}/pulls/${two.number}/reviews`, { event: "APPROVE" });
994 assert.equal((await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot)).state, "enabled");
995 await ok("PUT", `${R}/contents/agent-two-more.txt`, { message: "more", content: b64("more\n"), branch: "agent-two" }, T.bot);
996 assert.ok((await pull(two.number)).auto_merge, "the agent's own push keeps auto-merge on");
997 await ok("PUT", `${R}/contents/olive.txt`, { message: "olive's fix", content: b64("fix\n"), branch: "agent-two" });
998 assert.equal((await pull(two.number)).auto_merge, null);
999 const said = await ok("GET", `${R}/issues/${two.number}/comments`);
1000 assert.ok(said.some((c) => /Auto-merge was turned off: olive pushed new commits/.test(c.body)), JSON.stringify(said));
1001 // The pull request page turns it on and off for people, and the settings page has the switch.
1002 const cookie = `__Host-dfy_session=${S.olive}`;
1003 const web = async (path, form) => {
1004 const page = await fetch(`${base}/${OWNER}/landing/pull/${two.number}`, { headers: { cookie } });
1005 const html = await page.text();
1006 if (!form) return html;
1007 const csrf = /name="_csrf" value="([^"]+)"/.exec(html)?.[1];
1008 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
1009 const res = await fetch(`${base}/${OWNER}/landing${path}`, { method: "POST", body: new URLSearchParams({ _csrf: csrf, ...form }), redirect: "manual", headers: { cookie: `${cookie}; dfy_csrf=${csrfCookie}`, "sec-fetch-site": "same-origin" } });
1010 assert.equal(res.status, 303, `POST ${path}`);
1011 return html;
1012 };
1013 assert.match(await web(`/pull/${two.number}/auto-merge`, { method: "squash" }), /Enable auto-merge/);
1014 assert.equal((await pull(two.number)).auto_merge.enabled_by.login, OWNER);
1015 assert.match(await web(`/pull/${two.number}/auto-merge/disable`, {}), /Auto-merge is on[\s\S]*Disable auto-merge/);
1016 assert.equal((await pull(two.number)).auto_merge, null);
1017 const settings = await (await fetch(`${base}/${OWNER}/landing/settings/branches`, { headers: { cookie } })).text();
1018 assert.match(settings, /Allow agents to land pull requests through auto-merge/);
1019 assert.doesNotMatch(settings, /<select|type="checkbox"/);
1020 // Turned on again, then off on request.
1021 await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot);
1022 await status(204, "DELETE", `${R}/pulls/${two.number}/auto-merge`, undefined, T.bot);
1023 assert.equal((await pull(two.number)).auto_merge, null);
1024 // Taking the setting away turns an agent's waiting auto-merge off.
1025 await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot);
1026 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
1027 await until("auto-merge turned off", async () => (await pull(two.number)).auto_merge === null);
1028
1029 // ------------------------------------------------------------ the merge queue path, for agents with the setting
1030 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1031 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1032 const q = await agentPull("agent-queue", "train");
1033 await ok("POST", `${R}/pulls/${q.number}/reviews`, { event: "APPROVE" });
1034 await status(403, "PUT", `${R}/pulls/${q.number}/merge-queue`, {}, T.bot);
1035 await status(403, "PUT", `${R}/pulls/${q.number}/auto-merge`, {}, T.bot);
1036 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" }, allowAgentAutoMerge: true });
1037 // Auto-merge waits for the head's check, then joins the queue; the merge group's check gates the merge.
1038 const queued = await ok("PUT", `${R}/pulls/${q.number}/auto-merge`, {}, T.bot);
1039 assert.deepEqual([queued.state, queued.auto_merge.merge_method], ["enabled", "squash"]);
1040 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: q.head, status: "completed", conclusion: "success" });
1041 const entry = await until("queued by auto-merge", async () => (await ok("GET", `${R}/merge-queue/train`)).entries.find((e) => e.number === q.number && e.merge_group));
1042 assert.equal(entry.enqueued_by.login, "olive-bot");
1043 assert.equal((await pull(q.number)).merged, false);
1044 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: entry.merge_group.head_sha, status: "completed", conclusion: "success" });
1045 assert.equal((await until("merged through the queue", async () => ((await pull(q.number)).merged ? pull(q.number) : null))).merged_by.login, "olive-bot");
1046 // An agent may also add a ready pull request to the queue itself.
1047 const q2 = await agentPull("agent-queue-2", "train", (await ok("GET", `${R}/branches/train`)).commit.sha);
1048 await ok("POST", `${R}/pulls/${q2.number}/reviews`, { event: "APPROVE" });
1049 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: q2.head, status: "completed", conclusion: "success" });
1050 const direct = await status(201, "PUT", `${R}/pulls/${q2.number}/merge-queue`, {}, T.bot);
1051 assert.equal(direct.state, "queued");
1052 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: direct.entry.merge_group.head_sha, status: "completed", conclusion: "success" });
1053 await until("second queue merge", async () => (await pull(q2.number)).merged);
1054
1055 // ------------------------------------------------------------ all of it is on the record
1056 await until("auto-merge audit entries", async () => {
1057 const setting = auditLog("repo.protection.agent_auto_merge").filter((e) => e.target === `${OWNER}/landing`);
1058 const on = auditLog("pull_request.auto_merge_enabled").filter((e) => e.target.startsWith(`${OWNER}/landing#`));
1059 const offs = auditLog("pull_request.auto_merge_disabled").filter((e) => e.target === `${OWNER}/landing#${two.number}`);
1060 const done = auditLog("pull_request.auto_merged").find((e) => e.target === `${OWNER}/landing#${one.number}`);
1061 return setting.length >= 3 && setting.every((e) => e.actor_login === OWNER) && on.some((e) => e.actor_login === "olive-bot") && on.some((e) => e.actor_login === OWNER) && offs.length >= 2 && done?.actor_login === "olive-bot";
1062 });
1063});
1064
1065test("security: an admin can let agents' auto-merges land on green checks without an approval, and nothing more", async () => {
1066 const R = `/repos/${OWNER}/waived`;
1067 const mainSha = await repoWithReadme("waived");
1068 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1069 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1070 /** A pull request `as` opens from a new branch off `from`, writing `path`. */
1071 const opened = async (branch, as, from = mainSha, path = `${branch}.txt`) => {
1072 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from }, as);
1073 const put = await ok("PUT", `${R}/contents/${path}`, { message: branch, content: b64(`${branch}\n`), branch }, as);
1074 const pr = await ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main" }, as);
1075 return { number: pr.number, head: put.commit.sha };
1076 };
1077 const green = (head) => ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" });
1078 const rule = { requirePullRequest: true, requiredChecks: ["ci"], requiredApprovals: 1, allowAgentAutoMerge: true };
1079
1080 // ------------------------------------------------------------ only an admin sets it, only alongside allowAgentAutoMerge
1081 await status(422, "PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], agentAutoMergeWithoutApproval: true });
1082 await status(422, "PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: "yes" });
1083 await status(403, "PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: true }, T.bot);
1084 await ok("PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: true });
1085 await until("waiver audit", async () => auditLog("repo.protection.agent_approval_waiver").some((e) => JSON.parse(e.detail).enabled === true && e.actor_login === OWNER));
1086
1087 // ------------------------------------------------------------ an agent's pull request lands on the green check alone
1088 const one = await opened("agent-one", T.bot);
1089 assert.equal((await ok("PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot)).state, "enabled");
1090 await sleep(1000);
1091 assert.equal((await pull(one.number)).merged, false, "the required check still gates it");
1092 await green(one.head);
1093 const merged = await until("waived auto-merge", async () => {
1094 const x = await pull(one.number);
1095 return x.merged ? x : null;
1096 });
1097 assert.equal(merged.merged_by.login, "olive-bot");
1098 assert.equal(merged.approvals, 0);
1099 // A direct merge by the agent is still refused.
1100 const direct = await opened("agent-direct", T.bot, merged.merge_commit_sha);
1101 await green(direct.head);
1102 assert.match((await status(405, "PUT", `${R}/pulls/${direct.number}/merge`, { merge_method: "squash" }, T.bot)).message, /agents may not merge/);
1103
1104 // ------------------------------------------------------------ a person's requested changes and workflow edits still need a person
1105 const objected = await opened("agent-objected", T.bot, merged.merge_commit_sha);
1106 await ok("POST", `${R}/pulls/${objected.number}/reviews`, { event: "REQUEST_CHANGES", body: "not like this" });
1107 await green(objected.head);
1108 assert.equal((await ok("PUT", `${R}/pulls/${objected.number}/auto-merge`, {}, T.bot)).state, "enabled");
1109 await sleep(1500);
1110 const held = await pull(objected.number);
1111 assert.equal(held.merged, false);
1112 assert.ok(held.merge_blockers.some((b) => /changes requested by/.test(b)), JSON.stringify(held.merge_blockers));
1113 const wf = await opened("agent-workflow", T.bot, merged.merge_commit_sha, ".github/workflows/ci.yml");
1114 await green(wf.head);
1115 assert.match((await status(422, "PUT", `${R}/pulls/${wf.number}/auto-merge`, {}, T.bot)).message, /workflow file/);
1116
1117 // ------------------------------------------------------------ people's own pull requests keep the rule's approvals
1118 const mine = await opened("person", undefined, merged.merge_commit_sha);
1119 await green(mine.head);
1120 assert.equal((await ok("PUT", `${R}/pulls/${mine.number}/auto-merge`, {})).state, "enabled");
1121 await sleep(1500);
1122 const waiting = await pull(mine.number);
1123 assert.equal(waiting.merged, false);
1124 assert.ok(waiting.merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(waiting.merge_blockers));
1125
1126 // ------------------------------------------------------------ the settings page shows it; turning allowAgentAutoMerge off ends it
1127 const settings = await (await fetch(`${base}/${OWNER}/waived/settings/branches`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } })).text();
1128 assert.match(settings, /Let agents&#39; auto-merges land without an approving review|Let agents' auto-merges land without an approving review/);
1129 assert.doesNotMatch(settings, /<select|type="checkbox"/);
1130 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], requiredApprovals: 1 });
1131 await until("waiver off audit", async () => auditLog("repo.protection.agent_approval_waiver").some((e) => JSON.parse(e.detail).enabled === false));
1132 await ok("PUT", `${R}/branches/main/protection`, rule);
1133 const after = await opened("agent-after", T.bot, merged.merge_commit_sha);
1134 await green(after.head);
1135 assert.equal((await ok("PUT", `${R}/pulls/${after.number}/auto-merge`, {}, T.bot)).state, "enabled");
1136 await sleep(1500);
1137 const again = await pull(after.number);
1138 assert.equal(again.merged, false, "the waiver does not come back with allowAgentAutoMerge");
1139 // A person's approval lands it, as before the waiver.
1140 await ok("POST", `${R}/pulls/${after.number}/reviews`, { event: "APPROVE" });
1141 await until("merged after the approval", async () => (await pull(after.number)).merged);
1142});
1143
1144test("security: an archived repository lands nothing by itself: archiving ends auto-merge and empties the merge queue", async () => {
1145 const R = `/repos/${OWNER}/shelved`;
1146 const mainSha = await repoWithReadme("shelved");
1147 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1148 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1149 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1150 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1151 const said = async (n) => (await ok("GET", `${R}/issues/${n}/comments`)).map((c) => c.body);
1152 const opened = async (branch, base) => {
1153 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: mainSha });
1154 const put = await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1155 return { number: (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base })).number, head: put.commit.sha };
1156 };
1157 // One pull request waits for its check with auto-merge on; another waits in the merge queue for its group's check.
1158 const waiting = await opened("waiting", "main");
1159 assert.equal((await ok("PUT", `${R}/pulls/${waiting.number}/auto-merge`, {})).state, "enabled");
1160 const queued = await opened("queued", "train");
1161 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: queued.head, status: "completed", conclusion: "success" });
1162 const entry = await status(201, "PUT", `${R}/pulls/${queued.number}/merge-queue`, {});
1163 assert.ok(entry.entry.merge_group);
1164
1165 // ------------------------------------------------------------ archiving turns both off, saying why
1166 assert.equal((await ok("PATCH", R, { archived: true })).archived, true);
1167 assert.equal((await pull(waiting.number)).auto_merge, null);
1168 assert.deepEqual((await ok("GET", `${R}/merge-queue/train`)).entries, []);
1169 assert.ok((await said(waiting.number)).includes("Auto-merge was turned off: the repository is archived."), JSON.stringify(await said(waiting.number)));
1170 assert.ok((await said(queued.number)).includes("This pull request was removed from the merge queue: the repository is archived."), JSON.stringify(await said(queued.number)));
1171 await status(403, "PUT", `${R}/pulls/${waiting.number}/auto-merge`, {});
1172
1173 // ------------------------------------------------------------ unarchived, nothing comes back by itself
1174 await ok("PATCH", R, { archived: false });
1175 for (const n of [waiting.number, queued.number]) assert.equal((await pull(n)).merged, false);
1176 assert.equal((await pull(waiting.number)).auto_merge, null);
1177 assert.equal((await ok("PUT", `${R}/pulls/${waiting.number}/auto-merge`, {})).state, "enabled");
1178 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: waiting.head, status: "completed", conclusion: "success" });
1179 await until("auto-merged once unarchived", async () => (await pull(waiting.number)).merged);
1180});
1181
1182test("security: landing a pull request deletes its head branch only when asked, through auto-merge and the queue too, and never a protected one", async () => {
1183 const R = `/repos/${OWNER}/tidy`;
1184 const mainSha = await repoWithReadme("tidy");
1185 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1186 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1187 const green = (head) => ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" });
1188 const exists = async (branch) => (await api("GET", `${R}/branches/${branch}`)).status === 200;
1189 const opened = async (branch, base = "main", from = mainSha) => {
1190 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from });
1191 const put = await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1192 return { number: (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base })).number, head: put.commit.sha };
1193 };
1194
1195 // ------------------------------------------------------------ a protected head branch stays, even where the rule allows deleting it
1196 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/release", sha: mainSha });
1197 const rel = await ok("PUT", `${R}/contents/release.txt`, { message: "release", content: b64("release\n"), branch: "release" });
1198 await ok("PUT", `${R}/branches/release/protection`, { allowDeletion: true });
1199 const release = (await ok("POST", `${R}/pulls`, { title: "release", head: "release", base: "main" })).number;
1200 await green(rel.commit.sha);
1201 await ok("PUT", `${R}/pulls/${release}/merge`, { delete_branch: true });
1202 assert.equal((await pull(release)).merged, true);
1203 assert.equal(await exists("release"), true, "a protected head branch is never deleted by a merge");
1204
1205 // ------------------------------------------------------------ auto-merge keeps delete_branch, like a manual merge
1206 const gone = await opened("auto-delete");
1207 const on = await ok("PUT", `${R}/pulls/${gone.number}/auto-merge`, { delete_branch: true });
1208 assert.deepEqual([on.state, on.auto_merge.delete_branch, (await pull(gone.number)).auto_merge.delete_branch], ["enabled", true, true]);
1209 await status(422, "PUT", `${R}/pulls/${gone.number}/auto-merge`, { delete_branch: "yes" });
1210 await status(409, "PUT", `${R}/pulls/${gone.number}/auto-merge`, { sha: mainSha });
1211 await green(gone.head);
1212 await until("auto-merged", async () => (await pull(gone.number)).merged);
1213 await until("its head branch deleted", async () => !(await exists("auto-delete")));
1214 const kept = await opened("auto-keep");
1215 await ok("PUT", `${R}/pulls/${kept.number}/auto-merge`, {});
1216 await green(kept.head);
1217 await until("auto-merged, keeping the branch", async () => (await pull(kept.number)).merged);
1218 assert.equal(await exists("auto-keep"), true);
1219
1220 // ------------------------------------------------------------ through the merge queue, by auto-merge
1221 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1222 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1223 const q = await opened("queue-delete", "train");
1224 await ok("PUT", `${R}/pulls/${q.number}/auto-merge`, { delete_branch: true });
1225 await green(q.head);
1226 const entry = await until("queued by auto-merge", async () => (await ok("GET", `${R}/merge-queue/train`)).entries.find((e) => e.number === q.number && e.merge_group));
1227 assert.equal(entry.delete_branch, true);
1228 await green(entry.merge_group.head_sha);
1229 await until("merged through the queue", async () => (await pull(q.number)).merged);
1230 await until("its head branch deleted", async () => !(await exists("queue-delete")));
1231});
1232
1233test("security: agents see what auto-merge needs next to the refusal to merge directly", async () => {
1234 const R = `/repos/${OWNER}/insight`;
1235 const mainSha = await repoWithReadme("insight");
1236 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1237 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true });
1238 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-insight", sha: mainSha }, T.bot);
1239 const put = await ok("PUT", `${R}/contents/insight.txt`, { message: "insight", content: b64("insight\n"), branch: "agent-insight" }, T.bot);
1240 const pr = (await ok("POST", `${R}/pulls`, { title: "insight", head: "agent-insight", base: "main" }, T.bot)).number;
1241 const viaMcp = async (as = T.bot) => (await mcpTool(as, "get_pull_request", { owner: OWNER, repo: "insight", number: pr })).data;
1242
1243 // ------------------------------------------------------------ the agent may not merge, but auto-merge only waits for CI and a person
1244 let m = await viaMcp();
1245 assert.ok(m.mergeability.blockers.some((b) => /agents may not merge/.test(b)), JSON.stringify(m.mergeability.blockers));
1246 assert.ok(Array.isArray(m.auto_merge_blockers), JSON.stringify(Object.keys(m)));
1247 assert.ok(!m.auto_merge_blockers.some((b) => /agents may not merge/.test(b)), JSON.stringify(m.auto_merge_blockers));
1248 assert.ok(m.auto_merge_blockers.some((b) => /required check 'ci' has not run/.test(b)), JSON.stringify(m.auto_merge_blockers));
1249 assert.ok(m.auto_merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(m.auto_merge_blockers));
1250 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: put.commit.sha, status: "completed", conclusion: "success" });
1251 await ok("POST", `${R}/pulls/${pr}/reviews`, { event: "APPROVE" });
1252 m = await viaMcp();
1253 assert.deepEqual(m.auto_merge_blockers, []);
1254 assert.ok(m.mergeability.blockers.some((b) => /agents may not merge/.test(b)), "the refusal to merge directly still shows");
1255 // The REST API says the same.
1256 const rest = await ok("GET", `${R}/pulls/${pr}`, undefined, T.bot);
1257 assert.deepEqual(rest.auto_merge_blockers, []);
1258 assert.ok(rest.merge_blockers.some((b) => /agents may not merge/.test(b)));
1259 // People merge and auto-merge on the same terms, so they get no second list.
1260 assert.equal((await ok("GET", `${R}/pulls/${pr}`)).auto_merge_blockers, undefined);
1261 assert.equal((await viaMcp(T.olive)).auto_merge_blockers, undefined);
1262 // Without the setting, auto-merge's own refusal shows there.
1263 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
1264 assert.ok((await viaMcp()).auto_merge_blockers.some((b) => /allowAgentAutoMerge/.test(b)));
1265 assert.equal((await pull(pr)).merged, false);
1266 async function pull(n) {
1267 return ok("GET", `${R}/pulls/${n}`);
1268 }
1269});
1270
1271test("security: the queue's bypass button does what it says, and a merge queue can't contradict linear history", async () => {
1272 const R = `/repos/${OWNER}/bypass`;
1273 const mainSha = await repoWithReadme("bypass");
1274 // ------------------------------------------------------------ a queue that would make merge commits on a linear branch is refused
1275 const contradiction = await status(422, "PUT", `${R}/branches/main/protection`, { requireLinearHistory: true, mergeQueue: { method: "merge" } });
1276 assert.match(contradiction.message, /linear history/);
1277 await ok("PUT", `${R}/branches/main/protection`, { requireLinearHistory: true, mergeQueue: {} });
1278 assert.equal((await ok("GET", `${R}/branches/main/protection`)).rules.mergeQueue.method, "squash", "without a method, a linear branch's queue squashes");
1279
1280 // ------------------------------------------------------------ the web button sends what its label promises
1281 const cookie = `__Host-dfy_session=${S.olive}`;
1282 const opened = async (branch) => {
1283 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: mainSha });
1284 await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1285 return (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main" })).number;
1286 };
1287 /** The pull request page's form that merges directly, its button label, and the result of submitting it. */
1288 const bypassForm = async (n) => {
1289 const page = await fetch(`${base}/${OWNER}/bypass/pull/${n}`, { headers: { cookie } });
1290 const html = await page.text();
1291 const form = [...html.matchAll(/<form[^>]*action="([^"]+)"[^>]*>([\s\S]*?)<\/form>/g)].find((m) => m[1].endsWith(`/pull/${n}/merge`));
1292 if (!form) return null;
1293 const fields = Object.fromEntries([...form[2].matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)"/g)].map((m) => [m[1], m[2]]));
1294 const label = />([^<]*)<\/button>/.exec(form[2])?.[1];
1295 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
1296 const submit = () => fetch(`${base}${form[1]}`, { method: "POST", body: new URLSearchParams(fields), redirect: "manual", headers: { cookie: `${cookie}; dfy_csrf=${csrfCookie}`, "sec-fetch-site": "same-origin" } });
1297 return { fields, label, submit };
1298 };
1299 const merged = async (n) => (await ok("GET", `${R}/pulls/${n}`)).merged;
1300
1301 // Rules met: the button skips only the queue.
1302 await ok("PUT", `${R}/branches/main/protection`, { mergeQueue: { method: "squash" } });
1303 const ready = await opened("ready");
1304 const plain = await bypassForm(ready);
1305 assert.equal(plain.fields.bypass_queue, "1");
1306 assert.equal(plain.fields.bypass_rules, undefined);
1307 assert.match(plain.label, /bypass the queue/);
1308 assert.equal((await plain.submit()).status, 303);
1309 assert.equal(await merged(ready), true);
1310
1311 // Rules unmet: an admin who may bypass them gets a button that says so, sends bypass_rules, and is audited.
1312 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1, mergeQueue: { method: "squash" } });
1313 const unreviewed = await opened("unreviewed");
1314 const both = await bypassForm(unreviewed);
1315 assert.deepEqual([both.fields.bypass_queue, both.fields.bypass_rules], ["1", "1"]);
1316 assert.match(both.label, /bypass the queue and the unmet requirements/);
1317 assert.equal((await both.submit()).status, 303);
1318 assert.equal(await merged(unreviewed), true);
1319 await until("bypass audit", async () => auditLog("pull_request.merge_bypassed").some((e) => e.target === `${OWNER}/bypass#${unreviewed}` && /approving review/.test(e.detail) && /merge queue/.test(e.detail)));
1320
1321 // Admins held to the rules see no button at all, and a reader neither.
1322 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1, enforceAdmins: true, mergeQueue: { method: "squash" } });
1323 const held = await opened("held");
1324 assert.equal(await bypassForm(held), null);
1325});
1326
1327test("security: no token can mint a token, an agent or a sandbox, through the API or the web forms", async () => {
1328 await repoWithReadme("minting");
1329 const limited = (await ok("POST", "/diffinery/tokens", { name: "limited-mint", scopes: ["admin"], repositories: [`${OWNER}/minting`] }, { cookie: S.olive })).token;
1330 // A job token's shape: minting refuses job and sandbox tokens before any repository checks them.
1331 const job = `djt_repo_job_${"0".repeat(48)}`;
1332 const tokens = async () => (await ok("GET", "/diffinery/tokens", undefined, { cookie: S.olive })).length;
1333 const before = await tokens();
1334 // Admin, agent, read-only and repository-limited tokens, and job tokens: never.
1335 for (const as of [T.olive, T.bot, T.reader, limited, job]) {
1336 const r = await api("POST", "/diffinery/tokens", { name: "escalate", scopes: ["admin"] }, as);
1337 assert.equal(r.status, 403, JSON.stringify(r.json));
1338 assert.equal((await api("POST", "/diffinery/agents", { login: `mint-${randomBytes(3).toString("hex")}` }, as)).status, 403);
1339 assert.equal((await api("POST", "/diffinery/agents/olive-bot/tokens", { scopes: ["admin"] }, as)).status, 403);
1340 }
1341 assert.match((await api("POST", "/diffinery/tokens", { name: "escalate" }, T.olive)).json.message, /browser session/);
1342 // The web form with a token and a forged double-submit cookie: refused, nothing minted.
1343 const form = (fields) => ({ method: "POST", redirect: "manual", body: new URLSearchParams({ _csrf: "forged", ...fields }), headers: { authorization: `Bearer ${T.olive}`, cookie: "dfy_csrf=forged" } });
1344 assert.equal((await fetch(`${base}/settings/tokens`, form({ name: "escalate", scope: "admin", expires: "90" }))).status, 403);
1345 assert.equal((await fetch(`${base}/settings/agents`, form({ login: "web-escalate" }))).status, 403);
1346 assert.equal(await tokens(), before);
1347 // A browser session still mints.
1348 await ok("POST", "/diffinery/tokens", { name: "from the browser", scopes: ["read"] }, { cookie: S.olive });
1349 assert.equal(await tokens(), before + 1);
1350 // A repository-limited token can't create repositories through an import either.
1351 await status(403, "POST", "/diffinery/imports", { source: "octo/hello", owner: OWNER }, limited);
1352 // Job and sandbox tokens can't start sandboxes, whose tokens would outlive them.
1353 await status(403, "POST", `/repos/${OWNER}/minting/diffinery/sandboxes`, {}, job);
1354});
1355
1356test("security: repository variable endpoints see only the repository's own, and organization variable deletes are checked", async () => {
1357 await status(201, "POST", "/orgs/guild/actions/variables", { name: "REGION", value: "org-eu" });
1358 await ok("POST", "/orgs/guild/repos", { name: "tools", private: true });
1359 const R = "/repos/guild/tools";
1360 // The organization's variable isn't the repository's to read or change.
1361 await status(404, "GET", `${R}/actions/variables/REGION`);
1362 await status(404, "PATCH", `${R}/actions/variables/REGION`, { value: "changed" });
1363 assert.deepEqual((await ok("GET", `${R}/actions/variables`)).variables, []);
1364 // A repository variable of the same name can be created; it overrides the organization's in workflows.
1365 await status(201, "POST", `${R}/actions/variables`, { name: "region", value: "repo-us" });
1366 assert.equal((await ok("GET", `${R}/actions/variables/REGION`)).value, "repo-us");
1367 assert.equal((await ok("GET", "/orgs/guild/actions/variables/REGION")).value, "org-eu");
1368 // Deleting it ignores letter case, like every other variable endpoint.
1369 await status(204, "DELETE", `${R}/actions/variables/region`);
1370 await status(404, "GET", `${R}/actions/variables/REGION`);
1371
1372 // Deleting an organization variable that doesn't exist is a 404 and leaves no audit entry; API changes say so.
1373 await status(404, "DELETE", "/orgs/guild/actions/variables/NEVER_SET");
1374 await status(204, "DELETE", "/orgs/guild/actions/variables/REGION");
1375 await status(404, "GET", "/orgs/guild/actions/variables/REGION");
1376 const deleted = await until("the variable's audit entry", async () => auditLog("org.variable_delete").find((e) => JSON.parse(e.detail).name === "REGION"));
1377 assert.equal(JSON.parse(deleted.detail).via, "api");
1378 assert.ok(!auditLog("org.variable_delete").some((e) => JSON.parse(e.detail).name === "NEVER_SET"));
1379 assert.equal(JSON.parse(auditLog("org.variable_set").find((e) => JSON.parse(e.detail).name === "REGION").detail).via, "api");
1380});
1381
1382test("security: milestones are checked before an issue is saved, and lists filter by them", async () => {
1383 const R = "/repos/guild/tools";
1384 // A milestone can be created closed.
1385 const done = await status(201, "POST", `${R}/milestones`, { title: "Already done", state: "closed" });
1386 assert.equal(done.state, "closed");
1387 assert.ok(done.closed_at);
1388 const v1 = await status(201, "POST", `${R}/milestones`, { title: "v1" });
1389 assert.equal(v1.state, "open");
1390 const planned = await status(201, "POST", `${R}/issues`, { title: "Planned" });
1391 const unplanned = await status(201, "POST", `${R}/issues`, { title: "Unplanned" });
1392
1393 // A milestone that doesn't exist is refused before the rest of the edit is saved.
1394 await status(422, "PATCH", `${R}/issues/${planned.number}`, { title: "Renamed", milestone: 999 });
1395 assert.equal((await ok("GET", `${R}/issues/${planned.number}`)).title, "Planned");
1396 await status(422, "PATCH", `${R}/issues/${planned.number}`, { milestone: "v1" });
1397 // The response carries the new milestone.
1398 const set = await ok("PATCH", `${R}/issues/${planned.number}`, { title: "Planned for v1", milestone: v1.number });
1399 assert.deepEqual([set.title, set.milestone?.number], ["Planned for v1", v1.number]);
1400
1401 const numbers = async (q) => (await ok("GET", `${R}/issues?${q}`)).map((i) => i.number);
1402 assert.deepEqual(await numbers(`milestone=${v1.number}`), [planned.number]);
1403 assert.deepEqual(await numbers("milestone=*"), [planned.number]);
1404 assert.deepEqual(await numbers("milestone=none"), [unplanned.number]);
1405 await status(422, "GET", `${R}/issues?milestone=v1`);
1406
1407 // The milestone's link opens the issue list filtered to it.
1408 const cookie = `__Host-dfy_session=${S.olive}`;
1409 const page = await fetch(`${base}/guild/tools/milestone/${v1.number}`, { headers: { cookie }, redirect: "manual" });
1410 assert.equal(page.status, 302);
1411 const list = await fetch(new URL(page.headers.get("location"), base), { headers: { cookie } });
1412 const html = await list.text();
1413 assert.equal(list.status, 200);
1414 assert.match(html, /Planned for v1/);
1415 assert.doesNotMatch(html, /Unplanned/);
1416 assert.match(html, /Milestone: <b>v1<\/b>/);
1417
1418 // Removing it.
1419 assert.equal((await ok("PATCH", `${R}/issues/${planned.number}`, { milestone: null })).milestone, null);
1420});
1421
1422test("security: push protection reads large files, and revoking a token through the API is on the record", async () => {
1423 const R = `/repos/${OWNER}/big-leak`;
1424 const mainSha = await repoWithReadme("big-leak");
1425 // A credential after 1.5 MiB of text, built at run time so this file holds none.
1426 const big = `${"x".repeat(80) + "\n"}`.repeat(20_000) + `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n`;
1427 assert.ok(big.length > 1.5 * 1024 * 1024);
1428 const viaContents = await status(422, "PUT", `${R}/contents/big.env`, { message: "leak", content: b64(big) });
1429 assert.match(viaContents.message, /push protection.*AWS access key/);
1430 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "big.env", content: big }] });
1431 // ...and the same file through git.
1432 const clone = join(work, "big-leak");
1433 const authed = `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/big-leak.git`;
1434 execFileSync("git", ["clone", "-q", authed, clone], { stdio: "pipe" });
1435 writeFileSync(join(clone, "big.env"), big);
1436 const g = (...args) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe" });
1437 g("add", "big.env");
1438 g("commit", "-q", "-m", "leak");
1439 assert.throws(() => g("push", "-q", "origin", "HEAD:main"), /secret detected/);
1440 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1441
1442 // ------------------------------------------------------------ revoking a token through the API is audited, like the settings page
1443 const minted = await ok("POST", "/diffinery/tokens", { name: "short-lived", scopes: ["read"] }, { cookie: S.olive });
1444 await status(204, "DELETE", `/diffinery/tokens/${minted.id}`);
1445 await until("the revoke in the audit log", async () => auditLog("token.revoke").some((e) => e.target === minted.id && JSON.parse(e.detail ?? "{}").via === "api"));
1446});
1447
1448test("security: git request bodies are bounded, compressed or not, before anything reads them", async () => {
1449 await repoWithReadme("bounded");
1450 await ok("PATCH", `/repos/${OWNER}/bounded`, { visibility: "public" });
1451 const url = `${base}/${OWNER}/bounded.git/git-upload-pack`;
1452 const headers = { "content-type": "application/x-git-upload-pack-request" };
1453 // 64 MiB of zeros in about 64 KB of gzip, sent without signing in.
1454 const bomb = gzipSync(Buffer.alloc(64 * 1024 * 1024));
1455 assert.ok(bomb.length < 1024 * 1024);
1456 const r = await fetch(url, { method: "POST", body: bomb, headers: { ...headers, "content-encoding": "gzip" } });
1457 assert.equal(r.status, 413, await r.text());
1458 const plain = await fetch(url, { method: "POST", body: Buffer.alloc(17 * 1024 * 1024, 48), headers });
1459 assert.equal(plain.status, 413);
1460 // A real fetch still works.
1461 execFileSync("git", ["-c", "protocol.version=2", "clone", "-q", `${base}/${OWNER}/bounded.git`, join(work, "bounded")], { stdio: "pipe" });
1462});
1463
1464test("security: a file rewritten from scratch is diffed quickly, even for anonymous readers", async () => {
1465 const R = `/repos/${OWNER}/rewrite`;
1466 await repoWithReadme("rewrite", { private: false });
1467 // 2 x 20k lines with nothing in common, Myers' worst case: unbounded, one diff of it took minutes.
1468 const lines = (tag) => Array.from({ length: 20_000 }, (_, i) => `${tag} ${i}\n`).join("");
1469 const first = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "first", files: [{ path: "data.txt", content: lines("old") }] });
1470 const second = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "rewrite", files: [{ path: "data.txt", content: lines("new") }] });
1471 const sha = second.sha ?? second.commit?.sha;
1472 const t = Date.now();
1473 const commit = await ok("GET", `${R}/commits/${sha}`, undefined, null);
1474 assert.ok(Date.now() - t < 15_000, `the diff took ${Date.now() - t} ms`);
1475 const file = commit.files.find((f) => f.filename === "data.txt");
1476 assert.deepEqual([file.additions, file.deletions], [20_000, 20_000]);
1477 const compared = await ok("GET", `${R}/compare/${first.sha ?? first.commit?.sha}...${sha}`, undefined, null);
1478 assert.equal(compared.files.find((f) => f.filename === "data.txt").additions, 20_000);
1479});
1480
1481test("security: signed out, a private repository and a missing one look the same everywhere", async () => {
1482 await repoWithReadme("secret-plans");
1483 const probe = async (name) => {
1484 const raw = async (method, path, init = {}) => {
1485 const r = await fetch(`${base}${path}`, { method, redirect: "manual", ...init });
1486 return [r.status, (r.headers.get("location") ?? "").replace(name, "NAME"), (await r.text()).replaceAll(name, "NAME")];
1487 };
1488 return {
1489 read: await raw("GET", `/api/v3/repos/${OWNER}/${name}`),
1490 issues: await raw("GET", `/api/v3/repos/${OWNER}/${name}/issues`),
1491 write: await raw("POST", `/api/v3/repos/${OWNER}/${name}/issues`, { headers: { "content-type": "application/json" }, body: JSON.stringify({ title: "probe" }) }),
1492 git: await raw("GET", `/${OWNER}/${name}.git/info/refs?service=git-upload-pack`, { headers: { "git-protocol": "version=2" } }),
1493 fetch: await raw("POST", `/${OWNER}/${name}.git/git-upload-pack`, { headers: { "git-protocol": "version=2", "content-type": "application/x-git-upload-pack-request" }, body: "0014command=ls-refs\n0000" }),
1494 lfs: await raw("POST", `/${OWNER}/${name}.git/info/lfs/objects/batch`, { headers: { accept: "application/vnd.git-lfs+json", "content-type": "application/vnd.git-lfs+json" }, body: JSON.stringify({ operation: "download", objects: [] }) }),
1495 page: await raw("GET", `/${OWNER}/${name}`),
1496 blob: await raw("GET", `/${OWNER}/${name}/blob/main/README.md`),
1497 };
1498 };
1499 const hidden = await probe("secret-plans");
1500 assert.deepEqual(hidden, await probe("never-existed"));
1501 assert.equal(hidden.read[0], 404);
1502 assert.equal(hidden.write[0], 401);
1503 assert.equal(hidden.git[0], 401);
1504 assert.equal(hidden.page[0], 302);
1505 assert.match(hidden.page[1], /\/login\?next=/);
1506});
1507
1508test("security: live updates say only that something changed, and never carry audit entries or payloads", async () => {
1509 const R = `/repos/${OWNER}/on-air`;
1510 await repoWithReadme("on-air", { private: false });
1511 // A signed-out reader watching the public repository.
1512 const ws = new WebSocket(`${base.replace("http", "ws")}/${OWNER}/on-air/live?topics=repo`);
1513 const got = [];
1514 ws.onmessage = (e) => e.data !== "pong" && got.push(JSON.parse(e.data));
1515 await new Promise((ok, fail) => ((ws.onopen = ok), (ws.onerror = fail)));
1516 // A dispatch with a payload, and a commit refused by push protection (an audit entry naming the path).
1517 await status(204, "POST", `${R}/dispatches`, { event_type: "deploy", client_payload: { note: "for writers only" } });
1518 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "keys/prod.env", content: `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n` }] });
1519 await until("the dispatch on the socket", async () => got.some((m) => m.data?.type === "repository_dispatch"));
1520 await sleep(500);
1521 ws.close();
1522 const text = JSON.stringify(got);
1523 assert.doesNotMatch(text, /for writers only|keys\/prod\.env|audit|blocked_secret/);
1524 for (const m of got) assert.deepEqual(Object.keys(m.data).sort(), ["kind", "type"]);
1525});
1526
1527test("security: push protection reads commit and tag messages, UTF-16 files and Diffinery's own tokens, and records opt-outs", async () => {
1528 const R = `/repos/${OWNER}/messages`;
1529 const mainSha = await repoWithReadme("messages");
1530 const key = `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3`;
1531 // A commit message, through git.
1532 const clone = join(work, "messages");
1533 execFileSync("git", ["clone", "-q", `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/messages.git`, clone], { stdio: "pipe" });
1534 const g = (...args) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe" });
1535 g("commit", "-q", "--allow-empty", "-m", `deploy\n\n${key}`);
1536 assert.throws(() => g("push", "-q", "origin", "HEAD:main"), /secret detected/);
1537 // ...an annotated tag's message.
1538 g("reset", "-q", "--hard", "origin/main");
1539 g("tag", "-a", "v1", "-m", key);
1540 assert.throws(() => g("push", "-q", "origin", "v1"), /secret detected/);
1541 // ...and without git: the commits API and the git data API.
1542 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: `notes\n${key}`, files: [{ path: "a.txt", content: "a\n" }] });
1543 const tree = (await ok("GET", `${R}/git/commits/${mainSha}`)).tree.sha;
1544 await status(422, "POST", `${R}/git/commits`, { message: key, tree, parents: [mainSha] });
1545 await status(422, "POST", `${R}/git/tags`, { tag: "v2", message: key, object: mainSha, type: "commit" });
1546 // A UTF-16 file has NUL bytes but is text.
1547 const utf16 = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`${key}\n`, "utf16le")]);
1548 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "utf16", files: [{ path: "creds.txt", content: utf16.toString("base64"), encoding: "base64" }] });
1549 // A job, sandbox or model token.
1550 const token = `dmt_${"0b1e5c4e-58a0-4f7c-9d39-0e2c6a1c3f00"}_${"Zm9vYmFyYmF6cXV4cXV1eHF1dXhxdXV4cXV1eA"}`;
1551 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "token", files: [{ path: "token.txt", content: token }] });
1552 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1553 // A file that opts out still goes in, and the opt-out is on the record.
1554 await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "fixture", files: [{ path: "fixture.env", content: `${key} # ${"diffinery"}:allow-secret\n` }] });
1555 const entry = await until("the opt-out in the audit log", async () => auditLog("api.secret_marked").find((e) => e.target === `${OWNER}/messages`));
1556 assert.deepEqual(JSON.parse(entry.detail).paths, ["fixture.env"]);
1557});
1558
1559test("security: required checks gate direct pushes to a protected branch, as on GitHub", async () => {
1560 const R = `/repos/${OWNER}/gated`;
1561 const mainSha = await repoWithReadme("gated");
1562 await status(204, "PUT", `${R}/collaborators/rita`, { permission: "write" });
1563 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1564 // A writer's commit straight to main hasn't been checked: refused, whichever way it comes.
1565 const refused = await status(403, "PUT", `${R}/contents/direct.txt`, { message: "direct", content: b64("x\n"), branch: "main" }, T.rita);
1566 assert.match(refused.message, /required check 'ci' has not run/);
1567 // The same commit, tested on a branch first, can move main.
1568 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/tested", sha: mainSha }, T.rita);
1569 const tested = (await ok("PUT", `${R}/contents/direct.txt`, { message: "tested", content: b64("x\n"), branch: "tested" }, T.rita)).commit.sha;
1570 assert.match((await status(403, "PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita)).message, /has not run/);
1571 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: tested, status: "in_progress" });
1572 assert.match((await status(403, "PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita)).message, /has not finished/);
1573 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: tested, status: "completed", conclusion: "success" });
1574 // (Two runs named ci: the in-progress one still counts until it completes.)
1575 const runs = (await ok("GET", `${R}/commits/${tested}/check-runs`)).check_runs.filter((r) => r.status !== "completed");
1576 for (const r of runs) await ok("PATCH", `${R}/check-runs/${r.id}`, { status: "completed", conclusion: "success" });
1577 await ok("PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita);
1578 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, tested);
1579 // A repository admin isn't held to it unless the rule says so.
1580 await ok("PUT", `${R}/contents/admin.txt`, { message: "admin", content: b64("y\n"), branch: "main" });
1581});
1582
1583test("security: issue, pull request and comment text has GitHub's length limits", async () => {
1584 await ok("POST", "/user/repos", { name: "long-text" });
1585 const R = `/repos/${OWNER}/long-text`;
1586 const long = "x".repeat(65_537);
1587 const tooLong = (r) => assert.match(r.message, /too long \(maximum is (65536|256) characters\)/);
1588 tooLong(await status(422, "POST", `${R}/issues`, { title: "Big", body: long }));
1589 tooLong(await status(422, "POST", `${R}/issues`, { title: "t".repeat(257) }));
1590 const issue = await status(201, "POST", `${R}/issues`, { title: "Small", body: "x".repeat(65_536) });
1591 tooLong(await status(422, "PATCH", `${R}/issues/${issue.number}`, { body: long }));
1592 tooLong(await status(422, "POST", `${R}/issues/${issue.number}/comments`, { body: long }));
1593 const comment = await status(201, "POST", `${R}/issues/${issue.number}/comments`, { body: "fine" });
1594 tooLong(await status(422, "PATCH", `${R}/issues/comments/${comment.id}`, { body: long }));
1595 assert.equal((await ok("GET", `${R}/issues/${issue.number}`)).body.length, 65_536);
1596});
1597
1598test("security: deleting a repository deletes its stored objects too", async () => {
1599 await repoWithReadme("doomed");
1600 // Objects over 512 KiB compressed live in R2, under repos/<id>/.
1601 const big = randomBytes(700 * 1024);
1602 await ok("PUT", `/repos/${OWNER}/doomed/contents/big.bin`, { message: "big", content: big.toString("base64") });
1603 const oid = createHash("sha1").update(Buffer.concat([Buffer.from(`blob ${big.length}\0`), big])).digest("hex");
1604 const persist = join(work, "state");
1605 const run = (...args) => execFileSync("pnpm", ["exec", "wrangler", ...args], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } }).toString();
1606 const rows = JSON.parse(run("d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--json", "--command", "SELECT id FROM repos WHERE name = 'doomed'"));
1607 const repoId = rows[0].results[0].id;
1608 const key = `diffinery-data-dev/repos/${repoId}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`;
1609 const stored = () => {
1610 try {
1611 run("r2", "object", "get", key, "--local", "-e", "dev", "--persist-to", persist, "--pipe");
1612 return true;
1613 } catch {
1614 return false;
1615 }
1616 };
1617 assert.ok(stored(), "the large blob is in R2 before the repository is deleted");
1618 await status(204, "DELETE", `/repos/${OWNER}/doomed`);
1619 await until("the repository's objects are deleted", () => !stored(), 30_000);
1620});
1621
1622test("security: pushes are checked like git's fsck: no '..' or '.git' entries, no unsafe .gitmodules", async () => {
1623 const R = `/repos/${OWNER}/fsck`;
1624 const mainSha = await repoWithReadme("fsck");
1625 const clone = join(work, "fsck");
1626 const authed = `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/fsck.git`;
1627 execFileSync("git", ["clone", "-q", authed, clone], { stdio: "pipe" });
1628 const g = (args, input) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe", input }).toString().trim();
1629 const push = (sha) => spawnSync("git", ["push", "origin", `${sha}:refs/heads/main`], { cwd: clone, encoding: "utf8" });
1630 const blob = g(["hash-object", "-w", "--stdin"], "payload\n");
1631 // A tree git itself would never write: git's own tools refuse these names, so build it by hand.
1632 const crafted = (name) => {
1633 const bytes = Buffer.concat([Buffer.from(`100644 ${name}\0`), Buffer.from(blob, "hex")]);
1634 const tree = g(["hash-object", "-t", "tree", "-w", "--literally", "--stdin"], bytes);
1635 return g(["commit-tree", tree, "-p", mainSha, "-m", `entry ${name}`]);
1636 };
1637 for (const [name, why] of [["..", /not a valid name/], [".git", /reserved/], [".GIT", /reserved/], ["git~1", /reserved/]]) {
1638 const r = push(crafted(name));
1639 assert.notEqual(r.status, 0, `a tree entry named ${name} was accepted`);
1640 assert.match(r.stderr, why);
1641 }
1642 // .gitmodules that would make git run an option (CVE-2018-17456).
1643 writeFileSync(join(clone, ".gitmodules"), '[submodule "x"]\n\tpath = x\n\turl = --upload-pack=touch /tmp/pwned\n');
1644 g(["add", ".gitmodules"]);
1645 g(["commit", "-q", "-m", "submodule"]);
1646 const r = push("HEAD");
1647 assert.notEqual(r.status, 0);
1648 assert.match(r.stderr, /url that starts with '-'/);
1649 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1650 // An ordinary .gitmodules goes through.
1651 g(["reset", "-q", "--hard", mainSha]);
1652 writeFileSync(join(clone, ".gitmodules"), '[submodule "x"]\n\tpath = x\n\turl = https://example.com/x.git\n');
1653 g(["add", ".gitmodules"]);
1654 g(["commit", "-q", "-m", "submodule"]);
1655 assert.equal(push("HEAD").status, 0);
1656});
1657
1658test("security: a job's runner gets only the secrets the job names", async () => {
1659 const R = `/repos/${OWNER}/few-secrets`;
1660 await repoWithReadme("few-secrets");
1661 await status(204, "PUT", `${R}/actions/secrets/USED`, { value: "used-value" });
1662 await status(204, "PUT", `${R}/actions/secrets/UNUSED`, { value: "unused-value" });
1663 const wf = "name: ci\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n env:\n T: ${{ secrets.used }}\n dump:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo '${{ toJSON(secrets) }}'\n";
1664 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1665 const specs = {};
1666 await until("both jobs claimed", async () => {
1667 const r = await api("POST", `${R}/actions/runners/claim`, { name: "secrets-runner", labels: ["linux"] });
1668 if (r.status === 200) {
1669 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1670 specs[spec.jobKey] = Object.keys(spec.secrets).sort();
1671 await fetch(`${base}/runner/jobs/${r.json.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${r.json.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
1672 }
1673 return Object.keys(specs).length === 2;
1674 });
1675 assert.deepEqual(specs.build, ["DIFFINERY_TOKEN", "GITHUB_TOKEN", "USED"]);
1676 // toJSON(secrets) can't be narrowed, so that job gets them all, as on GitHub.
1677 assert.deepEqual(specs.dump, ["DIFFINERY_TOKEN", "GITHUB_TOKEN", "UNUSED", "USED"]);
1678});
1679
1680test("security: runs of agent code get no repository secrets unless an admin allows it", async () => {
1681 const R = `/repos/${OWNER}/agent-secrets`;
1682 await repoWithReadme("agent-secrets");
1683 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1684 await status(204, "PUT", `${R}/actions/secrets/DEPLOY`, { value: "deploy-value" });
1685 const settings = await ok("GET", `${R}/actions/permissions/workflow`);
1686 assert.equal(settings.agent_runs_use_secrets, false);
1687 const wf = (n) => `name: ci\non: push\njobs:\n build${n}:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n env:\n T: \${{ secrets.DEPLOY }}\n`;
1688 const secretsOfNextJob = async () => {
1689 let names;
1690 await until("the agent's job", async () => {
1691 const r = await api("POST", `${R}/actions/runners/claim`, { name: "agent-runner", labels: ["linux"] });
1692 if (r.status !== 200) return false;
1693 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1694 names = Object.keys(spec.secrets).sort();
1695 await fetch(`${base}/runner/jobs/${r.json.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${r.json.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
1696 return true;
1697 });
1698 return names;
1699 };
1700 // An agent pushes a workflow that asks for the deploy secret: its run gets only the job token.
1701 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-work", sha: (await ok("GET", `${R}/branches/main`)).commit.sha }, T.bot);
1702 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf(1)), branch: "agent-work" }, T.bot);
1703 assert.deepEqual(await secretsOfNextJob(), ["DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1704 // Only a person can allow it; then the agent's runs get what they name.
1705 await status(403, "PUT", `${R}/actions/permissions/workflow`, { agent_runs_use_secrets: true }, T.bot);
1706 await status(204, "PUT", `${R}/actions/permissions/workflow`, { agent_runs_use_secrets: true });
1707 const file = await ok("GET", `${R}/contents/.github/workflows/ci.yml?ref=agent-work`, undefined, T.bot);
1708 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci 2", content: b64(wf(2)), branch: "agent-work", sha: file.sha }, T.bot);
1709 assert.deepEqual(await secretsOfNextJob(), ["DEPLOY", "DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1710});
1711
1712test("security: adding someone by email always invites them, so the address doesn't reveal their username and they agree first", async () => {
1713 await ok("POST", "/user/orgs", { login: "by-mail" });
1714 const members = async () => (await ok("GET", "/orgs/by-mail/members")).map((u) => u.login);
1715
1716 // sam has an account with this address, but the admin gets the same invitation as for a stranger.
1717 const added = await oliveSubmits("/by-mail?tab=people", "/by-mail/-/org/people", { who: "Sam@Example.com", role: "member" });
1718 assert.equal(added.status, 200, added.flash);
1719 assert.match(added.text, /Invitation sent to Sam@Example\.com/);
1720 assert.doesNotMatch(added.flash + added.text, /Added sam|\bsam (is|now)\b/);
1721 assert.ok(!(await members()).includes("sam"));
1722 const link = /\/invite\/([A-Za-z0-9_-]+)/.exec(added.text)?.[1];
1723 assert.ok(link);
1724 // The link the admin holds doesn't say whether the address has an account either.
1725 const landing = await (await fetch(`${base}/invite/${link}`)).text();
1726 assert.match(landing, /Confirm your email/);
1727 assert.doesNotMatch(landing, /already has a Diffinery account/);
1728
1729 // sam joins by accepting it.
1730 const accepted = await submitsAs(S.sam, `/invite/${link}`, `/invite/${link}`, {});
1731 assert.equal(accepted.status, 303, accepted.flash);
1732 assert.ok((await members()).includes("sam"));
1733
1734 // Inviting a member's address again doesn't name them.
1735 const again = await oliveSubmits("/by-mail?tab=people", "/by-mail/-/org/people", { who: "sam@example.com", role: "admin" });
1736 assert.doesNotMatch(again.flash + again.text, /sam is already a member/);
1737 assert.match(again.text, /Invitation sent to sam@example\.com/);
1738
1739 // The same for a repository's collaborators.
1740 await repoWithReadme("by-mail-repo");
1741 const repo = await oliveSubmits(`/${OWNER}/by-mail-repo/settings/access`, `/${OWNER}/by-mail-repo/settings/access/people`, { who: "sam@example.com", role: "write" });
1742 assert.equal(repo.status, 200, repo.flash);
1743 assert.match(repo.text, /Invitation sent to sam@example\.com/);
1744 await status(404, "GET", `/repos/${OWNER}/by-mail-repo`, undefined, T.sam);
1745});
1746
1747test("security: a job's log is capped, and oversized workflow files aren't parsed", async () => {
1748 const R = `/repos/${OWNER}/big-logs`;
1749 await repoWithReadme("big-logs");
1750 const wf = "name: ci\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n";
1751 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1752 let claim;
1753 await until("the job claimed", async () => {
1754 const r = await api("POST", `${R}/actions/runners/claim`, { name: "log-runner", labels: ["linux"] });
1755 if (r.status === 200) claim = r.json;
1756 return !!claim;
1757 });
1758 const headers = { authorization: `Bearer ${claim.token}`, "content-type": "application/json" };
1759 const text = "x".repeat(16384);
1760 const post = async (n) => {
1761 const r = await fetch(`${base}/runner/jobs/${claim.job_id}/logs`, { method: "POST", headers, body: JSON.stringify({ lines: Array.from({ length: n }, () => ({ t: new Date().toISOString(), step: 0, text })) }) });
1762 assert.equal(r.status, 200, await r.text());
1763 };
1764 // 1,200 lines of 16 KiB: the log keeps 16 MiB of them, then one line saying it was cut off; later lines are dropped.
1765 await post(600);
1766 await post(600);
1767 await post(10);
1768 await fetch(`${base}/runner/jobs/${claim.job_id}/complete`, { method: "POST", headers, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
1769 const lines = await ok("GET", `${R}/actions/jobs/${claim.job_id}/logs?format=json`);
1770 assert.equal(lines.length, 1025);
1771 assert.match(lines.at(-1).text, /cut off here: a job's log is limited to 16 MiB/);
1772
1773 // A workflow file over 512 KiB is listed as invalid without being parsed.
1774 await ok("PUT", `${R}/contents/.github/workflows/huge.yml`, { message: "huge", content: b64(`${wf}# ${"y".repeat(600 * 1024)}\n`) });
1775 const { workflows } = await ok("GET", `${R}/actions/workflows`);
1776 const huge = workflows.find((w) => w.path === ".github/workflows/huge.yml");
1777 assert.equal(huge.state, "invalid");
1778 assert.match(huge.errors.join("\n"), /larger than 512 KiB/);
1779});
1780
1781test("security: a workflow's token can't use another repository's private packages, and a repository's name is its own", async () => {
1782 await repoWithReadme("pkg-home", { private: true });
1783 await repoWithReadme("pkg-other", { private: true });
1784 // olive pushes an image named after pkg-home, so it's linked to it and private.
1785 await pushTinyImage(`${OWNER}/pkg-home`, "v1", T.olive);
1786 const wf = "name: ci\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n permissions:\n contents: read\n packages: write\n steps:\n - run: echo hi\n";
1787 await ok("PUT", `/repos/${OWNER}/pkg-other/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1788 let claim;
1789 await until("the job claimed", async () => {
1790 const r = await api("POST", `/repos/${OWNER}/pkg-other/actions/runners/claim`, { name: "pkg-runner", labels: ["linux"] });
1791 if (r.status === 200) claim = r.json;
1792 return !!claim;
1793 });
1794 // The runner reads its job first; that settles the token's permissions.
1795 await fetch(`${base}/runner/jobs/${claim.job_id}`, { headers: { authorization: `Bearer ${claim.token}` } });
1796 // pkg-other's workflow can't pull pkg-home's image, nor take a name that belongs to pkg-home.
1797 assert.equal((await pullManifest(`${OWNER}/pkg-home`, "v1", claim.token)).status, 404);
1798 const basic = (as) => ({ authorization: `Basic ${Buffer.from(`anyone:${as}`).toString("base64")}`, "content-type": "application/octet-stream" });
1799 const blob = Buffer.from("squat");
1800 const digest = `sha256:${createHash("sha256").update(blob).digest("hex")}`;
1801 const squat = await fetch(`${base}/v2/${OWNER}/pkg-home/tools/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(claim.token) });
1802 assert.equal(squat.status, 403);
1803 assert.match(await squat.text(), /named after the olive\/pkg-home repository/);
1804 // Its own names still work.
1805 const own = await fetch(`${base}/v2/${OWNER}/pkg-other/tools/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(claim.token) });
1806 assert.equal(own.status, 201, await own.text());
1807
1808 // A person who can't write to a repository can't take its name either: milo, a guild member, only reads guild/vault.
1809 const taken = await fetch(`${base}/v2/guild/vault/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(T.milo) });
1810 assert.equal(taken.status, 403);
1811 assert.match(await taken.text(), /named after the guild\/vault repository/);
1812});