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.

2793 lines · 197.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.
23// Site administrators' kill switches stop Actions and sandboxes for a repository, an
24// account or (hosted compute) the whole instance. Images from other sites in Markdown
25// load through Diffinery's signed image proxy, never straight from the other site.
26import { spawn, spawnSync, execFileSync } from "node:child_process";
27import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";
28import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
29import { gzipSync } from "node:zlib";
30import { tmpdir } from "node:os";
31import { join, dirname, resolve } from "node:path";
32import { fileURLToPath } from "node:url";
33import { createServer } from "node:net";
34import { createServer as createHttpServer } from "node:http";
35import { test, before, after } from "node:test";
36import assert from "node:assert/strict";
37
38const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
39const work = mkdtempSync(join(tmpdir(), "diffinery-security-"));
40let base;
41let dev;
42let devLog = "";
43
44const hash = (s) => createHash("sha256").update(s).digest("hex");
45const tok = (name) => `dfy_${name}_${randomBytes(12).toString("hex")}`;
46const T = { sully: tok("sully"), 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") };
47const 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")}` };
48const OWNER = "olive";
49/** One minute of an environment's wait timer, in this Worker (WAIT_TIMER_MINUTE_MS). */
50const TIMER_MINUTE_MS = 10_000;
51
52const freePort = () =>
53 new Promise((res) => {
54 const s = createServer();
55 s.listen(0, "127.0.0.1", () => {
56 const { port } = s.address();
57 s.close(() => res(port));
58 });
59 });
60
61const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
62async function until(what, fn, timeoutMs = 60_000) {
63 const end = Date.now() + timeoutMs;
64 while (Date.now() < end) {
65 const v = await fn();
66 if (v) return v;
67 await sleep(300);
68 }
69 assert.fail(`timed out waiting for ${what}\n--- wrangler log tail ---\n${devLog.slice(-4000)}`);
70}
71
72/** Call the REST API as a token (`as`), a session cookie (`{ cookie }`) or anonymously (null). */
73async function api(method, path, body, as = T.olive) {
74 const headers = { "content-type": "application/json" };
75 if (typeof as === "string") headers.authorization = `Bearer ${as}`;
76 else if (as?.cookie) headers.cookie = `__Host-dfy_session=${as.cookie}`;
77 const send = () => fetch(`${base}/api/v3${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
78 // wrangler dev closes idle keep-alive connections (the audit checks pause for seconds), so a reused one can be gone.
79 const res = await send().catch((e) => (e.cause?.code === "UND_ERR_SOCKET" ? send() : Promise.reject(e)));
80 const text = await res.text();
81 let json = null;
82 try {
83 json = text ? JSON.parse(text) : null;
84 } catch {
85 json = text;
86 }
87 return { status: res.status, json };
88}
89
90/**
91 * Claim a waiting self-hosted job as a registered runner offering `labels`, the way `diffinery runner`
92 * does (personal tokens can't claim jobs): one runner per repository and set of labels.
93 */
94const e2eRunners = new Map();
95async function runnerClaim(repoPath, labels = ["linux"]) {
96 const key = `${repoPath} ${labels.join(",")}`;
97 if (!e2eRunners.has(key)) {
98 const reg = await api("POST", `${repoPath}/actions/runners/registration-token`);
99 assert.equal(reg.status, 201, JSON.stringify(reg.json));
100 const runner = await api("POST", `${repoPath}/actions/runners/register`, { registration_token: reg.json.token, name: `e2e-runner-${e2eRunners.size + 1}`, labels });
101 assert.equal(runner.status, 201, JSON.stringify(runner.json));
102 e2eRunners.set(key, runner.json.token);
103 }
104 const r = await api("POST", `${repoPath}/actions/runners/claim`, {}, e2eRunners.get(key));
105 // A repository deleted and created again under the same name needs a new runner.
106 if (r.status !== 401) return r;
107 e2eRunners.delete(key);
108 return runnerClaim(repoPath, labels);
109}
110async function ok(method, path, body, as) {
111 const r = await api(method, path, body, as);
112 assert.ok(r.status >= 200 && r.status < 300, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
113 return r.json;
114}
115async function status(expected, method, path, body, as) {
116 const r = await api(method, path, body, as);
117 assert.equal(r.status, expected, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
118 return r.json;
119}
120const b64 = (s) => Buffer.from(s).toString("base64");
121
122/**
123 * Give someone access to a repository as GitHub does: someone new gets an invitation (201), which
124 * they accept with their own token; an existing collaborator's role changes at once (204).
125 */
126async function collaborator(repo, login, permission, invitee, as = T.olive) {
127 const r = await api("PUT", `${repo}/collaborators/${login}`, { permission }, as);
128 if (r.status === 204) return;
129 assert.equal(r.status, 201, `PUT ${repo}/collaborators/${login} -> ${r.status} ${JSON.stringify(r.json)}`);
130 await status(204, "PATCH", `/user/repository_invitations/${r.json.id}`, undefined, invitee);
131}
132
133before(async () => {
134 const port = await freePort();
135 base = `http://127.0.0.1:${port}`;
136 const persist = join(work, "state");
137 const wrangler = (...args) => execFileSync("pnpm", ["exec", "wrangler", ...args], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } });
138 wrangler("d1", "migrations", "apply", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist);
139 const at = new Date().toISOString();
140 const later = new Date(Date.now() + 30 * 86400_000).toISOString();
141 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}')`;
142 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}')`;
143 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}')`;
144 wrangler(
145 "d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--command",
146 [
147 account("u-olive", "olive", "user", "active"),
148 account("u-sully", "sully", "user", "active"),
149 "UPDATE accounts SET site_admin = 1 WHERE id = 'u-sully'",
150 token("t-sully", "u-sully", T.sully, ["admin"]),
151 account("a-bot", "olive-bot", "agent", "active", "u-olive"),
152 account("u-rita", "rita", "user", "active"),
153 account("u-penny", "penny", "user", "pending"),
154 account("u-dora", "dora", "user", "disabled"),
155 account("u-gone", "gone", "user", "disabled"),
156 account("a-orphan", "gone-bot", "agent", "active", "u-gone"),
157 token("t1", "u-olive", T.olive, ["admin"]),
158 token("t2", "a-bot", T.bot, ["admin"]),
159 token("t3", "u-rita", T.rita, ["write"]),
160 token("t4", "u-dora", T.dora, ["write"]),
161 token("t5", "a-orphan", T.orphan, ["write"]),
162 account("o-guild", "guild", "org", "active"),
163 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-guild', 'u-olive', 'owner', '${at}'), ('o-guild', 'u-rita', 'admin', '${at}')`,
164 token("t6", "u-olive", T.reader, ["read"]),
165 token("t7", "u-rita", T.ritaAdmin, ["admin"]),
166 account("u-milo", "milo", "user", "active"),
167 token("t8", "u-milo", T.milo, ["admin"]),
168 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-guild', 'u-milo', 'member', '${at}')`,
169 session("s1", "u-penny", S.penny),
170 session("s2", "u-dora", S.dora),
171 session("s3", "u-olive", S.olive),
172 account("o-shop", "shop", "org", "active"),
173 account("u-sam", "sam", "user", "active"),
174 token("t9", "u-sam", T.sam, ["admin"]),
175 account("a-helper", "olive-helper", "agent", "active", "u-olive"),
176 token("t10", "a-helper", T.helper, ["write"]),
177 `INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('o-shop', 'u-olive', 'owner', '${at}'), ('o-shop', 'u-sam', 'member', '${at}')`,
178 session("s4", "u-sam", S.sam),
179 "UPDATE accounts SET email = 'sam@example.com' WHERE id = 'u-sam'",
180 // olive's other browsers: one signed in 3 hours ago, one 100 days ago (used every day since), one spare.
181 session("s5", "u-olive", S.oliveOld).replace(`'${at}', '${at}'`, `'${new Date(Date.now() - 3 * 3600_000).toISOString()}', '${at}'`),
182 session("s6", "u-olive", S.oliveStale).replace(`'${at}', '${at}'`, `'${new Date(Date.now() - 100 * 86400_000).toISOString()}', '${at}'`),
183 session("s7", "u-olive", S.oliveSpare),
184 ].join("; "),
185 );
186 dev = spawn(
187 "pnpm",
188 ["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", `WAIT_TIMER_MINUTE_MS:${TIMER_MINUTE_MS}`, "--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"],
189 { cwd: APP, env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" }, stdio: ["ignore", "pipe", "pipe"], detached: true },
190 );
191 dev.stdout.on("data", (d) => (devLog += d));
192 dev.stderr.on("data", (d) => (devLog += d));
193 await until(
194 "wrangler dev",
195 async () => {
196 try {
197 return (await fetch(`${base}/healthz`)).ok;
198 } catch {
199 return false;
200 }
201 },
202 120_000,
203 );
204});
205
206after(() => {
207 if (dev?.pid) {
208 try {
209 process.kill(-dev.pid, "SIGTERM");
210 } catch {}
211 }
212 if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true });
213});
214
215/** A private repository owned by olive with one commit on main. */
216async function repoWithReadme(name, extra = {}) {
217 await ok("POST", "/user/repos", { name, ...extra });
218 const put = await ok("PUT", `/repos/${OWNER}/${name}/contents/README.md`, { message: "init", content: b64(`# ${name}\n`) });
219 return put.commit.sha;
220}
221
222test("security: search, required checks, environments, reviews, locks, archives, drafts and tree names", async () => {
223 // ------------------------------------------------------------ setup: a private repo the agent and rita can use
224 const R = `/repos/${OWNER}/guarded`;
225 const mainSha = await repoWithReadme("guarded");
226 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
227 await collaborator(R, "rita", "read", T.rita);
228 await status(204, "PUT", `${R}/collaborators/gone-bot`, { permission: "write" });
229 const issue = await ok("POST", `${R}/issues`, { title: "needle in a haystack" });
230
231 // ------------------------------------------------------------ search only shows what the caller may read
232 const found = await ok("GET", "/search/issues?q=needle");
233 assert.equal(found.total_count, 1);
234 assert.equal(found.items[0].number, issue.number);
235 assert.equal((await ok("GET", "/search/issues?q=needle", undefined, T.rita)).total_count, 1);
236 for (const [who, as] of [
237 ["pending account (session)", { cookie: S.penny }],
238 ["disabled account (session)", { cookie: S.dora }],
239 ["anonymous", null],
240 ]) {
241 const r = await api("GET", "/search/issues?q=needle", undefined, as);
242 assert.equal(r.status, 200, `${who}: ${JSON.stringify(r.json)}`);
243 assert.equal(r.json.total_count, 0, `${who} must not find private issues`);
244 const repos = await ok("GET", "/search/repositories?q=guarded", undefined, as);
245 assert.equal(repos.total_count, 0, `${who} must not find private repos`);
246 }
247 await status(401, "GET", "/search/issues?q=needle", undefined, T.dora);
248 // An agent's tokens stop working while its owner is disabled, as they do while it's suspended.
249 await status(401, "GET", "/search/issues?q=needle", undefined, T.orphan);
250 await status(401, "GET", R, undefined, T.orphan);
251 // Search input is bounded.
252 await status(422, "GET", `/search/issues?q=${"x".repeat(300)}`);
253 await status(422, "GET", "/search/issues");
254
255 // ------------------------------------------------------------ required checks: an agent can't turn its failing PR green
256 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
257 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-change", sha: mainSha }, T.bot);
258 const change = await ok("PUT", `${R}/contents/change.txt`, { message: "agent change", content: b64("hi\n"), branch: "agent-change" }, T.bot);
259 const head = change.commit.sha;
260 const pr = await ok("POST", `${R}/pulls`, { title: "Agent change", head: "agent-change", base: "main" }, T.bot);
261 await ok("POST", `${R}/pulls/${pr.number}/reviews`, { event: "APPROVE", body: "fine by me" });
262 const failing = await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "failure" });
263 assert.equal(typeof failing.id, "number");
264 const mergeState = async () =>
265 until("mergeability", async () => {
266 const p = await ok("GET", `${R}/pulls/${pr.number}`);
267 return typeof p.mergeable === "boolean" ? p.mergeable_state : null;
268 });
269 assert.equal(await mergeState(), "blocked");
270 // 1. PATCH someone else's check run.
271 await status(403, "PATCH", `${R}/check-runs/${failing.id}`, { conclusion: "success" }, T.bot);
272 // 2. A green commit status with the same name.
273 await ok("POST", `${R}/statuses/${head}`, { state: "success", context: "ci" }, T.bot);
274 assert.equal(await mergeState(), "blocked");
275 // 3. A green check run of its own with the same name.
276 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" }, T.bot);
277 assert.equal(await mergeState(), "blocked");
278
279 // ------------------------------------------------------------ deployments verify every context unless told otherwise
280 await status(409, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging" });
281 await status(201, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging", required_contexts: [] });
282 await status(409, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging", required_contexts: ["ci"] });
283
284 // The real reporter fixes its check: now the PR is mergeable and deployable.
285 await ok("PATCH", `${R}/check-runs/${failing.id}`, { conclusion: "success" });
286 assert.equal(await mergeState(), "clean");
287 await status(201, "POST", `${R}/deployments`, { ref: "agent-change", environment: "staging" });
288
289 // ------------------------------------------------------------ review dismissal: maintainers only, never the author or an agent
290 const reviews = await ok("GET", `${R}/pulls/${pr.number}/reviews`);
291 const approval = reviews.find((r) => r.state === "APPROVED");
292 await status(403, "PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "nope" }, T.bot);
293 await status(403, "PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "nope" }, T.rita);
294 const dismissed = await ok("PUT", `${R}/pulls/${pr.number}/reviews/${approval.id}/dismissals`, { message: "stale" });
295 assert.equal(dismissed.state, "DISMISSED");
296
297 // ------------------------------------------------------------ environments: admins who are people, not agents
298 await status(403, "PUT", `${R}/environments/production`, {}, T.bot);
299 await ok("PUT", `${R}/environments/production`, { deployment_branch_policy: { protected_branches: false, custom_branch_policies: true } });
300 await status(403, "POST", `${R}/environments/production/deployment-branch-policies`, { name: "v*", type: "tag" }, T.bot);
301 const policy = await ok("POST", `${R}/environments/production/deployment-branch-policies`, { name: "release/*", type: "branch" });
302 await status(403, "DELETE", `${R}/environments/production/deployment-branch-policies/${policy.id}`, undefined, T.bot);
303 await status(403, "DELETE", `${R}/environments/production`, undefined, T.bot);
304 await status(403, "PUT", `${R}/environments/production/secrets/TOKEN`, { value: "s3cret" }, T.bot);
305 // The first secret limits an environment without rules to protected branches.
306 await ok("PUT", `${R}/environments/vault`, {});
307 assert.equal((await ok("GET", `${R}/environments/vault`)).deployment_branch_policy, null);
308 await status(201, "PUT", `${R}/environments/vault/secrets/API_KEY`, { value: "s3cret" });
309 const vault = await ok("GET", `${R}/environments/vault`);
310 assert.equal(vault.deployment_branch_policy?.protected_branches, true);
311 assert.ok(!JSON.stringify(vault).includes("s3cret"));
312
313 // ------------------------------------------------------------ locked conversations
314 await status(204, "PUT", `${R}/issues/${pr.number}/lock`, { lock_reason: "resolved" });
315 await status(403, "POST", `${R}/pulls/${pr.number}/comments`, { body: "late", commit_id: head, path: "change.txt", line: 1, side: "RIGHT" }, T.rita);
316 await status(403, "POST", `${R}/issues/${pr.number}/reactions`, { content: "+1" }, T.rita);
317 await status(201, "POST", `${R}/issues/${issue.number}/reactions`, { content: "+1" }, T.rita);
318
319 // ------------------------------------------------------------ unsafe tree entry names, on every write path
320 for (const path of [".git/config", ".GIT/hooks/pre-commit", "x/.git./config", "git~1/config", "a\\b", "x/../y"]) {
321 await status(422, "POST", `${R}/git/trees`, { tree: [{ path, mode: "100644", type: "blob", content: "x" }] });
322 }
323 for (const path of [".Git/hooks/post-checkout", "git~1/HEAD", "sub/.git/config"]) {
324 await status(422, "PUT", `${R}/contents/${path}`, { message: "bad", content: b64("x") });
325 }
326
327 // ------------------------------------------------------------ a tree bomb can't blow up archives or languages
328 const leaf = await ok("POST", `${R}/git/trees`, { tree: [{ path: "a.js", mode: "100644", type: "blob", content: "x" }] });
329 const wide = await ok("POST", `${R}/git/trees`, { tree: Array.from({ length: 400 }, (_, i) => ({ path: `d${i}`, mode: "040000", type: "tree", sha: leaf.sha })) });
330 const bomb = await ok("POST", `${R}/git/trees`, { tree: Array.from({ length: 400 }, (_, i) => ({ path: `e${i}`, mode: "040000", type: "tree", sha: wide.sha })) });
331 const bombCommit = await ok("POST", `${R}/git/commits`, { message: "bomb", tree: bomb.sha, parents: [mainSha] });
332 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/bomb", sha: bombCommit.sha });
333 const zip = await fetch(`${base}/api/v3${R}/zipball/bomb`, { headers: { authorization: `Bearer ${T.olive}` }, redirect: "manual" });
334 assert.equal(zip.status, 413, await zip.text());
335 await status(200, "GET", `${R}/languages`);
336
337 // ------------------------------------------------------------ labels with a percent sign (no double decoding)
338 await ok("POST", `${R}/labels`, { name: "50%", color: "ff0000" });
339 assert.equal((await ok("GET", `${R}/labels/50%25`)).name, "50%");
340 assert.equal((await ok("PATCH", `${R}/labels/50%25`, { description: "half" })).description, "half");
341 await ok("POST", `${R}/issues/${issue.number}/labels`, { labels: ["50%"] });
342 await ok("DELETE", `${R}/issues/${issue.number}/labels/50%25`);
343 await status(204, "DELETE", `${R}/labels/50%25`);
344
345 // ------------------------------------------------------------ archived repositories are read-only for everyone
346 const A = `/repos/${OWNER}/attic`;
347 await repoWithReadme("attic");
348 const old = await ok("POST", `${A}/issues`, { title: "old" });
349 assert.equal((await ok("PATCH", A, { archived: true })).archived, true);
350 await status(403, "POST", `${A}/issues/${old.number}/reactions`, { content: "heart" });
351 await status(403, "PUT", `${A}/environments/production`, {});
352 await status(403, "POST", `${A}/releases`, { tag_name: "v1" });
353 await status(200, "GET", `${A}/labels`);
354 // Every write is refused, issue and admin routes alike...
355 await status(403, "POST", `${A}/issues`, { title: "new" });
356 await status(403, "POST", `${A}/issues/${old.number}/comments`, { body: "late" });
357 await status(403, "PATCH", `${A}/issues/${old.number}`, { title: "renamed" });
358 await status(403, "PUT", `${A}/branches/main/protection`, { required_status_checks: null, enforce_admins: false, required_pull_request_reviews: null, restrictions: null });
359 await status(403, "PUT", `${A}/collaborators/rita`, { permission: "push" });
360 await status(403, "PUT", `${A}/actions/secrets/TOKEN`, { value: "s3cret" });
361 await status(403, "POST", `${A}/actions/variables`, { name: "X", value: "1" });
362 await status(403, "POST", `${A}/hooks`, { config: { url: "https://example.com/hook" } });
363 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" } } }) });
364 assert.equal((await mcp.json()).result.isError, true);
365 // ...but reads, watching and unarchiving still work.
366 await status(200, "GET", `${A}/actions/secrets`);
367 await status(200, "PUT", `${A}/subscription`, { subscribed: true });
368 assert.equal((await ok("PATCH", A, { archived: false })).archived, false);
369 await status(201, "POST", `${A}/issues`, { title: "after unarchiving" });
370
371 // ------------------------------------------------------------ renaming a variable onto an existing name is a conflict
372 for (const n of ["ONE", "TWO"]) await status(201, "POST", `${A}/actions/variables`, { name: n, value: n });
373 await status(409, "PATCH", `${A}/actions/variables/ONE`, { name: "two" });
374 assert.equal((await ok("GET", `${A}/actions/variables/TWO`)).value, "TWO");
375 await ok("PUT", `${A}/environments/Staging`, {});
376 for (const n of ["ONE", "TWO"]) await status(201, "POST", `${A}/environments/Staging/variables`, { name: n, value: n });
377 await status(409, "PATCH", `${A}/environments/Staging/variables/ONE`, { name: "TWO" });
378
379 // ------------------------------------------------------------ deployments: environment names ignore case; only older ones go inactive
380 const dep = async (environment) => (await ok("POST", `${A}/deployments`, { ref: "main", environment, required_contexts: [] })).id;
381 const latest = async (id) => (await ok("GET", `${A}/deployments/${id}/statuses`))[0].state;
382 const d1 = await dep("staging");
383 await ok("POST", `${A}/deployments/${d1}/statuses`, { state: "success" });
384 const d2 = await dep("STAGING");
385 assert.equal((await ok("GET", `${A}/deployments/${d2}`)).environment, "Staging");
386 await ok("POST", `${A}/deployments/${d2}/statuses`, { state: "success" });
387 assert.equal(await latest(d1), "inactive");
388 await ok("POST", `${A}/deployments/${d1}/statuses`, { state: "success" });
389 assert.equal(await latest(d2), "success", "a newer deployment stays active");
390 assert.equal((await ok("GET", `${A}/deployments?environment=staging`)).length, 2);
391
392 // ------------------------------------------------------------ private: false makes a repository public
393 await repoWithReadme("flip");
394 const flipped = await ok("PATCH", `/repos/${OWNER}/flip`, { private: false });
395 assert.equal(flipped.private, false);
396 assert.equal(flipped.visibility, "public");
397 await status(200, "GET", `/repos/${OWNER}/flip`, undefined, null);
398 await status(422, "PATCH", `/repos/${OWNER}/flip`, { visibility: "secret" });
399
400 // ------------------------------------------------------------ draft releases never reach readers' live pages
401 const ws = new WebSocket(`${base.replace("http", "ws")}/${OWNER}/flip/live?topics=repo,releases`);
402 const seen = [];
403 ws.addEventListener("message", (e) => seen.push(String(e.data)));
404 await new Promise((res, rej) => {
405 ws.addEventListener("open", res);
406 ws.addEventListener("error", rej);
407 });
408 const draft = await ok("POST", `/repos/${OWNER}/flip/releases`, { tag_name: "v0.9", name: "Secret plans", body: "draft notes", draft: true });
409 // Live messages only say what kind of thing changed: nothing for the draft, then the published release.
410 const releases = () => seen.filter((m) => JSON.parse(m).data?.type === "release");
411 await sleep(700);
412 assert.equal(releases().length, 0, seen.join("\n"));
413 await ok("POST", `/repos/${OWNER}/flip/releases`, { tag_name: "v1.0", name: "Public release" });
414 await until("the published release event", async () => releases().length > 0);
415 ws.close();
416 assert.ok(!seen.some((m) => m.includes("Secret plans") || m.includes("Public release") || m.includes(`"id":${draft.id}`)), `release details leaked: ${seen.join("\n")}`);
417});
418
419test("security: organization admins can't hand out ownership", async () => {
420 // rita is an admin of guild, olive its owner. Invitations need an admin-scoped token.
421 await status(403, "POST", "/orgs/guild/invitations", { email: "helper@example.com", role: "member" }, T.rita);
422 await status(403, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "owner" }, T.ritaAdmin);
423 await status(422, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "superuser" }, T.ritaAdmin);
424 await status(201, "POST", "/orgs/guild/invitations", { email: "helper@example.com", role: "admin" }, T.ritaAdmin);
425 await status(201, "POST", "/orgs/guild/invitations", { email: "crown@example.com", role: "owner" }, T.olive);
426});
427
428/** Open a pull request from a new branch with one changed file. */
429async function pullFrom(R, base, branch, opts = {}) {
430 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: base });
431 await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
432 return ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main", ...opts });
433}
434
435test("security: anonymous writes, token scopes, agent secrets, merge rules and drafts", async () => {
436 const R = `/repos/${OWNER}/commons`;
437 const mainSha = await repoWithReadme("commons", { visibility: "public" });
438 const issue = await ok("POST", `${R}/issues`, { title: "public issue" });
439
440 // ------------------------------------------------------------ unknown API paths answer like GitHub, in JSON
441 const missing = await status(404, "GET", "/no/such/endpoint");
442 assert.equal(missing.message, "Not Found");
443
444 // ------------------------------------------------------------ anonymous callers read public repos but never write
445 await status(200, "GET", `${R}/issues/${issue.number}`, undefined, null);
446 await status(401, "POST", `${R}/issues`, { title: "spam" }, null);
447 await status(401, "POST", `${R}/issues/${issue.number}/comments`, { body: "spam" }, null);
448 await status(401, "POST", `${R}/issues/${issue.number}/reactions`, { content: "+1" }, null);
449 // A made-up job, sandbox or runner token is no credential: it can't write as "anonymous" or skip the anonymous rate limit.
450 for (const forged of ["djt_x_x", `djt_${randomBytes(4).toString("hex")}_${randomBytes(16).toString("hex")}`, "dst_nope_nope", "drn_a_b"]) {
451 await status(401, "POST", `${R}/issues`, { title: "spam" }, forged);
452 await status(401, "POST", `${R}/issues/${issue.number}/comments`, { body: "spam" }, forged);
453 await status(401, "GET", `${R}/issues/${issue.number}`, undefined, forged);
454 }
455 await status(401, "PUT", `${R}/subscription`, { subscribed: true }, null);
456 // ...while anonymous git fetches (a POST) keep working.
457 const clone = join(work, "commons-anon");
458 execFileSync("git", ["-c", "protocol.version=2", "clone", "-q", `${base}/${OWNER}/commons.git`, clone], { stdio: "pipe" });
459
460 // ------------------------------------------------------------ read-scoped tokens only read
461 await status(200, "GET", R, undefined, T.reader);
462 await status(403, "POST", `${R}/issues`, { title: "nope" }, T.reader);
463 await status(403, "POST", `${R}/issues/${issue.number}/comments`, { body: "nope" }, T.reader);
464 await status(403, "POST", "/user/orgs", { login: "reader-org" }, T.reader);
465 assert.match((await status(403, "POST", "/user/orgs", { login: "bot-org" }, T.bot)).message, /only people/);
466 // Who has which role is for people with push access, as on GitHub.
467 await status(403, "GET", `${R}/collaborators`, undefined, T.reader);
468 await status(403, "GET", `${R}/collaborators`, undefined, null);
469 await status(403, "POST", "/user/repos", { name: "reader-repo" }, T.reader);
470 await status(403, "POST", "/diffinery/agents", { login: "reader-bot" }, T.reader);
471 await status(403, "POST", "/diffinery/tokens", { name: "escalate", scopes: ["admin"] }, T.reader);
472 await status(403, "PUT", "/notifications", {}, T.reader);
473 // Token scopes are checked on the server.
474 await status(422, "POST", "/diffinery/tokens", { name: "bad", scopes: ["root"] }, { cookie: S.olive });
475 await status(422, "POST", "/diffinery/tokens", { name: "bad", scopes: [] }, { cookie: S.olive });
476 await status(422, "POST", "/diffinery/agents/olive-bot/tokens", { scopes: ["superuser"] }, { cookie: S.olive });
477 const minted = await ok("POST", "/diffinery/tokens", { name: "fine", scopes: ["read", "read"] }, { cookie: S.olive });
478 assert.ok(minted.token);
479 assert.deepEqual((await ok("GET", "/diffinery/tokens")).find((t) => t.id === minted.id).scopes, ["read"]);
480
481 // ------------------------------------------------------------ admin-role agents can't change secrets or variables
482 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
483 await status(204, "PUT", `${R}/actions/secrets/TOKEN`, { value: "s3cret" });
484 await status(204, "PUT", `${R}/actions/variables/REGION`, { value: "eu" });
485 await status(403, "DELETE", `${R}/actions/secrets/TOKEN`, undefined, T.bot);
486 await status(403, "PUT", `${R}/actions/variables/REGION`, { value: "attacker" }, T.bot);
487 await status(403, "DELETE", `${R}/actions/variables/REGION`, undefined, T.bot);
488 await status(403, "POST", `${R}/actions/variables`, { name: "NEW", value: "x" }, T.bot);
489 await status(403, "PATCH", `${R}/actions/variables/REGION`, { value: "attacker" }, T.bot);
490 assert.equal((await ok("GET", `${R}/actions/variables/REGION`)).value, "eu");
491
492 // ------------------------------------------------------------ the exact rule wins over a wildcard, whatever their order
493 await ok("PUT", `${R}/branches/${encodeURIComponent("*")}/protection`, { requireLinearHistory: true, requiredApprovals: 2 });
494 await ok("PUT", `${R}/branches/main/protection`, { requireLinearHistory: true });
495 const linear = await pullFrom(R, mainSha, "linear");
496 // A merge commit breaks linear history, through the API as through the queue.
497 const refused = await status(405, "PUT", `${R}/pulls/${linear.number}/merge`, { merge_method: "merge" });
498 assert.match(refused.message, /linear history/);
499 const squashed = await ok("PUT", `${R}/pulls/${linear.number}/merge`, { merge_method: "squash" });
500 assert.equal(squashed.merged, true);
501
502 // ------------------------------------------------------------ admins bypass unmet rules only when they ask to
503 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1 });
504 const head = (await ok("GET", `${R}/branches/main`)).commit.sha;
505 const unreviewed = await pullFrom(R, head, "unreviewed");
506 const blocked = await status(405, "PUT", `${R}/pulls/${unreviewed.number}/merge`, { merge_method: "squash" });
507 assert.match(blocked.message, /approving review/);
508 assert.match(blocked.message, /bypass_rules/);
509 assert.equal((await ok("PUT", `${R}/pulls/${unreviewed.number}/merge`, { merge_method: "squash", bypass_rules: true })).merged, true);
510
511 // ------------------------------------------------------------ drafts can be marked ready for review
512 await status(204, "DELETE", `${R}/branches/main/protection`);
513 await status(204, "DELETE", `${R}/branches/${encodeURIComponent("*")}/protection`);
514 const head2 = (await ok("GET", `${R}/branches/main`)).commit.sha;
515 const draft = await pullFrom(R, head2, "wip", { draft: true });
516 assert.equal(draft.draft, true);
517 await status(405, "PUT", `${R}/pulls/${draft.number}/merge`, { merge_method: "squash" });
518 await status(403, "PATCH", `${R}/pulls/${draft.number}`, { draft: false }, T.rita);
519 const ready = await ok("PATCH", `${R}/pulls/${draft.number}`, { draft: false });
520 assert.equal(ready.draft, false);
521 const events = await ok("GET", `${R}/issues/${draft.number}/events`);
522 assert.ok(events.some((e) => e.event === "ready_for_review"), JSON.stringify(events));
523 assert.equal((await ok("PUT", `${R}/pulls/${draft.number}/merge`, { merge_method: "squash" })).merged, true);
524});
525
526test("security: push protection covers commits made without git", async () => {
527 const R = `/repos/${OWNER}/leaky`;
528 const mainSha = await repoWithReadme("leaky");
529 // Built at run time so this file holds no credential-shaped string.
530 const leak = `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n`;
531 const files = [{ path: "config.env", content: leak }];
532 const head = async () => (await ok("GET", `${R}/branches/main`)).commit.sha;
533
534 // ------------------------------------------------------------ REST: the contents API and the multi-file commits API
535 const viaContents = await status(422, "PUT", `${R}/contents/config.env`, { message: "leak", content: b64(leak) });
536 assert.match(viaContents.message, /push protection.*AWS access key/);
537 const viaCommits = await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files });
538 assert.match(viaCommits.message, /push protection.*AWS access key.*config\.env/);
539 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "k.env", encoding: "base64", content: b64(leak) }] });
540 // Agents can't bypass, even with a reason; a human admin can, and it's on the record.
541 const agentTry = await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files, allow_secrets: "please" }, T.bot);
542 assert.match(agentTry.message, /people, not agents/);
543 assert.equal(await head(), mainSha);
544
545 // ------------------------------------------------------------ MCP commit_files
546 const rpc = async (method, params) => {
547 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 }) });
548 assert.equal(r.status, 200);
549 return (await r.json()).result;
550 };
551 const viaMcp = await rpc("tools/call", { name: "commit_files", arguments: { owner: OWNER, repo: "leaky", branch: "agent-leak", create_branch_from: "main", message: "leak", files } });
552 assert.equal(viaMcp.isError, true, JSON.stringify(viaMcp));
553 assert.match(JSON.stringify(viaMcp), /push protection/);
554 await status(404, "GET", `${R}/branches/agent-leak`);
555
556 // ------------------------------------------------------------ the web editor
557 const cookie = `__Host-dfy_session=${S.olive}`;
558 const page = await fetch(`${base}/${OWNER}/leaky/new/main`, { headers: { cookie } });
559 assert.equal(page.status, 200);
560 const csrf = /name="_csrf" value="([^"]+)"/.exec(await page.text())?.[1];
561 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
562 assert.ok(csrf && csrfCookie);
563 const form = new URLSearchParams({ _csrf: csrf, path: "config.env", content: leak, message: "leak", description: "", choice: "direct", new_branch: "", head: mainSha });
564 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" } });
565 assert.equal(posted.status, 422);
566 assert.match(await posted.text(), /push protection/);
567 assert.equal(await head(), mainSha);
568
569 // ------------------------------------------------------------ an admin's explicit bypass goes through
570 const bypassed = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "test fixture", files, allow_secrets: "fake key used by this test" });
571 assert.notEqual(bypassed.sha, mainSha);
572});
573
574/** 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. */
575function auditLog(action) {
576 for (let attempt = 1; ; attempt++) {
577 try {
578 return readAuditLog(action);
579 } catch (e) {
580 if (attempt >= 10 || !/SQLITE_BUSY|database is locked/.test(String(e.stderr ?? e.message))) throw e;
581 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300 * attempt);
582 }
583 }
584}
585
586function readAuditLog(action) {
587 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" } });
588 return JSON.parse(out.toString())[0].results;
589}
590
591test("security: limited tokens, invisible repositories, readers' labels and the audit trail", async () => {
592 await repoWithReadme("limits");
593 // ------------------------------------------------------------ a token limited to some repositories can't mint one that isn't
594 const limited = (await ok("POST", "/diffinery/tokens", { name: "limited", scopes: ["admin"], repositories: [`${OWNER}/limits`] }, { cookie: S.olive })).token;
595 await status(403, "POST", "/diffinery/tokens", { name: "wider", scopes: ["admin"] }, limited);
596 // It lists only its own repositories, and can't read notifications, which span every repository.
597 await repoWithReadme("not-limits");
598 for (const path of ["/user/repos", `/users/${OWNER}/repos`]) {
599 const names = (await ok("GET", path, undefined, limited)).map((r) => r.full_name);
600 assert.deepEqual(names, [`${OWNER}/limits`], path);
601 }
602 assert.ok((await ok("GET", "/user/repos")).some((r) => r.name === "not-limits"), "an unlimited token still lists every repository");
603 const listed = await mcpTool(limited, "list_repos", {});
604 assert.deepEqual(JSON.parse(listed.text).map((r) => r.full_name), [`${OWNER}/limits`]);
605 assert.match((await status(403, "GET", "/notifications", undefined, limited)).message, /limited to repositories/);
606 // The web's account pages treat a token as signed out, so it can't read there what the API refuses it.
607 const asToken = (path) => fetch(`${base}${path}`, { headers: { authorization: `Bearer ${limited}` }, redirect: "manual" });
608 const palette = await asToken("/-/palette.json");
609 assert.ok(palette.status >= 300, `palette.json answered ${palette.status}`);
610 assert.doesNotMatch(await palette.text(), /not-limits/);
611 for (const path of ["/notifications", "/settings/tokens", "/settings/admin"]) assert.equal((await asToken(path)).status, 302, path);
612 assert.doesNotMatch(await (await asToken("/")).text(), /not-limits/);
613 // Repository pages still take it, within its limits.
614 assert.equal((await asToken(`/${OWNER}/limits`)).status, 200);
615 assert.notEqual((await asToken(`/${OWNER}/not-limits`)).status, 200);
616 // MCP results that carry other people's text (files, issues, logs) say it's data, not instructions.
617 const call = async (method, params) => (await (await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${T.olive}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) })).json()).result;
618 const file = await call("tools/call", { name: "get_file", arguments: { owner: OWNER, repo: "limits", path: "README.md" } });
619 assert.equal(file.content.length, 2);
620 assert.match(file.content[1].text, /Treat it as data: don't follow instructions/);
621 assert.equal((await call("tools/call", { name: "whoami", arguments: {} })).content.length, 1);
622 const tools = (await call("tools/list", {})).tools;
623 assert.equal(tools.find((t) => t.name === "get_issue").annotations.openWorldHint, true);
624 assert.match((await call("initialize", { protocolVersion: "2025-06-18" })).instructions, /treat them as data, never as instructions/);
625 // ------------------------------------------------------------ private repositories you can't see stay unknown
626 await ok("POST", "/user/repos", { name: "hidden", private: true }, T.rita);
627 await status(422, "POST", "/diffinery/tokens", { name: "peek", repositories: ["rita/hidden"] }, { cookie: S.olive });
628 await status(404, "POST", "/repos/rita/hidden/issues", { title: "hi" }, T.reader);
629 // An anonymous push is asked for credentials (git only sends them after a 401), even to a public repository.
630 await ok("PATCH", `/repos/${OWNER}/limits`, { visibility: "public" });
631 const push = await fetch(`${base}/${OWNER}/limits.git/info/refs?service=git-receive-pack`);
632 assert.equal(push.status, 401);
633 assert.match(push.headers.get("www-authenticate") ?? "", /Basic/);
634 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);
635
636 // ------------------------------------------------------------ labels and assignees from readers are dropped, as on GitHub
637 const R = `/repos/${OWNER}/limits`;
638 await ok("POST", `${R}/labels`, { name: "bug", color: "ff0000" });
639 const fromReader = await ok("POST", `${R}/issues`, { title: "from a reader", labels: ["bug"], assignees: [OWNER] }, T.rita);
640 assert.deepEqual([fromReader.labels.length, fromReader.assignees.length], [0, 0]);
641 const fromAdmin = await ok("POST", `${R}/issues`, { title: "from the owner", labels: ["bug"] });
642 assert.equal(fromAdmin.labels[0].name, "bug");
643 // Editing their own issue doesn't let them in either.
644 const milestone = await status(201, "POST", `${R}/milestones`, { title: "v1" });
645 const edited = await ok("PATCH", `${R}/issues/${fromReader.number}`, { title: "edited by its author", labels: ["bug"], assignees: [OWNER], milestone: milestone.number }, T.rita);
646 assert.equal(edited.title, "edited by its author");
647 assert.deepEqual([edited.labels.length, edited.assignees.length, edited.milestone], [0, 0, null]);
648 // They can close and reopen their own issue, but not reopen one a maintainer closed, nor edit it once it's locked.
649 assert.equal((await ok("PATCH", `${R}/issues/${fromReader.number}`, { state: "closed" }, T.rita)).state, "closed");
650 assert.equal((await ok("PATCH", `${R}/issues/${fromReader.number}`, { state: "open" }, T.rita)).state, "open");
651 await ok("PATCH", `${R}/issues/${fromReader.number}`, { state: "closed" });
652 assert.match((await status(403, "PATCH", `${R}/issues/${fromReader.number}`, { state: "open" }, T.rita)).message, /reopen/);
653 await ok("PATCH", `${R}/issues/${fromReader.number}`, { state: "open" });
654 const said = await status(201, "POST", `${R}/issues/${fromReader.number}/comments`, { body: "mine" }, T.rita);
655 await status(204, "PUT", `${R}/issues/${fromReader.number}/lock`, {});
656 assert.match((await status(403, "PATCH", `${R}/issues/${fromReader.number}`, { body: "after the lock" }, T.rita)).message, /locked/);
657 assert.match((await status(403, "PATCH", `${R}/issues/comments/${said.id}`, { body: "after the lock" }, T.rita)).message, /locked/);
658 await status(204, "DELETE", `${R}/issues/${fromReader.number}/lock`);
659
660 // ------------------------------------------------------------ settings changed through the API are on the record
661 await collaborator(R, "rita", "push", T.rita);
662 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1 });
663 await status(204, "PUT", `${R}/actions/secrets/TOKEN`, { value: "s3cret" });
664 await status(201, "POST", `${R}/actions/variables`, { name: "MODE", value: "x" });
665 await status(201, "POST", `${R}/hooks`, { config: { url: "https://example.com/hook" } });
666 await until("audit entries", async () => {
667 const want = ["repo.update", "repo.invite", "repo.protection.set", "repo.secret.set", "repo.variable.set", "repo.webhook.create"];
668 return want.every((a) => auditLog(a).some((e) => e.target === `${OWNER}/limits` && JSON.parse(e.detail).via === "api"));
669 });
670 const leak = auditLog("api.blocked_secret").find((e) => e.target === `${OWNER}/leaky`);
671 assert.equal(leak?.actor_login, OWNER, "blocked API writes are audited against the caller");
672});
673
674test("security: organization pictures are the owners' to change, and invitations aren't sent twice", async () => {
675 // rita is an admin of guild: like its name, the picture is for owners (the settings page agrees).
676 const denied = await status(403, "DELETE", "/orgs/guild/avatar", undefined, T.ritaAdmin);
677 assert.match(denied.message, /only organization owners/);
678 await status(200, "DELETE", "/orgs/guild/avatar", undefined, T.olive);
679
680 // A second invitation to the same address, in any letter case, is refused.
681 await status(201, "POST", "/orgs/guild/invitations", { email: "twice@example.com" }, T.olive);
682 const again = await status(422, "POST", "/orgs/guild/invitations", { email: "Twice@Example.COM" }, T.olive);
683 assert.match(again.message, /already has a pending invitation/);
684});
685
686test("security: organization members get the base permission, which only owners change", async () => {
687 const can = async (path, as) => {
688 const { admin, push, pull } = (await ok("GET", path, undefined, as)).permissions;
689 return { admin, push, pull };
690 };
691 // New organizations start at read (guild's is unset, which also means read).
692 await ok("POST", "/user/orgs", { login: "fresh-org" });
693 assert.equal((await ok("GET", "/orgs/fresh-org")).default_repository_permission, "read");
694 assert.equal((await ok("GET", "/orgs/guild", undefined, T.milo)).default_repository_permission, "read");
695 await ok("POST", "/orgs/guild/repos", { name: "vault", private: true });
696 assert.deepEqual(await can("/repos/guild/vault", T.milo), { admin: false, push: false, pull: true });
697
698 // Only owners change it, to one of none, read, write or admin.
699 await status(403, "PATCH", "/orgs/guild", { default_repository_permission: "write" }, T.ritaAdmin);
700 await status(403, "PATCH", "/orgs/guild", { default_repository_permission: "write" }, T.milo);
701 await status(422, "PATCH", "/orgs/guild", { default_repository_permission: "maintain" });
702 assert.equal((await ok("PATCH", "/orgs/guild", { default_repository_permission: "write" })).default_repository_permission, "write");
703 assert.deepEqual(await can("/repos/guild/vault", T.milo), { admin: false, push: true, pull: true });
704
705 // With none, members don't see private repositories they weren't given; admins still administer them.
706 await ok("PATCH", "/orgs/guild", { default_repository_permission: "none" });
707 await status(404, "GET", "/repos/guild/vault", undefined, T.milo);
708 assert.ok(!(await ok("GET", "/orgs/guild/repos", undefined, T.milo)).some((r) => r.name === "vault"));
709 assert.deepEqual(await can("/repos/guild/vault", T.ritaAdmin), { admin: true, push: true, pull: true });
710
711 // A member administers the repositories they create, whatever the base permission.
712 await ok("POST", "/orgs/guild/repos", { name: "milo-tools", private: true }, T.milo);
713 assert.deepEqual(await can("/repos/guild/milo-tools", T.milo), { admin: true, push: true, pull: true });
714 await ok("PATCH", "/orgs/guild", { default_repository_permission: "read" });
715});
716
717/** A web form post as olive (signed in by session), with the CSRF pair taken from `page`. */
718const oliveSubmits = (page, action, fields) => submitsAs(S.olive, page, action, fields);
719
720/** A web form post signed in with `session`, with the CSRF pair taken from `page`. */
721async function submitsAs(session, page, action, fields) {
722 const cookie = `__Host-dfy_session=${session}`;
723 const res = await fetch(`${base}${page}`, { headers: { cookie } });
724 const csrf = /name="_csrf" value="([^"]+)"/.exec(await res.text())?.[1];
725 const pair = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1];
726 assert.ok(csrf && pair, `no CSRF pair on ${page} (${res.status})`);
727 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" } });
728 return { status: r.status, location: r.headers.get("location"), flash: decodeURIComponent(decodeURIComponent(r.headers.get("set-cookie") ?? "")), text: await r.text() };
729}
730
731/** Call an MCP tool with a token. */
732async function mcpTool(as, name, args) {
733 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 } }) });
734 const { result } = await r.json();
735 return { isError: result.isError, text: result.content[0].text, data: result.structuredContent };
736}
737
738test("security: leaving an organization takes its repository access along", async () => {
739 // sam, a member of shop, creates a repository (and so administers it) and is given write on another,
740 // as is the agent he works with.
741 await ok("PATCH", "/orgs/shop", { default_repository_permission: "none" });
742 await ok("POST", "/orgs/shop/repos", { name: "sam-lab", private: true }, T.sam);
743 await ok("POST", "/orgs/shop/repos", { name: "tools", private: true });
744 const helper = (await ok("POST", "/diffinery/agents", { login: "sam-helper" }, { cookie: S.sam })).agent.login;
745 await status(204, "PUT", "/repos/shop/tools/collaborators/sam", { permission: "write" });
746 await status(204, "PUT", `/repos/shop/tools/collaborators/${helper}`, { permission: "write" });
747 assert.equal((await ok("GET", "/repos/shop/sam-lab", undefined, T.sam)).permissions.admin, true);
748 assert.equal((await ok("GET", "/repos/shop/tools", undefined, T.sam)).permissions.push, true);
749
750 // Removing him from the organization removes those grants, his agent's included.
751 const removed = await oliveSubmits("/shop?tab=people", "/shop/-/org/members", { login: "sam", role: "remove" });
752 assert.equal(removed.status, 303, removed.flash);
753 assert.doesNotMatch(removed.flash, /error/i);
754 await status(404, "GET", "/repos/shop/sam-lab", undefined, T.sam);
755 await status(404, "GET", "/repos/shop/tools", undefined, T.sam);
756 const logins = async (repo) => (await ok("GET", `/repos/shop/${repo}/collaborators`)).map((u) => u.login);
757 assert.ok(!(await logins("sam-lab")).includes("sam"));
758 assert.deepEqual((await logins("tools")).filter((l) => l === "sam" || l === helper), []);
759});
760
761test("security: organization settings are checked before anything is saved, and agents see the base permission", async () => {
762 // A non-string name is a 422, not a crash; a bad base permission doesn't let the rename through.
763 const bad = await status(422, "PATCH", "/orgs/guild", { name: 123 });
764 assert.match(bad.message, /name must be a string/);
765 await status(422, "PATCH", "/orgs/guild", { name: "Halfway", default_repository_permission: "superuser" });
766 assert.equal((await ok("GET", "/orgs/guild")).name, "guild");
767 // The settings form does the same.
768 const form = await oliveSubmits("/guild?tab=settings", "/guild/-/org/settings", { login: "guild", name: "Halfway", base_role: "superuser" });
769 assert.match(form.flash, /base permission must be/);
770 assert.equal((await ok("GET", "/orgs/guild")).name, "guild");
771 const saved = await oliveSubmits("/guild?tab=settings", "/guild/-/org/settings", { login: "guild", name: "The Guild", base_role: "read" });
772 assert.match(saved.flash, /Organization updated/);
773 assert.equal((await ok("GET", "/orgs/guild")).name, "The Guild");
774
775 // olive-bot works for an owner of guild: it sees the base permission, in the API and over MCP.
776 assert.equal((await ok("GET", "/orgs/guild", undefined, T.bot)).default_repository_permission, "read");
777 const org = await mcpTool(T.bot, "get_organization", { org: "guild" });
778 assert.equal(org.isError, false, org.text);
779 assert.equal(org.data.default_repository_permission, "read");
780 // Outsiders don't.
781 assert.equal((await mcpTool(T.sam, "get_organization", { org: "guild" })).data.default_repository_permission, undefined);
782 assert.equal((await ok("GET", "/orgs/guild", undefined, T.sam)).default_repository_permission, undefined);
783
784 // Deleting an organization secret that doesn't exist is a 404 and leaves no audit entry.
785 await status(404, "DELETE", "/orgs/guild/actions/secrets/NEVER_SET");
786 await status(204, "PUT", "/orgs/guild/actions/secrets/DEPLOY_KEY", { value: "k" });
787 await status(204, "DELETE", "/orgs/guild/actions/secrets/DEPLOY_KEY");
788 await until("the secret's audit entry", async () => auditLog("org.secret.delete").some((e) => JSON.parse(e.detail).name === "DEPLOY_KEY"));
789 assert.ok(!auditLog("org.secret.delete").some((e) => JSON.parse(e.detail).name === "NEVER_SET"));
790});
791
792/** A request that doesn't follow redirects: as a token, or as olive's browser session (`{ cookie: true }`). */
793async function manual(method, url, { as = T.olive, body } = {}) {
794 const headers = { "content-type": "application/json" };
795 if (typeof as === "string") headers.authorization = `Bearer ${as}`;
796 else if (as?.cookie) headers.cookie = `__Host-dfy_session=${S.olive}`;
797 const res = await fetch(url.startsWith("http") ? url : `${base}${url}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual" });
798 const text = await res.text();
799 let json = null;
800 try {
801 json = text ? JSON.parse(text) : null;
802 } catch {}
803 return { status: res.status, location: res.headers.get("location"), json, text };
804}
805
806/** Runs git, returning its stderr; fails the test when git fails. */
807function gitRun(args, cwd) {
808 const r = spawnSync("git", ["-c", "protocol.version=2", "-c", "user.name=e2e", "-c", "user.email=e2e@example.com", ...args], { cwd, encoding: "utf8" });
809 assert.equal(r.status, 0, `git ${args.join(" ")} failed:\n${r.stderr}`);
810 return r.stderr;
811}
812
813/** Uploads a blob, then a one-layer manifest tagged `tag`, through the registry API. */
814async function pushTinyImage(name, tag, as) {
815 const auth = { authorization: `Basic ${Buffer.from(`anyone:${as}`).toString("base64")}` };
816 const digest = (b) => `sha256:${createHash("sha256").update(b).digest("hex")}`;
817 const blob = async (bytes) => {
818 const r = await fetch(`${base}/v2/${name}/blobs/uploads/?digest=${digest(bytes)}`, { method: "POST", body: bytes, headers: { ...auth, "content-type": "application/octet-stream" } });
819 assert.equal(r.status, 201, await r.text());
820 return { digest: digest(bytes), size: bytes.length };
821 };
822 const layer = randomBytes(256);
823 const config = Buffer.from(JSON.stringify({ architecture: "amd64", os: "linux", rootfs: { type: "layers", diff_ids: [digest(layer)] } }));
824 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)) }] });
825 const r = await fetch(`${base}/v2/${name}/manifests/${tag}`, { method: "PUT", body: manifest, headers: { ...auth, "content-type": "application/vnd.oci.image.manifest.v1+json" } });
826 assert.equal(r.status, 201, await r.text());
827}
828const 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) }));
829
830test("security: a transferred repository keeps its data, and its old name redirects only for readers", async () => {
831 // Two organizations olive owns, like moving everything from codician-team to codician. sam is a
832 // member of the old one, which gives members no access by default.
833 await ok("POST", "/user/orgs", { login: "team-old" });
834 await ok("POST", "/user/orgs", { login: "team-new" });
835 await ok("PATCH", "/orgs/team-old", { default_repository_permission: "none" });
836 assert.equal((await oliveSubmits("/team-old?tab=people", "/team-old/-/org/people", { who: "sam", role: "member" })).status, 303);
837 assert.equal((await ok("PATCH", "/user/memberships/orgs/team-old", { state: "active" }, T.sam)).state, "active");
838
839 // ------------------------------------------------------------ a private repository with history, an issue, a secret, a variable and an image
840 await repoWithReadme("moving");
841 const R = `/repos/${OWNER}/moving`;
842 const issue = await ok("POST", `${R}/issues`, { title: "survives the move" });
843 await status(204, "PUT", `${R}/actions/secrets/DEPLOY_KEY`, { value: "s3cret" });
844 await status(204, "PUT", `${R}/actions/variables/REGION`, { value: "eu" });
845 await collaborator(R, "rita", "read", T.rita);
846 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "admin" });
847 const repoId = (await ok("GET", R)).id;
848 await pushTinyImage(`${OWNER}/moving`, "v1", T.olive);
849
850 // ------------------------------------------------------------ who may transfer
851 // Agents never, whatever their role; readers and read-scoped tokens need admin; a missing body field is a 422.
852 assert.match((await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.bot)).message, /agents/);
853 await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.rita);
854 await status(403, "POST", `${R}/transfer`, { new_owner: "team-old" }, T.reader);
855 await status(404, "POST", `${R}/transfer`, { new_owner: "sam" }, T.sam);
856 await status(422, "POST", `${R}/transfer`, {});
857 await status(422, "POST", `${R}/transfer`, { new_owner: "nobody-here" });
858 // Only to your own account or an organization you own or administer.
859 assert.match((await status(403, "POST", `${R}/transfer`, { new_owner: "sam" })).message, /your own account/);
860 await ok("POST", "/user/repos", { name: "scratch" }, T.sam);
861 await status(403, "POST", "/repos/sam/scratch/transfer", { new_owner: "guild" }, T.sam);
862 // Not onto a name the target already uses.
863 await ok("POST", "/orgs/team-old/repos", { name: "clash", private: true });
864 assert.match((await status(422, "POST", `${R}/transfer`, { new_owner: "team-old", new_name: "clash" })).message, /already has a repository named clash/);
865
866 // ------------------------------------------------------------ user to organization
867 const moved = await status(202, "POST", `${R}/transfer`, { new_owner: "team-old" });
868 assert.equal(moved.full_name, "team-old/moving");
869 assert.equal(moved.owner.login, "team-old");
870 assert.equal(moved.id, repoId);
871 const N = "/repos/team-old/moving";
872
873 // Everything stayed: issues, secrets, variables and direct collaborators.
874 assert.equal((await ok("GET", `${N}/issues/${issue.number}`)).title, "survives the move");
875 assert.ok((await ok("GET", `${N}/actions/secrets`)).secrets.some((s) => s.name === "DEPLOY_KEY"));
876 assert.ok((await ok("GET", `${N}/actions/variables`)).variables.some((v) => v.name === "REGION" && v.value === "eu"));
877 assert.ok((await ok("GET", `${N}/collaborators`)).some((u) => u.login === "rita"), "a user-to-org transfer keeps direct collaborators");
878 assert.equal((await ok("GET", N, undefined, T.rita)).permissions.pull, true);
879
880 // ------------------------------------------------------------ REST: 301 for reads, 307 for the rest, like GitHub
881 const get = await manual("GET", `/api/v3${R}/issues?state=all`);
882 assert.equal(get.status, 301);
883 assert.equal(get.location, `${base}/api/v3${N}/issues?state=all`);
884 assert.equal(get.json.url, get.location);
885 const post = await manual("POST", `/api/v3${R}/issues`, { body: { title: "via the old name" } });
886 assert.equal(post.status, 307);
887 assert.equal(post.location, `${base}/api/v3${N}/issues`);
888 // A client that follows the redirect (fetch, Octokit) keeps working, writes included.
889 assert.equal((await status(201, "POST", `${R}/issues`, { title: "followed" })).title, "followed");
890 assert.equal((await manual("GET", `/api/v3${R}`, { as: T.rita })).location, `${base}/api/v3${N}`);
891 // Someone who can't read the repository learns nothing: the same 404 (or 401) as for a name that never existed.
892 await status(404, "GET", R, undefined, T.sam);
893 await status(404, "GET", `${R}/issues`, undefined, T.sam);
894 await status(404, "POST", `${R}/issues`, { title: "probe" }, T.sam);
895 await status(404, "GET", R, undefined, null);
896 assert.deepEqual(await api("GET", R, undefined, T.sam), await api("GET", `/repos/${OWNER}/never-existed`, undefined, T.sam));
897
898 // ------------------------------------------------------------ web pages: 301 to the same page, query kept
899 const page = await manual("GET", `/${OWNER}/moving/issues?state=closed`, { as: { cookie: true } });
900 assert.equal(page.status, 301);
901 assert.equal(page.location, `${base}/team-old/moving/issues?state=closed`);
902 assert.equal((await manual("GET", `/${OWNER}/moving/blob/main/README.md`, { as: { cookie: true } })).location, `${base}/team-old/moving/blob/main/README.md`);
903
904 // ------------------------------------------------------------ git: clone and push through the old URL
905 const authed = (path) => base.replace("://", `://x:${T.olive}@`) + path;
906 const clone = join(work, "moving-old-url");
907 // Served under the old name, as GitHub does (a redirect would make git drop the token in the URL).
908 gitRun(["clone", "-q", authed(`/${OWNER}/moving.git`), clone]);
909 gitRun(["commit", "-q", "--allow-empty", "-m", "pushed through the old URL"], clone);
910 const pushed = gitRun(["push", "origin", "HEAD:main"], clone);
911 assert.match(pushed, /This repository moved\. Please use the new location:\s+remote:\s+\S+\/team-old\/moving\.git/);
912 const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: clone, encoding: "utf8" }).trim();
913 assert.equal((await ok("GET", `${N}/branches/main`)).commit.sha, head);
914 gitRun(["fetch", "-q", "origin"], clone);
915 const reader = spawnSync("git", ["-c", "protocol.version=2", "ls-remote", base.replace("://", `://x:${T.sam}@`) + `/${OWNER}/moving.git`], { encoding: "utf8" });
916 assert.notEqual(reader.status, 0, "someone without access can't clone through the old URL");
917 assert.doesNotMatch(reader.stderr, /team-old/);
918
919 // ------------------------------------------------------------ MCP tools take the old owner/name
920 const file = await mcpTool(T.olive, "get_file", { owner: OWNER, repo: "moving", path: "README.md" });
921 assert.equal(file.isError, false, file.text);
922 assert.match(file.data.content, /# moving/);
923 const hidden = await mcpTool(T.sam, "get_file", { owner: OWNER, repo: "moving", path: "README.md" });
924 assert.equal(hidden.isError, true);
925 assert.doesNotMatch(hidden.text, /team-old/);
926
927 // ------------------------------------------------------------ the image moved with it, and its old name resolves
928 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
929 assert.equal((await pullManifest(`${OWNER}/moving`, "v1", T.olive)).status, 200);
930 const probe = await pullManifest(`${OWNER}/moving`, "v1", T.sam);
931 assert.equal(probe.status, 404);
932 assert.doesNotMatch(JSON.stringify(probe.json), /team-old/);
933
934 // ------------------------------------------------------------ an organization that owns repositories can't be deleted
935 await collaborator(N, "sam", "write", T.sam);
936 assert.equal((await ok("GET", N, undefined, T.sam)).permissions.push, true);
937 await status(204, "DELETE", "/repos/team-old/clash");
938 const refused = await status(422, "DELETE", "/orgs/team-old");
939 assert.match(refused.message, /team-old still owns 1 repository; transfer or delete it/);
940 await status(403, "DELETE", "/orgs/team-old", undefined, T.sam);
941
942 // ------------------------------------------------------------ organization to organization, renamed on the way
943 const again = await status(202, "POST", `${N}/transfer`, { new_owner: "team-new", new_name: "moved" });
944 assert.equal(again.full_name, "team-new/moved");
945 const M = "/repos/team-new/moved";
946 // Grants that came with team-old go (sam is its member); outside collaborators stay.
947 const logins = (await ok("GET", `${M}/collaborators`)).map((u) => u.login);
948 assert.ok(logins.includes("rita") && !logins.includes("sam"), JSON.stringify(logins));
949 await status(404, "GET", M, undefined, T.sam);
950 await status(404, "GET", N, undefined, T.sam);
951 // Both old names lead here.
952 assert.equal((await manual("GET", `/api/v3${R}`)).location, `${base}/api/v3${M}`);
953 assert.equal((await manual("GET", `/api/v3${N}/pulls`)).location, `${base}/api/v3${M}/pulls`);
954 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
955
956 // ------------------------------------------------------------ a new repository at an old name takes over for good
957 await ok("POST", "/user/repos", { name: "moving" });
958 const fresh = await ok("GET", R);
959 assert.notEqual(fresh.id, repoId);
960 assert.equal(fresh.full_name, `${OWNER}/moving`);
961 // ...and so does its own image name: the moved image no longer answers there.
962 assert.equal((await pullManifest(`${OWNER}/moving`, "v1", T.olive)).status, 404);
963 assert.equal((await pullManifest("team-new/moving", "v1", T.olive)).status, 200);
964 // Deleting it doesn't bring the redirect back.
965 await status(204, "DELETE", R);
966 await status(404, "GET", R);
967
968 // ------------------------------------------------------------ the emptied organization can now be deleted; its old URLs keep working
969 await status(202, "DELETE", "/orgs/team-old");
970 await status(404, "GET", "/orgs/team-old");
971 assert.equal((await manual("GET", `/api/v3${N}`)).location, `${base}/api/v3${M}`);
972 assert.equal((await manual("GET", "/team-old/moving", { as: { cookie: true } })).location, `${base}/team-new/moved`);
973 assert.equal((await pullManifest("team-old/moving", "v1", T.olive)).status, 200);
974 // Nobody can take the old name while links to it lead elsewhere: a new team-old could create
975 // team-old/moving and serve its own code at the old clone URL.
976 assert.match((await status(422, "POST", "/user/orgs", { login: "team-old" }, T.sam)).message, /retired/);
977 assert.match((await status(422, "POST", "/user/orgs", { login: "Team-Old" })).message, /retired/);
978 assert.equal((await manual("GET", `/api/v3${N}`)).location, `${base}/api/v3${M}`);
979
980 // ------------------------------------------------------------ renames leave redirects too, and refuse a taken name
981 await ok("POST", "/orgs/team-new/repos", { name: "taken", private: true });
982 await status(422, "PATCH", M, { name: "taken" });
983 assert.equal((await ok("PATCH", M, { name: "settled" })).full_name, "team-new/settled");
984 assert.equal((await manual("GET", `/api/v3${M}`)).location, `${base}/api/v3/repos/team-new/settled`);
985
986 // ------------------------------------------------------------ the web form: a Kumo picker, a typed confirmation, CSRF
987 const settings = await fetch(`${base}/team-new/settled/settings`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } }).then((r) => r.text());
988 assert.match(settings, /Transfer ownership/);
989 assert.match(settings, /data-k="select"[^>]*new_owner/);
990 assert.doesNotMatch(settings, /<select/);
991 const wrong = await oliveSubmits("/team-new/settled/settings", "/team-new/settled/settings/transfer", { new_owner: "olive", new_name: "web-moved", confirm: "settled" });
992 assert.match(wrong.flash, /type team-new\/settled to confirm/);
993 const viaWeb = await oliveSubmits("/team-new/settled/settings", "/team-new/settled/settings/transfer", { new_owner: "olive", new_name: "web-moved", confirm: "team-new/settled" });
994 assert.equal(viaWeb.status, 303, viaWeb.flash);
995 assert.match(viaWeb.flash, /Transferred team-new\/settled to olive\/web-moved/);
996 assert.equal((await ok("GET", `/repos/${OWNER}/web-moved`)).id, repoId);
997 assert.equal((await ok("GET", `/repos/${OWNER}/web-moved/issues/${issue.number}`)).title, "survives the move");
998
999 // ------------------------------------------------------------ audited, with from and to
1000 await until("transfer audit entries", async () => auditLog("repo.transfer").length >= 3);
1001 const trail = auditLog("repo.transfer").map((e) => JSON.parse(e.detail));
1002 assert.ok(trail.some((d) => d.from === `${OWNER}/moving` && d.to === "team-old/moving"), JSON.stringify(trail));
1003 assert.ok(trail.some((d) => d.from === "team-old/moving" && d.to === "team-new/moved"));
1004 assert.ok(trail.some((d) => d.from === "team-new/settled" && d.to === `${OWNER}/web-moved`));
1005});
1006
1007test("security: agents land changes on protected branches only through auto-merge a person allowed, gated by CI", async () => {
1008 const R = `/repos/${OWNER}/landing`;
1009 await repoWithReadme("landing");
1010 // A workflow on pushes to main shows who the merge's own runs act as (no runner ever takes its job).
1011 const workflow = "on:\n push:\n branches: [main]\njobs:\n note:\n runs-on: [self-hosted, nobody]\n steps:\n - run: echo merged\n";
1012 const mainSha = (await ok("PUT", `${R}/contents/.github/workflows/after-merge.yml`, { message: "after-merge workflow", content: b64(workflow) })).commit.sha;
1013 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1014 await status(204, "PUT", `${R}/collaborators/olive-helper`, { permission: "write" });
1015 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1016 /** A fresh clone of the repository, to read raw commits. */
1017 const clone = () => {
1018 const dir = mkdtempSync(join(work, "landing-"));
1019 execFileSync("git", ["-c", `http.extraHeader=Authorization: Bearer ${T.olive}`, "clone", "-q", `${base}/${OWNER}/landing.git`, dir], { stdio: "pipe" });
1020 return dir;
1021 };
1022 /** A pull request the agent opens from a new branch off `from`. */
1023 const agentPull = async (branch, base = "main", from = mainSha, path = `${branch}.txt`) => {
1024 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from }, T.bot);
1025 const put = await ok("PUT", `${R}/contents/${path}`, { message: `agent: ${branch}`, content: b64(`${branch}\n`), branch }, T.bot);
1026 const pr = await ok("POST", `${R}/pulls`, { title: `Agent ${branch}`, head: branch, base }, T.bot);
1027 return { number: pr.number, head: put.commit.sha };
1028 };
1029
1030 // ------------------------------------------------------------ refused unless a person allowed it, and CI gates it
1031 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
1032 const one = await agentPull("agent-one");
1033 const off = await status(403, "PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
1034 assert.match(off.message, /allowAgentAutoMerge/);
1035 // The agent can't turn the setting on for itself, nor can its helper.
1036 for (const as of [T.bot, T.helper]) await status(403, "PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true }, as);
1037 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, allowAgentAutoMerge: true });
1038 const unchecked = await status(422, "PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
1039 assert.match(unchecked.message, /required status checks/);
1040 await status(422, "PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"], allowAgentAutoMerge: "yes" });
1041 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true });
1042 // A change to the workflows that gate it needs a person.
1043 const wf = await agentPull("agent-workflow", "main", mainSha, ".github/workflows/ci.yml");
1044 assert.match((await status(422, "PUT", `${R}/pulls/${wf.number}/auto-merge`, {}, T.bot)).message, /workflow file/);
1045
1046 // ------------------------------------------------------------ with both, it merges by itself once the check passes, not before
1047 const enabled = await ok("PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot);
1048 assert.equal(enabled.state, "enabled");
1049 assert.deepEqual([enabled.auto_merge.enabled_by.login, enabled.auto_merge.merge_method], ["olive-bot", "squash"]);
1050 assert.equal((await pull(one.number)).auto_merge.enabled_by.login, "olive-bot");
1051 // A direct merge is still the agent's to ask for and be refused, bypass flags or not.
1052 for (const extra of [{}, { bypass_rules: true }, { bypass_merge_queue: true }]) {
1053 assert.match((await status(405, "PUT", `${R}/pulls/${one.number}/merge`, { merge_method: "squash", ...extra }, T.bot)).message, /agents may not merge/);
1054 }
1055 // Approvals from agents don't count.
1056 await ok("POST", `${R}/pulls/${one.number}/reviews`, { event: "APPROVE", body: "lgtm" }, T.helper);
1057 const run = await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: one.head, status: "in_progress" });
1058 let p = await pull(one.number);
1059 assert.equal(p.approvals, 0);
1060 assert.ok(p.merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(p.merge_blockers));
1061 // A person approves; the required check is still running, so nothing merges yet.
1062 await ok("POST", `${R}/pulls/${one.number}/reviews`, { event: "APPROVE", body: "ship it" });
1063 await sleep(1500);
1064 p = await pull(one.number);
1065 assert.equal(p.merged, false);
1066 assert.deepEqual(p.merge_blockers, ["required check 'ci' is in_progress"]);
1067 assert.ok(p.auto_merge);
1068 // The check passes: Diffinery merges, as the agent, and main moves to that commit.
1069 await ok("PATCH", `${R}/check-runs/${run.id}`, { status: "completed", conclusion: "success" });
1070 const merged = await until("auto-merge", async () => {
1071 const x = await pull(one.number);
1072 return x.merged ? x : null;
1073 });
1074 assert.equal(merged.merged_by.login, "olive-bot");
1075 assert.equal(merged.auto_merge, null);
1076 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, merged.merge_commit_sha);
1077 // The merge commit says who it acts for, and the workflows it triggers run as the agent's.
1078 assert.match(execFileSync("git", ["cat-file", "commit", merged.merge_commit_sha], { cwd: clone(), encoding: "utf8" }), /^diffinery-agent olive-bot on-behalf-of olive$/m);
1079 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));
1080 assert.equal(after.actor.login, "olive-bot");
1081
1082 // ------------------------------------------------------------ an approval counts only for the commit it approved
1083 const three = await agentPull("agent-three", "main", merged.merge_commit_sha);
1084 await ok("POST", `${R}/pulls/${three.number}/reviews`, { event: "APPROVE" });
1085 const later = await ok("PUT", `${R}/contents/agent-three-later.txt`, { message: "after the approval", content: b64("later\n"), branch: "agent-three" }, T.bot);
1086 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: later.commit.sha, status: "completed", conclusion: "success" });
1087 assert.equal((await ok("PUT", `${R}/pulls/${three.number}/auto-merge`, {}, T.bot)).state, "enabled");
1088 await sleep(1500);
1089 assert.equal((await pull(three.number)).merged, false, "the person approved an older commit");
1090 await ok("POST", `${R}/pulls/${three.number}/reviews`, { event: "APPROVE", body: "the new commit too" });
1091 await until("merged after the fresh approval", async () => (await pull(three.number)).merged);
1092
1093 // ------------------------------------------------------------ a push by someone else cancels it; the agent's own doesn't
1094 const two = await agentPull("agent-two");
1095 await ok("POST", `${R}/pulls/${two.number}/reviews`, { event: "APPROVE" });
1096 assert.equal((await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot)).state, "enabled");
1097 await ok("PUT", `${R}/contents/agent-two-more.txt`, { message: "more", content: b64("more\n"), branch: "agent-two" }, T.bot);
1098 assert.ok((await pull(two.number)).auto_merge, "the agent's own push keeps auto-merge on");
1099 await ok("PUT", `${R}/contents/olive.txt`, { message: "olive's fix", content: b64("fix\n"), branch: "agent-two" });
1100 assert.equal((await pull(two.number)).auto_merge, null);
1101 const said = await ok("GET", `${R}/issues/${two.number}/comments`);
1102 assert.ok(said.some((c) => /Auto-merge was turned off: olive pushed new commits/.test(c.body)), JSON.stringify(said));
1103 // The pull request page turns it on and off for people, and the settings page has the switch.
1104 const cookie = `__Host-dfy_session=${S.olive}`;
1105 const web = async (path, form) => {
1106 const page = await fetch(`${base}/${OWNER}/landing/pull/${two.number}`, { headers: { cookie } });
1107 const html = await page.text();
1108 if (!form) return html;
1109 const csrf = /name="_csrf" value="([^"]+)"/.exec(html)?.[1];
1110 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
1111 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" } });
1112 assert.equal(res.status, 303, `POST ${path}`);
1113 return html;
1114 };
1115 assert.match(await web(`/pull/${two.number}/auto-merge`, { method: "squash" }), /Enable auto-merge/);
1116 assert.equal((await pull(two.number)).auto_merge.enabled_by.login, OWNER);
1117 assert.match(await web(`/pull/${two.number}/auto-merge/disable`, {}), /Auto-merge is on[\s\S]*Disable auto-merge/);
1118 assert.equal((await pull(two.number)).auto_merge, null);
1119 const settings = await (await fetch(`${base}/${OWNER}/landing/settings/branches`, { headers: { cookie } })).text();
1120 assert.match(settings, /Allow agents to land pull requests through auto-merge/);
1121 assert.doesNotMatch(settings, /<select|type="checkbox"/);
1122 // Turned on again, then off on request.
1123 await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot);
1124 await status(204, "DELETE", `${R}/pulls/${two.number}/auto-merge`, undefined, T.bot);
1125 assert.equal((await pull(two.number)).auto_merge, null);
1126 // Taking the setting away turns an agent's waiting auto-merge off.
1127 await ok("PUT", `${R}/pulls/${two.number}/auto-merge`, {}, T.bot);
1128 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
1129 await until("auto-merge turned off", async () => (await pull(two.number)).auto_merge === null);
1130
1131 // ------------------------------------------------------------ the merge queue path, for agents with the setting
1132 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1133 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1134 const q = await agentPull("agent-queue", "train");
1135 await ok("POST", `${R}/pulls/${q.number}/reviews`, { event: "APPROVE" });
1136 await status(403, "PUT", `${R}/pulls/${q.number}/merge-queue`, {}, T.bot);
1137 await status(403, "PUT", `${R}/pulls/${q.number}/auto-merge`, {}, T.bot);
1138 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" }, allowAgentAutoMerge: true });
1139 // Auto-merge waits for the head's check, then joins the queue; the merge group's check gates the merge.
1140 const queued = await ok("PUT", `${R}/pulls/${q.number}/auto-merge`, {}, T.bot);
1141 assert.deepEqual([queued.state, queued.auto_merge.merge_method], ["enabled", "squash"]);
1142 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: q.head, status: "completed", conclusion: "success" });
1143 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));
1144 assert.equal(entry.enqueued_by.login, "olive-bot");
1145 assert.equal((await pull(q.number)).merged, false);
1146 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: entry.merge_group.head_sha, status: "completed", conclusion: "success" });
1147 assert.equal((await until("merged through the queue", async () => ((await pull(q.number)).merged ? pull(q.number) : null))).merged_by.login, "olive-bot");
1148 // An agent may also add a ready pull request to the queue itself.
1149 const q2 = await agentPull("agent-queue-2", "train", (await ok("GET", `${R}/branches/train`)).commit.sha);
1150 await ok("POST", `${R}/pulls/${q2.number}/reviews`, { event: "APPROVE" });
1151 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: q2.head, status: "completed", conclusion: "success" });
1152 const direct = await status(201, "PUT", `${R}/pulls/${q2.number}/merge-queue`, {}, T.bot);
1153 assert.equal(direct.state, "queued");
1154 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: direct.entry.merge_group.head_sha, status: "completed", conclusion: "success" });
1155 await until("second queue merge", async () => (await pull(q2.number)).merged);
1156
1157 // ------------------------------------------------------------ all of it is on the record
1158 await until("auto-merge audit entries", async () => {
1159 const setting = auditLog("repo.protection.agent_auto_merge").filter((e) => e.target === `${OWNER}/landing`);
1160 const on = auditLog("pull_request.auto_merge_enabled").filter((e) => e.target.startsWith(`${OWNER}/landing#`));
1161 const offs = auditLog("pull_request.auto_merge_disabled").filter((e) => e.target === `${OWNER}/landing#${two.number}`);
1162 const done = auditLog("pull_request.auto_merged").find((e) => e.target === `${OWNER}/landing#${one.number}`);
1163 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";
1164 });
1165});
1166
1167test("security: an admin can let agents' auto-merges land on green checks without an approval, and nothing more", async () => {
1168 const R = `/repos/${OWNER}/waived`;
1169 const mainSha = await repoWithReadme("waived");
1170 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1171 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1172 /** A pull request `as` opens from a new branch off `from`, writing `path`. */
1173 const opened = async (branch, as, from = mainSha, path = `${branch}.txt`) => {
1174 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from }, as);
1175 const put = await ok("PUT", `${R}/contents/${path}`, { message: branch, content: b64(`${branch}\n`), branch }, as);
1176 const pr = await ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main" }, as);
1177 return { number: pr.number, head: put.commit.sha };
1178 };
1179 const green = (head) => ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" });
1180 const rule = { requirePullRequest: true, requiredChecks: ["ci"], requiredApprovals: 1, allowAgentAutoMerge: true };
1181
1182 // ------------------------------------------------------------ only an admin sets it, only alongside allowAgentAutoMerge
1183 await status(422, "PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], agentAutoMergeWithoutApproval: true });
1184 await status(422, "PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: "yes" });
1185 await status(403, "PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: true }, T.bot);
1186 await ok("PUT", `${R}/branches/main/protection`, { ...rule, agentAutoMergeWithoutApproval: true });
1187 await until("waiver audit", async () => auditLog("repo.protection.agent_approval_waiver").some((e) => JSON.parse(e.detail).enabled === true && e.actor_login === OWNER));
1188
1189 // ------------------------------------------------------------ an agent's pull request lands on the green check alone
1190 const one = await opened("agent-one", T.bot);
1191 assert.equal((await ok("PUT", `${R}/pulls/${one.number}/auto-merge`, { merge_method: "squash" }, T.bot)).state, "enabled");
1192 await sleep(1000);
1193 assert.equal((await pull(one.number)).merged, false, "the required check still gates it");
1194 await green(one.head);
1195 const merged = await until("waived auto-merge", async () => {
1196 const x = await pull(one.number);
1197 return x.merged ? x : null;
1198 });
1199 assert.equal(merged.merged_by.login, "olive-bot");
1200 assert.equal(merged.approvals, 0);
1201 // A direct merge by the agent is still refused.
1202 const direct = await opened("agent-direct", T.bot, merged.merge_commit_sha);
1203 await green(direct.head);
1204 assert.match((await status(405, "PUT", `${R}/pulls/${direct.number}/merge`, { merge_method: "squash" }, T.bot)).message, /agents may not merge/);
1205
1206 // ------------------------------------------------------------ a person's requested changes and workflow edits still need a person
1207 const objected = await opened("agent-objected", T.bot, merged.merge_commit_sha);
1208 await ok("POST", `${R}/pulls/${objected.number}/reviews`, { event: "REQUEST_CHANGES", body: "not like this" });
1209 await green(objected.head);
1210 assert.equal((await ok("PUT", `${R}/pulls/${objected.number}/auto-merge`, {}, T.bot)).state, "enabled");
1211 await sleep(1500);
1212 const held = await pull(objected.number);
1213 assert.equal(held.merged, false);
1214 assert.ok(held.merge_blockers.some((b) => /changes requested by/.test(b)), JSON.stringify(held.merge_blockers));
1215 const wf = await opened("agent-workflow", T.bot, merged.merge_commit_sha, ".github/workflows/ci.yml");
1216 await green(wf.head);
1217 assert.match((await status(422, "PUT", `${R}/pulls/${wf.number}/auto-merge`, {}, T.bot)).message, /workflow file/);
1218
1219 // ------------------------------------------------------------ people's own pull requests keep the rule's approvals
1220 const mine = await opened("person", undefined, merged.merge_commit_sha);
1221 await green(mine.head);
1222 assert.equal((await ok("PUT", `${R}/pulls/${mine.number}/auto-merge`, {})).state, "enabled");
1223 await sleep(1500);
1224 const waiting = await pull(mine.number);
1225 assert.equal(waiting.merged, false);
1226 assert.ok(waiting.merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(waiting.merge_blockers));
1227
1228 // ------------------------------------------------------------ the settings page shows it; turning allowAgentAutoMerge off ends it
1229 const settings = await (await fetch(`${base}/${OWNER}/waived/settings/branches`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } })).text();
1230 assert.match(settings, /Let agents&#39; auto-merges land without an approving review|Let agents' auto-merges land without an approving review/);
1231 assert.doesNotMatch(settings, /<select|type="checkbox"/);
1232 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], requiredApprovals: 1 });
1233 await until("waiver off audit", async () => auditLog("repo.protection.agent_approval_waiver").some((e) => JSON.parse(e.detail).enabled === false));
1234 await ok("PUT", `${R}/branches/main/protection`, rule);
1235 const after = await opened("agent-after", T.bot, merged.merge_commit_sha);
1236 await green(after.head);
1237 assert.equal((await ok("PUT", `${R}/pulls/${after.number}/auto-merge`, {}, T.bot)).state, "enabled");
1238 await sleep(1500);
1239 const again = await pull(after.number);
1240 assert.equal(again.merged, false, "the waiver does not come back with allowAgentAutoMerge");
1241 // A person's approval lands it, as before the waiver.
1242 await ok("POST", `${R}/pulls/${after.number}/reviews`, { event: "APPROVE" });
1243 await until("merged after the approval", async () => (await pull(after.number)).merged);
1244});
1245
1246test("security: an archived repository lands nothing by itself: archiving ends auto-merge and empties the merge queue", async () => {
1247 const R = `/repos/${OWNER}/shelved`;
1248 const mainSha = await repoWithReadme("shelved");
1249 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1250 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1251 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1252 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1253 const said = async (n) => (await ok("GET", `${R}/issues/${n}/comments`)).map((c) => c.body);
1254 const opened = async (branch, base) => {
1255 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: mainSha });
1256 const put = await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1257 return { number: (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base })).number, head: put.commit.sha };
1258 };
1259 // One pull request waits for its check with auto-merge on; another waits in the merge queue for its group's check.
1260 const waiting = await opened("waiting", "main");
1261 assert.equal((await ok("PUT", `${R}/pulls/${waiting.number}/auto-merge`, {})).state, "enabled");
1262 const queued = await opened("queued", "train");
1263 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: queued.head, status: "completed", conclusion: "success" });
1264 const entry = await status(201, "PUT", `${R}/pulls/${queued.number}/merge-queue`, {});
1265 assert.ok(entry.entry.merge_group);
1266
1267 // ------------------------------------------------------------ archiving turns both off, saying why
1268 assert.equal((await ok("PATCH", R, { archived: true })).archived, true);
1269 assert.equal((await pull(waiting.number)).auto_merge, null);
1270 assert.deepEqual((await ok("GET", `${R}/merge-queue/train`)).entries, []);
1271 assert.ok((await said(waiting.number)).includes("Auto-merge was turned off: the repository is archived."), JSON.stringify(await said(waiting.number)));
1272 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)));
1273 await status(403, "PUT", `${R}/pulls/${waiting.number}/auto-merge`, {});
1274
1275 // ------------------------------------------------------------ unarchived, nothing comes back by itself
1276 await ok("PATCH", R, { archived: false });
1277 for (const n of [waiting.number, queued.number]) assert.equal((await pull(n)).merged, false);
1278 assert.equal((await pull(waiting.number)).auto_merge, null);
1279 assert.equal((await ok("PUT", `${R}/pulls/${waiting.number}/auto-merge`, {})).state, "enabled");
1280 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: waiting.head, status: "completed", conclusion: "success" });
1281 await until("auto-merged once unarchived", async () => (await pull(waiting.number)).merged);
1282});
1283
1284test("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 () => {
1285 const R = `/repos/${OWNER}/tidy`;
1286 const mainSha = await repoWithReadme("tidy");
1287 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1288 const pull = (n) => ok("GET", `${R}/pulls/${n}`);
1289 const green = (head) => ok("POST", `${R}/check-runs`, { name: "ci", head_sha: head, status: "completed", conclusion: "success" });
1290 const exists = async (branch) => (await api("GET", `${R}/branches/${branch}`)).status === 200;
1291 const opened = async (branch, base = "main", from = mainSha) => {
1292 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: from });
1293 const put = await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1294 return { number: (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base })).number, head: put.commit.sha };
1295 };
1296
1297 // ------------------------------------------------------------ a protected head branch stays, even where the rule allows deleting it
1298 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/release", sha: mainSha });
1299 const rel = await ok("PUT", `${R}/contents/release.txt`, { message: "release", content: b64("release\n"), branch: "release" });
1300 await ok("PUT", `${R}/branches/release/protection`, { allowDeletion: true });
1301 const release = (await ok("POST", `${R}/pulls`, { title: "release", head: "release", base: "main" })).number;
1302 await green(rel.commit.sha);
1303 await ok("PUT", `${R}/pulls/${release}/merge`, { delete_branch: true });
1304 assert.equal((await pull(release)).merged, true);
1305 assert.equal(await exists("release"), true, "a protected head branch is never deleted by a merge");
1306
1307 // ------------------------------------------------------------ auto-merge keeps delete_branch, like a manual merge
1308 const gone = await opened("auto-delete");
1309 const on = await ok("PUT", `${R}/pulls/${gone.number}/auto-merge`, { delete_branch: true });
1310 assert.deepEqual([on.state, on.auto_merge.delete_branch, (await pull(gone.number)).auto_merge.delete_branch], ["enabled", true, true]);
1311 await status(422, "PUT", `${R}/pulls/${gone.number}/auto-merge`, { delete_branch: "yes" });
1312 await status(409, "PUT", `${R}/pulls/${gone.number}/auto-merge`, { sha: mainSha });
1313 await green(gone.head);
1314 await until("auto-merged", async () => (await pull(gone.number)).merged);
1315 await until("its head branch deleted", async () => !(await exists("auto-delete")));
1316 const kept = await opened("auto-keep");
1317 await ok("PUT", `${R}/pulls/${kept.number}/auto-merge`, {});
1318 await green(kept.head);
1319 await until("auto-merged, keeping the branch", async () => (await pull(kept.number)).merged);
1320 assert.equal(await exists("auto-keep"), true);
1321
1322 // ------------------------------------------------------------ through the merge queue, by auto-merge
1323 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/train", sha: mainSha });
1324 await ok("PUT", `${R}/branches/train/protection`, { requiredChecks: ["ci"], mergeQueue: { method: "squash" } });
1325 const q = await opened("queue-delete", "train");
1326 await ok("PUT", `${R}/pulls/${q.number}/auto-merge`, { delete_branch: true });
1327 await green(q.head);
1328 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));
1329 assert.equal(entry.delete_branch, true);
1330 await green(entry.merge_group.head_sha);
1331 await until("merged through the queue", async () => (await pull(q.number)).merged);
1332 await until("its head branch deleted", async () => !(await exists("queue-delete")));
1333});
1334
1335test("security: agents see what auto-merge needs next to the refusal to merge directly", async () => {
1336 const R = `/repos/${OWNER}/insight`;
1337 const mainSha = await repoWithReadme("insight");
1338 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1339 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"], allowAgentAutoMerge: true });
1340 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-insight", sha: mainSha }, T.bot);
1341 const put = await ok("PUT", `${R}/contents/insight.txt`, { message: "insight", content: b64("insight\n"), branch: "agent-insight" }, T.bot);
1342 const pr = (await ok("POST", `${R}/pulls`, { title: "insight", head: "agent-insight", base: "main" }, T.bot)).number;
1343 const viaMcp = async (as = T.bot) => (await mcpTool(as, "get_pull_request", { owner: OWNER, repo: "insight", number: pr })).data;
1344
1345 // ------------------------------------------------------------ the agent may not merge, but auto-merge only waits for CI and a person
1346 let m = await viaMcp();
1347 assert.ok(m.mergeability.blockers.some((b) => /agents may not merge/.test(b)), JSON.stringify(m.mergeability.blockers));
1348 assert.ok(Array.isArray(m.auto_merge_blockers), JSON.stringify(Object.keys(m)));
1349 assert.ok(!m.auto_merge_blockers.some((b) => /agents may not merge/.test(b)), JSON.stringify(m.auto_merge_blockers));
1350 assert.ok(m.auto_merge_blockers.some((b) => /required check 'ci' has not run/.test(b)), JSON.stringify(m.auto_merge_blockers));
1351 assert.ok(m.auto_merge_blockers.some((b) => /needs 1 more approving review/.test(b)), JSON.stringify(m.auto_merge_blockers));
1352 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: put.commit.sha, status: "completed", conclusion: "success" });
1353 await ok("POST", `${R}/pulls/${pr}/reviews`, { event: "APPROVE" });
1354 m = await viaMcp();
1355 assert.deepEqual(m.auto_merge_blockers, []);
1356 assert.ok(m.mergeability.blockers.some((b) => /agents may not merge/.test(b)), "the refusal to merge directly still shows");
1357 // The REST API says the same.
1358 const rest = await ok("GET", `${R}/pulls/${pr}`, undefined, T.bot);
1359 assert.deepEqual(rest.auto_merge_blockers, []);
1360 assert.ok(rest.merge_blockers.some((b) => /agents may not merge/.test(b)));
1361 // People merge and auto-merge on the same terms, so they get no second list.
1362 assert.equal((await ok("GET", `${R}/pulls/${pr}`)).auto_merge_blockers, undefined);
1363 assert.equal((await viaMcp(T.olive)).auto_merge_blockers, undefined);
1364 // Without the setting, auto-merge's own refusal shows there.
1365 await ok("PUT", `${R}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci"] });
1366 assert.ok((await viaMcp()).auto_merge_blockers.some((b) => /allowAgentAutoMerge/.test(b)));
1367 assert.equal((await pull(pr)).merged, false);
1368 async function pull(n) {
1369 return ok("GET", `${R}/pulls/${n}`);
1370 }
1371});
1372
1373test("security: the queue's bypass button does what it says, and a merge queue can't contradict linear history", async () => {
1374 const R = `/repos/${OWNER}/bypass`;
1375 const mainSha = await repoWithReadme("bypass");
1376 // ------------------------------------------------------------ a queue that would make merge commits on a linear branch is refused
1377 const contradiction = await status(422, "PUT", `${R}/branches/main/protection`, { requireLinearHistory: true, mergeQueue: { method: "merge" } });
1378 assert.match(contradiction.message, /linear history/);
1379 await ok("PUT", `${R}/branches/main/protection`, { requireLinearHistory: true, mergeQueue: {} });
1380 assert.equal((await ok("GET", `${R}/branches/main/protection`)).rules.mergeQueue.method, "squash", "without a method, a linear branch's queue squashes");
1381
1382 // ------------------------------------------------------------ the web button sends what its label promises
1383 const cookie = `__Host-dfy_session=${S.olive}`;
1384 const opened = async (branch) => {
1385 await ok("POST", `${R}/git/refs`, { ref: `refs/heads/${branch}`, sha: mainSha });
1386 await ok("PUT", `${R}/contents/${branch}.txt`, { message: branch, content: b64(`${branch}\n`), branch });
1387 return (await ok("POST", `${R}/pulls`, { title: branch, head: branch, base: "main" })).number;
1388 };
1389 /** The pull request page's form that merges directly, its button label, and the result of submitting it. */
1390 const bypassForm = async (n) => {
1391 const page = await fetch(`${base}/${OWNER}/bypass/pull/${n}`, { headers: { cookie } });
1392 const html = await page.text();
1393 const form = [...html.matchAll(/<form[^>]*action="([^"]+)"[^>]*>([\s\S]*?)<\/form>/g)].find((m) => m[1].endsWith(`/pull/${n}/merge`));
1394 if (!form) return null;
1395 const fields = Object.fromEntries([...form[2].matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)"/g)].map((m) => [m[1], m[2]]));
1396 const label = />([^<]*)<\/button>/.exec(form[2])?.[1];
1397 const csrfCookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
1398 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" } });
1399 return { fields, label, submit };
1400 };
1401 const merged = async (n) => (await ok("GET", `${R}/pulls/${n}`)).merged;
1402
1403 // Rules met: the button skips only the queue.
1404 await ok("PUT", `${R}/branches/main/protection`, { mergeQueue: { method: "squash" } });
1405 const ready = await opened("ready");
1406 const plain = await bypassForm(ready);
1407 assert.equal(plain.fields.bypass_queue, "1");
1408 assert.equal(plain.fields.bypass_rules, undefined);
1409 assert.match(plain.label, /bypass the queue/);
1410 assert.equal((await plain.submit()).status, 303);
1411 assert.equal(await merged(ready), true);
1412
1413 // Rules unmet: an admin who may bypass them gets a button that says so, sends bypass_rules, and is audited.
1414 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1, mergeQueue: { method: "squash" } });
1415 const unreviewed = await opened("unreviewed");
1416 const both = await bypassForm(unreviewed);
1417 assert.deepEqual([both.fields.bypass_queue, both.fields.bypass_rules], ["1", "1"]);
1418 assert.match(both.label, /bypass the queue and the unmet requirements/);
1419 assert.equal((await both.submit()).status, 303);
1420 assert.equal(await merged(unreviewed), true);
1421 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)));
1422
1423 // Admins held to the rules see no button at all, and a reader neither.
1424 await ok("PUT", `${R}/branches/main/protection`, { requiredApprovals: 1, enforceAdmins: true, mergeQueue: { method: "squash" } });
1425 const held = await opened("held");
1426 assert.equal(await bypassForm(held), null);
1427});
1428
1429test("security: no token can mint a token, an agent or a sandbox, through the API or the web forms", async () => {
1430 await repoWithReadme("minting");
1431 const limited = (await ok("POST", "/diffinery/tokens", { name: "limited-mint", scopes: ["admin"], repositories: [`${OWNER}/minting`] }, { cookie: S.olive })).token;
1432 // A job token's shape: minting refuses job and sandbox tokens before any repository checks them.
1433 const job = `djt_repo_job_${"0".repeat(48)}`;
1434 const tokens = async () => (await ok("GET", "/diffinery/tokens", undefined, { cookie: S.olive })).length;
1435 const before = await tokens();
1436 // Admin, agent, read-only and repository-limited tokens, and job tokens: never.
1437 for (const as of [T.olive, T.bot, T.reader, limited, job]) {
1438 const r = await api("POST", "/diffinery/tokens", { name: "escalate", scopes: ["admin"] }, as);
1439 assert.equal(r.status, 403, JSON.stringify(r.json));
1440 assert.equal((await api("POST", "/diffinery/agents", { login: `mint-${randomBytes(3).toString("hex")}` }, as)).status, 403);
1441 assert.equal((await api("POST", "/diffinery/agents/olive-bot/tokens", { scopes: ["admin"] }, as)).status, 403);
1442 }
1443 assert.match((await api("POST", "/diffinery/tokens", { name: "escalate" }, T.olive)).json.message, /browser session/);
1444 // The web form with a token and a forged double-submit cookie: refused, nothing minted.
1445 const form = (fields) => ({ method: "POST", redirect: "manual", body: new URLSearchParams({ _csrf: "forged", ...fields }), headers: { authorization: `Bearer ${T.olive}`, cookie: "dfy_csrf=forged" } });
1446 assert.equal((await fetch(`${base}/settings/tokens`, form({ name: "escalate", scope: "admin", expires: "90" }))).status, 403);
1447 assert.equal((await fetch(`${base}/settings/agents`, form({ login: "web-escalate" }))).status, 403);
1448 assert.equal(await tokens(), before);
1449 // A browser session still mints.
1450 await ok("POST", "/diffinery/tokens", { name: "from the browser", scopes: ["read"] }, { cookie: S.olive });
1451 assert.equal(await tokens(), before + 1);
1452 // A repository-limited token can't create repositories through an import either.
1453 await status(403, "POST", "/diffinery/imports", { source: "octo/hello", owner: OWNER }, limited);
1454 // Job and sandbox tokens can't start sandboxes, whose tokens would outlive them.
1455 await status(403, "POST", `/repos/${OWNER}/minting/diffinery/sandboxes`, {}, job);
1456});
1457
1458test("security: repository variable endpoints see only the repository's own, and organization variable deletes are checked", async () => {
1459 await status(201, "POST", "/orgs/guild/actions/variables", { name: "REGION", value: "org-eu" });
1460 await ok("POST", "/orgs/guild/repos", { name: "tools", private: true });
1461 const R = "/repos/guild/tools";
1462 // The organization's variable isn't the repository's to read or change.
1463 await status(404, "GET", `${R}/actions/variables/REGION`);
1464 await status(404, "PATCH", `${R}/actions/variables/REGION`, { value: "changed" });
1465 assert.deepEqual((await ok("GET", `${R}/actions/variables`)).variables, []);
1466 // A repository variable of the same name can be created; it overrides the organization's in workflows.
1467 await status(201, "POST", `${R}/actions/variables`, { name: "region", value: "repo-us" });
1468 assert.equal((await ok("GET", `${R}/actions/variables/REGION`)).value, "repo-us");
1469 assert.equal((await ok("GET", "/orgs/guild/actions/variables/REGION")).value, "org-eu");
1470 // Deleting it ignores letter case, like every other variable endpoint.
1471 await status(204, "DELETE", `${R}/actions/variables/region`);
1472 await status(404, "GET", `${R}/actions/variables/REGION`);
1473
1474 // Deleting an organization variable that doesn't exist is a 404 and leaves no audit entry; API changes say so.
1475 await status(404, "DELETE", "/orgs/guild/actions/variables/NEVER_SET");
1476 await status(204, "DELETE", "/orgs/guild/actions/variables/REGION");
1477 await status(404, "GET", "/orgs/guild/actions/variables/REGION");
1478 const deleted = await until("the variable's audit entry", async () => auditLog("org.variable_delete").find((e) => JSON.parse(e.detail).name === "REGION"));
1479 assert.equal(JSON.parse(deleted.detail).via, "api");
1480 assert.ok(!auditLog("org.variable_delete").some((e) => JSON.parse(e.detail).name === "NEVER_SET"));
1481 assert.equal(JSON.parse(auditLog("org.variable_set").find((e) => JSON.parse(e.detail).name === "REGION").detail).via, "api");
1482});
1483
1484test("security: milestones are checked before an issue is saved, and lists filter by them", async () => {
1485 const R = "/repos/guild/tools";
1486 // A milestone can be created closed.
1487 const done = await status(201, "POST", `${R}/milestones`, { title: "Already done", state: "closed" });
1488 assert.equal(done.state, "closed");
1489 assert.ok(done.closed_at);
1490 const v1 = await status(201, "POST", `${R}/milestones`, { title: "v1" });
1491 assert.equal(v1.state, "open");
1492 const planned = await status(201, "POST", `${R}/issues`, { title: "Planned" });
1493 const unplanned = await status(201, "POST", `${R}/issues`, { title: "Unplanned" });
1494
1495 // A milestone that doesn't exist is refused before the rest of the edit is saved.
1496 await status(422, "PATCH", `${R}/issues/${planned.number}`, { title: "Renamed", milestone: 999 });
1497 assert.equal((await ok("GET", `${R}/issues/${planned.number}`)).title, "Planned");
1498 await status(422, "PATCH", `${R}/issues/${planned.number}`, { milestone: "v1" });
1499 // The response carries the new milestone.
1500 const set = await ok("PATCH", `${R}/issues/${planned.number}`, { title: "Planned for v1", milestone: v1.number });
1501 assert.deepEqual([set.title, set.milestone?.number], ["Planned for v1", v1.number]);
1502
1503 const numbers = async (q) => (await ok("GET", `${R}/issues?${q}`)).map((i) => i.number);
1504 assert.deepEqual(await numbers(`milestone=${v1.number}`), [planned.number]);
1505 assert.deepEqual(await numbers("milestone=*"), [planned.number]);
1506 assert.deepEqual(await numbers("milestone=none"), [unplanned.number]);
1507 await status(422, "GET", `${R}/issues?milestone=v1`);
1508
1509 // The milestone's link opens the issue list filtered to it.
1510 const cookie = `__Host-dfy_session=${S.olive}`;
1511 const page = await fetch(`${base}/guild/tools/milestone/${v1.number}`, { headers: { cookie }, redirect: "manual" });
1512 assert.equal(page.status, 302);
1513 const list = await fetch(new URL(page.headers.get("location"), base), { headers: { cookie } });
1514 const html = await list.text();
1515 assert.equal(list.status, 200);
1516 assert.match(html, /Planned for v1/);
1517 assert.doesNotMatch(html, /Unplanned/);
1518 assert.match(html, /Milestone: <b>v1<\/b>/);
1519
1520 // Removing it.
1521 assert.equal((await ok("PATCH", `${R}/issues/${planned.number}`, { milestone: null })).milestone, null);
1522});
1523
1524test("security: push protection reads large files, and revoking a token through the API is on the record", async () => {
1525 const R = `/repos/${OWNER}/big-leak`;
1526 const mainSha = await repoWithReadme("big-leak");
1527 // A credential after 1.5 MiB of text, built at run time so this file holds none.
1528 const big = `${"x".repeat(80) + "\n"}`.repeat(20_000) + `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n`;
1529 assert.ok(big.length > 1.5 * 1024 * 1024);
1530 const viaContents = await status(422, "PUT", `${R}/contents/big.env`, { message: "leak", content: b64(big) });
1531 assert.match(viaContents.message, /push protection.*AWS access key/);
1532 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "big.env", content: big }] });
1533 // ...and the same file through git.
1534 const clone = join(work, "big-leak");
1535 const authed = `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/big-leak.git`;
1536 execFileSync("git", ["clone", "-q", authed, clone], { stdio: "pipe" });
1537 writeFileSync(join(clone, "big.env"), big);
1538 const g = (...args) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe" });
1539 g("add", "big.env");
1540 g("commit", "-q", "-m", "leak");
1541 assert.throws(() => g("push", "-q", "origin", "HEAD:main"), /secret detected/);
1542 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1543
1544 // ------------------------------------------------------------ revoking a token through the API is audited, like the settings page
1545 const minted = await ok("POST", "/diffinery/tokens", { name: "short-lived", scopes: ["read"] }, { cookie: S.olive });
1546 await status(204, "DELETE", `/diffinery/tokens/${minted.id}`);
1547 await until("the revoke in the audit log", async () => auditLog("token.revoke").some((e) => e.target === minted.id && JSON.parse(e.detail ?? "{}").via === "api"));
1548});
1549
1550test("security: git request bodies are bounded, compressed or not, before anything reads them", async () => {
1551 await repoWithReadme("bounded");
1552 await ok("PATCH", `/repos/${OWNER}/bounded`, { visibility: "public" });
1553 const url = `${base}/${OWNER}/bounded.git/git-upload-pack`;
1554 const headers = { "content-type": "application/x-git-upload-pack-request" };
1555 // 64 MiB of zeros in about 64 KB of gzip, sent without signing in.
1556 const bomb = gzipSync(Buffer.alloc(64 * 1024 * 1024));
1557 assert.ok(bomb.length < 1024 * 1024);
1558 const r = await fetch(url, { method: "POST", body: bomb, headers: { ...headers, "content-encoding": "gzip" } });
1559 assert.equal(r.status, 413, await r.text());
1560 const plain = await fetch(url, { method: "POST", body: Buffer.alloc(17 * 1024 * 1024, 48), headers });
1561 assert.equal(plain.status, 413);
1562 // A real fetch still works.
1563 execFileSync("git", ["-c", "protocol.version=2", "clone", "-q", `${base}/${OWNER}/bounded.git`, join(work, "bounded")], { stdio: "pipe" });
1564});
1565
1566test("security: a file rewritten from scratch is diffed quickly, even for anonymous readers", async () => {
1567 const R = `/repos/${OWNER}/rewrite`;
1568 await repoWithReadme("rewrite", { private: false });
1569 // 2 x 20k lines with nothing in common, Myers' worst case: unbounded, one diff of it took minutes.
1570 const lines = (tag) => Array.from({ length: 20_000 }, (_, i) => `${tag} ${i}\n`).join("");
1571 const first = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "first", files: [{ path: "data.txt", content: lines("old") }] });
1572 const second = await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "rewrite", files: [{ path: "data.txt", content: lines("new") }] });
1573 const sha = second.sha ?? second.commit?.sha;
1574 const t = Date.now();
1575 const commit = await ok("GET", `${R}/commits/${sha}`, undefined, null);
1576 assert.ok(Date.now() - t < 15_000, `the diff took ${Date.now() - t} ms`);
1577 const file = commit.files.find((f) => f.filename === "data.txt");
1578 assert.deepEqual([file.additions, file.deletions], [20_000, 20_000]);
1579 const compared = await ok("GET", `${R}/compare/${first.sha ?? first.commit?.sha}...${sha}`, undefined, null);
1580 assert.equal(compared.files.find((f) => f.filename === "data.txt").additions, 20_000);
1581});
1582
1583test("security: signed out, a private repository and a missing one look the same everywhere", async () => {
1584 await repoWithReadme("secret-plans");
1585 const probe = async (name) => {
1586 const raw = async (method, path, init = {}) => {
1587 const r = await fetch(`${base}${path}`, { method, redirect: "manual", ...init });
1588 return [r.status, (r.headers.get("location") ?? "").replace(name, "NAME"), (await r.text()).replaceAll(name, "NAME")];
1589 };
1590 return {
1591 read: await raw("GET", `/api/v3/repos/${OWNER}/${name}`),
1592 issues: await raw("GET", `/api/v3/repos/${OWNER}/${name}/issues`),
1593 write: await raw("POST", `/api/v3/repos/${OWNER}/${name}/issues`, { headers: { "content-type": "application/json" }, body: JSON.stringify({ title: "probe" }) }),
1594 git: await raw("GET", `/${OWNER}/${name}.git/info/refs?service=git-upload-pack`, { headers: { "git-protocol": "version=2" } }),
1595 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" }),
1596 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: [] }) }),
1597 page: await raw("GET", `/${OWNER}/${name}`),
1598 blob: await raw("GET", `/${OWNER}/${name}/blob/main/README.md`),
1599 };
1600 };
1601 const hidden = await probe("secret-plans");
1602 assert.deepEqual(hidden, await probe("never-existed"));
1603 assert.equal(hidden.read[0], 404);
1604 assert.equal(hidden.write[0], 401);
1605 assert.equal(hidden.git[0], 401);
1606 assert.equal(hidden.page[0], 302);
1607 assert.match(hidden.page[1], /\/login\?next=/);
1608});
1609
1610test("security: live updates say only that something changed, and never carry audit entries or payloads", async () => {
1611 const R = `/repos/${OWNER}/on-air`;
1612 await repoWithReadme("on-air", { private: false });
1613 // A signed-out reader watching the public repository.
1614 const ws = new WebSocket(`${base.replace("http", "ws")}/${OWNER}/on-air/live?topics=repo`);
1615 const got = [];
1616 ws.onmessage = (e) => e.data !== "pong" && got.push(JSON.parse(e.data));
1617 await new Promise((ok, fail) => ((ws.onopen = ok), (ws.onerror = fail)));
1618 // A dispatch with a payload, and a commit refused by push protection (an audit entry naming the path).
1619 await status(204, "POST", `${R}/dispatches`, { event_type: "deploy", client_payload: { note: "for writers only" } });
1620 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "leak", files: [{ path: "keys/prod.env", content: `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3\n` }] });
1621 await until("the dispatch on the socket", async () => got.some((m) => m.data?.type === "repository_dispatch"));
1622 await sleep(500);
1623 ws.close();
1624 const text = JSON.stringify(got);
1625 assert.doesNotMatch(text, /for writers only|keys\/prod\.env|audit|blocked_secret/);
1626 for (const m of got) assert.deepEqual(Object.keys(m.data).sort(), ["kind", "type"]);
1627});
1628
1629test("security: push protection reads commit and tag messages, UTF-16 files and Diffinery's own tokens, and records opt-outs", async () => {
1630 const R = `/repos/${OWNER}/messages`;
1631 const mainSha = await repoWithReadme("messages");
1632 const key = `AWS_ACCESS_KEY_ID=${"AKIA"}IOSFODNN7EXAMPL3`;
1633 // A commit message, through git.
1634 const clone = join(work, "messages");
1635 execFileSync("git", ["clone", "-q", `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/messages.git`, clone], { stdio: "pipe" });
1636 const g = (...args) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe" });
1637 g("commit", "-q", "--allow-empty", "-m", `deploy\n\n${key}`);
1638 assert.throws(() => g("push", "-q", "origin", "HEAD:main"), /secret detected/);
1639 // ...an annotated tag's message.
1640 g("reset", "-q", "--hard", "origin/main");
1641 g("tag", "-a", "v1", "-m", key);
1642 assert.throws(() => g("push", "-q", "origin", "v1"), /secret detected/);
1643 // ...and without git: the commits API and the git data API.
1644 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: `notes\n${key}`, files: [{ path: "a.txt", content: "a\n" }] });
1645 const tree = (await ok("GET", `${R}/git/commits/${mainSha}`)).tree.sha;
1646 await status(422, "POST", `${R}/git/commits`, { message: key, tree, parents: [mainSha] });
1647 await status(422, "POST", `${R}/git/tags`, { tag: "v2", message: key, object: mainSha, type: "commit" });
1648 // A UTF-16 file has NUL bytes but is text.
1649 const utf16 = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`${key}\n`, "utf16le")]);
1650 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "utf16", files: [{ path: "creds.txt", content: utf16.toString("base64"), encoding: "base64" }] });
1651 // A job, sandbox or model token.
1652 const token = `dmt_${"0b1e5c4e-58a0-4f7c-9d39-0e2c6a1c3f00"}_${"Zm9vYmFyYmF6cXV4cXV1eHF1dXhxdXV4cXV1eA"}`;
1653 await status(422, "POST", `${R}/diffinery/commits`, { branch: "main", message: "token", files: [{ path: "token.txt", content: token }] });
1654 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1655 // A file that opts out still goes in, and the opt-out is on the record.
1656 await ok("POST", `${R}/diffinery/commits`, { branch: "main", message: "fixture", files: [{ path: "fixture.env", content: `${key} # ${"diffinery"}:allow-secret\n` }] });
1657 const entry = await until("the opt-out in the audit log", async () => auditLog("api.secret_marked").find((e) => e.target === `${OWNER}/messages`));
1658 assert.deepEqual(JSON.parse(entry.detail).paths, ["fixture.env"]);
1659});
1660
1661test("security: required checks gate direct pushes to a protected branch, as on GitHub", async () => {
1662 const R = `/repos/${OWNER}/gated`;
1663 const mainSha = await repoWithReadme("gated");
1664 await collaborator(R, "rita", "write", T.rita);
1665 await ok("PUT", `${R}/branches/main/protection`, { requiredChecks: ["ci"] });
1666 // A writer's commit straight to main hasn't been checked: refused, whichever way it comes.
1667 const refused = await status(403, "PUT", `${R}/contents/direct.txt`, { message: "direct", content: b64("x\n"), branch: "main" }, T.rita);
1668 assert.match(refused.message, /required check 'ci' has not run/);
1669 // The same commit, tested on a branch first, can move main.
1670 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/tested", sha: mainSha }, T.rita);
1671 const tested = (await ok("PUT", `${R}/contents/direct.txt`, { message: "tested", content: b64("x\n"), branch: "tested" }, T.rita)).commit.sha;
1672 assert.match((await status(403, "PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita)).message, /has not run/);
1673 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: tested, status: "in_progress" });
1674 assert.match((await status(403, "PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita)).message, /has not finished/);
1675 await ok("POST", `${R}/check-runs`, { name: "ci", head_sha: tested, status: "completed", conclusion: "success" });
1676 // (Two runs named ci: the in-progress one still counts until it completes.)
1677 const runs = (await ok("GET", `${R}/commits/${tested}/check-runs`)).check_runs.filter((r) => r.status !== "completed");
1678 for (const r of runs) await ok("PATCH", `${R}/check-runs/${r.id}`, { status: "completed", conclusion: "success" });
1679 await ok("PATCH", `${R}/git/refs/heads/main`, { sha: tested }, T.rita);
1680 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, tested);
1681 // A repository admin isn't held to it unless the rule says so.
1682 await ok("PUT", `${R}/contents/admin.txt`, { message: "admin", content: b64("y\n"), branch: "main" });
1683});
1684
1685test("security: issue, pull request and comment text has GitHub's length limits", async () => {
1686 await ok("POST", "/user/repos", { name: "long-text" });
1687 const R = `/repos/${OWNER}/long-text`;
1688 const long = "x".repeat(65_537);
1689 const tooLong = (r) => assert.match(r.message, /too long \(maximum is (65536|256) characters\)/);
1690 tooLong(await status(422, "POST", `${R}/issues`, { title: "Big", body: long }));
1691 tooLong(await status(422, "POST", `${R}/issues`, { title: "t".repeat(257) }));
1692 const issue = await status(201, "POST", `${R}/issues`, { title: "Small", body: "x".repeat(65_536) });
1693 tooLong(await status(422, "PATCH", `${R}/issues/${issue.number}`, { body: long }));
1694 tooLong(await status(422, "POST", `${R}/issues/${issue.number}/comments`, { body: long }));
1695 const comment = await status(201, "POST", `${R}/issues/${issue.number}/comments`, { body: "fine" });
1696 tooLong(await status(422, "PATCH", `${R}/issues/comments/${comment.id}`, { body: long }));
1697 assert.equal((await ok("GET", `${R}/issues/${issue.number}`)).body.length, 65_536);
1698});
1699
1700test("security: deleting a repository deletes its stored objects too", async () => {
1701 await repoWithReadme("doomed");
1702 // Objects over 512 KiB compressed live in R2, under repos/<id>/.
1703 const big = randomBytes(700 * 1024);
1704 await ok("PUT", `/repos/${OWNER}/doomed/contents/big.bin`, { message: "big", content: big.toString("base64") });
1705 const oid = createHash("sha1").update(Buffer.concat([Buffer.from(`blob ${big.length}\0`), big])).digest("hex");
1706 const persist = join(work, "state");
1707 const run = (...args) => execFileSync("pnpm", ["exec", "wrangler", ...args], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } }).toString();
1708 const rows = JSON.parse(run("d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--json", "--command", "SELECT id FROM repos WHERE name = 'doomed'"));
1709 const repoId = rows[0].results[0].id;
1710 const key = `diffinery-data-dev/repos/${repoId}/objects/${oid.slice(0, 2)}/${oid.slice(2)}`;
1711 const stored = () => {
1712 try {
1713 run("r2", "object", "get", key, "--local", "-e", "dev", "--persist-to", persist, "--pipe");
1714 return true;
1715 } catch {
1716 return false;
1717 }
1718 };
1719 assert.ok(stored(), "the large blob is in R2 before the repository is deleted");
1720 await status(204, "DELETE", `/repos/${OWNER}/doomed`);
1721 await until("the repository's objects are deleted", () => !stored(), 30_000);
1722});
1723
1724test("security: pushes are checked like git's fsck: no '..' or '.git' entries, no unsafe .gitmodules", async () => {
1725 const R = `/repos/${OWNER}/fsck`;
1726 const mainSha = await repoWithReadme("fsck");
1727 const clone = join(work, "fsck");
1728 const authed = `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/fsck.git`;
1729 execFileSync("git", ["clone", "-q", authed, clone], { stdio: "pipe" });
1730 const g = (args, input) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe", input }).toString().trim();
1731 const push = (sha) => spawnSync("git", ["push", "origin", `${sha}:refs/heads/main`], { cwd: clone, encoding: "utf8" });
1732 const blob = g(["hash-object", "-w", "--stdin"], "payload\n");
1733 // A tree git itself would never write: git's own tools refuse these names, so build it by hand.
1734 const crafted = (name) => {
1735 const bytes = Buffer.concat([Buffer.from(`100644 ${name}\0`), Buffer.from(blob, "hex")]);
1736 const tree = g(["hash-object", "-t", "tree", "-w", "--literally", "--stdin"], bytes);
1737 return g(["commit-tree", tree, "-p", mainSha, "-m", `entry ${name}`]);
1738 };
1739 for (const [name, why] of [["..", /not a valid name/], [".git", /reserved/], [".GIT", /reserved/], ["git~1", /reserved/]]) {
1740 const r = push(crafted(name));
1741 assert.notEqual(r.status, 0, `a tree entry named ${name} was accepted`);
1742 assert.match(r.stderr, why);
1743 }
1744 // .gitmodules that would make git run an option (CVE-2018-17456).
1745 writeFileSync(join(clone, ".gitmodules"), '[submodule "x"]\n\tpath = x\n\turl = --upload-pack=touch /tmp/pwned\n');
1746 g(["add", ".gitmodules"]);
1747 g(["commit", "-q", "-m", "submodule"]);
1748 const r = push("HEAD");
1749 assert.notEqual(r.status, 0);
1750 assert.match(r.stderr, /url that starts with '-'/);
1751 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
1752 // An ordinary .gitmodules goes through.
1753 g(["reset", "-q", "--hard", mainSha]);
1754 writeFileSync(join(clone, ".gitmodules"), '[submodule "x"]\n\tpath = x\n\turl = https://example.com/x.git\n');
1755 g(["add", ".gitmodules"]);
1756 g(["commit", "-q", "-m", "submodule"]);
1757 assert.equal(push("HEAD").status, 0);
1758});
1759
1760test("security: a job's runner gets only the secrets the job names", async () => {
1761 const R = `/repos/${OWNER}/few-secrets`;
1762 await repoWithReadme("few-secrets");
1763 await status(204, "PUT", `${R}/actions/secrets/USED`, { value: "used-value" });
1764 await status(204, "PUT", `${R}/actions/secrets/UNUSED`, { value: "unused-value" });
1765 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";
1766 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1767 const specs = {};
1768 await until("both jobs claimed", async () => {
1769 const r = await runnerClaim(R, ["linux"]);
1770 if (r.status === 200) {
1771 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1772 specs[spec.jobKey] = Object.keys(spec.secrets).sort();
1773 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: {} }) });
1774 }
1775 return Object.keys(specs).length === 2;
1776 });
1777 assert.deepEqual(specs.build, ["DIFFINERY_TOKEN", "GITHUB_TOKEN", "USED"]);
1778 // toJSON(secrets) can't be narrowed, so that job gets them all, as on GitHub.
1779 assert.deepEqual(specs.dump, ["DIFFINERY_TOKEN", "GITHUB_TOKEN", "UNUSED", "USED"]);
1780});
1781
1782test("security: runs of agent code get no repository secrets unless an admin allows it", async () => {
1783 const R = `/repos/${OWNER}/agent-secrets`;
1784 await repoWithReadme("agent-secrets");
1785 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1786 await status(204, "PUT", `${R}/actions/secrets/DEPLOY`, { value: "deploy-value" });
1787 const settings = await ok("GET", `${R}/actions/permissions/workflow`);
1788 assert.equal(settings.agent_runs_use_secrets, false);
1789 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`;
1790 const secretsOfNextJob = async () => {
1791 let names;
1792 await until("the agent's job", async () => {
1793 const r = await runnerClaim(R, ["linux"]);
1794 if (r.status !== 200) return false;
1795 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1796 names = Object.keys(spec.secrets).sort();
1797 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: {} }) });
1798 return true;
1799 });
1800 return names;
1801 };
1802 // An agent pushes a workflow that asks for the deploy secret: its run gets only the job token.
1803 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-work", sha: (await ok("GET", `${R}/branches/main`)).commit.sha }, T.bot);
1804 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf(1)), branch: "agent-work" }, T.bot);
1805 assert.deepEqual(await secretsOfNextJob(), ["DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1806 // Only a person can allow it; then the agent's runs get what they name.
1807 await status(403, "PUT", `${R}/actions/permissions/workflow`, { agent_runs_use_secrets: true }, T.bot);
1808 await status(204, "PUT", `${R}/actions/permissions/workflow`, { agent_runs_use_secrets: true });
1809 const file = await ok("GET", `${R}/contents/.github/workflows/ci.yml?ref=agent-work`, undefined, T.bot);
1810 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci 2", content: b64(wf(2)), branch: "agent-work", sha: file.sha }, T.bot);
1811 assert.deepEqual(await secretsOfNextJob(), ["DEPLOY", "DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1812});
1813
1814test("security: an agent's commits stay agent code when a person pushes on top, until a person merges them", async () => {
1815 const R = `/repos/${OWNER}/agent-laundry`;
1816 const mainSha = await repoWithReadme("agent-laundry");
1817 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
1818 await status(204, "PUT", `${R}/actions/secrets/DEPLOY`, { value: "deploy-value" });
1819 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.DEPLOY }}\n";
1820 const secretsOfNextJob = async () => {
1821 let names;
1822 await until("the next job", async () => {
1823 const r = await runnerClaim(R, ["linux"]);
1824 if (r.status !== 200) return false;
1825 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1826 names = Object.keys(spec.secrets).sort();
1827 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: {} }) });
1828 return true;
1829 });
1830 return names;
1831 };
1832 // The agent's commit asks for the secret: its own push runs without it.
1833 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/agent-work", sha: mainSha }, T.bot);
1834 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf), branch: "agent-work" }, T.bot);
1835 assert.deepEqual(await secretsOfNextJob(), ["DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1836 // A person pushing on top is the branch's last pusher, but the code still includes the agent's commit (ACT-3).
1837 await ok("PUT", `${R}/contents/notes.txt`, { message: "notes", content: b64("notes\n"), branch: "agent-work" });
1838 assert.deepEqual(await secretsOfNextJob(), ["DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1839 // A person merging it makes it theirs: the default branch's runs go by who moved it.
1840 const pr = await ok("POST", `${R}/pulls`, { title: "Agent work", head: "agent-work", base: "main" }, T.bot);
1841 // An agent's pull request needs a person's approval before a person merges it.
1842 await ok("POST", `${R}/pulls/${pr.number}/reviews`, { event: "APPROVE" });
1843 await ok("PUT", `${R}/pulls/${pr.number}/merge`, { merge_method: "merge" });
1844 assert.deepEqual(await secretsOfNextJob(), ["DEPLOY", "DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1845 // A person's new branch from there has no agent commits of its own.
1846 const tip = (await ok("GET", `${R}/branches/main`)).commit.sha;
1847 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/person-work", sha: tip });
1848 await ok("PUT", `${R}/contents/more.txt`, { message: "more", content: b64("more\n"), branch: "person-work" });
1849 assert.deepEqual(await secretsOfNextJob(), ["DEPLOY", "DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
1850});
1851
1852test("security: a workflow on another branch can't cancel a protected branch's run by naming its concurrency group", async () => {
1853 const R = `/repos/${OWNER}/deploy-group`;
1854 await repoWithReadme("deploy-group");
1855 await ok("PUT", `${R}/branches/main/protection`, { requireLinearHistory: true });
1856 const deploy = "name: deploy\non:\n push:\n branches: [main]\nconcurrency:\n group: production\n cancel-in-progress: false\njobs:\n deploy:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo deploying\n";
1857 await ok("PUT", `${R}/contents/.github/workflows/deploy.yml`, { message: "deploy", content: b64(deploy) });
1858 let claim;
1859 await until("the deploy job", async () => {
1860 const r = await runnerClaim(R, ["linux"]);
1861 if (r.status === 200) claim = r.json;
1862 return !!claim;
1863 });
1864 const runOf = async (path) => (await ok("GET", `${R}/actions/runs`)).workflow_runs.find((w) => w.path === path);
1865 const deployRun = await runOf(".github/workflows/deploy.yml");
1866 // A branch's workflow names the same group with cancel-in-progress (ACT-7).
1867 const rogue = "name: rogue\non: push\nconcurrency:\n group: production\n cancel-in-progress: true\njobs:\n noop:\n runs-on: [self-hosted, other]\n steps:\n - run: echo hi\n";
1868 await ok("POST", `${R}/git/refs`, { ref: "refs/heads/rogue", sha: (await ok("GET", `${R}/branches/main`)).commit.sha });
1869 await ok("PUT", `${R}/contents/.github/workflows/rogue.yml`, { message: "rogue", content: b64(rogue), branch: "rogue" });
1870 await until("the rogue run", async () => !!(await runOf(".github/workflows/rogue.yml")));
1871 await new Promise((r) => setTimeout(r, 2000));
1872 const still = await ok("GET", `${R}/actions/runs/${deployRun.id}`);
1873 assert.notEqual(still.conclusion, "cancelled", "the deploy run was cancelled from another branch");
1874 assert.equal(still.status, "in_progress");
1875 await fetch(`${base}/runner/jobs/${claim.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${claim.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
1876 const done = await until("the deploy run to finish", async () => {
1877 const r = await ok("GET", `${R}/actions/runs/${deployRun.id}`);
1878 return r.status === "completed" ? r : null;
1879 });
1880 assert.equal(done.conclusion, "success");
1881});
1882
1883test("security: adding someone by email always invites them, so the address doesn't reveal their username and they agree first", async () => {
1884 await ok("POST", "/user/orgs", { login: "by-mail" });
1885 const members = async () => (await ok("GET", "/orgs/by-mail/members")).map((u) => u.login);
1886
1887 // sam has an account with this address, but the admin gets the same invitation as for a stranger.
1888 const added = await oliveSubmits("/by-mail?tab=people", "/by-mail/-/org/people", { who: "Sam@Example.com", role: "member" });
1889 assert.equal(added.status, 200, added.flash);
1890 assert.match(added.text, /Invitation sent to Sam@Example\.com/);
1891 assert.doesNotMatch(added.flash + added.text, /Added sam|\bsam (is|now)\b/);
1892 assert.ok(!(await members()).includes("sam"));
1893 const link = /\/invite\/([A-Za-z0-9_-]+)/.exec(added.text)?.[1];
1894 assert.ok(link);
1895 // The link the admin holds doesn't say whether the address has an account either.
1896 const landing = await (await fetch(`${base}/invite/${link}`)).text();
1897 assert.match(landing, /Confirm your email/);
1898 assert.doesNotMatch(landing, /already has a Diffinery account/);
1899
1900 // sam joins by accepting it.
1901 const accepted = await submitsAs(S.sam, `/invite/${link}`, `/invite/${link}`, {});
1902 assert.equal(accepted.status, 303, accepted.flash);
1903 assert.ok((await members()).includes("sam"));
1904
1905 // Inviting a member's address again doesn't name them.
1906 const again = await oliveSubmits("/by-mail?tab=people", "/by-mail/-/org/people", { who: "sam@example.com", role: "admin" });
1907 assert.doesNotMatch(again.flash + again.text, /sam is already a member/);
1908 assert.match(again.text, /Invitation sent to sam@example\.com/);
1909
1910 // The same for a repository's collaborators.
1911 await repoWithReadme("by-mail-repo");
1912 const repo = await oliveSubmits(`/${OWNER}/by-mail-repo/settings/access`, `/${OWNER}/by-mail-repo/settings/access/people`, { who: "sam@example.com", role: "write" });
1913 assert.equal(repo.status, 200, repo.flash);
1914 assert.match(repo.text, /Invitation sent to sam@example\.com/);
1915 await status(404, "GET", `/repos/${OWNER}/by-mail-repo`, undefined, T.sam);
1916});
1917
1918test("security: a job's log is capped, and oversized workflow files aren't parsed", async () => {
1919 const R = `/repos/${OWNER}/big-logs`;
1920 await repoWithReadme("big-logs");
1921 const wf = "name: ci\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n";
1922 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1923 let claim;
1924 await until("the job claimed", async () => {
1925 const r = await runnerClaim(R, ["linux"]);
1926 if (r.status === 200) claim = r.json;
1927 return !!claim;
1928 });
1929 const headers = { authorization: `Bearer ${claim.token}`, "content-type": "application/json" };
1930 const text = "x".repeat(16384);
1931 const post = async (n) => {
1932 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 })) }) });
1933 assert.equal(r.status, 200, await r.text());
1934 };
1935 // 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.
1936 await post(600);
1937 await post(600);
1938 await post(10);
1939 await fetch(`${base}/runner/jobs/${claim.job_id}/complete`, { method: "POST", headers, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
1940 const lines = await ok("GET", `${R}/actions/jobs/${claim.job_id}/logs?format=json`);
1941 assert.equal(lines.length, 1025);
1942 assert.match(lines.at(-1).text, /cut off here: a job's log is limited to 16 MiB/);
1943
1944 // A workflow file over 512 KiB is listed as invalid without being parsed.
1945 await ok("PUT", `${R}/contents/.github/workflows/huge.yml`, { message: "huge", content: b64(`${wf}# ${"y".repeat(600 * 1024)}\n`) });
1946 const { workflows } = await ok("GET", `${R}/actions/workflows`);
1947 const huge = workflows.find((w) => w.path === ".github/workflows/huge.yml");
1948 assert.equal(huge.state, "invalid");
1949 assert.match(huge.errors.join("\n"), /larger than 512 KiB/);
1950});
1951
1952test("security: a workflow's token can't use another repository's private packages, and a repository's name is its own", async () => {
1953 await repoWithReadme("pkg-home", { private: true });
1954 await repoWithReadme("pkg-other", { private: true });
1955 // olive pushes an image named after pkg-home, so it's linked to it and private.
1956 await pushTinyImage(`${OWNER}/pkg-home`, "v1", T.olive);
1957 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";
1958 await ok("PUT", `/repos/${OWNER}/pkg-other/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1959 let claim;
1960 await until("the job claimed", async () => {
1961 const r = await runnerClaim(`/repos/${OWNER}/pkg-other`, ["linux"]);
1962 if (r.status === 200) claim = r.json;
1963 return !!claim;
1964 });
1965 // The runner reads its job first; that settles the token's permissions.
1966 await fetch(`${base}/runner/jobs/${claim.job_id}`, { headers: { authorization: `Bearer ${claim.token}` } });
1967 // pkg-other's workflow can't pull pkg-home's image, nor take a name that belongs to pkg-home.
1968 assert.equal((await pullManifest(`${OWNER}/pkg-home`, "v1", claim.token)).status, 404);
1969 const basic = (as) => ({ authorization: `Basic ${Buffer.from(`anyone:${as}`).toString("base64")}`, "content-type": "application/octet-stream" });
1970 const blob = Buffer.from("squat");
1971 const digest = `sha256:${createHash("sha256").update(blob).digest("hex")}`;
1972 const squat = await fetch(`${base}/v2/${OWNER}/pkg-home/tools/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(claim.token) });
1973 assert.equal(squat.status, 403);
1974 assert.match(await squat.text(), /named after the olive\/pkg-home repository/);
1975 // Its own names still work.
1976 const own = await fetch(`${base}/v2/${OWNER}/pkg-other/tools/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(claim.token) });
1977 assert.equal(own.status, 201, await own.text());
1978
1979 // A person who can't write to a repository can't take its name either: milo, a guild member, only reads guild/vault.
1980 const taken = await fetch(`${base}/v2/guild/vault/blobs/uploads/?digest=${digest}`, { method: "POST", body: blob, headers: basic(T.milo) });
1981 assert.equal(taken.status, 403);
1982 assert.match(await taken.text(), /named after the guild\/vault repository/);
1983});
1984
1985test("security: OIDC tokens name the environment a job deployed to, and carry ids that survive a reused name", async () => {
1986 const R = `/repos/${OWNER}/oidc-claims`;
1987 await repoWithReadme("oidc-claims");
1988 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";
1989 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
1990 const tokens = {};
1991 await until("both jobs claimed", async () => {
1992 const r = await runnerClaim(R, ["linux"]);
1993 if (r.status === 200) {
1994 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
1995 const res = await fetch(`${base}/runner/jobs/${r.json.job_id}/oidc?audience=sts.example.com`, { headers: { authorization: `Bearer ${r.json.token}` } });
1996 assert.equal(res.status, 200, await res.clone().text());
1997 tokens[spec.jobKey] = JSON.parse(Buffer.from((await res.json()).value.split(".")[1], "base64url").toString());
1998 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: {} }) });
1999 }
2000 return Object.keys(tokens).length === 2;
2001 });
2002 const repo = await ok("GET", R);
2003 assert.equal(tokens.plain.sub, `repo:${OWNER}/oidc-claims:ref:refs/heads/main`);
2004 assert.equal(tokens.deploy.sub, `repo:${OWNER}/oidc-claims:environment:production`);
2005 assert.equal(tokens.deploy.environment, "production");
2006 assert.equal(tokens.plain.environment, undefined);
2007 assert.equal(tokens.plain.agent_origin, false);
2008 assert.equal(tokens.plain.aud, "sts.example.com");
2009 assert.equal(tokens.plain.repository_id, String(repo.id));
2010 assert.equal(tokens.plain.repository_owner_id, String(repo.owner.id));
2011 assert.match(tokens.plain.actor_id, /^\d+$/);
2012});
2013
2014test("security: sensitive actions need a recent sign-in, sessions end 90 days after it, and one browser can be signed out", async () => {
2015 const confirm = (next) => `/login?confirm=1&next=${encodeURIComponent(next)}`;
2016 // A session signed in 100 days ago has ended, however often it was used since.
2017 await status(401, "GET", "/user", undefined, { cookie: S.oliveStale });
2018 assert.equal((await ok("GET", "/user", undefined, { cookie: S.oliveOld })).login, "olive");
2019
2020 // Signed in 3 hours ago: minting a token, adding a passkey or deleting a repository asks olive to sign in again.
2021 const minted = await status(403, "POST", "/diffinery/tokens", { name: "late", scopes: ["admin"] }, { cookie: S.oliveOld });
2022 assert.equal(minted.confirm, confirm("/settings/tokens"));
2023 const form = await submitsAs(S.oliveOld, "/settings/tokens", "/settings/tokens", { name: "late", scope: "admin", days: "30" });
2024 assert.equal(form.status, 303);
2025 assert.equal(form.location, confirm("/settings/tokens"));
2026 const passkey = await fetch(`${base}/auth/passkey/register/options`, { method: "POST", headers: { "content-type": "application/json", cookie: `__Host-dfy_session=${S.oliveOld}` }, body: "{}" });
2027 assert.equal(passkey.status, 403);
2028 assert.equal((await passkey.json()).confirm, confirm("/settings/security"));
2029 await ok("POST", "/user/repos", { name: "sudo-check", private: true });
2030 await status(403, "DELETE", `/repos/${OWNER}/sudo-check`, undefined, { cookie: S.oliveOld });
2031 const del = await submitsAs(S.oliveOld, `/${OWNER}/sudo-check/settings`, `/${OWNER}/sudo-check/settings/delete`, { confirm: `${OWNER}/sudo-check` });
2032 assert.equal(del.location, confirm(`/${OWNER}/sudo-check/settings`));
2033 await ok("GET", `/repos/${OWNER}/sudo-check`);
2034 const rename = await submitsAs(S.oliveOld, "/settings", "/settings/profile", { login: "olive-renamed", name: "olive" });
2035 assert.equal(rename.location, confirm("/settings"));
2036 assert.equal((await ok("GET", "/user", undefined, { cookie: S.oliveOld })).login, "olive");
2037 assert.equal((await ok("GET", "/diffinery/tokens")).filter((t) => t.name === "late").length, 0);
2038
2039 // The sign-in page asks the old session to confirm; a fresh one goes straight back.
2040 const page = await fetch(`${base}${confirm("/settings/tokens")}`, { headers: { cookie: `__Host-dfy_session=${S.oliveOld}` }, redirect: "manual" });
2041 assert.equal(page.status, 200);
2042 assert.match(await page.text(), /Confirm it&#39;s you|Confirm it's you/);
2043 const fresh = await fetch(`${base}${confirm("/settings/tokens")}`, { headers: { cookie: `__Host-dfy_session=${S.olive}` }, redirect: "manual" });
2044 assert.equal(fresh.status, 302);
2045 assert.equal(new URL(fresh.headers.get("location"), base).pathname, "/settings/tokens");
2046 // A fresh sign-in may; a token is bounded by its scope instead.
2047 await ok("POST", "/diffinery/tokens", { name: "fresh", scopes: ["read"] }, { cookie: S.olive });
2048 const opts = await fetch(`${base}/auth/passkey/register/options`, { method: "POST", headers: { "content-type": "application/json", cookie: `__Host-dfy_session=${S.olive}` }, body: "{}" });
2049 assert.equal(opts.status, 200);
2050 await status(204, "DELETE", `/repos/${OWNER}/sudo-check`);
2051
2052 // Sign out one browser: only your own.
2053 const sams = await submitsAs(S.sam, "/settings/security", `/settings/security/sessions/${hash(S.oliveSpare)}/revoke`, {});
2054 assert.match(sams.flash, /already signed out/);
2055 assert.equal((await ok("GET", "/user", undefined, { cookie: S.oliveSpare })).login, "olive");
2056 const mine = await submitsAs(S.olive, "/settings/security", `/settings/security/sessions/${hash(S.oliveSpare)}/revoke`, {});
2057 assert.match(mine.flash, /Signed out of that browser/);
2058 await status(401, "GET", "/user", undefined, { cookie: S.oliveSpare });
2059 assert.equal((await ok("GET", "/user", undefined, { cookie: S.oliveOld })).login, "olive");
2060});
2061
2062test("security: self-hosted runners register with a one-hour token and claim jobs with their own", async () => {
2063 const R = `/repos/${OWNER}/runner-home`;
2064 await repoWithReadme("runner-home", { private: true });
2065 await repoWithReadme("runner-other", { private: true });
2066 await collaborator(R, "rita", "write", T.rita);
2067 // Only the repository's admins get a registration token.
2068 await status(403, "POST", `${R}/actions/runners/registration-token`, undefined, T.rita);
2069 const reg = await status(201, "POST", `${R}/actions/runners/registration-token`);
2070 assert.match(reg.token, /^drg_/);
2071 assert.ok(Date.parse(reg.expires_at) - Date.now() <= 3600_000);
2072 // Registering takes only that token; a wrong one, another repository or a missing one all get the same answer.
2073 for (const repo of ["runner-other", "no-such-repo"]) await status(401, "POST", `/repos/${OWNER}/${repo}/actions/runners/register`, { registration_token: reg.token, name: "m1" }, null);
2074 await status(401, "POST", `${R}/actions/runners/register`, { registration_token: "drg_wrong", name: "m1" }, null);
2075 const m1 = await status(201, "POST", `${R}/actions/runners/register`, { registration_token: reg.token, name: "m1", labels: ["linux"] }, null);
2076 const m2 = await status(201, "POST", `${R}/actions/runners/register`, { registration_token: reg.token, name: "m2", labels: ["linux"], ephemeral: true }, null);
2077 assert.match(m1.token, /^drn_/);
2078 assert.deepEqual(m1.labels, ["linux"]);
2079
2080 // A runner's token claims this repository's jobs and nothing else, with the labels it registered.
2081 await status(404, "GET", R, undefined, m1.token);
2082 await status(401, "POST", `/repos/${OWNER}/runner-other/actions/runners/claim`, {}, m1.token);
2083 // A personal token, even a repository admin's, can't claim jobs: only registered runners do.
2084 assert.match((await status(403, "POST", `${R}/actions/runners/claim`, { name: "old-runner", labels: ["linux"] })).message, /register this runner/);
2085 const wf = "name: ci\non: push\njobs:\n gpu:\n runs-on: [self-hosted, gpu]\n steps:\n - run: echo gpu\n a:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo a\n b:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo b\n";
2086 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
2087 let first;
2088 await until("m1 claims a job", async () => {
2089 const r = await api("POST", `${R}/actions/runners/claim`, { labels: ["gpu"] }, m1.token);
2090 if (r.status === 200) first = r.json;
2091 return !!first;
2092 });
2093 assert.notEqual(first.name, "gpu");
2094 // The ephemeral runner takes one job, then its token stops working.
2095 const second = await status(200, "POST", `${R}/actions/runners/claim`, {}, m2.token);
2096 assert.notEqual(second.name, first.name);
2097 await status(401, "POST", `${R}/actions/runners/claim`, {}, m2.token);
2098 const listed = await ok("GET", `${R}/actions/runners`);
2099 assert.deepEqual(listed.runners.map((r) => [r.name, r.busy, r.ephemeral]), [["m1", true, false], ["m2", true, true]]);
2100 assert.deepEqual(listed.runners[0].labels.map((l) => l.name), ["self-hosted", "linux"]);
2101 await status(403, "GET", `${R}/actions/runners`, undefined, T.rita);
2102 // Once its job finishes, the ephemeral runner is gone.
2103 await fetch(`${base}/runner/jobs/${second.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${second.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
2104 assert.deepEqual((await ok("GET", `${R}/actions/runners`)).runners.map((r) => r.name), ["m1"]);
2105 // Removing a runner ends its token at once.
2106 await status(204, "DELETE", `${R}/actions/runners/${m1.id}`);
2107 await status(401, "POST", `${R}/actions/runners/claim`, {}, m1.token);
2108});
2109
2110test("security: an organization secret reaches only the repositories it's shared with", async () => {
2111 // Three of guild's repositories: two private, one public.
2112 const repos = {};
2113 for (const [name, priv] of [["sec-a", true], ["sec-b", true], ["sec-pub", false]]) {
2114 repos[name] = await ok("POST", "/orgs/guild/repos", { name, private: priv });
2115 await ok("PUT", `/repos/guild/${name}/contents/README.md`, { message: "init", content: b64(`# ${name}\n`) });
2116 }
2117 await status(204, "PUT", "/orgs/guild/actions/secrets/EVERYWHERE", { value: "e" });
2118 await status(204, "PUT", "/orgs/guild/actions/secrets/PRIVATE_ONLY", { value: "p", visibility: "private" });
2119 await status(204, "PUT", "/orgs/guild/actions/secrets/ONLY_A", { value: "a", visibility: "selected", selected_repository_ids: [repos["sec-a"].id] });
2120 await status(422, "PUT", "/orgs/guild/actions/secrets/BAD", { value: "x", visibility: "selected", selected_repository_ids: [12345] });
2121 await status(422, "PUT", "/orgs/guild/actions/secrets/BAD", { value: "x", visibility: "some" });
2122 const listed = await ok("GET", "/orgs/guild/actions/secrets");
2123 const vis = Object.fromEntries(listed.secrets.map((s) => [s.name, s.visibility]));
2124 assert.deepEqual([vis.EVERYWHERE, vis.PRIVATE_ONLY, vis.ONLY_A], ["all", "private", "selected"]);
2125 assert.deepEqual((await ok("GET", "/orgs/guild/actions/secrets/ONLY_A/repositories")).repositories.map((r) => r.name), ["sec-a"]);
2126 // Updating the value keeps the selection.
2127 await status(204, "PUT", "/orgs/guild/actions/secrets/ONLY_A", { value: "a2" });
2128 await status(409, "PUT", `/orgs/guild/actions/secrets/EVERYWHERE/repositories/${repos["sec-a"].id}`);
2129
2130 // Each repository's job asks for every secret by name and gets only what it's shared.
2131 const wf = "name: ci\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo '${{ toJSON(secrets) }}'\n";
2132 const got = async (name, write = true) => {
2133 if (write) await ok("PUT", `/repos/guild/${name}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64(wf) });
2134 let names;
2135 await until(`${name}'s job claimed`, async () => {
2136 const r = await runnerClaim(`/repos/guild/${name}`, ["linux"]);
2137 if (r.status !== 200) return false;
2138 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
2139 names = Object.keys(spec.secrets).filter((k) => !/_TOKEN$/.test(k)).sort();
2140 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: {} }) });
2141 return true;
2142 });
2143 return names;
2144 };
2145 assert.deepEqual(await got("sec-a"), ["EVERYWHERE", "ONLY_A", "PRIVATE_ONLY"]);
2146 assert.deepEqual(await got("sec-b"), ["EVERYWHERE", "PRIVATE_ONLY"]);
2147 assert.deepEqual(await got("sec-pub"), ["EVERYWHERE"]);
2148
2149 // Adding sec-b to the selection shares it from the next job.
2150 await status(204, "PUT", `/orgs/guild/actions/secrets/ONLY_A/repositories/${repos["sec-b"].id}`);
2151 await ok("PUT", "/repos/guild/sec-b/contents/again.txt", { message: "again", content: b64("again\n") });
2152 assert.deepEqual(await got("sec-b", false), ["EVERYWHERE", "ONLY_A", "PRIVATE_ONLY"]);
2153});
2154
2155test("security: an admin can purge objects a force-push left unreachable", async () => {
2156 const R = `/repos/${OWNER}/purge-me`;
2157 const mainSha = await repoWithReadme("purge-me");
2158 await collaborator(R, "rita", "write", T.rita);
2159 const clone = join(work, "purge-me");
2160 const authed = `${base.replace("://", `://x:${T.olive}@`)}/${OWNER}/purge-me.git`;
2161 execFileSync("git", ["clone", "-q", authed, clone], { stdio: "pipe" });
2162 const g = (args) => execFileSync("git", ["-c", "user.name=Olive", "-c", "user.email=olive@example.com", ...args], { cwd: clone, stdio: "pipe" }).toString().trim();
2163 // A secret pushed by mistake, then force-pushed away.
2164 writeFileSync(join(clone, "leak.txt"), "AKIA-not-really-a-key-1234567890\n");
2165 g(["add", "leak.txt"]);
2166 g(["commit", "-q", "-m", "oops"]);
2167 const leak = g(["rev-parse", "HEAD"]);
2168 const blob = g(["rev-parse", "HEAD:leak.txt"]);
2169 g(["push", "-q", "origin", "HEAD:main"]);
2170 g(["push", "-q", "-f", "origin", `${mainSha}:main`]);
2171 // Unreachable, but still served by its SHA.
2172 await ok("GET", `${R}/git/commits/${leak}`);
2173 await ok("GET", `${R}/git/blobs/${blob}`);
2174
2175 await status(403, "POST", `${R}/diffinery/purge-unreachable`, undefined, T.rita);
2176 const purged = await ok("POST", `${R}/diffinery/purge-unreachable`);
2177 assert.equal(purged.objects, 3, JSON.stringify(purged)); // the commit, its tree and the blob
2178 await status(404, "GET", `${R}/git/commits/${leak}`);
2179 await status(404, "GET", `${R}/git/blobs/${blob}`);
2180 // Everything a branch reaches is still there, and a fresh clone checks out.
2181 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, mainSha);
2182 const fresh = join(work, "purge-me-fresh");
2183 execFileSync("git", ["clone", "-q", authed, fresh], { stdio: "pipe" });
2184 execFileSync("git", ["fsck", "--full"], { cwd: fresh, stdio: "pipe" });
2185 // A second purge finds nothing, and pushing works as before.
2186 assert.equal((await ok("POST", `${R}/diffinery/purge-unreachable`)).objects, 0);
2187 g(["reset", "-q", "--hard", mainSha]);
2188 writeFileSync(join(clone, "ok.txt"), "fine\n");
2189 g(["add", "ok.txt"]);
2190 g(["commit", "-q", "-m", "fine"]);
2191 g(["push", "-q", "origin", "HEAD:main"]);
2192 assert.equal((await ok("GET", `${R}/branches/main`)).commit.sha, g(["rev-parse", "HEAD"]));
2193});
2194
2195test("security: webhooks reach only public hosts other than Diffinery, at most 20 per repository", async () => {
2196 const R = `/repos/${OWNER}/hooked`;
2197 await repoWithReadme("hooked");
2198 const own = new URL(base).hostname;
2199 for (const url of ["https://localhost./x", "https://127.0.0.1/x", "https://[::1]/x", "https://169.254.169.254/latest", "http://example.com/x", "https://metadata.internal/x", `https://${own}/x`]) {
2200 const refused = await status(422, "POST", `${R}/hooks`, { config: { url } });
2201 assert.match(refused.message, /webhook URL/, url);
2202 }
2203 for (let i = 0; i < 20; i++) await status(201, "POST", `${R}/hooks`, { config: { url: `https://example.com/hook/${i}` } });
2204 const full = await status(422, "POST", `${R}/hooks`, { config: { url: "https://example.com/hook/20" } });
2205 assert.match(full.message, /at most 20 webhooks/);
2206});
2207
2208test("security: invitations and test emails have limits, so an account can't be used to send mail in bulk", async () => {
2209 // rita administers guild but isn't a site admin: at most 50 invitations in 24 hours (some went out in earlier tests).
2210 let refused = null;
2211 for (let i = 0; i < 51 && !refused; i++) {
2212 const r = await fetch(`${base}/api/v3/orgs/guild/invitations`, { method: "POST", headers: { authorization: `Bearer ${T.ritaAdmin}`, "content-type": "application/json" }, body: JSON.stringify({ email: `bulk-${i}@example.com` }) });
2213 if (r.status === 429) refused = (await r.json()).message;
2214 else assert.equal(r.status, 201, `invitation ${i}`);
2215 }
2216 assert.match(refused ?? "", /at most 50 invitations in 24 hours/);
2217 // A site admin isn't held to it.
2218 await status(201, "POST", "/orgs/guild/invitations", { email: "after-the-limit@example.com" }, T.olive);
2219
2220 // At most 5 test emails an hour, through the API or the settings page.
2221 for (let i = 0; i < 5; i++) await ok("POST", "/diffinery/emails/test", {}, T.rita);
2222 assert.match((await status(429, "POST", "/diffinery/emails/test", {}, T.rita)).message, /at most 5 test emails an hour/);
2223});
2224
2225test("security: inputs that were taken on trust are checked (collaborators, check links, paging, MCP batches, reserved names)", async () => {
2226 const R = `/repos/${OWNER}/checked-inputs`;
2227 const sha = await repoWithReadme("checked-inputs");
2228 // A collaborator's permission is one of GitHub's, and an organization can't be one.
2229 assert.match((await status(422, "PUT", `${R}/collaborators/rita`, { permission: "root" })).message, /permission must be/);
2230 assert.match((await status(422, "PUT", `${R}/collaborators/guild`, { permission: "push" })).message, /organization can't be a collaborator/);
2231 await collaborator(R, "rita", "triage", T.rita);
2232 // A check run's link is a web address.
2233 for (const details_url of ["javascript:alert(1)", "data:text/html,hi", "//evil.example/x"]) await status(422, "POST", `${R}/check-runs`, { name: "ext", head_sha: sha, details_url });
2234 await status(201, "POST", `${R}/check-runs`, { name: "ext", head_sha: sha, details_url: "https://ci.example/run/1" });
2235 // Paging that isn't a number falls back to the defaults instead of an odd query.
2236 assert.equal((await ok("GET", `${R}/actions/runs?page=-3&per_page=abc`)).total_count, 0);
2237 // Commit history pages only so deep: one request doesn't walk millions of commits.
2238 assert.equal((await ok("GET", `${R}/commits?per_page=100&page=2`)).length, 0);
2239 assert.match((await status(422, "GET", `${R}/commits?per_page=100&page=101`)).message, /pagination is limited/);
2240 // One MCP request carries at most 20 calls.
2241 const batch = Array.from({ length: 21 }, (_, i) => ({ jsonrpc: "2.0", id: i, method: "ping" }));
2242 const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${T.olive}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify(batch) });
2243 assert.equal(r.status, 400);
2244 assert.match((await r.json()).error.message, /at most 20 requests/);
2245 // Names people would trust aren't for the taking.
2246 for (const login of ["ghost", "github-actions", "noreply", "support", "abuse"]) await status(422, "POST", "/user/orgs", { login });
2247});
2248
2249test("security: environment reviewers hold a deploy job until a listed person approves, and nobody else can", async () => {
2250 const R = `/repos/${OWNER}/gated-deploy`;
2251 await repoWithReadme("gated-deploy");
2252 await collaborator(R, "rita", "read", T.rita);
2253 await collaborator(R, "sam", "read", T.sam);
2254 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
2255 const ritaId = (await ok("GET", "/user", undefined, T.rita)).id;
2256
2257 // Only people with access can be reviewers, never an agent or a team; limits are GitHub's; agents can't set them.
2258 await ok("PUT", `${R}/environments/production`, {});
2259 await status(422, "PUT", `${R}/environments/production`, { reviewers: [{ type: "User", login: "olive-bot" }] });
2260 await status(422, "PUT", `${R}/environments/production`, { reviewers: [{ type: "Team", id: 1 }] });
2261 await status(422, "PUT", `${R}/environments/production`, { reviewers: [{ type: "User", login: "milo" }] });
2262 await status(422, "PUT", `${R}/environments/production`, { wait_timer: 43_201 });
2263 await status(403, "PUT", `${R}/environments/production`, { reviewers: [{ type: "User", login: "rita" }] }, T.bot);
2264 await status(201, "PUT", `${R}/environments/production/secrets/DEPLOY_KEY`, { value: "deploy-value" });
2265 const env = await ok("PUT", `${R}/environments/production`, { reviewers: [{ type: "User", id: ritaId }, { type: "User", login: "sam" }, { type: "User", login: "olive" }], prevent_self_review: true, deployment_branch_policy: null });
2266 assert.equal(env.can_admins_bypass, false);
2267 const rule = env.protection_rules.find((r) => r.type === "required_reviewers");
2268 assert.deepEqual(rule.reviewers.map((r) => r.reviewer.login).sort(), ["olive", "rita", "sam"]);
2269 assert.equal(rule.prevent_self_review, true);
2270
2271 const wf = (n) => `name: deploy\non: push\njobs:\n ship${n}:\n runs-on: [self-hosted, linux]\n environment: production\n steps:\n - run: echo ship\n env:\n K: \${{ secrets.DEPLOY_KEY }}\n`;
2272 const claim = async () => {
2273 const r = await runnerClaim(R, ["linux"]);
2274 if (r.status !== 200) return null;
2275 const spec = await (await fetch(`${base}/runner/jobs/${r.json.job_id}`, { headers: { authorization: `Bearer ${r.json.token}` } })).json();
2276 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: {} }) });
2277 return spec;
2278 };
2279 const waitingRun = async (sha) => {
2280 const run = await until("a run waiting for review", async () => (await ok("GET", `${R}/actions/runs`)).workflow_runs.find((r) => r.head_sha === sha && r.status === "waiting"));
2281 const jobs = (await ok("GET", `${R}/actions/runs/${run.id}/jobs`)).jobs;
2282 assert.equal(jobs.length, 1);
2283 assert.equal(jobs[0].status, "waiting");
2284 // Held before anything starts: no runner can claim it, so no token or secret has left.
2285 assert.equal(await claim(), null);
2286 return run;
2287 };
2288
2289 // olive pushes: the job waits, and the deployment says so.
2290 const first = (await ok("PUT", `${R}/contents/.github/workflows/deploy.yml`, { message: "deploy", content: b64(wf(1)) })).commit.sha;
2291 const run = await waitingRun(first);
2292 const pendingAs = async (as, id = run.id) => (await ok("GET", `${R}/actions/runs/${id}/pending_deployments`, undefined, as))[0];
2293 const p = await pendingAs(T.rita);
2294 assert.equal(p.environment.name, "production");
2295 assert.equal(p.current_user_can_approve, true);
2296 assert.equal((await pendingAs(T.olive)).current_user_can_approve, false, "olive started the run and the environment prevents self-review");
2297 const deployment = (await ok("GET", `${R}/deployments?environment=production`))[0];
2298 assert.equal((await ok("GET", `${R}/deployments/${deployment.id}/statuses`))[0].state, "waiting");
2299
2300 // Nobody but a listed person, other than the run's starter, with a token that may write, decides.
2301 const body = { environment_ids: [p.environment.id], state: "approved", comment: "ship it" };
2302 assert.match((await api("POST", `${R}/actions/runs/${run.id}/pending_deployments`, body)).json.message, /doesn't let whoever started a run approve it/);
2303 assert.equal((await api("POST", `${R}/actions/runs/${run.id}/pending_deployments`, body, T.bot)).status, 403);
2304 assert.equal((await api("POST", `${R}/actions/runs/${run.id}/pending_deployments`, body, T.reader)).status, 403);
2305 assert.equal((await api("POST", `${R}/actions/runs/${run.id}/pending_deployments`, body, T.milo)).status, 404);
2306 await status(422, "POST", `${R}/actions/runs/${run.id}/pending_deployments`, { ...body, environment_ids: [999] }, T.rita);
2307 const approved = await ok("POST", `${R}/actions/runs/${run.id}/pending_deployments`, body, T.rita);
2308 assert.equal(approved[0].environment, "production");
2309 // One decision counts: a second one finds nothing waiting.
2310 await status(422, "POST", `${R}/actions/runs/${run.id}/pending_deployments`, { ...body, state: "rejected" }, T.sam);
2311
2312 // Now the job starts, and only now gets the environment's secret.
2313 const spec = await until("the approved job", claim);
2314 assert.equal(spec.secrets.DEPLOY_KEY, "deploy-value");
2315 const done = await until("the run done", async () => {
2316 const r = await ok("GET", `${R}/actions/runs/${run.id}`);
2317 return r.status === "completed" ? r : null;
2318 });
2319 assert.equal(done.conclusion, "success");
2320 const approvals = await ok("GET", `${R}/actions/runs/${run.id}/approvals`);
2321 assert.deepEqual(approvals.map((a) => [a.state, a.user.login, a.comment, a.environments[0].name]), [["approved", "rita", "ship it", "production"]]);
2322 assert.deepEqual((await ok("GET", `${R}/deployments/${deployment.id}/statuses`)).map((s) => s.state), ["success", "in_progress", "waiting"]);
2323
2324 // A rejection fails the job without starting it. sam decides in the browser, from the run page.
2325 const file = await ok("GET", `${R}/contents/.github/workflows/deploy.yml`);
2326 const second = (await ok("PUT", `${R}/contents/.github/workflows/deploy.yml`, { message: "deploy 2", content: b64(wf(2)), sha: file.sha })).commit.sha;
2327 const run2 = await waitingRun(second);
2328 const page = await (await fetch(`${base}/${OWNER}/gated-deploy/actions/runs/${run2.id}`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } })).text();
2329 assert.match(page, /Waiting for review/);
2330 assert.match(page, /You started this run, and this environment doesn&#39;t let you approve it|You started this run, and this environment doesn't let you approve it/);
2331 const envId = (await pendingAs(T.rita, run2.id)).environment.id;
2332 const rejected = await submitsAs(S.sam, `/${OWNER}/gated-deploy/actions/runs/${run2.id}`, `/${OWNER}/gated-deploy/actions/runs/${run2.id}/review`, { environment: String(envId), comment: "not today", state: "rejected" });
2333 assert.equal(rejected.status, 303);
2334 assert.match(rejected.flash, /Rejected/);
2335 const failed = await until("the rejected run done", async () => {
2336 const r = await ok("GET", `${R}/actions/runs/${run2.id}`);
2337 return r.status === "completed" ? r : null;
2338 });
2339 assert.equal(failed.conclusion, "failure");
2340 const job = (await ok("GET", `${R}/actions/runs/${run2.id}/jobs`)).jobs[0];
2341 assert.match(job.failure.message, /rejected by sam: not today/);
2342 assert.equal(await claim(), null);
2343
2344 // Self-review compares accounts, not names: sam starts a run, renames, and still can't approve it.
2345 await collaborator(R, "sam", "write", T.sam);
2346 const file3 = await ok("GET", `${R}/contents/.github/workflows/deploy.yml`);
2347 const fourth = (await ok("PUT", `${R}/contents/.github/workflows/deploy.yml`, { message: "deploy 4", content: b64(wf(4)), sha: file3.sha }, T.sam)).commit.sha;
2348 const run4 = await waitingRun(fourth);
2349 const env4 = (await pendingAs(T.rita, run4.id)).environment.id;
2350 const renamed = await submitsAs(S.sam, "/settings", "/settings/profile", { login: "sam-renamed", name: "sam" });
2351 assert.equal(renamed.status, 303);
2352 try {
2353 assert.equal((await ok("GET", "/user", undefined, T.sam)).login, "sam-renamed");
2354 assert.equal((await pendingAs(T.sam, run4.id)).current_user_can_approve, false);
2355 const self = await api("POST", `${R}/actions/runs/${run4.id}/pending_deployments`, { environment_ids: [env4], state: "approved" }, T.sam);
2356 assert.equal(self.status, 403);
2357 assert.match(self.json.message, /doesn't let whoever started a run approve it/);
2358 } finally {
2359 assert.equal((await submitsAs(S.sam, "/settings", "/settings/profile", { login: "sam", name: "sam" })).status, 303);
2360 }
2361
2362 // Access counts when deciding, not only when the list was set: on a public repository, where
2363 // anyone may read, a reviewer removed from it no longer approves.
2364 await ok("PATCH", R, { visibility: "public" });
2365 await status(204, "DELETE", `${R}/collaborators/rita`);
2366 assert.equal((await pendingAs(T.rita, run4.id)).current_user_can_approve, false);
2367 const removed = await api("POST", `${R}/actions/runs/${run4.id}/pending_deployments`, { environment_ids: [env4], state: "approved" }, T.rita);
2368 assert.equal(removed.status, 403);
2369 assert.match(removed.json.message, /only people with access to this repository/);
2370 await ok("POST", `${R}/actions/runs/${run4.id}/pending_deployments`, { environment_ids: [env4], state: "rejected", comment: "cleanup" });
2371 await ok("PATCH", R, { visibility: "private" });
2372 await collaborator(R, "rita", "read", T.rita);
2373
2374 // A wait timer alone holds the job until it passes; nobody skips it.
2375 await ok("PUT", `${R}/environments/production`, { reviewers: [], wait_timer: 1 });
2376 const file2 = await ok("GET", `${R}/contents/.github/workflows/deploy.yml`);
2377 const third = (await ok("PUT", `${R}/contents/.github/workflows/deploy.yml`, { message: "deploy 3", content: b64(wf(3)), sha: file2.sha })).commit.sha;
2378 const run3 = await waitingRun(third);
2379 const timer = await pendingAs(T.rita, run3.id);
2380 assert.equal(timer.wait_timer, 1);
2381 assert.equal(timer.current_user_can_approve, false);
2382 await status(422, "POST", `${R}/actions/runs/${run3.id}/pending_deployments`, { environment_ids: [timer.environment.id], state: "approved" }, T.rita);
2383 // The Worker runs with a short wait-timer minute (WAIT_TIMER_MINUTE_MS), so the timer passes in seconds.
2384 if (Date.now() < Date.parse(timer.wait_timer_started_at) + TIMER_MINUTE_MS - 2000) assert.equal(await claim(), null, "nothing starts before the timer passes");
2385 const timed = await until("the job after its wait timer", claim, 60_000);
2386 assert.ok(Date.now() >= Date.parse(timer.wait_timer_started_at) + TIMER_MINUTE_MS - 1000, "the job waited for its timer");
2387 assert.equal(timed.secrets.DEPLOY_KEY, "deploy-value");
2388});
2389
2390test("security: adding someone by username sends an invitation, and they get access only once they accept", async () => {
2391 // ------------------------------------------------------------ a repository: milo is invited, not added
2392 await repoWithReadme("by-name");
2393 const R = `/repos/${OWNER}/by-name`;
2394 const inv = await status(201, "PUT", `${R}/collaborators/milo`, { permission: "write" });
2395 assert.equal(inv.invitee.login, "milo");
2396 assert.equal(inv.permissions, "write");
2397 await status(404, "GET", R, undefined, T.milo);
2398 // The admin's list names the username, never the person's email address.
2399 const listed = await ok("GET", `${R}/invitations`);
2400 assert.deepEqual(listed.map((i) => [i.login, i.email, i.role]), [["milo", null, "write"]]);
2401 // In-app and in milo's own list.
2402 assert.ok((await ok("GET", "/notifications", undefined, T.milo)).some((n) => /olive invited you to olive\/by-name/.test(n.title)));
2403 const mine = await ok("GET", "/user/repository_invitations", undefined, T.milo);
2404 assert.deepEqual(mine.map((i) => [i.id, i.repository.full_name]), [[inv.id, `${OWNER}/by-name`]]);
2405 // Nobody else can accept it, and a read token can't either.
2406 await status(404, "PATCH", `/user/repository_invitations/${inv.id}`, undefined, T.rita);
2407 assert.deepEqual(await ok("GET", "/user/repository_invitations", undefined, T.rita), []);
2408 await status(404, "GET", R, undefined, T.rita);
2409 // Asking again changes the pending invitation's role rather than sending another.
2410 assert.equal((await status(201, "PUT", `${R}/collaborators/milo`, { permission: "admin" })).id, inv.id);
2411 // milo accepts and has the role offered.
2412 await status(204, "PATCH", `/user/repository_invitations/${inv.id}`, undefined, T.milo);
2413 assert.equal((await ok("GET", R, undefined, T.milo)).permissions.admin, true);
2414 await status(404, "PATCH", `/user/repository_invitations/${inv.id}`, undefined, T.milo);
2415 // A collaborator's role then changes at once.
2416 await status(204, "PUT", `${R}/collaborators/milo`, { permission: "read" });
2417 assert.equal((await ok("GET", R, undefined, T.milo)).permissions.push, false);
2418 // The settings form that sets a role invites someone new the same way.
2419 const viaForm = await oliveSubmits(`/${OWNER}/by-name/settings/access`, `/${OWNER}/by-name/settings/access`, { login: "rita", role: "write" });
2420 assert.equal(viaForm.status, 303);
2421 assert.match(viaForm.flash, /Invited rita/);
2422 await status(404, "GET", R, undefined, T.rita);
2423 // rita declines: no access, and the invitation is gone.
2424 const ritas = await ok("GET", "/user/repository_invitations", undefined, T.rita);
2425 assert.equal(ritas.length, 1);
2426 await status(204, "DELETE", `/user/repository_invitations/${ritas[0].id}`, undefined, T.rita);
2427 await status(404, "GET", R, undefined, T.rita);
2428 assert.deepEqual(await ok("GET", `${R}/invitations`), []);
2429 // Agents are still added directly: they act for a person who already has access.
2430 await status(204, "PUT", `${R}/collaborators/olive-bot`, { permission: "write" });
2431
2432 // ------------------------------------------------------------ an organization: Add people and the role form both invite
2433 await ok("POST", "/user/orgs", { login: "by-name-org" });
2434 const members = async () => (await ok("GET", "/orgs/by-name-org/members")).map((u) => u.login);
2435 const added = await oliveSubmits("/by-name-org?tab=people", "/by-name-org/-/org/people", { who: "milo", role: "member" });
2436 assert.equal(added.status, 303);
2437 assert.match(added.flash, /Invited milo to by-name-org/);
2438 const roleForm = await oliveSubmits("/by-name-org?tab=people", "/by-name-org/-/org/members", { login: "sam", role: "admin" });
2439 assert.match(roleForm.flash, /Invited sam to by-name-org/);
2440 assert.deepEqual(await members(), ["olive"]);
2441 assert.equal((await ok("GET", "/user/memberships/orgs/by-name-org", undefined, T.milo)).state, "pending");
2442 assert.deepEqual((await ok("GET", "/user/memberships/orgs?state=pending", undefined, T.milo)).map((m) => m.organization.login), ["by-name-org"]);
2443 // milo accepts through the API, sam declines on the web.
2444 assert.equal((await ok("PATCH", "/user/memberships/orgs/by-name-org", { state: "active" }, T.milo)).state, "active");
2445 const samInvite = (await ok("GET", "/orgs/by-name-org/invitations")).find((i) => i.login === "sam");
2446 const page = await (await fetch(`${base}/settings/invitations`, { headers: { cookie: `__Host-dfy_session=${S.sam}` } })).text();
2447 assert.match(page, /by-name-org/);
2448 const declined = await submitsAs(S.sam, "/settings/invitations", `/settings/invitations/${samInvite.id}/decline`, {});
2449 assert.match(declined.flash, /Invitation declined/);
2450 assert.deepEqual((await members()).sort(), ["milo", "olive"]);
2451 await status(404, "GET", "/user/memberships/orgs/by-name-org", undefined, T.sam);
2452
2453 // ------------------------------------------------------------ someone waiting for an invite accepts it from the waiting page
2454 await repoWithReadme("for-penny");
2455 const pennyInvite = await status(201, "PUT", `/repos/${OWNER}/for-penny/collaborators/penny`, { permission: "read" });
2456 const waiting = await (await fetch(base, { headers: { cookie: `__Host-dfy_session=${S.penny}` } })).text();
2457 assert.match(waiting, /Waiting for an invite/);
2458 assert.match(waiting, new RegExp(`${OWNER}/for-penny`));
2459 const accepted = await submitsAs(S.penny, "/", `/settings/invitations/${pennyInvite.id}/accept`, {});
2460 assert.equal(accepted.status, 303, accepted.flash);
2461 assert.equal(accepted.location, `/${OWNER}/for-penny`);
2462 assert.equal((await fetch(`${base}/${OWNER}/for-penny`, { headers: { cookie: `__Host-dfy_session=${S.penny}` } })).status, 200);
2463
2464 // ------------------------------------------------------------ a repository with invitations can still be deleted
2465 await repoWithReadme("invited-then-deleted");
2466 await status(201, "PUT", `/repos/${OWNER}/invited-then-deleted/collaborators/rita`, { permission: "read" });
2467 await status(204, "DELETE", `/repos/${OWNER}/invited-then-deleted`);
2468 assert.deepEqual(await ok("GET", "/user/repository_invitations", undefined, T.rita), []);
2469});
2470
2471test("security: per-account quotas on hosted minutes, hosted jobs at once, sandboxes and repositories", async () => {
2472 // Only site administrators see or change another account's quotas.
2473 await status(403, "PATCH", "/admin/accounts/rita/quotas", { repositories: 1 });
2474 await status(403, "GET", "/admin/accounts/rita/quotas", undefined, T.rita);
2475 await status(422, "PATCH", "/admin/accounts/rita/quotas", { storage: 1 }, T.sully);
2476 const set = await ok("PATCH", "/admin/accounts/rita/quotas", { repositories: 1, hosted_minutes: 0, sandboxes: 0 }, T.sully);
2477 assert.deepEqual([set.repositories.limit, set.hosted_minutes.limit, set.sandboxes.limit, set.exempt], [1, 0, 0, false]);
2478 await until("the audit entry", async () => auditLog("account.quotas.set").some((e) => e.target === "rita" && e.actor_login === "sully"));
2479 // rita sees her own usage and limits.
2480 const mine = await ok("GET", "/user/usage", undefined, T.rita);
2481 assert.deepEqual([mine.account, mine.repositories.limit, mine.hosted_minutes.used], ["rita", 1, 0]);
2482
2483 // ------------------------------------------------------------ repositories
2484 const owned = mine.repositories.count;
2485 await setRitaRepos(owned + 1);
2486 await ok("POST", "/user/repos", { name: "rita-quota-1" }, T.rita);
2487 assert.match((await status(403, "POST", "/user/repos", { name: "rita-quota-2" }, T.rita)).message, /rita has reached its limit of \d+ repositories/);
2488
2489 // ------------------------------------------------------------ hosted minutes: a hosted job isn't started
2490 const R = "/repos/rita/rita-quota-1";
2491 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "ci", content: b64("name: ci\non: push\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n") }, T.rita);
2492 const job = await until("the job to fail", async () => {
2493 const runs = (await ok("GET", `${R}/actions/runs`, undefined, T.rita)).workflow_runs;
2494 if (!runs.length) return null;
2495 const jobs = (await ok("GET", `${R}/actions/runs/${runs[0].id}/jobs`, undefined, T.rita)).jobs;
2496 return jobs[0]?.status === "completed" ? { run: runs[0].id, job: jobs[0] } : null;
2497 });
2498 assert.equal(job.job.conclusion, "failure");
2499 const page = await (await fetch(`${base}/rita/rita-quota-1/actions/runs/${job.run}`, { headers: { authorization: `Bearer ${T.rita}` } })).text();
2500 assert.match(page, /used its 0 hosted minutes for this month/);
2501
2502 // ------------------------------------------------------------ sandboxes: the minutes count for them too, and so does their own limit
2503 assert.match((await status(429, "POST", `${R}/diffinery/sandboxes`, {}, T.rita)).message, /used its 0 hosted minutes/);
2504 await ok("PATCH", "/admin/accounts/rita/quotas", { hosted_minutes: null, hosted_jobs: 0 }, T.sully);
2505 assert.match((await status(429, "POST", `${R}/diffinery/sandboxes`, {}, T.rita)).message, /already has 0 agent sandboxes open/);
2506
2507 // ------------------------------------------------------------ hosted jobs at once: the job waits, then starts once there's room
2508 const file = await ok("GET", `${R}/contents/.github/workflows/ci.yml`, undefined, T.rita);
2509 await ok("PUT", `${R}/contents/.github/workflows/ci.yml`, { message: "again", sha: file.sha, content: b64("name: ci\non: push\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - run: echo again\n") }, T.rita);
2510 const held = await until("a second run", async () => {
2511 const runs = (await ok("GET", `${R}/actions/runs`, undefined, T.rita)).workflow_runs;
2512 if (runs.length < 2) return null;
2513 const jobs = (await ok("GET", `${R}/actions/runs/${runs[0].id}/jobs`, undefined, T.rita)).jobs;
2514 return jobs[0] ? { run: runs[0].id, job: jobs[0] } : null;
2515 });
2516 await sleep(3000);
2517 assert.equal((await ok("GET", `${R}/actions/runs/${held.run}/jobs`, undefined, T.rita)).jobs[0].status, "queued");
2518 // With room again, the alarm starts it within a minute (here it then fails: no containers under wrangler dev).
2519 await ok("PATCH", "/admin/accounts/rita/quotas", { hosted_jobs: null }, T.sully);
2520 await until("the held job to leave the queue", async () => (await ok("GET", `${R}/actions/runs/${held.run}/jobs`, undefined, T.rita)).jobs[0].status !== "queued", 120_000);
2521});
2522
2523test("security: a per-account storage quota refuses pushes, Git LFS and release asset uploads past it; reads and deletes keep working", async () => {
2524 const R = "/repos/milo/hoard";
2525 await ok("POST", "/user/repos", { name: "hoard" }, T.milo);
2526 const usage = async () => (await ok("GET", "/user/usage", undefined, T.milo)).storage_bytes;
2527 assert.equal((await usage()).limit, 10 * 1024 ** 3);
2528 // Push main and a topic branch, and upload a release asset, while there is room.
2529 const clone = join(work, "hoard");
2530 const remote = `${base.replace("://", "://x:" + T.milo + "@")}/milo/hoard.git`;
2531 execFileSync("git", ["init", "-q", "-b", "main", clone]);
2532 const commit = (name) => {
2533 writeFileSync(join(clone, name), randomBytes(2000).toString("hex"));
2534 gitRun(["add", name], clone);
2535 gitRun(["commit", "-q", "-m", name], clone);
2536 };
2537 const push = (...args) => spawnSync("git", ["-c", "protocol.version=2", "push", remote, ...args], { cwd: clone, encoding: "utf8" });
2538 commit("a.txt");
2539 assert.equal(push("HEAD:main", "HEAD:refs/heads/topic").status, 0);
2540 // Repositories report what they store as it changes: wait until the count stops moving.
2541 const settled = async (what, test) => {
2542 let last = -1;
2543 return until(what, async () => {
2544 const u = (await usage()).used;
2545 if (u === last && test(u)) return u;
2546 last = u;
2547 await sleep(1000);
2548 return null;
2549 });
2550 };
2551 const pushed = await settled("the push to be counted", (u) => u > 2000);
2552 const rel = await ok("POST", `${R}/releases`, { tag_name: "v1", target_commitish: "main" }, T.milo);
2553 const upload = (bytes) => fetch(`${base}/api/uploads/repos/milo/hoard/releases/${rel.id}/assets?name=${bytes.length}.bin`, { method: "POST", headers: { authorization: `Bearer ${T.milo}`, "content-type": "application/octet-stream" }, body: bytes });
2554 const asset = await (await upload(randomBytes(3000))).json();
2555 assert.equal(asset.size, 3000);
2556 const used = await settled("the asset to be counted", (u) => u === pushed + 3000);
2557 assert.equal((await ok("GET", "/admin/accounts/milo/quotas", undefined, T.sully)).storage_bytes.used, used);
2558
2559 // ------------------------------------------------------------ at the limit: nothing new is stored
2560 const set = await ok("PATCH", "/admin/accounts/milo/quotas", { storage_bytes: used }, T.sully);
2561 assert.deepEqual(set.storage_bytes, { used, limit: used });
2562 const full = new RegExp(`milo has reached its storage limit of ${used} bytes`);
2563 commit("b.txt");
2564 const refused = push("HEAD:main");
2565 assert.notEqual(refused.status, 0);
2566 assert.match(refused.stderr, new RegExp(`remote: Push refused: ${full.source}`));
2567 assert.match(refused.stderr, /storage limit reached/);
2568 const lfsOid = (bytes) => createHash("sha256").update(bytes).digest("hex");
2569 const lfsBlob = randomBytes(1000);
2570 const batch = async () => {
2571 const r = await fetch(`${base}/milo/hoard.git/info/lfs/objects/batch`, { method: "POST", headers: { authorization: `Bearer ${T.milo}`, accept: "application/vnd.git-lfs+json", "content-type": "application/vnd.git-lfs+json" }, body: JSON.stringify({ operation: "upload", objects: [{ oid: lfsOid(lfsBlob), size: lfsBlob.length }] }) });
2572 assert.equal(r.status, 200);
2573 return (await r.json()).objects[0];
2574 };
2575 const lfs = await batch();
2576 assert.equal(lfs.error.code, 507);
2577 assert.match(lfs.error.message, full);
2578 const put = await fetch(`${base}/milo/hoard.git/info/lfs/objects/${lfsOid(lfsBlob)}`, { method: "PUT", headers: { authorization: `Bearer ${T.milo}`, "content-type": "application/octet-stream" }, body: lfsBlob });
2579 assert.equal(put.status, 507);
2580 const late = await upload(randomBytes(10));
2581 assert.equal(late.status, 403);
2582 assert.match((await late.json()).message, full);
2583 assert.match((await status(403, "PUT", `${R}/contents/c.txt`, { message: "c", content: b64("more") }, T.milo)).message, full);
2584 assert.match((await status(403, "POST", `${R}/git/blobs`, { content: "more" }, T.milo)).message, full);
2585 // A chunked registry upload declares no length, so its bytes are counted as they arrive.
2586 const reg = { authorization: `Basic ${Buffer.from(`milo:${T.milo}`).toString("base64")}` };
2587 const started = await fetch(`${base}/v2/milo/hoard/blobs/uploads/`, { method: "POST", headers: reg });
2588 assert.equal(started.status, 202, await started.clone().text());
2589 const chunked = new ReadableStream({
2590 start(ctl) {
2591 ctl.enqueue(randomBytes(1000));
2592 ctl.close();
2593 },
2594 });
2595 const sneak = await fetch(`${base}${started.headers.get("location")}`, { method: "PATCH", headers: { ...reg, "content-type": "application/octet-stream" }, body: chunked, duplex: "half" });
2596 assert.equal(sneak.status, 403);
2597 assert.match(await sneak.text(), /milo has reached its storage limit/);
2598 // An upload refused at the quota can't finish, so it is gone with its bytes: a retry has to start again.
2599 assert.equal((await fetch(`${base}${started.headers.get("location")}`, { headers: reg })).status, 404);
2600
2601 // ------------------------------------------------------------ reads, ref deletions and ref moves still work
2602 assert.equal((await ok("GET", `${R}/contents/a.txt`, undefined, T.milo)).size, 4000);
2603 assert.equal(push(":refs/heads/topic").status, 0);
2604 assert.equal(push("HEAD~1:refs/heads/copy").status, 0);
2605 assert.deepEqual((await ok("GET", `${R}/branches`, undefined, T.milo)).map((b) => b.name).sort(), ["copy", "main"]);
2606
2607 // ------------------------------------------------------------ deleting brings usage down, and there is room again
2608 await status(204, "DELETE", `${R}/releases/assets/${asset.id}`, undefined, T.milo);
2609 await until("the asset's bytes to be given back", async () => (await usage()).used === used - 3000);
2610 assert.ok((await batch()).actions.upload);
2611 await ok("PATCH", "/admin/accounts/milo/quotas", { storage_bytes: null }, T.sully);
2612 assert.equal(push("HEAD:main").status, 0);
2613});
2614
2615/** Set rita's repository quota (site administrators only). */
2616async function setRitaRepos(n) {
2617 await ok("PATCH", "/admin/accounts/rita/quotas", { repositories: n }, T.sully);
2618}
2619
2620test("security: kill switches suspend Actions for a repository or an account, and pause hosted compute on the instance", async () => {
2621 const R = `/repos/${OWNER}/halted`;
2622 const S = `/admin/repos/${OWNER}/halted/actions-suspension`;
2623 const A = `/admin/accounts/${OWNER}/actions-suspension`;
2624 const P = "/admin/hosted-compute-pause";
2625 await repoWithReadme("halted");
2626 const runs = async () => (await ok("GET", `${R}/actions/runs`)).workflow_runs;
2627 const html = async (path, as = T.olive) => (await fetch(`${base}${path}`, { headers: { authorization: `Bearer ${as}` } })).text();
2628 const push = async (path, text) => ok("PUT", `${R}/contents/${path}`, { message: path, content: b64(text) });
2629 // A self-hosted job that no runner takes yet: the run stays in progress.
2630 await push(".github/workflows/ci.yml", "name: ci\non:\n push:\n workflow_dispatch:\n repository_dispatch:\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n");
2631 const first = await until("a run waiting for a runner", async () => {
2632 const [run] = await runs();
2633 return run && (await ok("GET", `${R}/actions/runs/${run.id}/jobs`)).jobs.length ? run : null;
2634 });
2635
2636 try {
2637 // ------------------------------------------------------------ only site administrators
2638 for (const path of [S, A, P]) {
2639 for (const method of ["GET", "PUT", "DELETE"]) assert.match((await status(403, method, path, method === "PUT" ? { reason: "mine" } : undefined, T.olive)).message, /only site administrators/);
2640 await status(401, "PUT", path, { reason: "no token" }, null);
2641 }
2642 await status(422, "PUT", S, {}, T.sully);
2643 await status(404, "PUT", `/admin/repos/${OWNER}/nowhere/actions-suspension`, { reason: "x" }, T.sully);
2644 await status(404, "PUT", "/admin/accounts/olive-bot/actions-suspension", { reason: "x" }, T.sully);
2645 assert.equal((await ok("GET", S, undefined, T.sully)).suspended, false);
2646
2647 // ------------------------------------------------------------ a repository: what runs stops, nothing new starts
2648 const s = await ok("PUT", S, { reason: "crypto mining" }, T.sully);
2649 assert.deepEqual([s.suspended, s.reason, s.suspended_by, s.stopped.runs, s.stopped.jobs], [true, "crypto mining", "sully", 1, 1]);
2650 const cancelled = await until("the run to be cancelled", async () => {
2651 const r = await ok("GET", `${R}/actions/runs/${first.id}`);
2652 return r.status === "completed" ? r : null;
2653 });
2654 assert.equal(cancelled.conclusion, "cancelled");
2655 assert.match(await html(`/${OWNER}/halted/actions/runs/${first.id}`), /Cancelled: Actions are suspended for this repository by a site administrator: crypto mining/);
2656 assert.equal((await runnerClaim(R, ["linux"])).status, 204);
2657 assert.match((await status(403, "POST", `${R}/actions/workflows/ci.yml/dispatches`, { ref: "main" })).message, /Actions are suspended for this repository by a site administrator: crypto mining/);
2658 assert.match((await status(403, "POST", `${R}/dispatches`, { event_type: "go" })).message, /suspended for this repository/);
2659 assert.match((await status(403, "POST", `${R}/actions/runs/${first.id}/rerun`)).message, /suspended for this repository/);
2660 assert.match((await status(403, "POST", `${R}/diffinery/sandboxes`, {})).message, /suspended for this repository/);
2661 const before = (await runs()).length;
2662 await push("one.txt", "one\n");
2663 await sleep(3000);
2664 assert.equal((await runs()).length, before, "a push starts no run while Actions are suspended");
2665 for (const path of [`/${OWNER}/halted/actions`, `/${OWNER}/halted/settings`]) assert.match(await html(path), /Actions are suspended for this repository by a site administrator/, path);
2666 assert.match(await html("/settings/admin/kill-switches", T.sully), new RegExp(`${OWNER}/halted`));
2667 await until("the suspension's audit entry", async () => auditLog("actions.suspend").some((e) => e.target === `${OWNER}/halted` && e.actor_login === "sully" && JSON.parse(e.detail).reason === "crypto mining"));
2668
2669 // Lifting it lets new work start; nothing restarts.
2670 assert.equal((await ok("DELETE", S, undefined, T.sully)).suspended, false);
2671 assert.equal((await ok("GET", `${R}/actions/runs/${first.id}`)).conclusion, "cancelled");
2672 await push("two.txt", "two\n");
2673 await until("a new run", async () => (await runs()).length > before);
2674 await ok("POST", `${R}/actions/workflows/ci.yml/dispatches`, { ref: "main" });
2675 const sandbox = await api("POST", `${R}/diffinery/sandboxes`, {});
2676 assert.notEqual(sandbox.status, 403, JSON.stringify(sandbox.json)); // 503 here: no sandbox pool under this test
2677 await until("the lift's audit entry", async () => auditLog("actions.unsuspend").some((e) => e.target === `${OWNER}/halted` && e.actor_login === "sully"));
2678
2679 // ------------------------------------------------------------ an account: every repository it owns
2680 const a = await ok("PUT", A, { reason: "abuse report" }, T.sully);
2681 assert.deepEqual([a.account, a.suspended, a.reason], [OWNER, true, "abuse report"]);
2682 assert.ok(a.stopped.runs >= 1, JSON.stringify(a.stopped));
2683 assert.equal((await ok("GET", S, undefined, T.sully)).owner_suspended, true);
2684 assert.match((await status(403, "POST", `${R}/actions/workflows/ci.yml/dispatches`, { ref: "main" })).message, /Actions are suspended for every repository of olive by a site administrator: abuse report/);
2685 assert.match((await status(403, "POST", `${R}/diffinery/sandboxes`, {})).message, /every repository of olive/);
2686 const during = (await runs()).length;
2687 await push("three.txt", "three\n");
2688 await sleep(3000);
2689 assert.equal((await runs()).length, during);
2690 assert.match(await html(`/${OWNER}/halted/actions`), /Actions are suspended for every repository of olive by a site administrator/);
2691 assert.equal((await ok("DELETE", A, undefined, T.sully)).suspended, false);
2692 await until("the account's audit entries", async () => auditLog("actions.suspend").some((e) => e.target === OWNER && JSON.parse(e.detail).kind === "account") && auditLog("actions.unsuspend").some((e) => e.target === OWNER));
2693
2694 // ------------------------------------------------------------ the instance: hosted compute stops, self-hosted runners go on
2695 const p = await ok("PUT", P, { reason: "cost overrun" }, T.sully);
2696 assert.deepEqual([p.paused, p.reason, p.paused_by], [true, "cost overrun", "sully"]);
2697 assert.equal((await ok("GET", P, undefined, T.sully)).paused, true);
2698 assert.match((await status(403, "POST", `${R}/diffinery/sandboxes`, {})).message, /Agent sandboxes are paused on this instance by a site administrator: cost overrun/);
2699 assert.match(await html("/settings/admin", T.sully), /Hosted compute is paused on this instance/);
2700 assert.match(await html(`/${OWNER}/halted/actions`), /Hosted runners are paused on this instance by a site administrator/);
2701 await push(".github/workflows/hosted.yml", "name: hosted\non: push\njobs:\n cloud:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n");
2702 const hosted = await until("the hosted job to fail", async () => {
2703 const run = (await runs()).find((r) => r.name === "hosted");
2704 if (!run) return null;
2705 const [job] = (await ok("GET", `${R}/actions/runs/${run.id}/jobs`)).jobs;
2706 return job?.status === "completed" ? { run: run.id, job } : null;
2707 });
2708 assert.equal(hosted.job.conclusion, "failure");
2709 assert.match(await html(`/${OWNER}/halted/actions/runs/${hosted.run}`), /The job was not started: Hosted runners are paused on this instance by a site administrator: cost overrun/);
2710 // The self-hosted job of the same push is still handed to a runner.
2711 const claim = await until("a self-hosted job claimed", async () => {
2712 const r = await runnerClaim(R, ["linux"]);
2713 return r.status === 200 ? r.json : null;
2714 });
2715 await fetch(`${base}/runner/jobs/${claim.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${claim.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
2716 assert.equal((await ok("DELETE", P, undefined, T.sully)).paused, false);
2717 assert.doesNotMatch(await html("/settings/admin", T.sully), /Hosted compute is paused/);
2718 assert.notEqual((await api("POST", `${R}/diffinery/sandboxes`, {})).status, 403);
2719 await until("the pause's audit entries", async () => auditLog("compute.pause").some((e) => e.actor_login === "sully" && JSON.parse(e.detail).reason === "cost overrun") && auditLog("compute.unpause").length > 0);
2720 } finally {
2721 for (const path of [S, A, P]) await api("DELETE", path, undefined, T.sully);
2722 }
2723});
2724
2725test("security: Markdown images from other sites load through Diffinery's signed image proxy", async () => {
2726 // A stand-in for another site, which records what it is sent.
2727 const seen = [];
2728 const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63f8ffff3f0005fe02fea7d6a4c50000000049454e44ae426082", "hex");
2729 const site = createHttpServer((req, res) => {
2730 seen.push({ url: req.url, headers: req.headers });
2731 if (req.url === "/pixel.png") return res.writeHead(200, { "content-type": "image/png", "cache-control": "max-age=3600" }).end(PNG);
2732 if (req.url === "/moved.png") return res.writeHead(302, { location: "/pixel.png" }).end();
2733 if (req.url === "/page.html") return res.writeHead(200, { "content-type": "text/html" }).end("<script>alert(1)</script>");
2734 if (req.url === "/drawing.svg") return res.writeHead(200, { "content-type": "image/svg+xml" }).end('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>');
2735 res.writeHead(404).end();
2736 });
2737 await new Promise((r) => site.listen(0, "127.0.0.1", r));
2738 const other = `http://127.0.0.1:${site.address().port}`;
2739 try {
2740 await repoWithReadme("pictures");
2741 const body = [`![pixel](${other}/pixel.png)`, `[![moved](${other}/moved.png)](${other}/page.html)`, `![page](${other}/page.html)`, `![drawing](${other}/drawing.svg)`, "![own](/static/none.png)"].join("\n\n");
2742 const issue = await ok("POST", `/repos/${OWNER}/pictures/issues`, { title: "pictures", body });
2743 const page = await fetch(`${base}/${OWNER}/pictures/issues/${issue.number}`, { headers: { cookie: `__Host-dfy_session=${S.olive}` } });
2744 assert.equal(page.status, 200);
2745 const csp = page.headers.get("content-security-policy") ?? "";
2746 assert.match(csp, /img-src 'self' data: blob:(;|$)/);
2747 assert.doesNotMatch(csp, /img-src[^;]*https:/);
2748 const html = await page.text();
2749 const srcs = [...html.matchAll(/<img src="([^"]*)" alt="(pixel|moved|page|drawing|own)"/g)].map((m) => [m[2], m[1].replaceAll("&amp;", "&")]);
2750 const src = Object.fromEntries(srcs);
2751 assert.deepEqual(Object.keys(src).sort(), ["drawing", "moved", "own", "page", "pixel"]);
2752 for (const name of ["pixel", "moved", "page", "drawing"]) assert.match(src[name], /^\/-\/camo\/[\w-]{43}\/[\w-]+$/, name);
2753 assert.equal(src.own, `/${OWNER}/pictures/raw/main/static/none.png`);
2754 assert.ok(!html.includes(`src="${other}`), "no image loads from the other site directly");
2755 // Links keep their original target.
2756 assert.ok(html.includes(`href="${other}/page.html"`));
2757 assert.equal(seen.length, 0, "rendering fetches nothing");
2758
2759 // The proxy fetches the image without the viewer's cookies, and answers from its cache next time.
2760 const get = (path, init = {}) => fetch(`${base}${path}`, init);
2761 const first = await get(src.pixel, { headers: { cookie: `__Host-dfy_session=${S.olive}`, "user-agent": "viewer-browser/1" } });
2762 assert.equal(first.status, 200);
2763 assert.equal(first.headers.get("content-type"), "image/png");
2764 assert.equal(first.headers.get("x-content-type-options"), "nosniff");
2765 assert.match(first.headers.get("cache-control") ?? "", /^public, max-age=3600$/);
2766 assert.equal(first.headers.get("set-cookie"), null);
2767 assert.deepEqual(Buffer.from(await first.arrayBuffer()), PNG);
2768 assert.equal(seen.length, 1);
2769 assert.equal(seen[0].headers.cookie, undefined);
2770 assert.match(seen[0].headers["user-agent"] ?? "", /^Diffinery-Camo/);
2771 assert.equal((await get(src.pixel)).status, 200);
2772 assert.equal(seen.filter((r) => r.url === "/pixel.png").length, 1, "the second view is served from the cache");
2773
2774 // Redirects are followed; HTML is refused; SVG can't run scripts.
2775 assert.equal((await get(src.moved)).status, 200);
2776 assert.equal((await get(src.page)).status, 404);
2777 const svg = await get(src.drawing);
2778 assert.equal(svg.status, 200);
2779 assert.equal(svg.headers.get("content-type"), "image/svg+xml");
2780 assert.equal(svg.headers.get("content-security-policy"), "default-src 'none'; style-src 'unsafe-inline'; sandbox");
2781
2782 // Only URLs Diffinery signed: a tampered signature or URL, or one Diffinery never signed, is a 404 that fetches nothing.
2783 const before = seen.length;
2784 const [, , , sig, enc] = src.pixel.split("/");
2785 const evil = Buffer.from(`${other}/page.html?x`).toString("base64url");
2786 for (const path of [`/-/camo/${sig}/${evil}`, `/-/camo/${sig.slice(0, -2)}AA/${enc}`, `/-/camo/x/${enc}`, `/-/camo/${sig}`, `/-/camo/${"A".repeat(43)}/${Buffer.from(base).toString("base64url")}`]) {
2787 assert.equal((await get(path)).status, 404, path);
2788 }
2789 assert.equal(seen.length, before);
2790 } finally {
2791 site.close();
2792 }
2793});