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.

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