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.

3079 lines · 186.5 KBRaw History
1// End-to-end: a real `wrangler dev` Worker, the real git CLI and the real runner agent.
2//
3// pnpm --filter @diffinery/runner build && pnpm --filter @diffinery/app e2e
4//
5// Covers: token auth, repo creation, git push/clone/fetch (protocol v2), push
6// protection, workflows triggered by push and pull_request and executed by a
7// self-hosted runner (the same agent that runs in Cloudflare Containers),
8// check runs, branch protection with required checks and human review for
9// agent-authored PRs, merging, the REST contents API, the MCP server and
10// profile pictures (WASM image processing in the Worker).
11import { spawn, spawnSync, execFileSync } from "node:child_process";
12import { mkdtempSync, writeFileSync, mkdirSync, readFileSync, existsSync, rmSync, openSync } from "node:fs";
13import { tmpdir } from "node:os";
14import { createHash, randomBytes } from "node:crypto";
15import { join, dirname, resolve } from "node:path";
16import { fileURLToPath } from "node:url";
17import { createServer } from "node:net";
18import { crc32, deflateSync } from "node:zlib";
19import { test, describe, before, after } from "node:test";
20import assert from "node:assert/strict";
21import { fakeGitHub, lfsObject } from "./fake-github.mjs";
22import { migratedState } from "./d1-state.mjs";
23
24const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
25const AGENT = resolve(APP, "../../containers/runner/dist/agent.mjs");
26const work = mkdtempSync(join(tmpdir(), "diffinery-e2e-"));
27let base;
28/** The shared server's Worker itself, behind wrangler dev's proxy (see startServer). */
29let direct;
30// The dev server writes to a file, not a pipe: a long synchronous git command keeps this process
31// from reading a pipe, and a full one (retried webhooks log a stack each) stalls the server mid-push.
32const devLogFile = join(work, "wrangler.log");
33const devLog = () => (existsSync(devLogFile) ? readFileSync(devLogFile, "utf8") : "");
34let token;
35let agentToken;
36
37const freePort = () =>
38 new Promise((res) => {
39 const s = createServer();
40 s.listen(0, "127.0.0.1", () => {
41 const { port } = s.address();
42 s.close(() => res(port));
43 });
44 });
45
46async function api(method, path, body, tok = token) {
47 const send = () =>
48 fetch(`${base}/api/v3${path}`, {
49 method,
50 headers: { ...(tok === null ? {} : { authorization: `Bearer ${tok}` }), "content-type": "application/json" },
51 body: body === undefined ? undefined : JSON.stringify(body),
52 });
53 // After minutes of git traffic alone, the kept-alive connection from the last API call may have
54 // been closed by the dev server just as it is reused ("other side closed"): a GET is sent again.
55 let res;
56 for (let i = 0; ; i++) {
57 try {
58 res = await send();
59 break;
60 } catch (e) {
61 if (method !== "GET" || i >= 2) throw new Error(`${method} ${path}: ${e.message} (${e.cause?.code ?? e.cause})\n--- wrangler log tail ---\n${devLog().slice(-3000)}`);
62 await sleep(1000);
63 }
64 }
65 const text = await res.text();
66 let json = null;
67 try {
68 json = text ? JSON.parse(text) : null;
69 } catch {
70 json = text;
71 }
72 return { status: res.status, json };
73}
74
75/**
76 * Claim a waiting self-hosted job as a registered runner offering `labels`, the way `diffinery runner`
77 * does (personal tokens can't claim jobs): one runner per repository and set of labels.
78 */
79const e2eRunners = new Map();
80async function runnerClaim(repoPath, labels = ["linux"]) {
81 const key = `${repoPath} ${labels.join(",")}`;
82 if (!e2eRunners.has(key)) {
83 const reg = await api("POST", `${repoPath}/actions/runners/registration-token`);
84 assert.equal(reg.status, 201, JSON.stringify(reg.json));
85 const runner = await api("POST", `${repoPath}/actions/runners/register`, { registration_token: reg.json.token, name: `e2e-runner-${e2eRunners.size + 1}`, labels });
86 assert.equal(runner.status, 201, JSON.stringify(runner.json));
87 e2eRunners.set(key, runner.json.token);
88 }
89 const r = await api("POST", `${repoPath}/actions/runners/claim`, {}, e2eRunners.get(key));
90 // A repository deleted and created again under the same name needs a new runner.
91 if (r.status !== 401) return r;
92 e2eRunners.delete(key);
93 return runnerClaim(repoPath, labels);
94}
95async function ok(method, path, body, tok) {
96 const r = await api(method, path, body, tok);
97 assert.ok(r.status >= 200 && r.status < 300, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
98 return r.json;
99}
100
101function git(cwd, args, tok = token, opts = {}) {
102 const auth = Buffer.from(`x-token:${tok}`).toString("base64");
103 try {
104 return execFileSync("git", ["-c", `http.extraHeader=Authorization: Basic ${auth}`, "-c", "protocol.version=2", ...args], {
105 cwd,
106 encoding: "utf8",
107 stdio: ["ignore", "pipe", "pipe"],
108 env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_AUTHOR_NAME: "E2E", GIT_AUTHOR_EMAIL: "e2e@example.com", GIT_COMMITTER_NAME: "E2E", GIT_COMMITTER_EMAIL: "e2e@example.com" },
109 ...opts,
110 });
111 } catch (e) {
112 // What the server said, for a git command that wasn't meant to fail (gitFails reads stderr, not this).
113 if (/HTTP 5\d\d/.test(e.stderr ?? "")) e.message += `\n--- wrangler log tail ---\n${devLog().slice(-4000)}`;
114 throw e;
115 }
116}
117function gitFails(cwd, args, tok) {
118 try {
119 git(cwd, args, tok);
120 } catch (e) {
121 return `${e.stdout ?? ""}${e.stderr ?? ""}`;
122 }
123 assert.fail(`expected git ${args.join(" ")} to fail`);
124}
125
126const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
127async function until(what, fn, timeoutMs = 60_000) {
128 const end = Date.now() + timeoutMs;
129 let last;
130 while (Date.now() < end) {
131 last = await fn();
132 if (last) return last;
133 await sleep(500);
134 }
135 assert.fail(`timed out waiting for ${what}\n--- wrangler log tail ---\n${devLog().slice(-4000)}`);
136}
137
138function spawnAsync(cmd, args, env, timeoutMs) {
139 return new Promise((done) => {
140 const child = spawn(cmd, args, { env: { ...process.env, ...env } });
141 let stdout = "";
142 let stderr = "";
143 child.stdout.on("data", (d) => (stdout += d));
144 child.stderr.on("data", (d) => (stderr += d));
145 const t = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
146 child.on("close", (status) => {
147 clearTimeout(t);
148 done({ status, stdout, stderr });
149 });
150 });
151}
152
153/**
154 * Claim one waiting self-hosted job and run it with the real agent.
155 * `envFor(claim)` adds environment for the agent (e.g. HOME, DIFFINERY_DISABLE_BUILTINS).
156 */
157async function runOneJob(owner, repo, { allowFailure = false, envFor = () => ({}), timeoutMs = 180_000, labels = ["linux"] } = {}) {
158 const claim = await until("a job to claim", async () => {
159 const r = await runnerClaim(`/repos/${owner}/${repo}`, labels);
160 return r.status === 200 ? r.json : null;
161 });
162 const jobEnv = { ...envFor(claim), DIFFINERY_API_URL: claim.api_url, DIFFINERY_JOB_ID: claim.job_id, DIFFINERY_JOB_TOKEN: claim.token };
163 // E2E_RUNNER_IMAGE runs the job inside the real runner image instead of the local agent bundle.
164 const image = process.env.E2E_RUNNER_IMAGE;
165 // Spawned asynchronously: a blocked event loop leaves undici holding keep-alive sockets the server already closed.
166 const r = image
167 ? await spawnAsync("docker", ["run", "--rm", "--network", "host", ...Object.entries(jobEnv).flatMap(([k, v]) => ["-e", `${k}=${v}`]), image], {}, timeoutMs + 120_000)
168 : await spawnAsync(process.execPath, [AGENT], { ...process.env, ...jobEnv, DIFFINERY_WORK_ROOT: join(work, `job-${claim.job_id}`) }, timeoutMs);
169 const out = `${r.stdout}${r.stderr}`;
170 if (r.status !== 0 && !allowFailure) {
171 const log = await fetch(`${base}/api/v3/repos/${owner}/${repo}/actions/jobs/${claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } }).then((x) => x.text(), (e) => String(e));
172 const job = await api("GET", `/repos/${owner}/${repo}/actions/jobs/${claim.job_id}`).catch((e) => ({ json: String(e) }));
173 assert.fail(`runner agent exited ${r.status}:\n${out}\n--- job ---\n${JSON.stringify(job.json, null, 2)}\n--- job log ---\n${log}\n--- wrangler log tail ---\n${devLog().slice(-3000)}`);
174 }
175 return { claim, out };
176}
177
178/**
179 * A `wrangler dev` server of its own with an admin token. Most tests share the one before() starts;
180 * the real histories each push to their own, so they run side by side on separate processes.
181 */
182const servers = [];
183async function startServer(name = "") {
184 const port = await freePort();
185 const url = `http://127.0.0.1:${port}`;
186 const persist = join(work, name ? `state-${name}` : "state");
187 const logFile = name ? join(work, `wrangler-${name}.log`) : devLogFile;
188 const debugLogFile = join(work, name ? `wrangler-debug-${name}.log` : "wrangler-debug.log");
189 const log = () => (existsSync(logFile) ? readFileSync(logFile, "utf8") : "");
190 migratedState(APP, persist);
191 // Until the web UI exists, run the same app through the API-only entry.
192 const entry = existsSync(join(APP, "src/web/routes.tsx")) ? [] : ["test/e2e/entry.ts"];
193 const out = openSync(logFile, "a");
194 const child = spawn("pnpm", ["exec", "wrangler", "dev", ...entry, "-e", "dev", "--ip", "127.0.0.1", "--port", String(port), "--inspector-port", String(await freePort()), "--persist-to", persist, "--var", `PUBLIC_URL:${url}`, "--var", `MASTER_KEY:${randomBytes(32).toString("base64")}`, "--var", "SCHEDULE_TICK_MINUTES:1", "--show-interactive-dev-session=false"], {
195 cwd: APP,
196 env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false", WRANGLER_LOG_PATH: debugLogFile },
197 stdio: ["ignore", out, out],
198 detached: true,
199 });
200 servers.push(child);
201 const end = Date.now() + 120_000;
202 while (!(await fetch(`${url}/healthz`).then((r) => r.ok, () => false))) {
203 if (Date.now() > end) assert.fail(`timed out waiting for wrangler dev${name ? ` (${name})` : ""}\n--- wrangler log tail ---\n${log().slice(-4000)}`);
204 await sleep(500);
205 }
206 // DEV_AUTH signs requests without credentials in as dev@diffinery.local; mint a real token for everything else.
207 const res = await fetch(`${url}/api/v3/diffinery/tokens`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "e2e", scopes: ["admin"] }) });
208 assert.equal(res.status, 201, await res.clone().text());
209 const stop = () => {
210 try {
211 process.kill(-child.pid, "SIGTERM");
212 } catch {}
213 };
214 return { base: url, direct: workerUrl(debugLogFile), workerUrl: () => workerUrl(debugLogFile), token: (await res.json()).token, log, stop };
215}
216
217/**
218 * wrangler dev answers on `base` through a proxy Worker of its own, which drops one of several large
219 * pushes streaming through it at once ("Error inside ProxyWorker ... Network connection lost": the
220 * push never reaches our Worker; 3 of 5 runs of three pushes, none of 5 sent to the Worker itself).
221 * Its debug log names the Worker's own address; null if it doesn't.
222 */
223function workerUrl(debugLogFile) {
224 const log = existsSync(debugLogFile) ? readFileSync(debugLogFile, "utf8") : "";
225 const at = [...log.matchAll(/"userWorkerUrl":\{"protocol":"(https?:)","hostname":"([^"]+)","port":"(\d+)"/g)].pop();
226 return at ? `${at[1]}//${at[2]}:${at[3]}` : null;
227}
228
229before(async () => {
230 assert.ok(existsSync(AGENT), `build the runner first: pnpm --filter @diffinery/runner build (missing ${AGENT})`);
231 ({ base, direct, token } = await startServer());
232});
233
234after(() => {
235 for (const dev of servers) {
236 try {
237 process.kill(-dev.pid, "SIGTERM");
238 } catch {}
239 }
240 if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true });
241});
242
243// Scheduled workflows: the dev environment has no cron trigger, like a deploy whose cron trigger
244// hasn't been applied yet, so schedules must fire from the scheduler's own alarm. The schedule is
245// registered first and checked by the last test, so its ticks (1 minute here) come while the rest runs.
246let tickRepo;
247test("scheduled workflows: a push to the default branch registers the schedule", async () => {
248 const me = await ok("GET", "/user");
249 tickRepo = `${me.login}/schedules`;
250 await ok("POST", "/user/repos", { name: "schedules" });
251 const src = join(work, "schedules");
252 mkdirSync(join(src, ".github/workflows"), { recursive: true });
253 writeFileSync(join(src, ".github/workflows/tick.yml"), `on:\n schedule:\n - cron: "* * * * *"\njobs:\n tick:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo tick\n`);
254 git(src, ["init", "-q", "-b", "main"]);
255 git(src, ["add", "-A"]);
256 git(src, ["commit", "-q", "-m", "schedule"]);
257 git(src, ["push", "-q", `${base}/${tickRepo}.git`, "main"]);
258});
259
260test("git hosting, Actions, protected PR flow and MCP", async () => {
261 const me = await ok("GET", "/user");
262 const owner = me.login;
263 assert.ok(me.site_admin, "dev user is a bootstrap admin");
264
265 // ------------------------------------------------------------ repo + first push
266 const repo = await ok("POST", "/user/repos", { name: "demo", description: "e2e" });
267 assert.equal(repo.full_name, `${owner}/demo`);
268 const src = join(work, "src");
269 mkdirSync(join(src, ".github/workflows"), { recursive: true });
270 writeFileSync(join(src, "README.md"), "# demo\n");
271 writeFileSync(join(src, "app.txt"), "one\ntwo\nthree\n");
272 writeFileSync(
273 join(src, ".github/workflows/ci.yml"),
274 `name: CI
275on:
276 push:
277 branches: [main]
278 pull_request:
279jobs:
280 build:
281 runs-on: [self-hosted, linux]
282 steps:
283 - uses: actions/checkout@v4
284 - name: Check files
285 run: |
286 test -f README.md
287 echo "event=\${{ github.event_name }} sha=\${{ github.sha }}"
288 grep -q bad app.txt && { echo "found bad line"; exit 1; } || true
289 - id: out
290 run: echo "lines=$(wc -l < app.txt | tr -d ' ')" >> "$GITHUB_OUTPUT"
291 - run: echo "app.txt has \${{ steps.out.outputs.lines }} lines"
292`,
293 );
294 git(src, ["init", "-q", "-b", "main"]);
295 git(src, ["add", "-A"]);
296 git(src, ["commit", "-q", "-m", "initial"]);
297 git(src, ["remote", "add", "origin", `${base}/${owner}/demo.git`]);
298 git(src, ["push", "-q", "origin", "main"]);
299 const mainSha = git(src, ["rev-parse", "HEAD"]).trim();
300
301 const branch = await ok("GET", `/repos/${owner}/demo/branches/main`);
302 assert.equal(branch.commit.sha, mainSha);
303
304 // ------------------------------------------------------------ the push ran CI on a self-hosted runner
305 const pushRun = await until("push run", async () => (await ok("GET", `/repos/${owner}/demo/actions/runs?event=push`)).workflow_runs[0]);
306 assert.equal(pushRun.head_sha, mainSha);
307 const job1 = await runOneJob(owner, "demo");
308 const finished = await until("push run to complete", async () => {
309 const r = await ok("GET", `/repos/${owner}/demo/actions/runs/${pushRun.id}`);
310 return r.status === "completed" ? r : null;
311 });
312 assert.equal(finished.conclusion, "success", job1.out);
313 const logs = await (await fetch(`${base}/api/v3/repos/${owner}/demo/actions/jobs/${job1.claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
314 assert.match(logs, /event=push/);
315 assert.match(logs, /app\.txt has 3 lines/);
316 const checks = await ok("GET", `/repos/${owner}/demo/commits/${mainSha}/check-runs`);
317 assert.equal(checks.check_runs.find((c) => c.name === "CI / build")?.conclusion, "success");
318
319 // ------------------------------------------------------------ clone over protocol v2
320 const clone = join(work, "clone");
321 git(work, ["clone", "-q", `${base}/${owner}/demo.git`, clone]);
322 assert.equal(readFileSync(join(clone, "app.txt"), "utf8"), "one\ntwo\nthree\n");
323
324 // ------------------------------------------------------------ secrets are blocked on push
325 // The key below is a fake that push protection must block in the pushed file; this
326 // marker exempts only the test source itself: diffinery:allow-secret
327 writeFileSync(join(clone, "config.env"), "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPL3\n");
328 git(clone, ["add", "-A"]);
329 git(clone, ["commit", "-q", "-m", "oops"]);
330 assert.match(gitFails(clone, ["push", "origin", "main"]), /secret|AWS/i);
331 // Objects from a blocked push are not kept, so retrying (even with push negotiation) is blocked too.
332 assert.match(gitFails(clone, ["-c", "push.negotiate=true", "push", "origin", "HEAD:refs/heads/fixture"]), /secret|AWS/i);
333 // A repository admin can push anyway by giving a reason; the bypass is audited.
334 assert.match(gitFails(clone, ["push", "-o", "allow-secrets=", "origin", "HEAD:refs/heads/fixture"]), /secret|AWS/i);
335 git(clone, ["push", "-q", "-o", "allow-secrets=fake key used by this test", "origin", "HEAD:refs/heads/fixture"]);
336 assert.ok((await ok("GET", `/repos/${owner}/demo/branches`)).some((b) => b.name === "fixture"));
337 git(clone, ["push", "-q", "origin", ":refs/heads/fixture"]);
338 git(clone, ["reset", "-q", "--hard", "origin/main"]);
339
340 // ------------------------------------------------------------ protect main: PR + green CI + review
341 await ok("PUT", `/repos/${owner}/demo/branches/main/protection`, {
342 requirePullRequest: true,
343 requiredApprovals: 0,
344 dismissStaleReviews: true,
345 requiredChecks: ["CI / build"],
346 allowForcePush: false,
347 allowDeletion: false,
348 requireLinearHistory: false,
349 enforceAdmins: true,
350 agentsMayPush: false,
351 agentsMayMerge: false,
352 });
353 writeFileSync(join(clone, "app.txt"), "one\ntwo\nthree\nfour\n");
354 git(clone, ["commit", "-q", "-am", "direct push"]);
355 assert.match(gitFails(clone, ["push", "origin", "main"]), /pull request|protected/i);
356 git(clone, ["reset", "-q", "--hard", "origin/main"]);
357
358 // ------------------------------------------------------------ an AI agent opens a PR
359 const created = await ok("POST", "/diffinery/agents", { login: "e2e-bot", name: "E2E Bot" }, null);
360 agentToken = created.token.token;
361 const agentClone = join(work, "agent");
362 git(work, ["clone", "-q", `${base}/${owner}/demo.git`, agentClone], agentToken);
363 git(agentClone, ["checkout", "-q", "-b", "feature"], agentToken);
364 writeFileSync(join(agentClone, "app.txt"), "one\ntwo\nthree\nfour\n");
365 git(agentClone, ["commit", "-q", "-am", "Add a fourth line"], agentToken);
366 assert.match(gitFails(agentClone, ["push", "origin", "HEAD:main"], agentToken), /agent|protected|pull request/i);
367 // push.negotiate=true makes git run a protocol v2 fetch with wait-for-done before pushing.
368 const negotiated = spawnSync("git", ["-c", `http.extraHeader=Authorization: Basic ${Buffer.from(`x-token:${agentToken}`).toString("base64")}`, "-c", "protocol.version=2", "-c", "push.negotiate=true", "push", "-q", "origin", "feature"], { cwd: agentClone, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
369 assert.equal(negotiated.status, 0, negotiated.stderr);
370 assert.doesNotMatch(negotiated.stderr, /negotiation failed|unexpected/i);
371 const pr = await ok("POST", `/repos/${owner}/demo/pulls`, { title: "Add a fourth line", head: "feature", base: "main", intent: "Extend app.txt for the e2e test" }, agentToken);
372 assert.equal(pr.number, 1);
373
374 // An agent may start an empty repository's default branch (as auto_init would), and then only through pull requests.
375 await ok("POST", "/user/repos", { name: "agent-seeded", private: true });
376 const seed = join(work, "agent-seeded");
377 git(work, ["init", "-q", "-b", "main", seed]);
378 mkdirSync(join(seed, ".github/workflows"), { recursive: true });
379 writeFileSync(join(seed, ".github/workflows/ci.yml"), "on: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: true\n");
380 writeFileSync(join(seed, "README.md"), "# seeded by an agent\n");
381 git(seed, ["add", "-A"]);
382 git(seed, ["commit", "-q", "-m", "Initial commit"]);
383 // Not with workflow files: those reach the default branch only through a pull request a person merges.
384 assert.match(gitFails(seed, ["push", `${base}/${owner}/agent-seeded.git`, "main"], agentToken), /can't add workflow file `\.github\/workflows\/ci\.yml`/);
385 git(seed, ["rm", "-q", "-r", ".github"]);
386 git(seed, ["commit", "-q", "--amend", "-m", "Initial commit"]);
387 git(seed, ["push", "-q", `${base}/${owner}/agent-seeded.git`, "main"], agentToken);
388 writeFileSync(join(seed, "README.md"), "# changed\n");
389 git(seed, ["commit", "-q", "-am", "Second commit"]);
390 assert.match(gitFails(seed, ["push", `${base}/${owner}/agent-seeded.git`, "main"], agentToken), /agents may not push to protected or default branches/);
391
392 // The pull_request run executes; until then the PR is blocked on the required check.
393 let m = await ok("GET", `/repos/${owner}/demo/pulls/1/merge`);
394 assert.equal(m.mergeable, false);
395 await runOneJob(owner, "demo");
396 await until("PR check to pass", async () => {
397 const r = await ok("GET", `/repos/${owner}/demo/pulls/1/merge`);
398 return r.checks?.length > 0 && r.checks.every((c) => c.state === "success") ? r : null;
399 });
400 m = await ok("GET", `/repos/${owner}/demo/pulls/1/merge`);
401 assert.equal(m.mergeable, false, "agent-authored PRs need a human approval");
402 assert.ok(JSON.stringify(m.blockers).match(/approv|human/i), JSON.stringify(m.blockers));
403
404 // The agent cannot approve or merge its own work.
405 const agentMerge = await api("PUT", `/repos/${owner}/demo/pulls/1/merge`, { merge_method: "squash" }, agentToken);
406 assert.ok([403, 405, 409].includes(agentMerge.status), JSON.stringify(agentMerge));
407
408 // Another agent's approval is advisory and does not unblock the merge.
409 const reviewer = (await ok("POST", "/diffinery/agents", { login: "e2e-reviewer" }, null)).token.token;
410 await ok("POST", `/repos/${owner}/demo/pulls/1/reviews`, { event: "APPROVE", body: "bot says ok" }, reviewer);
411 assert.equal((await ok("GET", `/repos/${owner}/demo/pulls/1/merge`)).mergeable, false);
412
413 // A human reviews (line comment + approval) and merges.
414 await ok("POST", `/repos/${owner}/demo/pulls/1/reviews`, { event: "APPROVE", body: "LGTM", comments: [{ path: "app.txt", line: 4, body: "nice line" }] });
415 m = await ok("GET", `/repos/${owner}/demo/pulls/1/merge`);
416 assert.equal(m.mergeable, true, JSON.stringify(m));
417 const merged = await ok("PUT", `/repos/${owner}/demo/pulls/1/merge`, { merge_method: "squash", delete_branch: true });
418 assert.ok(merged.sha);
419 const prAfter = await ok("GET", `/repos/${owner}/demo/pulls/1`);
420 assert.equal(prAfter.merged, true);
421
422 // ------------------------------------------------------------ fetch the merge, read through REST
423 git(clone, ["pull", "-q", "--ff-only", "origin", "main"]);
424 assert.equal(readFileSync(join(clone, "app.txt"), "utf8"), "one\ntwo\nthree\nfour\n");
425 const content = await ok("GET", `/repos/${owner}/demo/contents/app.txt`);
426 assert.equal(Buffer.from(content.content, "base64").toString(), "one\ntwo\nthree\nfour\n");
427 const branches = await ok("GET", `/repos/${owner}/demo/branches`);
428 assert.ok(!branches.some((b) => b.name === "feature"), "head branch deleted after merge");
429
430 // ------------------------------------------------------------ shallow clone, then deepen
431 const shallow = join(work, "shallow");
432 git(work, ["clone", "-q", "--depth", "1", `${base}/${owner}/demo.git`, shallow]);
433 assert.equal(git(shallow, ["rev-list", "--count", "HEAD"]).trim(), "1");
434 assert.equal(readFileSync(join(shallow, "app.txt"), "utf8"), "one\ntwo\nthree\nfour\n");
435 git(shallow, ["fetch", "-q", "--unshallow"]);
436 assert.equal(git(shallow, ["rev-list", "--count", "HEAD"]).trim(), "2");
437 git(shallow, ["fsck", "--no-progress"]);
438
439 // ------------------------------------------------------------ MCP: the agent works without git
440 const rpc = async (method, params, id = 1) => {
441 const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${agentToken}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id, method, params }) });
442 assert.equal(r.status, 200);
443 return (await r.json()).result;
444 };
445 const init = await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "e2e", version: "1" } });
446 assert.equal(init.serverInfo.name, "diffinery");
447 const tools = await rpc("tools/list", {});
448 assert.ok(tools.tools.some((t) => t.name === "commit_files"));
449 const file = await rpc("tools/call", { name: "get_file", arguments: { owner, repo: "demo", path: "README.md" } });
450 assert.equal(file.isError, false);
451 assert.equal(file.structuredContent.content, "# demo\n");
452 const commit = await rpc("tools/call", { name: "commit_files", arguments: { owner, repo: "demo", branch: "mcp-change", create_branch_from: "main", message: "Edit via MCP", files: [{ path: "docs/notes.md", content: "hello\n" }] } });
453 assert.equal(commit.isError, false, JSON.stringify(commit));
454 const blocked = await rpc("tools/call", { name: "commit_files", arguments: { owner, repo: "demo", branch: "main", message: "sneaky", files: [{ path: "x", content: "y" }] } });
455 assert.equal(blocked.isError, true);
456 const opened = await rpc("tools/call", { name: "create_pull_request", arguments: { owner, repo: "demo", title: "Notes", head: "mcp-change", intent: "Add notes" } });
457 assert.equal(opened.isError, false, JSON.stringify(opened));
458 assert.equal(opened.structuredContent.number, 2);
459
460 // ------------------------------------------------------------ web UI renders the same data (signed in via DEV_AUTH)
461 for (const path of ["/", `/${owner}`, `/${owner}/demo`, `/${owner}/demo/blob/main/app.txt`, `/${owner}/demo/commits/main`, `/${owner}/demo/pulls`, `/${owner}/demo/pull/1`, `/${owner}/demo/pull/1/files`, `/${owner}/demo/actions`, `/${owner}/demo/actions/runs/${pushRun.id}`, `/${owner}/demo/actions/runs/${pushRun.id}/job/${job1.claim.job_id}`, `/${owner}/demo/settings/branches`, "/settings/tokens"]) {
462 const res = await fetch(`${base}${path}`);
463 const html = await res.text();
464 assert.equal(res.status, 200, `${path} -> ${res.status}\n${html.slice(0, 500)}`);
465 assert.match(res.headers.get("content-type") ?? "", /text\/html/, path);
466 }
467 assert.match(await (await fetch(`${base}/${owner}/demo/pull/1`)).text(), /Add a fourth line/);
468 const forged = await fetch(`${base}/${owner}/demo/issues/1/comment`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: "https://evil.example", "sec-fetch-site": "cross-site" }, body: "body=hi" });
469 assert.equal(forged.status, 403);
470
471 // ------------------------------------------------------------ the CLI against the same server
472 const CLI = resolve(APP, "../cli/dist/diffinery.mjs");
473 if (existsSync(CLI)) {
474 const cli = (...args) => execFileSync(process.execPath, [CLI, ...args], { encoding: "utf8", cwd: clone, env: { ...process.env, DIFFINERY_URL: base, DIFFINERY_TOKEN: token, NO_COLOR: "1", XDG_CONFIG_HOME: join(work, "cfg") } });
475 assert.match(cli("whoami"), new RegExp(owner));
476 const prs = JSON.parse(cli("pr", "list", "--state", "all", "--json"));
477 assert.ok(prs.some((p) => p.number === 1));
478 assert.match(cli("workflow", "validate"), /ci\.yml/);
479 }
480
481 // The commit made through MCP carries the agent's identity.
482 const agentCommit = await ok("GET", `/repos/${owner}/demo/commits/mcp-change`);
483 assert.match(JSON.stringify(agentCommit), /e2e-bot/);
484});
485
486test("reusable workflows: inputs, secrets, outputs, nesting and skipped calls", async () => {
487 const owner = (await ok("GET", "/user")).login;
488 await ok("POST", "/user/repos", { name: "reuse" });
489 await api("PUT", `/repos/${owner}/reuse/actions/secrets/TOPSECRET`, { value: "s3cret" });
490 const src = join(work, "reuse");
491 mkdirSync(join(src, ".github/workflows"), { recursive: true });
492 writeFileSync(
493 join(src, ".github/workflows/lib.yml"),
494 `on:
495 workflow_call:
496 inputs:
497 greeting: { type: string, required: true }
498 loud: { type: boolean, default: false }
499 secrets:
500 TOPSECRET: { required: true }
501 outputs:
502 word:
503 value: \${{ jobs.shout.outputs.word }}
504jobs:
505 say:
506 runs-on: [self-hosted, linux]
507 outputs:
508 word: \${{ steps.s.outputs.word }}
509 steps:
510 - id: s
511 run: echo "word=\${{ inputs.greeting }}-there" >> "$GITHUB_OUTPUT"
512 - run: echo "secret ok=\${{ secrets.TOPSECRET == 's3cret' }} loud=\${{ inputs.loud }} job=\${{ github.job }}"
513 shout:
514 needs: say
515 runs-on: [self-hosted, linux]
516 outputs:
517 word: \${{ steps.s.outputs.word }}
518 steps:
519 - id: s
520 run: echo "word=\${{ needs.say.outputs.word }}!" >> "$GITHUB_OUTPUT"
521`,
522 );
523 writeFileSync(
524 join(src, ".github/workflows/main.yml"),
525 `name: Main
526on: push
527jobs:
528 call:
529 name: Greeter
530 uses: ./.github/workflows/lib.yml
531 with:
532 greeting: \${{ github.event_name == 'push' && 'hi' || 'no' }}
533 loud: true
534 secrets: inherit
535 nope:
536 if: \${{ false }}
537 uses: ./.github/workflows/lib.yml
538 with:
539 greeting: never
540 secrets:
541 TOPSECRET: \${{ secrets.TOPSECRET }}
542 after:
543 needs: [call, nope]
544 if: \${{ always() }}
545 runs-on: [self-hosted, linux]
546 steps:
547 - run: echo "got=\${{ needs.call.outputs.word }} call=\${{ needs.call.result }} nope=\${{ needs.nope.result }}"
548`,
549 );
550 git(src, ["init", "-q", "-b", "main"]);
551 git(src, ["add", "."]);
552 git(src, ["commit", "-q", "-m", "reusable"]);
553 git(src, ["remote", "add", "origin", `${base}/${owner}/reuse.git`]);
554 git(src, ["push", "-q", "origin", "main"]);
555
556 const run = await until("reuse run", async () => (await ok("GET", `/repos/${owner}/reuse/actions/runs`)).workflow_runs[0]);
557 const logOf = async (id) => (await fetch(`${base}/api/v3/repos/${owner}/reuse/actions/jobs/${id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
558 const say = await runOneJob(owner, "reuse");
559 assert.equal(say.claim.name, "Greeter / say");
560 const sayLog = await logOf(say.claim.job_id);
561 assert.match(sayLog, /secret ok=true loud=true job=say/);
562 assert.doesNotMatch(sayLog, /s3cret/);
563 const shout = await runOneJob(owner, "reuse");
564 assert.equal(shout.claim.name, "Greeter / shout");
565 const after = await runOneJob(owner, "reuse");
566 assert.equal(after.claim.name, "after");
567 assert.match(await logOf(after.claim.job_id), /got=hi-there! call=success nope=skipped/);
568 const done = await until("reuse run to complete", async () => {
569 const r = await ok("GET", `/repos/${owner}/reuse/actions/runs/${run.id}`);
570 return r.status === "completed" ? r : null;
571 });
572 assert.equal(done.conclusion, "success");
573 const jobs = (await ok("GET", `/repos/${owner}/reuse/actions/runs/${run.id}/jobs`)).jobs;
574 assert.deepEqual(jobs.filter((j) => j.conclusion === "skipped").map((j) => j.name).sort(), ["nope / say", "nope / shout"]);
575});
576
577test("job graph: needs-only scheduling, skip cascades, per-leg runs-on, continue-on-error, job concurrency and public payloads", async () => {
578 const owner = (await ok("GET", "/user")).login;
579 await ok("POST", "/user/repos", { name: "graph", private: false });
580 const src = join(work, "graph");
581 mkdirSync(join(src, ".github/workflows"), { recursive: true });
582 writeFileSync(
583 join(src, ".github/workflows/graph.yml"),
584 `name: Graph
585on: push
586jobs:
587 slow:
588 runs-on: [self-hosted, e2e-slow]
589 steps:
590 - run: echo slow
591 fast:
592 runs-on: [self-hosted, linux]
593 steps:
594 - run: echo "private=\${{ github.event.repository.private }} visibility=\${{ github.event.repository.visibility }}"
595 after-fast:
596 needs: fast
597 runs-on: [self-hosted, linux]
598 steps:
599 - run: echo after-fast
600 gate:
601 if: \${{ github.event_name == 'nope' }}
602 runs-on: [self-hosted, linux]
603 steps:
604 - run: echo never
605 middle:
606 needs: gate
607 if: \${{ always() }}
608 runs-on: [self-hosted, linux]
609 steps:
610 - run: echo "gate=\${{ needs.gate.result }}"
611 leaf:
612 needs: middle
613 runs-on: [self-hosted, linux]
614 steps:
615 - run: echo leaf
616 rescued:
617 needs: middle
618 if: \${{ !cancelled() && !failure() }}
619 runs-on: [self-hosted, linux]
620 steps:
621 - run: echo "middle=\${{ needs.middle.result }}"
622 lanes:
623 name: lane \${{ matrix.lane }}
624 strategy:
625 matrix:
626 include:
627 - lane: red
628 runner: [self-hosted, e2e-red]
629 - lane: blue
630 runner: [self-hosted, e2e-blue]
631 runs-on: \${{ matrix.runner }}
632 continue-on-error: \${{ matrix.lane == 'red' }}
633 environment: e2e-\${{ matrix.lane }}-\${{ strategy.job-total }}
634 steps:
635 - run: echo "lane=\${{ matrix.lane }}" && test "\${{ matrix.lane }}" = blue
636 after-lanes:
637 needs: lanes
638 runs-on: [self-hosted, linux]
639 steps:
640 - run: echo "lanes=\${{ needs.lanes.result }}"
641 deploy:
642 strategy:
643 matrix:
644 target: [prod, staging]
645 concurrency: e2e-\${{ matrix.target }}
646 runs-on: [self-hosted, e2e-deploy]
647 steps:
648 - run: echo "deploy \${{ matrix.target }}"
649 hotfix:
650 strategy:
651 matrix:
652 target: [prod]
653 concurrency: e2e-\${{ matrix.target }}
654 runs-on: [self-hosted, e2e-deploy]
655 steps:
656 - run: echo "hotfix \${{ matrix.target }}"
657`,
658 );
659 git(src, ["init", "-q", "-b", "main"]);
660 git(src, ["add", "."]);
661 git(src, ["commit", "-q", "-m", "graph"]);
662 git(src, ["remote", "add", "origin", `${base}/${owner}/graph.git`]);
663 git(src, ["push", "-q", "origin", "main"]);
664
665 const run = await until("graph run", async () => (await ok("GET", `/repos/${owner}/graph/actions/runs`)).workflow_runs[0]);
666 const logOf = async (id) => (await fetch(`${base}/api/v3/repos/${owner}/graph/actions/jobs/${id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
667 const jobs = async () => (await ok("GET", `/repos/${owner}/graph/actions/runs/${run.id}/jobs`)).jobs;
668
669 // Jobs start when their own needs finish: after-fast and rescued run while slow (no runner offers e2e-slow) still waits.
670 const linux = {};
671 for (let i = 0; i < 4; i++) {
672 const j = await runOneJob(owner, "graph");
673 linux[j.claim.name] = j.claim.job_id;
674 }
675 assert.deepEqual(Object.keys(linux).sort(), ["after-fast", "fast", "middle", "rescued"]);
676 assert.equal((await jobs()).find((j) => j.name === "slow").status, "waiting");
677 assert.match(await logOf(linux.fast), /private=false visibility=public/);
678 assert.match(await logOf(linux.middle), /gate=skipped/);
679 assert.match(await logOf(linux.rescued), /middle=success/);
680
681 // runs-on per matrix leg; the red leg fails but continues on error, so fail-fast spares the blue one.
682 const red = await runOneJob(owner, "graph", { labels: ["e2e-red"], allowFailure: true });
683 assert.equal(red.claim.name, "lane red");
684 const blue = await runOneJob(owner, "graph", { labels: ["e2e-blue"] });
685 assert.equal(blue.claim.name, "lane blue");
686 const afterLanes = await runOneJob(owner, "graph");
687 assert.equal(afterLanes.claim.name, "after-lanes");
688 assert.match(await logOf(afterLanes.claim.job_id), /lanes=success/);
689 const envs = (await ok("GET", `/repos/${owner}/graph/environments`)).environments.map((e) => e.name);
690 assert.ok(envs.includes("e2e-red-2") && envs.includes("e2e-blue-2"), `per-leg environments: ${envs}`);
691
692 // Job-level concurrency, evaluated per leg: one of the two prod jobs waits as pending until the other finishes.
693 const pending = await until("a pending prod job", async () => (await jobs()).find((j) => j.status === "pending"));
694 assert.ok(["deploy (prod)", "hotfix (prod)"].includes(pending.name), pending.name);
695 const first = await runOneJob(owner, "graph", { labels: ["e2e-deploy"] });
696 const second = await runOneJob(owner, "graph", { labels: ["e2e-deploy"] });
697 assert.deepEqual([first.claim.name, second.claim.name].sort(), ["deploy (prod)", "deploy (staging)", "hotfix (prod)"].filter((n) => n !== pending.name).sort());
698 const third = await runOneJob(owner, "graph", { labels: ["e2e-deploy"] });
699 assert.equal(third.claim.name, pending.name);
700
701 const slow = await runOneJob(owner, "graph", { labels: ["e2e-slow"] });
702 assert.equal(slow.claim.name, "slow");
703 const done = await until("graph run to complete", async () => {
704 const r = await ok("GET", `/repos/${owner}/graph/actions/runs/${run.id}`);
705 return r.status === "completed" ? r : null;
706 });
707 assert.equal(done.conclusion, "success", "a failed leg with continue-on-error does not fail the run");
708 const byName = Object.fromEntries((await jobs()).map((j) => [j.name, j]));
709 assert.equal(byName.gate.conclusion, "skipped");
710 assert.equal(byName.leaf.conclusion, "skipped", "a skipped ancestor skips the jobs below it");
711 assert.equal(byName["lane red"].conclusion, "failure");
712 assert.equal(byName["lane blue"].conclusion, "success");
713});
714
715test("re-runs: failed jobs only keep what passed, and one job re-runs with what depends on it", async () => {
716 const owner = (await ok("GET", "/user")).login;
717 await ok("POST", "/user/repos", { name: "rerun", private: true });
718 const src = join(work, "rerun");
719 mkdirSync(join(src, ".github/workflows"), { recursive: true });
720 writeFileSync(
721 join(src, ".github/workflows/rerun.yml"),
722 `name: Rerun
723on: push
724jobs:
725 build:
726 runs-on: [self-hosted, linux]
727 steps:
728 - run: echo "built in attempt \${{ github.run_attempt }}"
729 test:
730 needs: build
731 strategy:
732 matrix:
733 n: [1, 2]
734 runs-on: [self-hosted, linux]
735 steps:
736 - run: echo "leg \${{ matrix.n }}" && { test "\${{ matrix.n }}" = 1 || test "\${{ github.run_attempt }}" != 1; }
737 report:
738 needs: test
739 runs-on: [self-hosted, linux]
740 steps:
741 - run: echo "report in attempt \${{ github.run_attempt }}"
742`,
743 );
744 git(src, ["init", "-q", "-b", "main"]);
745 git(src, ["add", "."]);
746 git(src, ["commit", "-q", "-m", "rerun"]);
747 git(src, ["remote", "add", "origin", `${base}/${owner}/rerun.git`]);
748 git(src, ["push", "-q", "origin", "main"]);
749 const R = `/repos/${owner}/rerun`;
750 const finished = (id) =>
751 until(`run ${id} to complete`, async () => {
752 const r = await ok("GET", `${R}/actions/runs/${id}`);
753 return r.status === "completed" ? r : null;
754 });
755 const jobsOf = async (id) => Object.fromEntries((await ok("GET", `${R}/actions/runs/${id}/jobs`)).jobs.map((j) => [j.name, j]));
756 const logOf = async (id) => (await fetch(`${base}/api/v3${R}/actions/jobs/${id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
757
758 // Attempt 1: leg 2 fails, so report is skipped.
759 const first = await until("the first run", async () => (await ok("GET", `${R}/actions/runs`)).workflow_runs[0]);
760 const claimed = [];
761 for (let i = 0; i < 3; i++) claimed.push((await runOneJob(owner, "rerun", { allowFailure: true })).claim.name);
762 assert.deepEqual(claimed, ["build", "test (1)", "test (2)"]);
763 assert.equal((await finished(first.id)).conclusion, "failure");
764 assert.equal((await jobsOf(first.id)).report.conclusion, "skipped");
765
766 // Re-run failed jobs: build and leg 1 are kept as they were; leg 2 and report run again.
767 const second = (await api("POST", `${R}/actions/runs/${first.id}/rerun-failed-jobs`, { enable_debug_logging: false })).json.run_id;
768 assert.ok(second);
769 const again = [];
770 for (let i = 0; i < 2; i++) again.push((await runOneJob(owner, "rerun")).claim.name);
771 assert.deepEqual(again, ["test (2)", "report"]);
772 const done = await finished(second);
773 assert.deepEqual([done.conclusion, done.run_attempt, done.run_number], ["success", 2, first.run_number]);
774 const kept = await jobsOf(second);
775 const before = await jobsOf(first.id);
776 assert.equal(kept.build.carriedFrom, before.build.id);
777 assert.equal(kept["test (1)"].carriedFrom, before["test (1)"].id);
778 assert.equal(kept["test (2)"].carriedFrom, null);
779 assert.match(await logOf(kept.build.id), /built in attempt 1/);
780 assert.match(await logOf(kept.report.id), /report in attempt 2/);
781 assert.equal((await runnerClaim(R, ["linux"])).status, 204, "nothing else waits for a runner");
782
783 // Nothing failed any more; re-running one job runs it and what depends on it (nothing here), keeping the rest.
784 const none = await api("POST", `${R}/actions/runs/${second}/rerun-failed-jobs`);
785 assert.deepEqual([none.status, none.json.message], [409, "this run has no failed jobs to re-run"]);
786 const third = (await ok("POST", `${R}/actions/jobs/${kept.report.id}/rerun`)).run_id;
787 assert.equal((await runOneJob(owner, "rerun")).claim.name, "report");
788 assert.equal((await finished(third)).conclusion, "success");
789 const last = await jobsOf(third);
790 assert.equal(last.build.carriedFrom, before.build.id, "a job kept twice points at the job that ran");
791 assert.equal(last["test (2)"].carriedFrom, kept["test (2)"].id);
792 assert.equal(last.report.carriedFrom, null);
793});
794
795test("workflow_run: a workflow follows another one on the default branch", async () => {
796 const owner = (await ok("GET", "/user")).login;
797 await ok("POST", "/user/repos", { name: "chain" });
798 const src = join(work, "chain");
799 mkdirSync(join(src, ".github/workflows"), { recursive: true });
800 writeFileSync(join(src, ".github/workflows/ci.yml"), `name: CI\non: push\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo built\n`);
801 writeFileSync(
802 join(src, ".github/workflows/after.yml"),
803 `name: After CI
804on:
805 workflow_run:
806 workflows: [CI]
807 types: [completed]
808 branches: [main]
809jobs:
810 report:
811 if: \${{ github.event.workflow_run.conclusion == 'success' }}
812 runs-on: [self-hosted, linux]
813 steps:
814 - run: echo "followed \${{ github.event.workflow_run.name }} on \${{ github.event.workflow_run.head_branch }} (\${{ github.event.action }}) ref=\${{ github.ref }}"
815`,
816 );
817 git(src, ["init", "-q", "-b", "main"]);
818 git(src, ["add", "."]);
819 git(src, ["commit", "-q", "-m", "chain"]);
820 git(src, ["remote", "add", "origin", `${base}/${owner}/chain.git`]);
821 git(src, ["push", "-q", "origin", "main"]);
822
823 const runs = async () => (await ok("GET", `/repos/${owner}/chain/actions/runs`)).workflow_runs;
824 await until("CI run", async () => (await runs()).find((r) => r.name === "CI"));
825 assert.equal((await runs()).length, 1, "only CI runs before it completes");
826 const build = await runOneJob(owner, "chain");
827 assert.equal(build.claim.name, "build");
828 const follower = await until("follower run", async () => (await runs()).find((r) => r.event === "workflow_run"));
829 assert.equal(follower.name, "After CI");
830 assert.equal(follower.head_branch, "main");
831 const report = await runOneJob(owner, "chain");
832 assert.equal(report.claim.name, "report");
833 const log = await (await fetch(`${base}/api/v3/repos/${owner}/chain/actions/jobs/${report.claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
834 assert.match(log, /followed CI on main \(completed\) ref=refs\/heads\/main/);
835 const done = await until("follower to complete", async () => {
836 const r = await ok("GET", `/repos/${owner}/chain/actions/runs/${follower.id}`);
837 return r.status === "completed" ? r : null;
838 });
839 assert.equal(done.conclusion, "success");
840 assert.equal((await runs()).length, 2, "the follower does not trigger itself");
841
842 // A run whose jobs were all skipped is skipped, as on GitHub, so a follower that waits for success doesn't run.
843 writeFileSync(join(src, ".github/workflows/ci.yml"), `name: CI\non: push\njobs:\n build:\n if: \${{ false }}\n runs-on: [self-hosted, linux]\n steps:\n - run: echo built\n`);
844 git(src, ["commit", "-q", "-am", "skip the build"]);
845 git(src, ["push", "-q", "origin", "main"]);
846 const settled = await until("skipped CI and its follower", async () => {
847 const all = await runs();
848 return all.length === 4 && all.every((r) => r.status === "completed") ? all : null;
849 });
850 const sha = git(src, ["rev-parse", "HEAD"]).trim();
851 const skippedCi = settled.find((r) => r.name === "CI" && r.head_sha === sha);
852 assert.equal(skippedCi?.conclusion, "skipped");
853 assert.equal(settled.find((r) => r.event === "workflow_run" && r.id !== follower.id)?.conclusion, "skipped");
854});
855
856test("triggers from workflows: a job's repository_dispatch starts runs, a follower of agent code stays an agent's", { timeout: 600_000 }, async () => {
857 const owner = (await ok("GET", "/user")).login;
858 await ok("POST", "/user/repos", { name: "relay" });
859 const bot = (await ok("POST", "/diffinery/agents", { login: "relay-bot" }, null)).token.token;
860 const src = join(work, "relay");
861 mkdirSync(join(src, ".github/workflows"), { recursive: true });
862 writeFileSync(
863 join(src, ".github/workflows/send.yml"),
864 `name: Send
865on: workflow_dispatch
866jobs:
867 send:
868 runs-on: [self-hosted, linux]
869 permissions: { contents: write }
870 steps:
871 - env: { GH_TOKEN: "\${{ github.token }}" }
872 run: |
873 code=$(curl -s -o out.txt -w '%{http_code}' -X POST -H "authorization: Bearer $GH_TOKEN" -H 'content-type: application/json' -d '{"event_type":"ping","client_payload":{"from":"a job"}}' "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/dispatches")
874 echo "dispatch: $code $(cat out.txt)"
875`,
876 );
877 writeFileSync(
878 join(src, ".github/workflows/pinged.yml"),
879 `name: Pinged
880on:
881 repository_dispatch:
882 types: [ping]
883jobs:
884 pinged:
885 runs-on: [self-hosted, linux]
886 steps:
887 - run: echo "pinged from \${{ github.event.client_payload.from }}"
888`,
889 );
890 writeFileSync(join(src, ".github/workflows/ci.yml"), `name: CI\non: pull_request\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo built\n`);
891 writeFileSync(
892 join(src, ".github/workflows/after.yml"),
893 `name: After CI
894on:
895 workflow_run:
896 workflows: [CI]
897 types: [completed]
898jobs:
899 follow:
900 runs-on: [self-hosted, linux]
901 permissions: { contents: write }
902 steps:
903 - uses: actions/checkout@v4
904 with: { ref: main }
905 - env:
906 GIT_AUTHOR_NAME: bot
907 GIT_AUTHOR_EMAIL: bot@example.com
908 GIT_COMMITTER_NAME: bot
909 GIT_COMMITTER_EMAIL: bot@example.com
910 run: |
911 echo "after \${{ github.event.workflow_run.head_branch }}" >> followed.txt
912 git add followed.txt && git commit -qm followed
913 if git push -q origin HEAD:main 2>err.txt; then echo "main push: ok"; else echo "main push: refused $(tr '\\n' ' ' < err.txt)"; fi
914`,
915 );
916 git(src, ["init", "-q", "-b", "main"]);
917 git(src, ["add", "."]);
918 git(src, ["commit", "-q", "-m", "relay"]);
919 git(src, ["remote", "add", "origin", `${base}/${owner}/relay.git`]);
920 git(src, ["push", "-q", "origin", "main"]);
921
922 const runs = async () => (await ok("GET", `/repos/${owner}/relay/actions/runs`)).workflow_runs;
923 const logOf = async (claim) => (await (await fetch(`${base}/api/v3/repos/${owner}/relay/actions/jobs/${claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text()).replace(/^\S+Z /gm, "");
924
925 // Like GitHub, a job's GITHUB_TOKEN may send repository_dispatch, and that starts runs.
926 await ok("POST", `/repos/${owner}/relay/actions/workflows/send.yml/dispatches`, { ref: "main" });
927 const send = await runOneJob(owner, "relay");
928 assert.equal(send.claim.name, "send");
929 assert.match(await logOf(send.claim), /dispatch: 204/);
930 const pingedRun = await until("repository_dispatch run", async () => (await runs()).find((r) => r.event === "repository_dispatch"));
931 assert.equal(pingedRun.name, "Pinged");
932 const pinged = await runOneJob(owner, "relay");
933 assert.equal(pinged.claim.name, "pinged");
934 assert.match(await logOf(pinged.claim), /pinged from a job/);
935
936 /** Opens a pull request from `branch` as a person, runs its CI, then the follower; returns the follower's log. */
937 const follow = async (branch) => {
938 const seen = new Set((await runs()).map((r) => r.id));
939 await ok("POST", `/repos/${owner}/relay/pulls`, { title: branch, head: branch, base: "main" });
940 await until("CI run", async () => (await runs()).find((r) => !seen.has(r.id) && r.name === "CI"));
941 const build = await runOneJob(owner, "relay");
942 assert.equal(build.claim.name, "build");
943 await until("follower run", async () => (await runs()).find((r) => !seen.has(r.id) && r.event === "workflow_run"));
944 const f = await runOneJob(owner, "relay");
945 assert.equal(f.claim.name, "follow");
946 return logOf(f.claim);
947 };
948
949 // A person's pull request: the follower writes to main with the token it was granted.
950 git(src, ["checkout", "-q", "-b", "person-work"]);
951 writeFileSync(join(src, "person.txt"), "from a person\n");
952 git(src, ["add", "person.txt"]);
953 git(src, ["commit", "-q", "-m", "person change"]);
954 git(src, ["push", "-q", "origin", "person-work"]);
955 assert.match(await follow("person-work"), /main push: ok/);
956
957 // A person opens a pull request from a branch an agent pushed. CI runs the agent's code, so
958 // the follower, which acts on what CI produced, is an agent's too and may not push to main.
959 const agentClone = join(work, "relay-agent");
960 git(work, ["clone", "-q", `${base}/${owner}/relay.git`, agentClone], bot);
961 git(agentClone, ["checkout", "-q", "-b", "agent-work"], bot);
962 writeFileSync(join(agentClone, "agent.txt"), "from the agent\n");
963 git(agentClone, ["add", "agent.txt"], bot);
964 git(agentClone, ["commit", "-q", "-m", "agent change"], bot);
965 git(agentClone, ["push", "-q", "origin", "agent-work"], bot);
966 assert.match(await follow("agent-work"), /main push: refused .*agents may not push to protected or default branches/);
967});
968
969test("pull requests: test merge commits, pull_request_target and the merge queue", async () => {
970 const owner = (await ok("GET", "/user")).login;
971 await ok("POST", "/user/repos", { name: "queue" });
972 await api("PUT", `/repos/${owner}/queue/actions/secrets/TOPSECRET`, { value: "s3cret" });
973 const src = join(work, "queue");
974 mkdirSync(join(src, ".github/workflows"), { recursive: true });
975 writeFileSync(join(src, "app.txt"), "a\nb\nc\n");
976 writeFileSync(
977 join(src, ".github/workflows/ci.yml"),
978 `name: CI
979on:
980 pull_request:
981 merge_group:
982jobs:
983 test:
984 runs-on: [self-hosted, linux]
985 steps:
986 - uses: actions/checkout@v4
987 - run: |
988 echo "event=\${{ github.event_name }} ref=\${{ github.ref }} sha=\${{ github.sha }} head=$(git rev-parse HEAD)"
989 echo "parents=$(git rev-list --parents -n1 HEAD)"
990 echo "app=$(tr '\\n' ' ' < app.txt)"
991 if [ "\${{ github.event_name }}" = merge_group ] && grep -qs fail notes.txt; then echo "merge group failed"; exit 1; fi
992`,
993 );
994 writeFileSync(
995 join(src, ".github/workflows/target.yml"),
996 `name: Target
997on: pull_request_target
998jobs:
999 t:
1000 runs-on: [self-hosted, linux]
1001 steps:
1002 - run: echo "target from base secret=\${{ secrets.TOPSECRET == 's3cret' }} ref=\${{ github.ref }} head=\${{ github.event.pull_request.head.sha }}"
1003`,
1004 );
1005 git(src, ["init", "-q", "-b", "main"]);
1006 git(src, ["add", "."]);
1007 git(src, ["commit", "-q", "-m", "queue"]);
1008 git(src, ["remote", "add", "origin", `${base}/${owner}/queue.git`]);
1009 git(src, ["push", "-q", "origin", "main"]);
1010 const root = git(src, ["rev-parse", "HEAD"]).trim();
1011
1012 // f1 changes the first line and tries to rewrite the pull_request_target workflow.
1013 git(src, ["checkout", "-q", "-b", "f1"]);
1014 writeFileSync(join(src, "app.txt"), "A\nb\nc\n");
1015 writeFileSync(join(src, ".github/workflows/target.yml"), `name: Target\non: pull_request_target\njobs:\n t:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo "PWNED \${{ secrets.TOPSECRET }}"\n`);
1016 git(src, ["commit", "-q", "-am", "f1"]);
1017 git(src, ["push", "-q", "origin", "f1"]);
1018 const f1 = git(src, ["rev-parse", "HEAD"]).trim();
1019 // main moves on, so the test merge commit differs from both sides.
1020 git(src, ["checkout", "-q", "main"]);
1021 writeFileSync(join(src, "app.txt"), "a\nb\nC\n");
1022 git(src, ["commit", "-q", "-am", "main moves"]);
1023 git(src, ["push", "-q", "origin", "main"]);
1024 const main1 = git(src, ["rev-parse", "HEAD"]).trim();
1025
1026 const pr1 = await ok("POST", `/repos/${owner}/queue/pulls`, { title: "Capitalise a", head: "f1", base: "main" });
1027 const runs = async (q = "") => (await ok("GET", `/repos/${owner}/queue/actions/runs${q}`)).workflow_runs;
1028 const prRun = await until("pull_request run", async () => (await runs("?event=pull_request"))[0]);
1029 assert.equal(prRun.ref, "refs/pull/1/merge");
1030 assert.equal(prRun.head_sha, f1, "pull_request runs report on the PR head");
1031 assert.notEqual(prRun.sha, f1, "pull_request runs check out the test merge commit");
1032 assert.equal(prRun.head_branch, "f1");
1033 const targetRun = (await runs("?event=pull_request_target"))[0];
1034 assert.equal(targetRun.ref, "refs/heads/main");
1035 assert.equal(targetRun.sha, main1, "pull_request_target runs on the base commit");
1036 assert.equal(targetRun.head_sha, f1);
1037 // The merge ref is fetchable and its parents are [base, head]; refs/pull is read-only.
1038 git(src, ["fetch", "-q", "origin", "+refs/pull/1/merge:refs/remotes/pr/1"]);
1039 assert.equal(git(src, ["rev-parse", "refs/remotes/pr/1"]).trim(), prRun.sha);
1040 assert.equal(git(src, ["rev-list", "--parents", "-n1", "refs/remotes/pr/1"]).trim(), `${prRun.sha} ${main1} ${f1}`);
1041 assert.match(gitFails(src, ["push", "origin", `${root}:refs/pull/1/head`]), /refs\/pull|managed/);
1042
1043 const logOf = async (id) => (await fetch(`${base}/api/v3/repos/${owner}/queue/actions/jobs/${id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
1044 const ran = {};
1045 for (let i = 0; i < 2; i++) {
1046 const j = await runOneJob(owner, "queue");
1047 ran[j.claim.name] = await logOf(j.claim.job_id);
1048 }
1049 assert.match(ran.test, new RegExp(`event=pull_request ref=refs/pull/1/merge sha=${prRun.sha} head=${prRun.sha}`));
1050 assert.match(ran.test, /app=A b C/);
1051 assert.match(ran.t, /target from base secret=true ref=refs\/heads\/main/);
1052 assert.match(ran.t, new RegExp(`head=${f1}`));
1053 assert.doesNotMatch(ran.t, /PWNED/);
1054 await until("PR #1 checks", async () => {
1055 const c = (await ok("GET", `/repos/${owner}/queue/commits/${f1}/check-runs`)).check_runs;
1056 return c.length === 2 && c.every((x) => x.conclusion === "success") ? c : null;
1057 });
1058
1059 // ------------------------------------------------------------ merge queue
1060 await ok("PUT", `/repos/${owner}/queue/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["CI / test"], mergeQueue: { method: "merge", buildConcurrency: 5, checkTimeoutMinutes: 30 } });
1061 const direct = await api("PUT", `/repos/${owner}/queue/pulls/1/merge`, {});
1062 assert.equal(direct.status, 405);
1063 assert.match(JSON.stringify(direct.json), /merge queue/);
1064 assert.equal((await ok("GET", `/repos/${owner}/queue/pulls/1/merge`)).mergeQueue.method, "merge");
1065
1066 // Two more pull requests: one that merges cleanly and one that fails only in its merge group.
1067 const branch = async (name, file, content) => {
1068 git(src, ["checkout", "-q", "-b", name, main1]);
1069 writeFileSync(join(src, file), content);
1070 git(src, ["add", "."]);
1071 git(src, ["commit", "-q", "-m", name]);
1072 git(src, ["push", "-q", "origin", name]);
1073 const sha = git(src, ["rev-parse", "HEAD"]).trim();
1074 const pr = await ok("POST", `/repos/${owner}/queue/pulls`, { title: name, head: name, base: "main" });
1075 for (let i = 0; i < 2; i++) await runOneJob(owner, "queue");
1076 await until(`${name} checks`, async () => (await ok("GET", `/repos/${owner}/queue/commits/${sha}/check-runs`)).check_runs.filter((x) => x.conclusion === "success").length === 2);
1077 return { pr, sha };
1078 };
1079 const f2 = await branch("f2", "two.txt", "two\n");
1080 const f3 = await branch("f3", "notes.txt", "fail\n");
1081
1082 const q1 = await ok("PUT", `/repos/${owner}/queue/pulls/1/merge-queue`, { delete_branch: true });
1083 assert.equal(q1.state, "queued");
1084 assert.equal(q1.entry.position, 1);
1085 assert.equal(q1.entry.state, "checking");
1086 const q2 = await ok("PUT", `/repos/${owner}/queue/pulls/${f2.pr.number}/merge-queue`, {});
1087 const q3 = await ok("PUT", `/repos/${owner}/queue/pulls/${f3.pr.number}/merge-queue`, {});
1088 assert.equal(q2.entry.merge_group.base_sha, q1.entry.merge_group.head_sha, "each group builds on the one ahead");
1089 assert.equal(q3.entry.merge_group.base_sha, q2.entry.merge_group.head_sha);
1090 assert.equal(q1.entry.merge_group.head_ref, `refs/heads/gh-readonly-queue/main/pr-1-${f1}`);
1091 const queue = await ok("GET", `/repos/${owner}/queue/merge-queue/main`);
1092 assert.deepEqual(queue.entries.map((e) => e.number), [1, f2.pr.number, f3.pr.number]);
1093 assert.match(gitFails(src, ["push", "origin", `${root}:refs/heads/gh-readonly-queue/main/x`]), /read-only/);
1094
1095 // Merge groups run merge_group workflows, oldest first.
1096 const groupLogs = [];
1097 for (let i = 0; i < 3; i++) {
1098 const j = await runOneJob(owner, "queue", { allowFailure: i === 2 });
1099 groupLogs.push(await logOf(j.claim.job_id));
1100 }
1101 assert.match(groupLogs[0], new RegExp(`event=merge_group ref=refs/heads/gh-readonly-queue/main/pr-1-${f1} sha=${q1.entry.merge_group.head_sha}`));
1102 assert.match(groupLogs[2], /merge group failed/);
1103 const mainNow = await until("the queue to merge #1 and #2", async () => {
1104 const b = await ok("GET", `/repos/${owner}/queue/branches/main`);
1105 return b.commit.sha === q2.entry.merge_group.head_sha ? b : null;
1106 });
1107 assert.ok(mainNow);
1108 assert.equal((await ok("GET", `/repos/${owner}/queue/pulls/1`)).merged, true);
1109 assert.equal((await ok("GET", `/repos/${owner}/queue/pulls/${f2.pr.number}`)).merged, true);
1110 assert.equal((await ok("GET", `/repos/${owner}/queue/pulls/1`)).merge_commit_sha, q1.entry.merge_group.head_sha, "the tested commit is what merged");
1111 const f3After = await until("#3 to leave the queue", async () => {
1112 const q = await ok("GET", `/repos/${owner}/queue/merge-queue/main`);
1113 return q.entries.length === 0 ? q : null;
1114 });
1115 assert.ok(f3After);
1116 assert.equal((await ok("GET", `/repos/${owner}/queue/pulls/${f3.pr.number}`)).merged, false);
1117 const comments = await ok("GET", `/repos/${owner}/queue/issues/${f3.pr.number}/comments`);
1118 assert.match(JSON.stringify(comments), /removed from the merge queue: the required check 'CI \/ test' failed on its merge group/);
1119 git(src, ["fetch", "-q", "origin"]);
1120 assert.equal(git(src, ["show", "origin/main:app.txt"]), "A\nb\nC\n");
1121 assert.equal(git(src, ["show", "origin/main:two.txt"]), "two\n");
1122 assert.ok(!(await ok("GET", `/repos/${owner}/queue/branches`)).some((b) => b.name.startsWith("gh-readonly-queue/") || b.name === "f1"), "group branches and f1 are gone");
1123
1124 // A pull request that conflicts with its base runs no pull_request workflows (like GitHub), only pull_request_target.
1125 git(src, ["checkout", "-q", "-b", "f4", root]);
1126 writeFileSync(join(src, "app.txt"), "x\nb\nc\n");
1127 git(src, ["commit", "-q", "-am", "f4"]);
1128 git(src, ["push", "-q", "origin", "f4"]);
1129 const pr4 = await ok("POST", `/repos/${owner}/queue/pulls`, { title: "conflicts", head: "f4", base: "main" });
1130 const t4 = await until("pull_request_target run for #4", async () => (await runs("?event=pull_request_target")).find((r) => r.pull_request_number === pr4.number));
1131 assert.ok(t4);
1132 assert.equal((await runs("?event=pull_request")).filter((r) => r.pull_request_number === pr4.number).length, 0);
1133 await runOneJob(owner, "queue");
1134
1135 // The web UI shows the queue.
1136 const page = async (path) => {
1137 const res = await fetch(`${base}${path}`);
1138 assert.equal(res.status, 200, path);
1139 return res.text();
1140 };
1141 assert.match(await page(`/${owner}/queue/queue/main`), /The queue is empty/);
1142 assert.match(await page(`/${owner}/queue/pull/${pr4.number}`), /Merge when ready/);
1143 assert.match(await page(`/${owner}/queue/pull/${f3.pr.number}`), /removed from the merge queue/);
1144 assert.match(await page(`/${owner}/queue/settings/branches`), /merge queue/);
1145});
1146
1147const POLICY_WORKFLOW = `name: Policy
1148on:
1149 push:
1150 branches: [main, agent-work]
1151 pull_request:
1152jobs:
1153 probe:
1154 runs-on: [self-hosted, linux]
1155 permissions: { contents: write, pull-requests: write }
1156 steps:
1157 - uses: actions/checkout@v4
1158 with: { ref: main }
1159 - name: Push to main, push a workflow change, approve the pull request
1160 env:
1161 GH_TOKEN: \${{ github.token }}
1162 PR: \${{ github.event.pull_request.number }}
1163 GIT_AUTHOR_NAME: bot
1164 GIT_AUTHOR_EMAIL: bot@example.com
1165 GIT_COMMITTER_NAME: bot
1166 GIT_COMMITTER_EMAIL: bot@example.com
1167 run: |
1168 echo "run \${{ github.run_id }}" > note.txt
1169 git add note.txt && git commit -qm note
1170 if git push -q origin HEAD:main 2>err.txt; then echo "main push: ok"; else echo "main push: refused $(tr '\\n' ' ' < err.txt)"; fi
1171 git reset -q --hard HEAD~1
1172 echo "# edited" >> .github/workflows/policy.yml
1173 git commit -qam "edit the workflow"
1174 if git push -q origin "HEAD:refs/heads/wf-\${{ github.run_id }}" 2>err.txt; then echo "workflow push: ok"; else echo "workflow push: refused $(tr '\\n' ' ' < err.txt)"; fi
1175 if [ -n "$PR" ]; then
1176 code=$(curl -s -o out.json -w '%{http_code}' -X POST -H "authorization: Bearer $GH_TOKEN" -H 'content-type: application/json' -d '{"event":"APPROVE","body":"from a workflow"}' "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/pulls/$PR/reviews")
1177 echo "approve: $code $(cat out.json)"
1178 fi
1179 defaults:
1180 if: github.event_name == 'push' && github.ref == 'refs/heads/main'
1181 runs-on: [self-hosted, linux]
1182 steps:
1183 - env: { GH_TOKEN: "\${{ github.token }}" }
1184 run: |
1185 code=$(curl -s -o out.json -w '%{http_code}' -X POST -H "authorization: Bearer $GH_TOKEN" -H 'content-type: application/json' -d '{"title":"from the default token"}' "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/issues")
1186 echo "default token issue write: $code $(cat out.json)"
1187 code=$(curl -s -o /dev/null -w '%{http_code}' -H "authorization: Bearer $GH_TOKEN" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/README.md")
1188 echo "default token contents read: $code"
1189`;
1190
1191test("workflow tokens: read-only default, no approvals or workflow edits, agent code stays an agent", { timeout: 600_000 }, async () => {
1192 const owner = (await ok("GET", "/user")).login;
1193 await ok("POST", "/user/repos", { name: "policy" });
1194 const settingsPath = `/repos/${owner}/policy/actions/permissions/workflow`;
1195 // New repositories start like GitHub's: read-only token, no pull request approvals.
1196 assert.deepEqual(await ok("GET", settingsPath), { default_workflow_permissions: "read", can_approve_pull_request_reviews: false, agent_runs_use_secrets: false });
1197 const bot = (await ok("POST", "/diffinery/agents", { login: "policy-bot" }, null)).token.token;
1198 assert.equal((await api("PUT", settingsPath, { can_approve_pull_request_reviews: true }, bot)).status, 403, "agents cannot change what workflows may do");
1199 assert.equal((await api("PUT", settingsPath, { default_workflow_permissions: "admin" })).status, 422);
1200 // The same settings on the repository's Settings → Actions page.
1201 const actionsPage = `/${owner}/policy/settings/actions`;
1202 const form = async (fields) => {
1203 const res = await fetch(`${base}${actionsPage}`);
1204 const html = await res.text();
1205 assert.match(html, /Allow GitHub Actions to create and approve pull requests/);
1206 const csrf = /name="_csrf" value="([^"]+)"/.exec(html)?.[1];
1207 const cookie = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1];
1208 const r = await fetch(`${base}${actionsPage}`, { method: "POST", body: new URLSearchParams({ _csrf: csrf, ...fields }), redirect: "manual", headers: { cookie: `dfy_csrf=${cookie}`, "sec-fetch-site": "same-origin" } });
1209 assert.equal(r.status, 303);
1210 };
1211 await form({ default_permissions: "write", can_approve: "1" });
1212 assert.deepEqual(await ok("GET", settingsPath), { default_workflow_permissions: "write", can_approve_pull_request_reviews: true, agent_runs_use_secrets: false });
1213 await form({ default_permissions: "read" });
1214 assert.deepEqual(await ok("GET", settingsPath), { default_workflow_permissions: "read", can_approve_pull_request_reviews: false, agent_runs_use_secrets: false });
1215
1216 const src = join(work, "policy");
1217 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1218 writeFileSync(join(src, "README.md"), "# policy\n");
1219 writeFileSync(join(src, ".github/workflows/policy.yml"), POLICY_WORKFLOW);
1220 git(src, ["init", "-q", "-b", "main"]);
1221 git(src, ["add", "-A"]);
1222 git(src, ["commit", "-q", "-m", "policy"]);
1223 git(src, ["remote", "add", "origin", `${base}/${owner}/policy.git`]);
1224 git(src, ["push", "-q", "origin", "main"]);
1225
1226 /** Runs `count` jobs; returns their logs by job name. */
1227 const runJobs = async (count) => {
1228 const logs = {};
1229 for (let i = 0; i < count; i++) {
1230 const { claim } = await runOneJob(owner, "policy");
1231 const raw = await (await fetch(`${base}/api/v3/repos/${owner}/policy/actions/jobs/${claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
1232 logs[claim.name] = raw.replace(/^\S+Z /gm, "");
1233 }
1234 return logs;
1235 };
1236 const refused = (path) => new RegExp(`workflow push: refused .*refusing to allow a GitHub App to create or update workflow \`${path.replace(/\./g, "\\.")}\` without \`workflows\` permission`);
1237
1238 // A person's push: the job token writes what it was granted, but never workflow files;
1239 // the default token (no permissions:) only reads.
1240 let logs = await runJobs(2);
1241 assert.match(logs.probe, /main push: ok/);
1242 assert.match(logs.probe, refused(".github/workflows/policy.yml"));
1243 assert.match(logs.defaults, /default token issue write: 403 .*issues: write/);
1244 assert.match(logs.defaults, /default token contents read: 200/);
1245 const branches = (await ok("GET", `/repos/${owner}/policy/branches`)).map((b) => b.name);
1246 assert.ok(!branches.some((b) => b.startsWith("wf-")), JSON.stringify(branches));
1247 git(src, ["pull", "-q", "--ff-only", "origin", "main"]);
1248 assert.match(readFileSync(join(src, "note.txt"), "utf8"), /^run \d+/);
1249
1250 // An agent's push: the run executes the agent's code, so its token is an agent's and may not push to the default branch.
1251 const agentClone = join(work, "policy-agent");
1252 git(work, ["clone", "-q", `${base}/${owner}/policy.git`, agentClone], bot);
1253 git(agentClone, ["checkout", "-q", "-b", "agent-work"], bot);
1254 writeFileSync(join(agentClone, "agent.txt"), "from the agent\n");
1255 git(agentClone, ["add", "agent.txt"], bot);
1256 git(agentClone, ["commit", "-q", "-m", "agent change"], bot);
1257 git(agentClone, ["push", "-q", "origin", "agent-work"], bot);
1258 logs = await runJobs(1);
1259 assert.match(logs.probe, /main push: refused .*agents may not push to protected or default branches/);
1260 assert.match(logs.probe, refused(".github/workflows/policy.yml"));
1261
1262 // A person opens a pull request from the branch the agent pushed: still the agent's code.
1263 // Workflows may not approve pull requests unless the repository allows it.
1264 const pr1 = await ok("POST", `/repos/${owner}/policy/pulls`, { title: "Agent work", head: "agent-work", base: "main" });
1265 logs = await runJobs(1);
1266 assert.match(logs.probe, /main push: refused .*agents may not push/);
1267 assert.match(logs.probe, /approve: 403 .*GitHub Actions is not permitted to approve pull requests/);
1268 assert.equal((await ok("GET", `/repos/${owner}/policy/pulls/${pr1.number}/reviews`)).length, 0);
1269
1270 // Allowed: the approval is recorded, but only people's approvals count toward the required ones.
1271 await ok("PUT", settingsPath, { can_approve_pull_request_reviews: true });
1272 assert.deepEqual(await ok("GET", settingsPath), { default_workflow_permissions: "read", can_approve_pull_request_reviews: true, agent_runs_use_secrets: false });
1273 await ok("PUT", `/repos/${owner}/policy/branches/main/protection`, {
1274 requirePullRequest: true,
1275 requiredApprovals: 1,
1276 dismissStaleReviews: false,
1277 requiredChecks: [],
1278 allowForcePush: false,
1279 allowDeletion: false,
1280 requireLinearHistory: false,
1281 enforceAdmins: true,
1282 agentsMayPush: false,
1283 agentsMayMerge: false,
1284 });
1285 git(src, ["checkout", "-q", "-b", "feature"]);
1286 writeFileSync(join(src, "feature.txt"), "a person's change\n");
1287 git(src, ["add", "feature.txt"]);
1288 git(src, ["commit", "-q", "-m", "feature"]);
1289 git(src, ["push", "-q", "origin", "feature"]);
1290 const pr2 = await ok("POST", `/repos/${owner}/policy/pulls`, { title: "Feature", head: "feature", base: "main" });
1291 logs = await runJobs(1);
1292 assert.match(logs.probe, /main push: refused .*pull request/);
1293 assert.match(logs.probe, /approve: 20[01] /);
1294 const reviews = await ok("GET", `/repos/${owner}/policy/pulls/${pr2.number}/reviews`);
1295 assert.deepEqual(reviews.map((r) => r.state), ["APPROVED"]);
1296 const m = await ok("GET", `/repos/${owner}/policy/pulls/${pr2.number}/merge`);
1297 assert.equal(m.mergeable, false, JSON.stringify(m));
1298 assert.equal(m.approvals, 0, JSON.stringify(m));
1299 assert.match(JSON.stringify(m.blockers), /needs 1 more approving review/);
1300});
1301
1302const SCOPES_WORKFLOW = `name: Scopes
1303on:
1304 push:
1305 branches: [main, a, b]
1306 pull_request:
1307jobs:
1308 c:
1309 runs-on: [self-hosted, linux]
1310 steps:
1311 - uses: actions/cache@v4
1312 with: { path: built, key: "b-\${{ github.run_id }}", restore-keys: "b-" }
1313 - uses: actions/cache@v4
1314 env: { DIFFINERY_BUILTINS: "false" }
1315 with: { path: real, key: "r-\${{ github.run_id }}", restore-keys: "r-" }
1316 - run: |
1317 echo "restored built=[$(cat built/from 2>/dev/null)] real=[$(cat real/from 2>/dev/null)]"
1318 mkdir -p built real && echo "$GITHUB_REF" > built/from && echo "$GITHUB_REF" > real/from
1319 - if: github.ref == 'refs/heads/main'
1320 uses: actions/upload-artifact@v4
1321 with: { name: "builtin-\${{ github.run_id }}", path: built/from, retention-days: 1 }
1322 - if: github.ref == 'refs/heads/main'
1323 uses: actions/upload-artifact@v4
1324 env: { DIFFINERY_BUILTINS: "false" }
1325 with: { name: "real-\${{ github.run_id }}", path: built/from, retention-days: 3 }
1326 - if: github.ref == 'refs/heads/main'
1327 uses: actions/upload-artifact@v4
1328 with: { name: "capped-\${{ github.run_id }}", path: built/from, retention-days: 400 }
1329`;
1330
1331test("caches are scoped to branches and pull requests; artifacts keep their retention-days", { timeout: 900_000 }, async () => {
1332 const owner = (await ok("GET", "/user")).login;
1333 await ok("POST", "/user/repos", { name: "scopes" });
1334 const src = join(work, "scopes");
1335 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1336 writeFileSync(join(src, ".github/workflows/scopes.yml"), SCOPES_WORKFLOW);
1337 writeFileSync(join(src, "README.md"), "# scopes\n");
1338 git(src, ["init", "-q", "-b", "main"]);
1339 git(src, ["add", "-A"]);
1340 git(src, ["commit", "-q", "-m", "scopes"]);
1341 git(src, ["remote", "add", "origin", `${base}/${owner}/scopes.git`]);
1342 /** Runs the job a push or pull request started; returns what its caches restored. */
1343 const restored = async () => {
1344 const { claim } = await runOneJob(owner, "scopes", { timeoutMs: 300_000 });
1345 const log = await (await fetch(`${base}/api/v3/repos/${owner}/scopes/actions/jobs/${claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
1346 const m = /^\S+ restored built=\[(.*?)\] real=\[(.*?)\]$/m.exec(log);
1347 assert.ok(m, log);
1348 return { builtin: m[1], real: m[2] };
1349 };
1350 const branch = (name, from, file) => {
1351 git(src, ["checkout", "-q", "-b", name, from]);
1352 if (file) {
1353 writeFileSync(join(src, file), `${name}\n`);
1354 git(src, ["add", file]);
1355 git(src, ["commit", "-q", "-m", name]);
1356 }
1357 git(src, ["push", "-q", "origin", name]);
1358 };
1359
1360 // The default branch starts empty and saves its own entries.
1361 git(src, ["push", "-q", "origin", "main"]);
1362 assert.deepEqual(await restored(), { builtin: "", real: "" });
1363 // A branch falls back to the default branch's caches...
1364 branch("a", "main", "a.txt");
1365 assert.deepEqual(await restored(), { builtin: "refs/heads/main", real: "refs/heads/main" });
1366 // ...but never sees another branch's, though a's are newer and match the restore key.
1367 branch("b", "main", "b.txt");
1368 assert.deepEqual(await restored(), { builtin: "refs/heads/main", real: "refs/heads/main" });
1369 // A pull request reads its base branch's caches.
1370 branch("c", "a", "c.txt");
1371 await ok("POST", `/repos/${owner}/scopes/pulls`, { title: "c into a", head: "c", base: "a" });
1372 assert.deepEqual(await restored(), { builtin: "refs/heads/a", real: "refs/heads/a" });
1373 // Another pull request doesn't see the first one's (saved under refs/pull/<n>/merge).
1374 branch("d", "main", "d.txt");
1375 await ok("POST", `/repos/${owner}/scopes/pulls`, { title: "d into main", head: "d", base: "main" });
1376 assert.deepEqual(await restored(), { builtin: "refs/heads/main", real: "refs/heads/main" });
1377 const caches = await ok("GET", `/repos/${owner}/scopes/actions/caches?per_page=100`);
1378 assert.deepEqual([...new Set(caches.actions_caches.map((c) => c.ref))].sort(), ["refs/heads/a", "refs/heads/b", "refs/heads/main", "refs/pull/1/merge", "refs/pull/2/merge"]);
1379 // A page at a time, with GitHub's Link header.
1380 const page = await fetch(`${base}/api/v3/repos/${owner}/scopes/actions/caches?per_page=2`, { headers: { authorization: `Bearer ${token}` } });
1381 assert.equal((await page.json()).actions_caches.length, 2);
1382 assert.match(page.headers.get("link") ?? "", /[?&]page=2>; rel="next".*rel="last"/);
1383
1384 // retention-days (the built-in and the real upload-artifact), capped at 90 days.
1385 const days = (iso) => Math.round((Date.parse(iso) - Date.now()) / 86_400_000);
1386 const artifacts = (await ok("GET", `/repos/${owner}/scopes/actions/runs/1/artifacts`)).artifacts;
1387 const byName = Object.fromEntries(artifacts.map((a) => [a.name.replace(/-\d+$/, ""), a]));
1388 assert.equal(days(byName.builtin.expires_at), 1, JSON.stringify(byName.builtin));
1389 assert.equal(days(byName.real.expires_at), 3, JSON.stringify(byName.real));
1390 assert.equal(days(byName.capped.expires_at), 90, JSON.stringify(byName.capped));
1391 assert.ok(artifacts.every((a) => a.expired === false));
1392});
1393
1394test("an older runner's cache API is scoped the same way", async () => {
1395 const owner = (await ok("GET", "/user")).login;
1396 await ok("POST", "/user/repos", { name: "legacy-cache" });
1397 const src = join(work, "legacy-cache");
1398 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1399 writeFileSync(join(src, ".github/workflows/w.yml"), "on:\n push:\n branches: [main, a, b]\njobs:\n j:\n runs-on: [self-hosted, linux]\n steps: [{ run: echo }]\n");
1400 git(src, ["init", "-q", "-b", "main"]);
1401 git(src, ["add", "-A"]);
1402 git(src, ["commit", "-q", "-m", "legacy"]);
1403 git(src, ["remote", "add", "origin", `${base}/${owner}/legacy-cache.git`]);
1404
1405 /** Claims the job a push started and starts it, as an older runner would, without running steps. */
1406 const startJob = async () => {
1407 const claim = await until("a job to claim", async () => {
1408 const r = await runnerClaim(`/repos/${owner}/legacy-cache`, ["linux"]);
1409 return r.status === 200 ? r.json : null;
1410 });
1411 const h = { authorization: `Bearer ${claim.token}` };
1412 const at = `${base}/runner/jobs/${claim.job_id}`;
1413 assert.equal((await fetch(at, { headers: h })).status, 200);
1414 return {
1415 put: async (key, body) => (await fetch(`${at}/cache/${encodeURIComponent(key)}`, { method: "PUT", headers: { ...h, "content-length": String(body.length) }, body })).status,
1416 lookup: async (key, restore = "") => {
1417 const r = await fetch(`${at}/cache?key=${encodeURIComponent(key)}&restore=${encodeURIComponent(restore)}`, { headers: h });
1418 if (r.status !== 200) return { status: r.status };
1419 const hit = await r.json();
1420 const blob = await fetch(hit.url, { headers: h });
1421 return { key: hit.key, content: blob.status === 200 ? await blob.text() : blob.status };
1422 },
1423 blob: async (stored) => (await fetch(`${at}/cache/blob/${encodeURIComponent(stored)}`, { headers: h })).status,
1424 done: async () => assert.equal((await fetch(`${at}/complete`, { method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) })).status, 200),
1425 };
1426 };
1427
1428 const branch = (name) => {
1429 git(src, ["checkout", "-q", "-b", name, "main"]);
1430 writeFileSync(join(src, `${name}.txt`), `${name}\n`);
1431 git(src, ["add", "-A"]);
1432 git(src, ["commit", "-q", "-m", name]);
1433 git(src, ["push", "-q", "origin", name]);
1434 };
1435
1436 git(src, ["push", "-q", "origin", "main"]);
1437 let job = await startJob();
1438 assert.equal(await job.put("lk-main", "from main"), 200);
1439 await job.done();
1440
1441 branch("a");
1442 job = await startJob();
1443 assert.deepEqual(await job.lookup("lk-a", "lk-"), { key: "lk-main", content: "from main" });
1444 assert.equal(await job.put("lk-a", "from a"), 200);
1445 assert.deepEqual(await job.lookup("lk-a"), { key: "lk-a", content: "from a" });
1446 await job.done();
1447
1448 branch("b");
1449 job = await startJob();
1450 assert.deepEqual(await job.lookup("lk-a"), { status: 404 });
1451 assert.deepEqual(await job.lookup("lk-x", "lk-"), { key: "lk-main", content: "from main" });
1452 // a's entry can't be fetched directly either
1453 assert.equal(await job.blob("refs/heads/a\nlk-a"), 404);
1454 assert.equal(await job.blob("lk-a"), 404);
1455 await job.done();
1456});
1457
1458test("an older runner's artifact API needs the job's own token", async () => {
1459 const owner = (await ok("GET", "/user")).login;
1460 await ok("POST", "/user/repos", { name: "legacy-artifacts" });
1461 const src = join(work, "legacy-artifacts");
1462 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1463 writeFileSync(join(src, ".github/workflows/w.yml"), "on: push\njobs:\n j:\n runs-on: [self-hosted, linux]\n steps: [{ run: echo }]\n");
1464 git(src, ["init", "-q", "-b", "main"]);
1465 git(src, ["add", "-A"]);
1466 git(src, ["commit", "-q", "-m", "legacy"]);
1467 git(src, ["remote", "add", "origin", `${base}/${owner}/legacy-artifacts.git`]);
1468 git(src, ["push", "-q", "origin", "main"]);
1469 const claim = await until("a job to claim", async () => {
1470 const r = await runnerClaim(`/repos/${owner}/legacy-artifacts`, ["linux"]);
1471 return r.status === 200 ? r.json : null;
1472 });
1473 const at = `${base}/runner/jobs/${claim.job_id}/artifacts/out`;
1474 const real = { authorization: `Bearer ${claim.token}` };
1475 // Same shape (djt_<repo>_<job>_...) as the real token, but not it.
1476 const forged = { authorization: `Bearer ${claim.token.split("_").slice(0, 3).join("_")}_${"0".repeat(48)}` };
1477 assert.equal((await fetch(`${base}/runner/jobs/${claim.job_id}`, { headers: real })).status, 200);
1478 const put = async (h, body) => (await fetch(at, { method: "PUT", headers: { ...h, "content-length": String(body.length) }, body })).status;
1479 const get = async (h) => {
1480 const r = await fetch(at, { headers: h });
1481 return r.status === 200 ? await r.text() : r.status;
1482 };
1483 assert.equal(await put(real, "real bytes"), 200);
1484 assert.equal(await put(forged, "forged bytes"), 401);
1485 assert.equal(await get(forged), 401);
1486 assert.equal(await get({}), 401);
1487 // The forged upload never reached storage.
1488 assert.equal(await get(real), "real bytes");
1489 assert.equal((await fetch(`${base}/runner/jobs/${claim.job_id}/complete`, { method: "POST", headers: { ...real, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) })).status, 200);
1490 // A finished job's token no longer reads or writes.
1491 assert.equal(await get(real), 401);
1492});
1493
1494test("an older runner's artifacts are listed, downloaded and deleted through the REST API", async () => {
1495 const owner = (await ok("GET", "/user")).login;
1496 await ok("POST", "/user/repos", { name: "legacy-rest" });
1497 const src = join(work, "legacy-rest");
1498 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1499 writeFileSync(join(src, ".github/workflows/w.yml"), "on: push\njobs:\n j:\n runs-on: [self-hosted, linux]\n steps: [{ run: echo }]\n");
1500 git(src, ["init", "-q", "-b", "main"]);
1501 git(src, ["add", "-A"]);
1502 git(src, ["commit", "-q", "-m", "legacy"]);
1503 git(src, ["remote", "add", "origin", `${base}/${owner}/legacy-rest.git`]);
1504 git(src, ["push", "-q", "origin", "main"]);
1505 const claim = await until("a job to claim", async () => {
1506 const r = await runnerClaim(`/repos/${owner}/legacy-rest`, ["linux"]);
1507 return r.status === 200 ? r.json : null;
1508 });
1509 const h = { authorization: `Bearer ${claim.token}` };
1510 const at = `${base}/runner/jobs/${claim.job_id}`;
1511 assert.equal((await fetch(at, { headers: h })).status, 200);
1512 for (const name of ["one", "two", "three"]) {
1513 assert.equal((await fetch(`${at}/artifacts/${name}`, { method: "PUT", headers: { ...h, "content-length": String(name.length) }, body: name })).status, 200);
1514 }
1515 const rest = (path, init = {}) => fetch(`${base}/api/v3/repos/${owner}/legacy-rest${path}`, { ...init, headers: { authorization: `Bearer ${token}` } });
1516
1517 // Listed with numeric ids, across the repository and for the run, a page at a time.
1518 let r = await rest("/actions/artifacts?per_page=2");
1519 let body = await r.json();
1520 assert.equal(body.total_count, 3, JSON.stringify(body));
1521 assert.equal(body.artifacts.length, 2);
1522 assert.ok(body.artifacts.every((a) => Number.isSafeInteger(a.id) && a.expired === false), JSON.stringify(body));
1523 assert.match(r.headers.get("link") ?? "", /[?&]page=2>; rel="next"/);
1524 const runId = body.artifacts[0].workflow_run.id;
1525 r = await rest(`/actions/runs/${runId}/artifacts?per_page=2&page=2`);
1526 body = await r.json();
1527 assert.equal(body.total_count, 3);
1528 assert.equal(body.artifacts.length, 1);
1529 assert.match(r.headers.get("link") ?? "", /rel="prev"/);
1530 assert.doesNotMatch(r.headers.get("link") ?? "", /rel="next"/);
1531 const two = (await (await rest(`/actions/runs/${runId}/artifacts?name=two`)).json()).artifacts[0];
1532 assert.equal((await (await rest(`/actions/artifacts/${two.id}`)).json()).name, "two");
1533
1534 // The download is the tarball the runner uploaded.
1535 const zip = await rest(`/actions/artifacts/${two.id}/zip`, { redirect: "manual" });
1536 assert.equal(zip.status, 302);
1537 const blob = await fetch(zip.headers.get("location"));
1538 assert.equal(blob.status, 200);
1539 assert.equal(blob.headers.get("content-type"), "application/gzip");
1540 assert.match(blob.headers.get("content-disposition") ?? "", /two\.tar\.gz/);
1541 assert.equal(await blob.text(), "two");
1542
1543 // Deleting it removes it for the runner too.
1544 assert.equal((await rest(`/actions/artifacts/${two.id}`, { method: "DELETE" })).status, 204);
1545 assert.equal((await rest(`/actions/artifacts/${two.id}`)).status, 404);
1546 assert.equal((await fetch(`${at}/artifacts/two`, { headers: h })).status, 404);
1547 assert.equal(await (await fetch(`${at}/artifacts/one`, { headers: h })).text(), "one");
1548 assert.equal((await (await rest("/actions/artifacts")).json()).total_count, 2);
1549 assert.equal((await fetch(`${at}/complete`, { method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) })).status, 200);
1550});
1551
1552const hasDocker = spawnSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 }).status === 0;
1553
1554test("containers: a job container and service containers on a self-hosted runner", { skip: !hasDocker && "Docker is not available" }, async () => {
1555 const owner = (await ok("GET", "/user")).login;
1556 await ok("POST", "/user/repos", { name: "boxes" });
1557 const src = join(work, "boxes");
1558 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1559 // Docker Hub rate-limits anonymous pulls; mirror.gcr.io serves the same official images.
1560 writeFileSync(
1561 join(src, ".github/workflows/ci.yml"),
1562 `on: push
1563jobs:
1564 boxed:
1565 runs-on: [self-hosted, linux]
1566 container:
1567 image: mirror.gcr.io/library/debian:\${{ github.event_name == 'push' && 'bookworm-slim' || 'nope' }}
1568 services:
1569 cache:
1570 image: mirror.gcr.io/library/redis:7-alpine
1571 options: --health-cmd "redis-cli ping" --health-interval 1s --health-retries 30
1572 steps:
1573 - run: |
1574 grep -q bookworm /etc/os-release && echo "inside debian"
1575 exec 3<>/dev/tcp/cache/6379
1576 printf 'PING\\r\\n' >&3
1577 read -r line <&3
1578 echo "cache answered \${line%$'\\r'}"
1579`,
1580 );
1581 git(src, ["init", "-q", "-b", "main"]);
1582 git(src, ["add", "."]);
1583 git(src, ["commit", "-q", "-m", "containers"]);
1584 git(src, ["remote", "add", "origin", `${base}/${owner}/boxes.git`]);
1585 git(src, ["push", "-q", "origin", "main"]);
1586
1587 const run = await until("boxes run", async () => (await ok("GET", `/repos/${owner}/boxes/actions/runs`)).workflow_runs[0]);
1588 const boxed = await runOneJob(owner, "boxes");
1589 assert.equal(boxed.claim.name, "boxed");
1590 const log = await (await fetch(`${base}/api/v3/repos/${owner}/boxes/actions/jobs/${boxed.claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
1591 assert.match(log, /inside debian/);
1592 assert.match(log, /cache answered \+PONG/);
1593 const done = await until("boxes run to complete", async () => {
1594 const r = await ok("GET", `/repos/${owner}/boxes/actions/runs/${run.id}`);
1595 return r.status === "completed" ? r : null;
1596 });
1597 assert.equal(done.conclusion, "success");
1598});
1599
1600// ---------------------------------------------------------------- the official actions, unmodified
1601
1602// No workflow-level permissions: jobs get the repository default (write), like GitHub's permissive default.
1603const TOOLKIT_WORKFLOW = `name: Toolkit
1604on: push
1605jobs:
1606 produce:
1607 runs-on: [self-hosted, linux]
1608 steps:
1609 - uses: actions/checkout@v4
1610 with: { lfs: true, submodules: true, persist-credentials: false }
1611 - name: LFS, submodules, no persisted credentials
1612 run: |
1613 cat big.bin lib/lib.txt
1614 git config --get-regexp 'extraheader' || echo "no persisted credentials"
1615 - uses: actions/checkout@v4
1616 with: { path: sparse, sparse-checkout: docs }
1617 - run: echo "sparse=$(ls sparse | tr '\\n' ' ')"
1618 - id: real-cache
1619 uses: actions/cache@v4
1620 env: { DIFFINERY_BUILTINS: "false" }
1621 with: { path: deps, key: "deps-\${{ hashFiles('lock.txt') }}" }
1622 - if: steps.real-cache.outputs.cache-hit != 'true'
1623 run: mkdir -p deps && echo "saved by run \${{ github.run_id }}" > deps/marker
1624 - run: echo "real-hit=\${{ steps.real-cache.outputs.cache-hit }} $(cat deps/marker)"
1625 - id: builtin-cache
1626 uses: actions/cache/restore@v4
1627 with: { path: deps, key: "deps-\${{ hashFiles('lock.txt') }}", lookup-only: true }
1628 - id: v3-cache
1629 uses: actions/cache/restore@v3
1630 env: { DIFFINERY_BUILTINS: "false" }
1631 with: { path: deps, key: "deps-\${{ hashFiles('lock.txt') }}", lookup-only: true }
1632 - run: echo "builtin-hit=\${{ steps.builtin-cache.outputs.cache-hit }} v3-hit=\${{ steps.v3-cache.outputs.cache-hit }}"
1633 - run: mkdir -p dist/sub && echo one > dist/one.txt && echo two > dist/sub/two.txt && echo hidden > dist/.hidden
1634 - id: up-real
1635 uses: actions/upload-artifact@v4
1636 env: { DIFFINERY_BUILTINS: "false" }
1637 with: { name: dist-real, path: dist/, include-hidden-files: true, retention-days: 3 }
1638 - id: up-builtin
1639 uses: actions/upload-artifact@v4
1640 with: { name: dist-builtin, path: dist/, compression-level: 0 }
1641 - run: echo "ids=\${{ steps.up-real.outputs.artifact-id }},\${{ steps.up-builtin.outputs.artifact-id }} url=\${{ steps.up-real.outputs.artifact-url }}"
1642 consume:
1643 needs: produce
1644 runs-on: [self-hosted, linux]
1645 steps:
1646 - uses: actions/download-artifact@v4
1647 env: { DIFFINERY_BUILTINS: "false" }
1648 with: { path: all }
1649 - uses: actions/download-artifact@v4
1650 with: { pattern: dist-*, path: merged, merge-multiple: true }
1651 - uses: actions/download-artifact@v4
1652 env: { DIFFINERY_BUILTINS: "false" }
1653 with: { name: dist-builtin, path: one }
1654 - run: find all merged one -type f | LC_ALL=C sort | tr '\\n' ' '
1655 - uses: actions/checkout@v4
1656 with: { path: src }
1657 - id: prev
1658 run: echo "id=$(cat src/prev-run.txt 2>/dev/null)" >> "$GITHUB_OUTPUT"
1659 - if: steps.prev.outputs.id != ''
1660 uses: actions/download-artifact@v4
1661 env: { DIFFINERY_BUILTINS: "false" }
1662 with: { name: dist-real, path: prev-real, run-id: "\${{ steps.prev.outputs.id }}", github-token: "\${{ github.token }}", repository: "\${{ github.repository }}" }
1663 - if: steps.prev.outputs.id != ''
1664 uses: actions/download-artifact@v4
1665 with: { pattern: "dist-*", path: prev-builtin, run-id: "\${{ steps.prev.outputs.id }}", github-token: "\${{ github.token }}" }
1666 - if: steps.prev.outputs.id != ''
1667 run: echo "previous run $(cat prev-real/sub/two.txt) $(find prev-builtin -type f | LC_ALL=C sort | tr '\\n' ' ')"
1668 script:
1669 runs-on: [self-hosted, linux]
1670 steps:
1671 - id: gs
1672 uses: actions/github-script@v7
1673 with:
1674 result-encoding: string
1675 script: |
1676 const { owner, repo } = context.repo;
1677 const label = \`from-run-\${context.runId}\`;
1678 await github.rest.issues.createLabel({ owner, repo, name: label, color: "ff0000" });
1679 const { data: issue } = await github.rest.issues.create({ owner, repo, title: \`Opened by run \${context.runId}\`, body: "hello", labels: [label] });
1680 await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body: "commented by github-script" });
1681 const { data: comments } = await github.rest.issues.listComments({ owner, repo, issue_number: issue.number });
1682 const { data: got } = await github.rest.issues.get({ owner, repo, issue_number: issue.number });
1683 const { data: pulls } = await github.rest.pulls.list({ owner, repo, state: "all" });
1684 await github.rest.repos.createCommitStatus({ owner, repo, sha: context.sha, state: "success", context: "github-script", description: "set with the default GITHUB_TOKEN" });
1685 return \`issue=\${issue.number} labels=\${got.labels.map((l) => l.name)} comments=\${comments.length} pulls=\${pulls.length} event=\${context.eventName} repo=\${context.payload.repository.full_name} sender=\${context.payload.sender.login}\`;
1686 - run: echo "script says $RESULT"
1687 env: { RESULT: "\${{ steps.gs.outputs.result }}" }
1688 restricted:
1689 runs-on: [self-hosted, linux]
1690 permissions: { contents: read }
1691 steps:
1692 - id: gs
1693 uses: actions/github-script@v7
1694 with:
1695 result-encoding: string
1696 script: |
1697 const { owner, repo } = context.repo;
1698 const { data: meta } = await github.rest.repos.get({ owner, repo });
1699 try {
1700 await github.rest.issues.create({ owner, repo, title: "must not be created" });
1701 return "issue write allowed";
1702 } catch (e) {
1703 return \`repo=\${meta.name} issue write -> \${e.status}: \${e.message}\`;
1704 }
1705 - run: echo "restricted says $RESULT"
1706 env: { RESULT: "\${{ steps.gs.outputs.result }}" }
1707 node:
1708 runs-on: [self-hosted, linux]
1709 steps:
1710 - uses: actions/checkout@v4
1711 - id: node
1712 uses: actions/setup-node@v4
1713 with: { node-version: 20, cache: npm }
1714 - run: npm ci --no-audit --no-fund && echo "node=$(node --version) npm-cache-hit=\${{ steps.node.outputs.cache-hit }}"
1715 java:
1716 runs-on: [self-hosted, linux]
1717 steps:
1718 - uses: actions/checkout@v4
1719 - id: java
1720 uses: actions/setup-java@v4
1721 with: { distribution: oracle, java-version: "21", cache: maven }
1722 - run: |
1723 mkdir -p ~/.m2/repository/e2e && echo "run \${{ github.run_id }}" > ~/.m2/repository/e2e/marker
1724 echo "java=$(java -version 2>&1 | grep version) maven-cache-hit=\${{ steps.java.outputs.cache-hit }} $(cat ~/.m2/repository/e2e/marker)"
1725`;
1726
1727/** Runs every job of `run` with the real agent; returns their logs by job name. */
1728async function runToolkit(owner, run) {
1729 const home = join(work, "toolkit-home");
1730 const logs = {};
1731 for (let i = 0; i < 6; i++) {
1732 const job = await runOneJob(owner, "toolkit", {
1733 timeoutMs: 420_000,
1734 envFor: (claim) => {
1735 // A fresh HOME per job (at the same path, as on hosted runners): caches must come from the cache service.
1736 rmSync(home, { recursive: true, force: true });
1737 mkdirSync(home, { recursive: true });
1738 return {
1739 ...(process.env.E2E_RUNNER_IMAGE ? {} : { HOME: home, RUNNER_TOOL_CACHE: join(work, "toolcache") }),
1740 // The node job runs every action for real, checkout and setup-node included.
1741 ...(claim.name === "node" ? { DIFFINERY_DISABLE_BUILTINS: "1" } : {}),
1742 };
1743 },
1744 });
1745 // Without the timestamps, so assertions can span lines.
1746 const raw = await (await fetch(`${base}/api/v3/repos/${owner}/toolkit/actions/jobs/${job.claim.job_id}/logs`, { headers: { authorization: `Bearer ${token}` } })).text();
1747 logs[job.claim.name] = raw.replace(/^\S+Z /gm, "");
1748 // Kept with E2E_KEEP=1 for debugging.
1749 mkdirSync(join(work, "toolkit-logs"), { recursive: true });
1750 writeFileSync(join(work, "toolkit-logs", `run${run.run_number}-${job.claim.name}.log`), `${logs[job.claim.name]}\n--- agent ---\n${job.out}`);
1751 }
1752 const done = await until("toolkit run to complete", async () => {
1753 const r = await ok("GET", `/repos/${owner}/toolkit/actions/runs/${run.id}`);
1754 return r.status === "completed" ? r : null;
1755 });
1756 assert.equal(done.conclusion, "success", JSON.stringify(logs, null, 2).slice(-8000));
1757 return logs;
1758}
1759
1760const toolkit = {};
1761
1762test("official actions: checkout, cache, artifacts, github-script and setup-* run unmodified", { timeout: 1_200_000 }, async () => {
1763 const owner = (await ok("GET", "/user")).login;
1764 toolkit.owner = owner;
1765 // A submodule repository, then the main one (LFS object, submodule, sparse-checkout target).
1766 // Public: like GITHUB_TOKEN, the job token reads only its own repository and public ones.
1767 await ok("POST", "/user/repos", { name: "toolkit-lib", visibility: "public" });
1768 const lib = join(work, "toolkit-lib");
1769 mkdirSync(lib, { recursive: true });
1770 writeFileSync(join(lib, "lib.txt"), "from the submodule\n");
1771 git(lib, ["init", "-q", "-b", "main"]);
1772 git(lib, ["add", "."]);
1773 git(lib, ["commit", "-q", "-m", "lib"]);
1774 git(lib, ["remote", "add", "origin", `${base}/${owner}/toolkit-lib.git`]);
1775 git(lib, ["push", "-q", "origin", "main"]);
1776 const libSha = git(lib, ["rev-parse", "HEAD"]).trim();
1777
1778 await ok("POST", "/user/repos", { name: "toolkit" });
1779 // Jobs without permissions: write with the default token (the setting older repositories keep).
1780 await ok("PUT", `/repos/${owner}/toolkit/actions/permissions/workflow`, { default_workflow_permissions: "write" });
1781 const src = join(work, "toolkit");
1782 toolkit.src = src;
1783 mkdirSync(join(src, ".github/workflows"), { recursive: true });
1784 mkdirSync(join(src, "docs"));
1785 writeFileSync(join(src, ".github/workflows/toolkit.yml"), TOOLKIT_WORKFLOW);
1786 writeFileSync(join(src, "docs/guide.md"), "# guide\n");
1787 writeFileSync(join(src, "README.md"), "# toolkit\n");
1788 writeFileSync(join(src, "lock.txt"), "v1\n");
1789 writeFileSync(join(src, "package.json"), JSON.stringify({ name: "toolkit", version: "1.0.0", private: true }, null, 2) + "\n");
1790 writeFileSync(join(src, "package-lock.json"), JSON.stringify({ name: "toolkit", version: "1.0.0", lockfileVersion: 3, requires: true, packages: { "": { name: "toolkit", version: "1.0.0" } } }, null, 2) + "\n");
1791 writeFileSync(join(src, "pom.xml"), "<project><modelVersion>4.0.0</modelVersion><groupId>e2e</groupId><artifactId>toolkit</artifactId><version>1</version></project>\n");
1792 writeFileSync(join(src, ".gitmodules"), '[submodule "lib"]\n\tpath = lib\n\turl = ../toolkit-lib.git\n');
1793 git(src, ["init", "-q", "-b", "main"]);
1794 git(src, ["lfs", "install", "--local"]);
1795 git(src, ["lfs", "track", "*.bin"]);
1796 writeFileSync(join(src, "big.bin"), "the real LFS content\n");
1797 git(src, ["add", "-A"]);
1798 git(src, ["update-index", "--add", "--cacheinfo", `160000,${libSha},lib`]);
1799 git(src, ["commit", "-q", "-m", "toolkit"]);
1800 git(src, ["remote", "add", "origin", `${base}/${owner}/toolkit.git`]);
1801 git(src, ["push", "-q", "origin", "main"]);
1802 assert.match(git(src, ["show", "HEAD:big.bin"]), /git-lfs/, "big.bin is stored as an LFS pointer");
1803
1804 const run = await until("toolkit run", async () => (await ok("GET", `/repos/${owner}/toolkit/actions/runs`)).workflow_runs[0]);
1805 toolkit.firstRun = run;
1806 const logs = await runToolkit(owner, run);
1807
1808 // checkout: LFS content, submodule over HTTP with the job token, credentials not persisted, sparse
1809 assert.match(logs.produce, /the real LFS content\nfrom the submodule/);
1810 assert.match(logs.produce, /no persisted credentials/);
1811 assert.match(logs.produce, /sparse=README\.md big\.bin docs lib lock\.txt package-lock\.json package\.json pom\.xml /);
1812 // cache: a miss on the first run, for the real action and the built-in alike
1813 assert.match(logs.produce, /real-hit= saved by run 1\b/);
1814 assert.match(logs.produce, /builtin-hit= v3-hit=/);
1815 assert.match(logs.produce, /Cache saved with (the )?key: deps-[0-9a-f]{64}/);
1816 // artifacts: ids from both uploads, the URL points back at this server
1817 assert.match(logs.produce, new RegExp(`ids=\\d+,\\d+ url=${base}/${owner}/toolkit/actions/runs/1/artifacts/\\d+`));
1818 assert.match(
1819 logs.consume,
1820 /all\/dist-builtin\/one\.txt all\/dist-builtin\/sub\/two\.txt all\/dist-real\/\.hidden all\/dist-real\/one\.txt all\/dist-real\/sub\/two\.txt merged\/\.hidden merged\/one\.txt merged\/sub\/two\.txt one\/one\.txt one\/sub\/two\.txt/,
1821 );
1822 // github-script: REST calls with the job token
1823 assert.match(logs.script, /script says issue=1 labels=from-run-1 comments=1 pulls=0 event=push repo=[^/]+\/toolkit sender=\S+/);
1824 const issue = await ok("GET", `/repos/${owner}/toolkit/issues/1`);
1825 assert.equal(issue.title, "Opened by run 1");
1826 assert.deepEqual(issue.labels.map((l) => l.name), ["from-run-1"]);
1827 assert.equal((await ok("GET", `/repos/${owner}/toolkit/issues/1/comments`))[0].body, "commented by github-script");
1828 const statuses = await ok("GET", `/repos/${owner}/toolkit/commits/${run.head_sha}/statuses`);
1829 assert.equal(statuses.find((s) => s.context === "github-script")?.state, "success", JSON.stringify(statuses));
1830 // `permissions: { contents: read }`: reading works, issue writes are refused
1831 assert.match(logs.restricted, /restricted says repo=toolkit issue write -> 403: .*issues/);
1832 assert.equal((await ok("GET", `/repos/${owner}/toolkit/issues?state=all`)).filter((i) => i.title === "must not be created").length, 0);
1833 // setup-node (the real action, DIFFINERY_DISABLE_BUILTINS=1) and setup-java: installed, caches saved
1834 assert.match(logs.node, /node=v20\.\d+\.\d+ npm-cache-hit=false/);
1835 assert.match(logs.node, /Cache saved with (the )?key: node-cache-Linux-x64-npm-[0-9a-f]{64}/);
1836 assert.match(logs.java, /java=java version "21[^\n]* maven-cache-hit=false run 1/);
1837 assert.match(logs.java, /Cache saved with (the )?key: setup-java-Linux-x64-maven-[0-9a-f]{64}/);
1838
1839 // the REST API lists the run's artifacts and caches
1840 const artifacts = await ok("GET", `/repos/${owner}/toolkit/actions/runs/1/artifacts`);
1841 assert.deepEqual(artifacts.artifacts.map((a) => a.name).sort(), ["dist-builtin", "dist-real"]);
1842 const caches = await ok("GET", `/repos/${owner}/toolkit/actions/caches`);
1843 assert.equal(caches.total_count, 3, JSON.stringify(caches));
1844 const zip = await fetch(`${base}/api/v3/repos/${owner}/toolkit/actions/artifacts/${artifacts.artifacts[0].id}/zip`, { headers: { authorization: `Bearer ${token}` }, redirect: "manual" });
1845 assert.equal(zip.status, 302);
1846 assert.equal((await fetch(zip.headers.get("location"))).headers.get("content-type"), "application/zip");
1847});
1848
1849test("official actions: the second run hits every cache and reads the first run's artifacts", { timeout: 1_200_000 }, async () => {
1850 const { owner, src, firstRun } = toolkit;
1851 assert.ok(firstRun, "the first toolkit run must have completed");
1852 writeFileSync(join(src, "prev-run.txt"), `${firstRun.run_number}\n`);
1853 git(src, ["add", "prev-run.txt"]);
1854 git(src, ["commit", "-q", "-m", "second run"]);
1855 git(src, ["push", "-q", "origin", "main"]);
1856 const run = await until("second toolkit run", async () => (await ok("GET", `/repos/${owner}/toolkit/actions/runs`)).workflow_runs.find((r) => r.run_number === 2));
1857 const logs = await runToolkit(owner, run);
1858
1859 // The entry the real action saved restores with the real action (v4 and v3) and the built-in.
1860 assert.match(logs.produce, /real-hit=true saved by run 1\b/);
1861 assert.match(logs.produce, /builtin-hit=true v3-hit=true/);
1862 assert.match(logs.produce, /Cache hit occurred on the primary key deps-[0-9a-f]{64}, not saving cache\./);
1863 assert.match(logs.node, /npm-cache-hit=true/);
1864 assert.match(logs.java, /maven-cache-hit=true run 2/);
1865 // Artifacts of another run, through the REST API with github-token (real action and built-in).
1866 assert.match(logs.consume, /previous run two prev-builtin\/dist-builtin\/one\.txt prev-builtin\/dist-builtin\/sub\/two\.txt prev-builtin\/dist-real\/\.hidden prev-builtin\/dist-real\/one\.txt prev-builtin\/dist-real\/sub\/two\.txt/);
1867 assert.match(logs.script, /script says issue=2 labels=from-run-2 comments=1/);
1868});
1869
1870test("D1 sessions: bookmarks for token clients and browsers", async () => {
1871 // Token clients get the bookmark in a header and can send it back to read their own writes.
1872 const r = await fetch(`${base}/api/v3/user`, { headers: { authorization: `Bearer ${token}` } });
1873 assert.equal(r.status, 200);
1874 const bookmark = r.headers.get("x-d1-bookmark");
1875 assert.match(bookmark ?? "", /^[0-9a-f]+(-[0-9a-f]+)+$/i);
1876 assert.equal(r.headers.get("set-cookie"), null);
1877 const again = await fetch(`${base}/api/v3/user`, { headers: { authorization: `Bearer ${token}`, "x-d1-bookmark": bookmark } });
1878 assert.equal(again.status, 200);
1879 // A junk bookmark is ignored rather than breaking the request.
1880 assert.equal((await fetch(`${base}/api/v3/user`, { headers: { authorization: `Bearer ${token}`, "x-d1-bookmark": "nope" } })).status, 200);
1881 // Anonymous page views don't get a cookie; a browser that writes (any non-GET) does.
1882 assert.equal((await fetch(`${base}/`)).headers.get("set-cookie")?.includes("__Host-dfy_d1") ?? false, false);
1883 const post = await fetch(`${base}/auth/logout`, { method: "POST", redirect: "manual", headers: { "sec-fetch-site": "same-origin" } });
1884 assert.match(post.headers.get("set-cookie") ?? "", /__Host-dfy_d1=[0-9a-f-]+; Max-Age=86400; Path=\/; HttpOnly; Secure; SameSite=Lax/);
1885});
1886
1887test("GitHub REST compatibility: Octokit against releases, statuses, git data, issues, deployments and search", async () => {
1888 const { Octokit } = await import("@octokit/rest");
1889 const gh = new Octokit({ auth: token, baseUrl: `${base}/api/v3`, userAgent: "diffinery-e2e", request: { retries: 0 } });
1890 const owner = (await gh.rest.users.getAuthenticated()).data.login;
1891 const repo = "compat";
1892 const R = { owner, repo };
1893
1894 // ------------------------------------------------------------ repository, pushed with git
1895 const created = await gh.rest.repos.createForAuthenticatedUser({ name: repo, description: "Octokit compatibility" });
1896 assert.equal(created.status, 201);
1897 assert.equal(created.data.full_name, `${owner}/${repo}`);
1898 assert.match(created.data.node_id, /\S/);
1899 assert.equal(created.data.owner.login, owner);
1900 const src = join(work, "compat");
1901 mkdirSync(join(src, "src"), { recursive: true });
1902 writeFileSync(join(src, "README.md"), "# compat\n");
1903 writeFileSync(join(src, "src/main.ts"), "export const x = 1;\n");
1904 git(src, ["init", "-q", "-b", "main"]);
1905 git(src, ["add", "-A"]);
1906 git(src, ["commit", "-q", "-m", "initial"]);
1907 git(src, ["remote", "add", "origin", `${base}/${owner}/${repo}.git`]);
1908 git(src, ["push", "-q", "origin", "main"]);
1909 const mainSha = git(src, ["rev-parse", "HEAD"]).trim();
1910
1911 const r = await gh.rest.repos.get(R);
1912 assert.equal(r.data.default_branch, "main");
1913 assert.equal(r.data.permissions.admin, true);
1914 assert.equal(r.headers["x-github-media-type"], "github.v3; format=json");
1915 const rate = await gh.rest.rateLimit.get();
1916 assert.ok(rate.data.resources.core.remaining > 0);
1917
1918 // GitHub error bodies: message and documentation_url, surfaced by Octokit's RequestError.
1919 await assert.rejects(gh.rest.repos.getContent({ ...R, path: "missing.txt" }), (e) => e.status === 404 && typeof e.response.data.message === "string" && typeof e.response.data.documentation_url === "string");
1920
1921 // ------------------------------------------------------------ contents
1922 const readme = await gh.rest.repos.getContent({ ...R, path: "README.md" });
1923 assert.equal(readme.data.type, "file");
1924 assert.equal(Buffer.from(readme.data.content, "base64").toString(), "# compat\n");
1925 const rawReadme = await gh.rest.repos.getContent({ ...R, path: "README.md", mediaType: { format: "raw" } });
1926 assert.equal(rawReadme.data, "# compat\n");
1927 const dir = await gh.rest.repos.getContent({ ...R, path: "src" });
1928 assert.deepEqual(dir.data.map((e) => e.name), ["main.ts"]);
1929 await assert.rejects(gh.rest.repos.createOrUpdateFileContents({ ...R, path: "README.md", message: "stale", content: Buffer.from("x").toString("base64"), sha: "0".repeat(40) }), (e) => e.status === 409);
1930 const put = await gh.rest.repos.createOrUpdateFileContents({ ...R, path: "README.md", message: "Update README", content: Buffer.from("# compat\n\nUpdated.\n").toString("base64"), sha: readme.data.sha, committer: { name: "Release Bot", email: "bot@example.com" } });
1931 assert.equal(put.status, 200);
1932 assert.equal(put.data.commit.committer.name, "Release Bot");
1933 const added = await gh.rest.repos.createOrUpdateFileContents({ ...R, path: "docs/guide.md", message: "Add guide", content: Buffer.from("guide\n").toString("base64") });
1934 assert.equal(added.status, 201);
1935 const readmeApi = await gh.rest.repos.getReadme(R);
1936 assert.equal(readmeApi.data.path, "README.md");
1937
1938 // ------------------------------------------------------------ git data: blob -> tree -> commit -> ref, then git sees it
1939 const headSha = (await gh.rest.git.getRef({ ...R, ref: "heads/main" })).data.object.sha;
1940 assert.equal(headSha, added.data.commit.sha);
1941 const blob = await gh.rest.git.createBlob({ ...R, content: Buffer.from("made with the git data API\n").toString("base64"), encoding: "base64" });
1942 assert.equal(blob.status, 201);
1943 assert.equal(Buffer.from((await gh.rest.git.getBlob({ ...R, file_sha: blob.data.sha })).data.content, "base64").toString(), "made with the git data API\n");
1944 const headCommit = await gh.rest.git.getCommit({ ...R, commit_sha: headSha });
1945 const tree = await gh.rest.git.createTree({ ...R, base_tree: headCommit.data.tree.sha, tree: [{ path: "gitdata/hello.txt", mode: "100644", type: "blob", sha: blob.data.sha }, { path: "inline.txt", mode: "100644", type: "blob", content: "inline\n" }] });
1946 const full = await gh.rest.git.getTree({ ...R, tree_sha: tree.data.sha, recursive: "true" });
1947 assert.ok(full.data.tree.some((e) => e.path === "gitdata/hello.txt" && e.type === "blob"));
1948 assert.ok(full.data.tree.some((e) => e.path === "src/main.ts"));
1949 const commit = await gh.rest.git.createCommit({ ...R, message: "Commit from the git data API", tree: tree.data.sha, parents: [headSha], author: { name: "Diffy", email: "diffy@example.com", date: "2024-05-06T07:08:09Z" } });
1950 assert.equal(commit.data.author.name, "Diffy");
1951 assert.deepEqual(commit.data.parents.map((p) => p.sha), [headSha]);
1952 const ref = await gh.rest.git.createRef({ ...R, ref: "refs/heads/feature", sha: commit.data.sha });
1953 assert.equal(ref.data.ref, "refs/heads/feature");
1954 assert.equal(ref.data.object.type, "commit");
1955 await assert.rejects(gh.rest.git.createRef({ ...R, ref: "refs/heads/feature", sha: commit.data.sha }), (e) => e.status === 422);
1956 const matching = await gh.rest.git.listMatchingRefs({ ...R, ref: "heads/f" });
1957 assert.deepEqual(matching.data.map((x) => x.ref), ["refs/heads/feature"]);
1958 const tag = await gh.rest.git.createTag({ ...R, tag: "v0.1.0", message: "Annotated tag", object: commit.data.sha, type: "commit", tagger: { name: "Diffy", email: "diffy@example.com", date: "2024-05-06T07:08:09Z" } });
1959 await gh.rest.git.createRef({ ...R, ref: "refs/tags/v0.1.0", sha: tag.data.sha });
1960 assert.equal((await gh.rest.git.getTag({ ...R, tag_sha: tag.data.sha })).data.object.sha, commit.data.sha);
1961 assert.equal((await gh.rest.git.getRef({ ...R, ref: "tags/v0.1.0" })).data.object.type, "tag");
1962 git(src, ["fetch", "-q", "origin", "feature", "--tags"]);
1963 assert.equal(git(src, ["show", "FETCH_HEAD:gitdata/hello.txt"]), "made with the git data API\n");
1964 assert.equal(git(src, ["cat-file", "-t", "v0.1.0"]).trim(), "tag");
1965
1966 // ------------------------------------------------------------ commit statuses count as checks, also for required checks
1967 await ok("PUT", `/repos/${owner}/${repo}/branches/main/protection`, { requirePullRequest: true, requiredChecks: ["ci/external"] });
1968 const pr = await gh.rest.pulls.create({ ...R, title: "Feature", head: "feature", base: "main", body: "Adds files" });
1969 assert.equal(pr.status, 201);
1970 const pending = await until("mergeability", async () => {
1971 const p = (await gh.rest.pulls.get({ ...R, pull_number: pr.data.number })).data;
1972 return typeof p.mergeable === "boolean" ? p : null;
1973 });
1974 assert.equal(pending.mergeable, true);
1975 assert.equal(pending.mergeable_state, "blocked");
1976 assert.equal(pending.head.sha, commit.data.sha);
1977 const st = await gh.rest.repos.createCommitStatus({ ...R, sha: commit.data.sha, state: "success", context: "ci/external", description: "External CI passed", target_url: "https://ci.example.com/build/1" });
1978 assert.equal(st.status, 201);
1979 assert.equal(st.data.creator.login, owner);
1980 await assert.rejects(gh.rest.repos.createCommitStatus({ ...R, sha: commit.data.sha, state: "great" }), (e) => e.status === 422);
1981 const combined = await gh.rest.repos.getCombinedStatusForRef({ ...R, ref: "feature" });
1982 assert.equal(combined.data.state, "success");
1983 assert.equal(combined.data.total_count, 1);
1984 assert.equal(combined.data.statuses[0].context, "ci/external");
1985 assert.equal((await gh.rest.repos.listCommitStatusesForRef({ ...R, ref: commit.data.sha })).data.length, 1);
1986 const clean = (await gh.rest.pulls.get({ ...R, pull_number: pr.data.number })).data;
1987 assert.equal(clean.mergeable_state, "clean");
1988 const prPage = await (await fetch(`${base}/${owner}/${repo}/pull/${pr.data.number}/checks`)).text();
1989 assert.match(prPage, /ci\/external/);
1990 assert.match(prPage, /https:\/\/ci\.example\.com\/build\/1/);
1991
1992 // ------------------------------------------------------------ pull request sub-resources
1993 const byHead = await gh.rest.pulls.list({ ...R, head: `${owner}:feature`, state: "open" });
1994 assert.deepEqual(byHead.data.map((p) => p.number), [pr.data.number]);
1995 assert.equal((await gh.rest.pulls.list({ ...R, base: "other" })).data.length, 0);
1996 const assoc = await gh.rest.repos.listPullRequestsAssociatedWithCommit({ ...R, commit_sha: commit.data.sha });
1997 assert.deepEqual(assoc.data.map((p) => p.number), [pr.data.number]);
1998 const rc = await gh.rest.pulls.createReviewComment({ ...R, pull_number: pr.data.number, body: "Why this file?", commit_id: commit.data.sha, path: "inline.txt", line: 1, side: "RIGHT" });
1999 assert.equal(rc.status, 201);
2000 assert.equal(rc.data.path, "inline.txt");
2001 const reply = await gh.rest.pulls.createReplyForReviewComment({ ...R, pull_number: pr.data.number, comment_id: rc.data.id, body: "For the test." });
2002 assert.equal(reply.data.in_reply_to_id, rc.data.id);
2003 // Numeric ids, like GitHub's: actions parse them with Number() and pass them back.
2004 assert.equal(typeof rc.data.id, "number");
2005 assert.equal(typeof rc.data.pull_request_review_id, "number");
2006 assert.equal((await gh.rest.pulls.listReviewComments({ ...R, pull_number: pr.data.number })).data.length, 2);
2007 await gh.rest.reactions.createForPullRequestReviewComment({ ...R, comment_id: rc.data.id, content: "eyes" });
2008 const merged = await gh.rest.pulls.merge({ ...R, pull_number: pr.data.number, merge_method: "squash" });
2009 assert.equal(merged.data.merged, true);
2010 const merges = await gh.rest.issues.listEventsForTimeline({ ...R, issue_number: pr.data.number });
2011 assert.ok(merges.data.some((e) => e.event === "merged"));
2012
2013 // ------------------------------------------------------------ releases and assets
2014 const rel = await gh.rest.repos.createRelease({ ...R, tag_name: "v1.0.0", target_commitish: "main", name: "First", generate_release_notes: true });
2015 assert.equal(rel.status, 201);
2016 assert.match(rel.data.body, /Full Changelog/);
2017 assert.match(rel.data.body, /Feature by @/);
2018 assert.equal(rel.data.author.login, owner);
2019 assert.match(rel.data.upload_url, /\/api\/uploads\/repos\/.+\/releases\/\d+\/assets\{\?name,label\}$/);
2020 assert.match(git(src, ["ls-remote", "--tags", "origin"]), /refs\/tags\/v1\.0\.0/);
2021 const bytes = Buffer.from("hello from a release asset\n");
2022 const up = await gh.rest.repos.uploadReleaseAsset({ ...R, release_id: rel.data.id, name: "hello.txt", label: "Greeting", data: bytes, url: rel.data.upload_url, headers: { "content-type": "text/plain", "content-length": bytes.length } });
2023 assert.equal(up.status, 201);
2024 assert.equal(up.data.name, "hello.txt");
2025 assert.equal(up.data.size, bytes.length);
2026 assert.equal(up.data.state, "uploaded");
2027 const bin = Buffer.from(randomBytes(70_000));
2028 const up2 = await gh.rest.repos.uploadReleaseAsset({ ...R, release_id: rel.data.id, name: "tool linux.bin", data: bin, baseUrl: `${base}/api/uploads`, headers: { "content-type": "application/octet-stream", "content-length": bin.length } });
2029 assert.equal(up2.data.name, "tool.linux.bin");
2030 await assert.rejects(gh.rest.repos.uploadReleaseAsset({ ...R, release_id: rel.data.id, name: "hello.txt", data: bytes, url: rel.data.upload_url, headers: { "content-type": "text/plain", "content-length": bytes.length } }), (e) => e.status === 422);
2031 const viaApi = await gh.rest.repos.getReleaseAsset({ ...R, asset_id: up2.data.id, headers: { accept: "application/octet-stream" } });
2032 assert.deepEqual(Buffer.from(viaApi.data), bin);
2033 const browser = await fetch(up.data.browser_download_url);
2034 assert.equal(browser.status, 200);
2035 assert.equal(await browser.text(), bytes.toString());
2036 assert.match(browser.headers.get("content-disposition") ?? "", /attachment/);
2037 assert.equal((await gh.rest.repos.getReleaseAsset({ ...R, asset_id: up.data.id })).data.download_count, 1);
2038 assert.deepEqual((await gh.rest.repos.listReleaseAssets({ ...R, release_id: rel.data.id })).data.map((a) => a.name), ["hello.txt", "tool.linux.bin"]);
2039 assert.equal((await gh.rest.repos.updateReleaseAsset({ ...R, asset_id: up.data.id, label: "Hello" })).data.label, "Hello");
2040 assert.equal((await gh.rest.repos.getLatestRelease(R)).data.id, rel.data.id);
2041 assert.equal((await gh.rest.repos.getReleaseByTag({ ...R, tag: "v1.0.0" })).data.assets.length, 2);
2042 const notes = await gh.rest.repos.generateReleaseNotes({ ...R, tag_name: "v1.1.0", previous_tag_name: "v1.0.0" });
2043 assert.match(notes.data.body, /compare\/v1\.0\.0\.\.\.v1\.1\.0/);
2044 await gh.rest.reactions.createForRelease({ ...R, release_id: rel.data.id, content: "rocket" });
2045 assert.equal((await gh.rest.repos.getRelease({ ...R, release_id: rel.data.id })).data.reactions.rocket, 1);
2046
2047 // Drafts are for writers only; a read-only token sees neither the draft nor its tag lookup.
2048 const draft = await gh.rest.repos.createRelease({ ...R, tag_name: "v2.0.0-rc.1", name: "Next", draft: true, prerelease: true });
2049 assert.equal(draft.data.draft, true);
2050 const reader = await ok("POST", "/diffinery/tokens", { name: "reader", scopes: ["read"] }, null);
2051 const ro = new Octokit({ auth: reader.token, baseUrl: `${base}/api/v3`, request: { retries: 0 } });
2052 assert.deepEqual((await ro.rest.repos.listReleases(R)).data.map((x) => x.tag_name), ["v1.0.0"]);
2053 await assert.rejects(ro.rest.repos.getRelease({ ...R, release_id: draft.data.id }), (e) => e.status === 404);
2054 await assert.rejects(ro.rest.repos.createRelease({ ...R, tag_name: "v9" }), (e) => e.status === 403 || e.status === 404);
2055 const published = await gh.rest.repos.updateRelease({ ...R, release_id: draft.data.id, draft: false, make_latest: "false" });
2056 assert.equal(published.data.draft, false);
2057 assert.equal((await gh.rest.repos.getLatestRelease(R)).data.tag_name, "v1.0.0");
2058 await gh.rest.repos.deleteReleaseAsset({ ...R, asset_id: up2.data.id });
2059 assert.equal((await fetch(`${base}/${owner}/${repo}/releases/download/v1.0.0/tool.linux.bin`)).status, 404);
2060 await gh.rest.repos.deleteRelease({ ...R, release_id: published.data.id });
2061 await assert.rejects(gh.rest.repos.getReleaseByTag({ ...R, tag: "v2.0.0-rc.1" }), (e) => e.status === 404);
2062
2063 // Archives
2064 const zipball = await gh.rest.repos.downloadZipballArchive({ ...R, ref: "v1.0.0" });
2065 assert.equal(Buffer.from(zipball.data).subarray(0, 2).toString(), "PK");
2066 const tarball = await gh.rest.repos.downloadTarballArchive({ ...R, ref: "main" });
2067 assert.deepEqual([...Buffer.from(tarball.data).subarray(0, 2)], [0x1f, 0x8b]);
2068 const tgz = join(work, "compat.tar.gz");
2069 writeFileSync(tgz, Buffer.from(tarball.data));
2070 assert.match(execFileSync("tar", ["tzf", tgz], { encoding: "utf8" }), /\/gitdata\/hello\.txt/);
2071
2072 // The web UI: releases list, the release page and the form (CSRF, Kumo controls, multipart upload).
2073 const list = await (await fetch(`${base}/${owner}/${repo}/releases`)).text();
2074 assert.match(list, /First/);
2075 assert.match(list, /hello\.txt/);
2076 const form = await fetch(`${base}/${owner}/${repo}/releases/new`);
2077 const html = await form.text();
2078 assert.doesNotMatch(html, /<select|type="checkbox"|type="radio"/);
2079 const csrf = /name="_csrf" value="([^"]+)"/.exec(html)?.[1];
2080 const cookie = /dfy_csrf=([^;]+)/.exec(form.headers.get("set-cookie") ?? "")?.[1];
2081 assert.ok(csrf && cookie);
2082 const fd = new FormData();
2083 for (const [k, v] of Object.entries({ _csrf: csrf, tag: "", new_tag: "v3.0.0", target: "main", name: "From the web", body: "Notes from the form.", latest: "1", action: "publish" })) fd.append(k, v);
2084 fd.append("assets", new Blob(["web upload\n"], { type: "text/plain" }), "web.txt");
2085 const submit = await fetch(`${base}/${owner}/${repo}/releases`, { method: "POST", body: fd, redirect: "manual", headers: { cookie: `dfy_csrf=${cookie}` } });
2086 assert.equal(submit.status, 303, await submit.text());
2087 assert.equal(submit.headers.get("location"), `/${owner}/${repo}/releases/tag/v3.0.0`);
2088 assert.equal(await (await fetch(`${base}/${owner}/${repo}/releases/download/v3.0.0/web.txt`)).text(), "web upload\n");
2089 assert.equal((await gh.rest.repos.getLatestRelease(R)).data.tag_name, "v3.0.0");
2090 assert.match(await (await fetch(`${base}/${owner}/${repo}`)).text(), /From the web/);
2091
2092 // ------------------------------------------------------------ issues: labels, assignees, lock, reactions, events, pagination
2093 await gh.rest.issues.createLabel({ ...R, name: "bug", color: "d73a4a", description: "Something is broken" });
2094 await assert.rejects(gh.rest.issues.createLabel({ ...R, name: "bug", color: "d73a4a" }), (e) => e.status === 422);
2095 const issue = await gh.rest.issues.create({ ...R, title: "Crash on start", body: "It crashes.", labels: ["bug"], assignees: [owner] });
2096 assert.deepEqual(issue.data.labels.map((l) => [l.name, l.color]), [["bug", "d73a4a"]]);
2097 assert.equal(issue.data.assignees[0].login, owner);
2098 assert.equal(issue.data.user.login, owner);
2099 assert.match(issue.data.html_url, new RegExp(`/${owner}/${repo}/issues/${issue.data.number}$`));
2100 const n = issue.data.number;
2101 await gh.rest.issues.addLabels({ ...R, issue_number: n, labels: ["triage"] });
2102 assert.deepEqual((await gh.rest.issues.listLabelsOnIssue({ ...R, issue_number: n })).data.map((l) => l.name).sort(), ["bug", "triage"]);
2103 await gh.rest.issues.removeLabel({ ...R, issue_number: n, name: "triage" });
2104 await gh.rest.issues.removeAssignees({ ...R, issue_number: n, assignees: [owner] });
2105 await gh.rest.issues.addAssignees({ ...R, issue_number: n, assignees: [owner] });
2106 assert.equal((await gh.rest.issues.checkUserCanBeAssigned({ ...R, assignee: owner })).status, 204);
2107 const comment = await gh.rest.issues.createComment({ ...R, issue_number: n, body: "Same here." });
2108 assert.equal(typeof comment.data.id, "number");
2109 assert.equal((await gh.rest.issues.getComment({ ...R, comment_id: comment.data.id })).data.body, "Same here.");
2110 await gh.rest.issues.updateComment({ ...R, comment_id: comment.data.id, body: "Same here!" });
2111 assert.equal((await gh.rest.issues.getComment({ ...R, comment_id: String(comment.data.id) })).data.body, "Same here!");
2112 await gh.rest.reactions.createForIssue({ ...R, issue_number: n, content: "+1" });
2113 const heart = await gh.rest.reactions.createForIssueComment({ ...R, comment_id: comment.data.id, content: "heart" });
2114 assert.equal(heart.status, 201);
2115 assert.equal((await gh.rest.reactions.createForIssueComment({ ...R, comment_id: comment.data.id, content: "heart" })).status, 200);
2116 assert.deepEqual((await gh.rest.reactions.listForIssue({ ...R, issue_number: n })).data.map((x) => x.content), ["+1"]);
2117 assert.equal((await gh.rest.issues.get({ ...R, issue_number: n })).data.reactions["+1"], 1);
2118 await gh.rest.issues.lock({ ...R, issue_number: n, lock_reason: "resolved" });
2119 const locked = await gh.rest.issues.get({ ...R, issue_number: n });
2120 assert.equal(locked.data.locked, true);
2121 assert.equal(locked.data.active_lock_reason, "resolved");
2122 await gh.rest.issues.unlock({ ...R, issue_number: n });
2123 await gh.rest.issues.update({ ...R, issue_number: n, title: "Crash on startup", state: "closed", state_reason: "completed" });
2124 const events = (await gh.rest.issues.listEvents({ ...R, issue_number: n })).data.map((e) => e.event);
2125 for (const e of ["labeled", "unlabeled", "unassigned", "assigned", "locked", "unlocked", "renamed", "closed"]) assert.ok(events.includes(e), `${e} in ${events}`);
2126 const timeline = (await gh.rest.issues.listEventsForTimeline({ ...R, issue_number: n })).data;
2127 assert.ok(timeline.some((e) => e.event === "commented" && e.body === "Same here!" && e.id === comment.data.id));
2128 assert.ok((await gh.rest.issues.listCommentsForRepo(R)).data.some((x) => x.id === comment.data.id));
2129 await gh.rest.issues.deleteComment({ ...R, comment_id: comment.data.id });
2130 await assert.rejects(gh.rest.issues.getComment({ ...R, comment_id: comment.data.id }), (e) => e.status === 404);
2131
2132 for (let i = 0; i < 3; i++) await gh.rest.issues.create({ ...R, title: `Paged ${i}` });
2133 const page1 = await gh.rest.issues.listForRepo({ ...R, state: "all", per_page: 2 });
2134 assert.equal(page1.data.length, 2);
2135 assert.match(page1.headers.link ?? "", /rel="next"/);
2136 const all = await gh.paginate(gh.rest.issues.listForRepo, { ...R, state: "all", per_page: 2 });
2137 assert.equal(new Set(all.map((x) => x.number)).size, all.length);
2138 assert.ok(all.length >= 5, `paginated ${all.length} issues and pull requests`);
2139
2140 // ------------------------------------------------------------ search, over readable repositories only
2141 const found = await until("issue search", async () => {
2142 const s = await gh.rest.search.issuesAndPullRequests({ q: `repo:${owner}/${repo} is:issue label:bug crash` });
2143 return s.data.total_count ? s.data : null;
2144 });
2145 assert.deepEqual(found.items.map((x) => x.number), [n]);
2146 assert.equal((await gh.rest.search.issuesAndPullRequests({ q: `repo:${owner}/${repo} is:pr is:merged` })).data.items[0].number, pr.data.number);
2147 assert.equal((await gh.rest.search.issuesAndPullRequests({ q: `repo:${owner}/${repo} is:issue -label:bug Paged`, sort: "created", order: "asc" })).data.items.map((x) => x.title).join(","), "Paged 0,Paged 1,Paged 2");
2148 await gh.rest.repos.replaceAllTopics({ ...R, names: ["octokit", "e2e"] });
2149 assert.deepEqual((await gh.rest.repos.getAllTopics(R)).data.names, ["octokit", "e2e"]);
2150 const repos = await gh.rest.search.repos({ q: `topic:octokit user:${owner}` });
2151 assert.deepEqual(repos.data.items.map((x) => x.full_name), [`${owner}/${repo}`]);
2152 assert.ok("TypeScript" in (await gh.rest.repos.listLanguages(R)).data);
2153
2154 // ------------------------------------------------------------ deployments and environments
2155 const env = await gh.rest.repos.createOrUpdateEnvironment({ ...R, environment_name: "staging" });
2156 assert.equal(env.data.name, "staging");
2157 const dep = await gh.rest.repos.createDeployment({ ...R, ref: "main", environment: "staging", auto_merge: false, required_contexts: [], payload: { region: "eu" }, description: "Deploy to staging" });
2158 assert.equal(dep.status, 201);
2159 assert.equal(dep.data.sha, (await gh.rest.git.getRef({ ...R, ref: "heads/main" })).data.object.sha);
2160 assert.deepEqual(dep.data.payload, { region: "eu" });
2161 await gh.rest.repos.createDeploymentStatus({ ...R, deployment_id: dep.data.id, state: "in_progress" });
2162 const ds = await gh.rest.repos.createDeploymentStatus({ ...R, deployment_id: dep.data.id, state: "success", environment_url: "https://staging.example.com", log_url: "https://ci.example.com/deploy/1" });
2163 assert.equal(ds.data.state, "success");
2164 assert.deepEqual((await gh.rest.repos.listDeploymentStatuses({ ...R, deployment_id: dep.data.id })).data.map((x) => x.state), ["success", "in_progress"]);
2165 assert.equal((await gh.rest.repos.listDeployments({ ...R, environment: "staging" })).data.length, 1);
2166 assert.ok((await gh.rest.repos.getAllEnvironments(R)).data.environments.some((e) => e.name === "staging"));
2167 await gh.rest.actions.createEnvironmentVariable({ ...R, environment_name: "staging", name: "REGION", value: "eu" });
2168 assert.equal((await gh.rest.actions.getEnvironmentVariable({ ...R, environment_name: "staging", name: "REGION" })).data.value, "eu");
2169 await gh.rest.repos.deleteAnEnvironment({ ...R, environment_name: "staging" });
2170
2171 // ------------------------------------------------------------ repository_dispatch and repository variables
2172 assert.equal((await gh.rest.repos.createDispatchEvent({ ...R, event_type: "deploy", client_payload: { env: "prod" } })).status, 204);
2173 await gh.rest.actions.createRepoVariable({ ...R, name: "COLOR", value: "blue" });
2174 await gh.rest.actions.updateRepoVariable({ ...R, name: "COLOR", value: "green" });
2175 assert.equal((await gh.rest.actions.getRepoVariable({ ...R, name: "COLOR" })).data.value, "green");
2176});
2177
2178/** A small opaque RGBA PNG (a gradient), built by hand so the test needs no image tools. */
2179function pngGradient(width, height) {
2180 const chunk = (type, body) => {
2181 const out = Buffer.alloc(12 + body.length);
2182 out.writeUInt32BE(body.length, 0);
2183 out.write(type, 4, "latin1");
2184 body.copy(out, 8);
2185 out.writeUInt32BE(crc32(out.subarray(4, 8 + body.length)), 8 + body.length);
2186 return out;
2187 };
2188 const ihdr = Buffer.alloc(13);
2189 ihdr.writeUInt32BE(width, 0);
2190 ihdr.writeUInt32BE(height, 4);
2191 ihdr.set([8, 6, 0, 0, 0], 8);
2192 const raw = Buffer.alloc((width * 4 + 1) * height);
2193 for (let y = 0; y < height; y++)
2194 for (let x = 0; x < width; x++) raw.set([(x * 255) / width, (y * 255) / height, 128, 255], y * (width * 4 + 1) + 1 + x * 4);
2195 return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
2196}
2197
2198/** Width and height of a lossy or extended WebP, or null when it is not one. */
2199function webpSize(b) {
2200 if (b.toString("latin1", 0, 4) !== "RIFF" || b.toString("latin1", 8, 12) !== "WEBP") return null;
2201 const chunk = b.toString("latin1", 12, 16);
2202 if (chunk === "VP8 ") return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
2203 if (chunk === "VP8X") return { width: b.readUIntLE(24, 3) + 1, height: b.readUIntLE(27, 3) + 1 };
2204 return null;
2205}
2206
2207test("people and profiles: visibility, repository invitations, blank names and usernames", async () => {
2208 const me = await ok("GET", "/user");
2209 // A form post as the signed-in dev user, with the CSRF double-submit pair taken from `page`.
2210 const submit = async (page, action, fields) => {
2211 const res = await fetch(`${base}${page}`);
2212 const csrf = /name="_csrf" value="([^"]+)"/.exec(await res.text())?.[1];
2213 const cookie = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1];
2214 assert.ok(csrf && cookie, `no CSRF pair on ${page}`);
2215 return fetch(`${base}${action}`, { method: "POST", body: new URLSearchParams({ _csrf: csrf, ...fields }), redirect: "manual", headers: { cookie: `dfy_csrf=${cookie}`, "sec-fetch-site": "same-origin" } });
2216 };
2217 const flashOf = (res) => decodeURIComponent(decodeURIComponent(res.headers.get("set-cookie") ?? ""));
2218
2219 // "internal" is gone: creating and updating refuse it the same way.
2220 const created = await api("POST", "/user/repos", { name: "people-rules", visibility: "internal" });
2221 assert.equal(created.status, 422);
2222 await ok("POST", "/user/repos", { name: "people-rules" });
2223 const patched = await api("PATCH", `/repos/${me.login}/people-rules`, { visibility: "internal" });
2224 assert.equal(patched.status, 422);
2225 assert.equal(created.json.message, patched.json.message);
2226 assert.deepEqual(created.json.errors, patched.json.errors);
2227
2228 // Inviting the same email to a repository twice (any letter case) is refused.
2229 const access = `/${me.login}/people-rules/settings/access`;
2230 const first = await submit(access, `${access}/people`, { who: "newcomer@example.com", role: "read" });
2231 assert.equal(first.status, 200, flashOf(first));
2232 assert.match(await first.text(), /newcomer@example\.com/);
2233 const second = await submit(access, `${access}/people`, { who: "NewComer@Example.com", role: "write" });
2234 assert.equal(second.status, 303);
2235 assert.match(flashOf(second), /already has a pending invitation/);
2236
2237 // ...and it can be revoked: on the access page, in the API and over MCP. Then the address can be invited again.
2238 const mcp = async (name, args) => {
2239 const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "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 } }) });
2240 const { result } = await r.json();
2241 assert.equal(result.isError, false, result.content[0].text);
2242 return result.structuredContent;
2243 };
2244 const repoInvites = async () => ok("GET", `/repos/${me.login}/people-rules/invitations`);
2245 const [pending] = await repoInvites();
2246 assert.equal(pending.email, "newcomer@example.com");
2247 assert.match(await (await fetch(`${base}${access}`)).text(), new RegExp(`action="${access}/invites/${pending.id}/revoke"`));
2248 const revoked = await submit(access, `${access}/invites/${pending.id}/revoke`, {});
2249 assert.match(flashOf(revoked), /Invitation revoked/);
2250 assert.deepEqual(await repoInvites(), []);
2251 assert.equal((await submit(access, `${access}/people`, { who: "newcomer@example.com", role: "read" })).status, 200);
2252 const [again] = await repoInvites();
2253 assert.equal((await api("DELETE", `/repos/${me.login}/people-rules/invitations/${again.id}`)).status, 204);
2254 assert.equal((await api("DELETE", `/repos/${me.login}/people-rules/invitations/${again.id}`)).status, 404);
2255 await submit(access, `${access}/people`, { who: "newcomer@example.com", role: "read" });
2256 const listed = (await mcp("list_invitations", { owner: me.login, repo: "people-rules" })).result;
2257 assert.deepEqual(listed.map((i) => i.email), ["newcomer@example.com"]);
2258 assert.equal((await mcp("revoke_invitation", { owner: me.login, repo: "people-rules", invitation_id: listed[0].id })).revoked, true);
2259 assert.deepEqual(await repoInvites(), []);
2260
2261 // Organization and site invitations too; each revoke only reaches its own kind.
2262 await ok("POST", "/user/orgs", { login: "revokers" });
2263 const orgInvite = await ok("POST", "/orgs/revokers/invitations", { email: "joiner@example.com" });
2264 const siteInvite = await ok("POST", "/invitations", { email: "visitor@example.com" });
2265 assert.deepEqual((await ok("GET", "/orgs/revokers/invitations")).map((i) => i.id), [orgInvite.id]);
2266 const site = await ok("GET", "/invitations");
2267 assert.ok(site.some((i) => i.id === siteInvite.id) && !site.some((i) => i.id === orgInvite.id));
2268 assert.equal((await api("DELETE", `/invitations/${orgInvite.id}`)).status, 404);
2269 assert.equal((await api("DELETE", `/orgs/revokers/invitations/${siteInvite.id}`)).status, 404);
2270 assert.equal((await api("DELETE", `/orgs/revokers/invitations/${orgInvite.id}`)).status, 204);
2271 await ok("POST", "/orgs/revokers/invitations", { email: "joiner@example.com" });
2272 const [orgAgain] = (await mcp("list_invitations", { org: "revokers" })).result;
2273 assert.equal((await mcp("revoke_invitation", { org: "revokers", invitation_id: orgAgain.id })).revoked, true);
2274 assert.match(await (await fetch(`${base}/settings/admin`)).text(), new RegExp(`/settings/admin/invites/${siteInvite.id}/revoke`));
2275 assert.match(flashOf(await submit("/settings/admin", `/settings/admin/invites/${siteInvite.id}/revoke`, {})), /Invitation revoked/);
2276 assert.ok(!(await ok("GET", "/invitations")).some((i) => i.id === siteInvite.id));
2277
2278 // A blank display name falls back to the username.
2279 const saved = await submit("/settings", "/settings/profile", { login: me.login, name: " " });
2280 assert.match(flashOf(saved), /Profile saved\./);
2281 assert.equal((await ok("GET", `/users/${me.login}`)).name, null);
2282 assert.match(await (await fetch(`${base}/${me.login}`)).text(), new RegExp(`<h1[^>]*>${me.login}</h1>`));
2283
2284 // Usernames: the browser's pattern and the server agree that dots aren't allowed.
2285 const settings = await (await fetch(`${base}/settings`)).text();
2286 const pattern = /name="login"[^>]*pattern="([^"]+)"/.exec(settings)?.[1];
2287 assert.ok(pattern, "the username field has a pattern");
2288 assert.equal(new RegExp(`^(?:${pattern.replaceAll("&amp;", "&")})$`, "v").test("dot.name"), false);
2289 assert.equal((await api("POST", "/user/orgs", { login: "dot.name" })).status, 422);
2290});
2291
2292test("profile pictures: upload, resize, serve, cache headers and removal", async () => {
2293 const me = await ok("GET", "/user");
2294 const avatar = async (login, query = "") => {
2295 const r = await fetch(`${base}/api/avatars/${login}${query}`);
2296 assert.equal(r.status, 200);
2297 return { type: r.headers.get("content-type"), cache: r.headers.get("cache-control"), csp: r.headers.get("content-security-policy"), body: Buffer.from(await r.arrayBuffer()) };
2298 };
2299 const put = (path, body, tok = token) => fetch(`${base}/api/v3${path}`, { method: "PUT", headers: { authorization: `Bearer ${tok}`, "content-type": "image/png" }, body });
2300
2301 // Before any upload: generated initials, also for logins that don't exist.
2302 const initials = await avatar(me.login, "?s=64");
2303 assert.match(initials.type, /^image\/svg\+xml/);
2304 assert.equal(initials.csp, "default-src 'none'; style-src 'unsafe-inline'");
2305 assert.match((await avatar("no-such-user-here")).type, /^image\/svg\+xml/);
2306
2307 // REST upload: a 600×400 PNG becomes centred square WebPs.
2308 const up = await put("/user/avatar", pngGradient(600, 400));
2309 assert.equal(up.status, 200, await up.clone().text());
2310 const { avatar_url } = await up.json();
2311 const version = new URL(avatar_url).searchParams.get("v");
2312 assert.match(version ?? "", /^\d+$/);
2313 for (const s of [64, 128, 256]) {
2314 const a = await avatar(me.login, `?s=${s}&v=${version}`);
2315 assert.equal(a.type, "image/webp");
2316 assert.deepEqual(webpSize(a.body), { width: s, height: s });
2317 assert.ok(a.body.length < 10_000, `${s}px WebP is ${a.body.length} bytes`);
2318 assert.match(a.cache, /immutable/);
2319 }
2320 const current = await avatar(me.login, "?s=64");
2321 assert.equal(current.type, "image/webp");
2322 assert.match(current.cache, /max-age=600/);
2323
2324 // Only JPEG, PNG and WebP, sniffed from the bytes.
2325 const gif = await put("/user/avatar", Buffer.from("GIF89a\x01\x00\x01\x00\x00\x00\x00;", "latin1"));
2326 assert.equal(gif.status, 422);
2327 assert.equal((await gif.json()).message, "Use a JPEG, PNG or WebP image.");
2328 // Read-only tokens can't change a profile.
2329 const ro = (await ok("POST", "/diffinery/tokens", { name: "ro", scopes: ["read"] }, null)).token;
2330 assert.equal((await put("/user/avatar", pngGradient(8, 8), ro)).status, 403);
2331
2332 // The web form (multipart, CSRF double-submit) takes the original file and the server resizes it.
2333 const page = await fetch(`${base}/settings`);
2334 const csrf = /name="_csrf" value="([^"]+)"/.exec(await page.text())?.[1];
2335 const cookie = /dfy_csrf=([^;]+)/.exec(page.headers.get("set-cookie") ?? "")?.[1];
2336 assert.ok(csrf && cookie);
2337 const form = new FormData();
2338 form.set("_csrf", csrf);
2339 form.set("avatar", new Blob([pngGradient(300, 500)], { type: "image/png" }), "me.png");
2340 const posted = await fetch(`${base}/settings/avatar`, { method: "POST", body: form, redirect: "manual", headers: { cookie: `dfy_csrf=${cookie}`, "sec-fetch-site": "same-origin" } });
2341 assert.equal(posted.status, 303);
2342 assert.match(decodeURIComponent(decodeURIComponent(posted.headers.get("set-cookie") ?? "")), /"kind":"notice","message":"Profile picture updated\."/);
2343 const settings = await (await fetch(`${base}/settings`)).text();
2344 const newVersion = /\/api\/avatars\/[^"?]+\?s=256&amp;v=(\d+)/.exec(settings)?.[1];
2345 assert.ok(newVersion && newVersion !== version, "the settings page links the new version");
2346 // An old version's URL gets the current picture, but not as an immutable response.
2347 assert.match((await avatar(me.login, `?s=64&v=${version}`)).cache, /max-age=600/);
2348
2349 // Organizations: owners (admins get a 403; see the security tests).
2350 await ok("POST", "/user/orgs", { login: "picture-org" });
2351 const org = await put("/orgs/picture-org/avatar", pngGradient(64, 64));
2352 assert.equal(org.status, 200, await org.clone().text());
2353 assert.equal((await avatar("picture-org", "?s=128")).type, "image/webp");
2354 assert.equal((await fetch(`${base}/api/v3/orgs/picture-org/avatar`, { method: "DELETE", headers: { authorization: `Bearer ${token}` } })).status, 200);
2355 assert.match((await avatar("picture-org", "?s=128")).type, /^image\/svg\+xml/);
2356
2357 // Removal falls back to initials straight away (the cached copies are purged).
2358 const del = await fetch(`${base}/api/v3/user/avatar`, { method: "DELETE", headers: { authorization: `Bearer ${token}` } });
2359 assert.deepEqual(await del.json(), { avatar_url: `${base}/api/avatars/${me.login}` });
2360 assert.match((await avatar(me.login, "?s=64")).type, /^image\/svg\+xml/);
2361});
2362
2363// ---------------------------------------------------------------- GitHub imports
2364
2365/** Build the fake GitHub's repositories with real git: history with a merged pull request, a draft, a fork head, tags, LFS and an old secret. */
2366function githubFixture(root) {
2367 const g = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_AUTHOR_NAME: "Octo", GIT_AUTHOR_EMAIL: "octo@example.com", GIT_COMMITTER_NAME: "Octo", GIT_COMMITTER_EMAIL: "octo@example.com" } }).trim();
2368 const src = join(root, "work-app");
2369 mkdirSync(join(src, ".github/workflows"), { recursive: true });
2370 g(root, "init", "-q", "-b", "main", src);
2371 const asset = lfsObject(`binary asset ${randomBytes(8).toString("hex")}\n`);
2372 writeFileSync(join(src, "README.md"), "# app\n");
2373 writeFileSync(join(src, ".gitattributes"), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
2374 writeFileSync(join(src, "asset.bin"), asset.pointer);
2375 // Would start a run on every push if imports fired workflows.
2376 writeFileSync(join(src, ".github/workflows/ci.yml"), "name: CI\non: [push, pull_request]\njobs:\n build:\n runs-on: [self-hosted, linux]\n steps:\n - run: echo hi\n");
2377 // A credential committed long ago (built here so this file has none).
2378 writeFileSync(join(src, "settings.env"), `AWS_ACCESS_KEY_ID=${"AKIA"}${"Q3EGRK5V7XJZ2MWN"}\n`);
2379 g(src, "add", "-A");
2380 g(src, "-c", "core.hooksPath=/dev/null", "commit", "-q", "-m", "initial");
2381 g(src, "tag", "v0.1");
2382 g(src, "rm", "-q", "settings.env");
2383 g(src, "commit", "-q", "-m", "remove credentials");
2384 // Enough data that a small push budget needs several chunks.
2385 for (let i = 0; i < 4; i++) {
2386 writeFileSync(join(src, `data${i}.bin.txt`), randomBytes(90 * 1024).toString("base64"));
2387 g(src, "add", "-A");
2388 g(src, "commit", "-q", "-m", `data ${i}`);
2389 }
2390 g(src, "checkout", "-q", "-b", "feature");
2391 writeFileSync(join(src, "feature.txt"), "feature\n");
2392 g(src, "add", "-A");
2393 g(src, "commit", "-q", "-m", "feature");
2394 const featureSha = g(src, "rev-parse", "HEAD");
2395 g(src, "checkout", "-q", "main");
2396 g(src, "merge", "-q", "--no-ff", "-m", "Merge pull request #2 from octo/feature", "feature");
2397 const mergeSha = g(src, "rev-parse", "HEAD");
2398 g(src, "tag", "-a", "v1.0", "-m", "Version 1.0");
2399 g(src, "checkout", "-q", "-b", "draft-work");
2400 writeFileSync(join(src, "draft.txt"), "wip\n");
2401 g(src, "add", "-A");
2402 g(src, "commit", "-q", "-m", "draft");
2403 const draftSha = g(src, "rev-parse", "HEAD");
2404 // A fork's commit: only GitHub's refs/pull/6/head points at it.
2405 g(src, "checkout", "-q", "--detach", "main");
2406 writeFileSync(join(src, "fork.txt"), "from a fork\n");
2407 g(src, "add", "-A");
2408 g(src, "commit", "-q", "-m", "fork change");
2409 const forkSha = g(src, "rev-parse", "HEAD");
2410 g(src, "checkout", "-q", "main");
2411 const bare = join(root, "octo", "app.git");
2412 mkdirSync(join(root, "octo"), { recursive: true });
2413 g(root, "clone", "-q", "--bare", src, bare);
2414 g(bare, "update-ref", "refs/pull/2/head", featureSha);
2415 g(bare, "update-ref", "refs/pull/2/merge", mergeSha);
2416 g(bare, "update-ref", "refs/pull/5/head", draftSha);
2417 g(bare, "update-ref", "refs/pull/6/head", forkSha);
2418 g(bare, "update-ref", "refs/heads/gh-readonly-queue/main/pr-9-0123456789abcdef", mergeSha);
2419 // A second repository for the organization import.
2420 const lib = join(root, "work-lib");
2421 g(root, "init", "-q", "-b", "trunk", lib);
2422 writeFileSync(join(lib, "lib.txt"), "lib\n");
2423 g(lib, "add", "-A");
2424 g(lib, "commit", "-q", "-m", "lib");
2425 g(root, "clone", "-q", "--bare", lib, join(root, "octo", "lib.git"));
2426 return { asset, featureSha, mergeSha, draftSha, forkSha, mainSha: mergeSha };
2427}
2428
2429test("import from GitHub: git data, issues and pull requests with their numbers, no side effects", async () => {
2430 const me = await ok("GET", "/user");
2431 const owner = me.login;
2432 const ghRoot = join(work, "github");
2433 const fx = githubFixture(ghRoot);
2434 const GH_TOKEN = `ghfake${randomBytes(12).toString("hex")}`;
2435 const t = "2024-01-02T03:04:05Z";
2436 const u = (login, id) => ({ login, id, type: "User" });
2437 const octoDev = u("octo-dev", 1001);
2438 const alice = u("alice", 2001);
2439 const bob = u("bob", 3001);
2440 let ghBase;
2441 let linkNonce = ""; // set from the link challenge, then served back in octo-dev's public gist
2442 let listHuge = false; // the organization lists an oversized repository once set
2443 const pr = (number, extra) => ({ number, title: `PR ${number}`, body: `Body of #${number}`, state: "open", user: alice, labels: [], assignees: [], milestone: null, locked: false, created_at: t, updated_at: t, closed_at: null, draft: false, merged_at: null, merge_commit_sha: null, requested_reviewers: [], head: { ref: "x", sha: fx.mainSha, label: "octo:x", repo: { full_name: "octo/app" } }, base: { ref: "main", repo: { full_name: "octo/app" } }, ...extra });
2444 const issue = (number, extra) => ({ number, title: `Issue ${number}`, body: `Body of #${number}`, state: "open", state_reason: null, user: octoDev, labels: [], assignees: [], milestone: null, locked: false, created_at: t, updated_at: t, closed_at: null, ...extra });
2445 const pulls = [
2446 pr(2, { title: "Add feature", state: "closed", closed_at: "2024-02-01T00:00:00Z", merged_at: "2024-02-01T00:00:00Z", merge_commit_sha: fx.mergeSha, labels: [{ name: "docs" }], head: { ref: "feature", sha: fx.featureSha, label: "octo:feature", repo: { full_name: "octo/app" } } }),
2447 pr(5, { title: "Work in progress", draft: true, requested_reviewers: [bob], head: { ref: "draft-work", sha: fx.draftSha, label: "octo:draft-work", repo: { full_name: "octo/app" } } }),
2448 pr(6, { title: "From a fork", state: "closed", closed_at: "2024-03-01T00:00:00Z", head: { ref: "patch", sha: fx.forkSha, label: "forker:patch", repo: { full_name: "forker/app" } } }),
2449 ];
2450 const issues = [
2451 issue(1, { title: "First bug", labels: [{ name: "bug", color: "d73a4a" }], assignees: [octoDev], milestone: { number: 1 } }),
2452 ...pulls.map((p) => ({ ...p, pull_request: { url: "x" } })),
2453 issue(3, { title: "Won't fix", user: alice, state: "closed", state_reason: "not_planned", closed_at: "2024-01-05T00:00:00Z", locked: true }),
2454 // #4 was deleted on GitHub: the number stays unused.
2455 issue(7, { title: "Latest", user: { login: "ghost-user", id: 9999 } }),
2456 ];
2457 const repoJson = (name, extra) => ({ name, full_name: `octo/${name}`, owner: { login: "octo" }, private: true, visibility: "private", fork: false, archived: false, description: `The ${name}`, homepage: "https://app.example.com", topics: ["demo", "import"], default_branch: "main", ...extra });
2458 const empty = [];
2459 const routes = {
2460 "GET /user": octoDev,
2461 // Gist-proof account linking: octo-dev's public profile, their gists, and the gist body with the nonce.
2462 "GET /users/octo-dev": octoDev,
2463 "GET /users/octo-dev/gists": () => [{ id: "proofgist", public: true, description: "", files: { "proof.md": { raw_url: `${ghBase}/raw/proofgist` } } }],
2464 "GET /gists/proofgist": () => ({ files: { "proof.md": { content: `linking to diffinery: ${linkNonce}` } } }),
2465 "GET /users/octo": { login: "octo", type: "Organization" },
2466 "GET /orgs/octo/repos": () => [repoJson("app"), repoJson("lib", { default_branch: "trunk", topics: [] }), ...(listHuge ? [repoJson("huge", { size: 99_999_999 })] : [])].map((r) => ({ ...r, clone_url: `${ghBase}/${r.full_name}.git` })),
2467 "GET /repos/octo/huge": () => ({ ...repoJson("huge", { size: 99_999_999 }), clone_url: `${ghBase}/octo/huge.git` }),
2468 // Only ORG_REGION reaches every repository on GitHub; Diffinery's organization variables always do.
2469 "GET /orgs/octo/actions/variables": { variables: [{ name: "ORG_REGION", value: "eu-west", visibility: "all" }, { name: "ORG_PRIVATE_HOST", value: "internal.example", visibility: "private" }, { name: "ORG_SELECTED_KEY", value: "few", visibility: "selected" }] },
2470 "GET /orgs/octo/actions/secrets": { secrets: [{ name: "ORG_DEPLOY_KEY" }] },
2471 "GET /repos/octo/app": () => ({ ...repoJson("app"), clone_url: `${ghBase}/octo/app.git`, html_url: `${ghBase}/octo/app` }),
2472 "GET /repos/octo/app/labels": [{ name: "bug", color: "d73a4a", description: "Something isn't working" }, { name: "docs", color: "0075ca", description: "Documentation" }, { name: "wontfix", color: "ffffff", description: "" }],
2473 "GET /repos/octo/app/milestones": [{ number: 1, title: "v1", description: "First release", state: "open", due_on: "2030-01-01T00:00:00Z", created_at: t, updated_at: t, closed_at: null, creator: octoDev }],
2474 "GET /repos/octo/app/pulls": pulls,
2475 "GET /repos/octo/app/issues": issues,
2476 "GET /repos/octo/app/issues/comments": () => [
2477 { id: 11, body: "I can reproduce this", user: alice, created_at: "2024-01-03T00:00:00Z", updated_at: "2024-01-03T00:00:00Z", issue_url: `${ghBase}/api/v3/repos/octo/app/issues/1` },
2478 { id: 12, body: "Thanks!", user: octoDev, created_at: "2024-01-04T00:00:00Z", updated_at: "2024-01-04T00:00:00Z", issue_url: `${ghBase}/api/v3/repos/octo/app/issues/1` },
2479 { id: 13, body: "Merging this", user: octoDev, created_at: "2024-01-31T00:00:00Z", updated_at: "2024-01-31T00:00:00Z", issue_url: `${ghBase}/api/v3/repos/octo/app/issues/2` },
2480 ],
2481 "GET /repos/octo/app/pulls/2/reviews": [{ id: 501, user: bob, state: "APPROVED", body: "Looks good", commit_id: fx.featureSha, submitted_at: "2024-01-30T00:00:00Z" }],
2482 "GET /repos/octo/app/pulls/5/reviews": [{ id: 505, user: octoDev, state: "APPROVED", body: "looks fine", commit_id: fx.draftSha, submitted_at: "2024-01-20T00:00:00Z" }],
2483 "GET /repos/octo/app/pulls/6/reviews": [{ id: 502, user: alice, state: "PENDING", body: "", commit_id: fx.forkSha, submitted_at: null }],
2484 "GET /repos/octo/app/pulls/2": { ...pulls[0], merged_by: octoDev },
2485 "GET /repos/octo/app/pulls/comments": () => [
2486 { id: 601, pull_request_review_id: 501, pull_request_url: `${ghBase}/api/v3/repos/octo/app/pulls/2`, user: bob, body: "Nice file", path: "feature.txt", line: 1, side: "RIGHT", commit_id: fx.featureSha, created_at: "2024-01-30T00:00:00Z", updated_at: "2024-01-30T00:00:00Z" },
2487 { id: 602, pull_request_review_id: 503, pull_request_url: `${ghBase}/api/v3/repos/octo/app/pulls/2`, in_reply_to_id: 601, user: alice, body: "Agreed", path: "feature.txt", line: 1, side: "RIGHT", commit_id: fx.featureSha, created_at: "2024-01-30T01:00:00Z", updated_at: "2024-01-30T01:00:00Z" },
2488 ],
2489 "GET /repos/octo/app/branches": [{ name: "main" }],
2490 "GET /repos/octo/app/branches/main/protection": { required_status_checks: { contexts: ["build"] }, required_pull_request_reviews: { required_approving_review_count: 1, dismiss_stale_reviews: true }, enforce_admins: { enabled: false }, allow_force_pushes: { enabled: false } },
2491 "GET /repos/octo/app/actions/variables": { variables: [{ name: "DEPLOY_ENV", value: "staging" }, { name: "REGION", value: "us" }] },
2492 "GET /repos/octo/app/actions/secrets": { secrets: [{ name: "NPM_TOKEN" }, { name: "SLACK_WEBHOOK" }] },
2493 "GET /repos/octo/app/releases": [{ id: 1, tag_name: "v1.0.0", name: "1.0.0", body: "first release", draft: false, prerelease: false, created_at: "2024-01-01T00:00:00Z", published_at: "2024-01-01T00:00:00Z", author: { login: "octocat", id: 1 }, assets: [] }],
2494 "GET /repos/octo/lib": () => ({ ...repoJson("lib", { default_branch: "trunk", topics: [] }), clone_url: `${ghBase}/octo/lib.git` }),
2495 "GET /repos/octo/lib/labels": empty,
2496 "GET /repos/octo/lib/milestones": empty,
2497 "GET /repos/octo/lib/pulls": empty,
2498 "GET /repos/octo/lib/issues": [issue(1, { title: "Lib issue" })],
2499 "GET /repos/octo/lib/issues/comments": empty,
2500 "GET /repos/octo/lib/pulls/comments": empty,
2501 "GET /repos/octo/lib/branches": empty,
2502 "GET /repos/octo/lib/actions/variables": { variables: [] },
2503 "GET /repos/octo/lib/actions/secrets": { secrets: [] },
2504 "GET /repos/octo/lib/releases": empty,
2505 };
2506 const gh = fakeGitHub({ root: ghRoot, token: GH_TOKEN, routes, lfs: new Map([[fx.asset.oid, fx.asset.data]]), anonymous: ["octo/lib"] });
2507 ghBase = await gh.listen();
2508 const apiUrl = `${ghBase}/api/v3`;
2509
2510 /** Run the import agent (the runner image's import mode) for an import waiting for one, like the container would. */
2511 const transfer = async (id) => {
2512 await until(`import ${id} to wait for an agent`, async () => (await ok("GET", `/diffinery/imports/${id}`)).git?.phase === "waiting", 120_000);
2513 const { token: pushToken } = await ok("POST", `/diffinery/imports/${id}/claim`);
2514 const r = await spawnAsync(process.execPath, [AGENT], { DIFFINERY_API_URL: base, DIFFINERY_IMPORT_ID: id, DIFFINERY_IMPORT_TOKEN: pushToken, DIFFINERY_IMPORT_CHUNK_BYTES: String(160 * 1024), DIFFINERY_IMPORT_LARGE_BLOB_BYTES: String(100 * 1024), DIFFINERY_WORK_ROOT: join(work, `import-${id}`) }, 240_000);
2515 const out = `${r.stdout}${r.stderr}`;
2516 assert.ok(!out.includes(GH_TOKEN) && !out.includes(pushToken), "the agent never prints tokens");
2517 return { ...r, out, pushToken };
2518 };
2519 const finished = (id, timeout = 180_000) =>
2520 until(`import ${id} to finish`, async () => {
2521 const r = await ok("GET", `/diffinery/imports/${id}`);
2522 return ["succeeded", "failed", "cancelled"].includes(r.status) ? r : null;
2523 }, timeout);
2524
2525 // ------------------------------------------------------------ people: link a GitHub account by gist proof (no token)
2526 const challenge = await ok("POST", "/diffinery/user/linked-accounts/github/challenge", { api_url: apiUrl });
2527 assert.match(challenge.nonce, /^diffinery-link-[0-9a-f]+$/);
2528 // Before the gist carries the nonce, linking is refused.
2529 assert.equal((await api("POST", "/diffinery/user/linked-accounts/github", { login: "octo-dev", api_url: apiUrl })).status, 422);
2530 linkNonce = challenge.nonce; // now octo-dev's public gist contains it
2531 const link = await ok("POST", "/diffinery/user/linked-accounts/github", { login: "octo-dev", api_url: apiUrl });
2532 assert.equal(link.login, "octo-dev");
2533
2534 // ------------------------------------------------------------ input validation and permissions
2535 assert.equal((await api("POST", "/diffinery/imports", { source: "octo/app", owner, options: { nope: true }, github_api_url: apiUrl })).status, 422);
2536 assert.equal((await api("POST", "/diffinery/imports", { source: "octo/app", owner: "nobody-here", github_api_url: apiUrl })).status, 422);
2537 assert.equal((await api("POST", "/diffinery/imports", { source: "octo/app", owner, github_token: "wrong", github_api_url: apiUrl })).status, 422);
2538 const bot = (await ok("POST", "/diffinery/agents", { login: "import-bot" }, null)).token.token;
2539 // An agent may import where its owner may, its owner's own account included: this one gets past
2540 // the permission check and stops only because the GitHub repository does not exist.
2541 const botTry = await api("POST", "/diffinery/imports", { source: "octo/missing", owner, github_token: GH_TOKEN, github_api_url: apiUrl }, bot);
2542 assert.equal(botTry.status, 422, JSON.stringify(botTry.json));
2543 assert.match(botTry.json.message, /octo\/missing was not found/);
2544
2545 // ------------------------------------------------------------ one repository
2546 const started = await ok("POST", "/diffinery/imports", { source: "octo/app", owner, name: "imported-app", github_token: GH_TOKEN, github_api_url: apiUrl });
2547 assert.equal(started.status, "queued");
2548 assert.ok(!JSON.stringify(started).includes(GH_TOKEN), "the token is never returned");
2549 // While the import holds the repository it created, nothing else writes to it but settings such as
2550 // secrets: the REST API, the web UI and MCP get 423 Locked (reads still work). The import's own
2551 // writes go through below.
2552 await until(`import ${started.id} to wait for an agent`, async () => (await ok("GET", `/diffinery/imports/${started.id}`)).git?.phase === "waiting", 120_000);
2553 const L = `/repos/${owner}/imported-app`;
2554 for (const [method, path, body] of [
2555 ["POST", `${L}/hooks`, { config: { url: "https://hooks.invalid/import-sink" }, events: ["*"] }],
2556 ["POST", `${L}/issues`, { title: "too early" }],
2557 ["PUT", `${L}/contents/early.txt`, { message: "too early", content: Buffer.from("early\n").toString("base64") }],
2558 ["POST", `${L}/labels`, { name: "early", color: "ffffff" }],
2559 ["PATCH", L, { description: "changed during the import" }],
2560 ]) {
2561 const r = await api(method, path, body);
2562 assert.equal(r.status, 423, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`);
2563 assert.match(r.json.message, /locked by an import/);
2564 }
2565 assert.equal((await api("GET", `${L}/issues`)).status, 200, "reads are not locked");
2566 // Settings that don't touch Git data, issues or pull requests can be set up while it imports.
2567 assert.equal((await api("PUT", `${L}/actions/secrets/EARLY_SECRET`, { value: "set during the import" })).status, 204);
2568 assert.ok((await ok("GET", `${L}/actions/secrets`)).secrets.some((x) => x.name === "EARLY_SECRET"));
2569 assert.equal((await api("DELETE", `${L}/actions/secrets/EARLY_SECRET`)).status, 204);
2570 const csrf = randomBytes(16).toString("hex");
2571 const webWrite = await fetch(`${base}/${owner}/imported-app/issues`, { method: "POST", headers: { cookie: `dfy_csrf=${csrf}`, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ _csrf: csrf, title: "too early" }), redirect: "manual" });
2572 assert.equal(webWrite.status, 423, await webWrite.text());
2573 const mcpWrite = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "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, repo: "imported-app", title: "too early" } } }) }).then((r) => r.json());
2574 assert.equal(mcpWrite.result.isError, true, JSON.stringify(mcpWrite));
2575 assert.match(mcpWrite.result.content[0].text, /locked by an import/);
2576 const agent = await transfer(started.id);
2577 assert.equal(agent.status, 0, agent.out);
2578 const done = await finished(started.id);
2579 assert.equal(done.status, "succeeded", JSON.stringify(done, null, 2));
2580 // No side effects: no workflow runs (ci.yml runs on push and pull_request), no webhook deliveries.
2581 // The lock is released: a webhook can be added now, and nothing the import queued reaches it.
2582 const hook = await ok("POST", `/repos/${owner}/imported-app/hooks`, { config: { url: "https://hooks.invalid/import-sink" }, events: ["*"] });
2583 await sleep(2000);
2584 assert.equal((await ok("GET", `/repos/${owner}/imported-app/actions/runs`)).total_count, 0);
2585 const sink = (await ok("GET", `/repos/${owner}/imported-app/hooks`)).find((h) => h.id === hook.id);
2586 assert.equal(sink.last_response.code, null, "no webhook was delivered");
2587 assert.equal(sink.last_response.status, "unused");
2588 assert.ok(done.steps.every((s) => s.status === "done" || s.status === "skipped"), JSON.stringify(done.steps));
2589 assert.ok(done.summary.git.chunks >= 3, `history went in chunks: ${JSON.stringify(done.summary.git)}`);
2590 // The data files count as large here (DIFFINERY_IMPORT_LARGE_BLOB_BYTES): they went first, whole,
2591 // under temporary refs naming trees, which the server takes and the import removes at the end.
2592 assert.match(agent.out, /4 version\(s\) of large files/);
2593 assert.equal(done.summary.git.branches, 3);
2594 assert.equal(done.summary.git.tags, 2);
2595 assert.equal(done.summary.git.lfsObjects, 1);
2596 assert.deepEqual(done.summary.secretNames, ["NPM_TOKEN", "SLACK_WEBHOOK"]);
2597 assert.ok(done.summary.findings.some((f) => f.kind === "AWS access key"), "bypassed findings are listed");
2598 assert.ok(done.summary.people.imported.includes("alice") && done.summary.people.linked.includes("octo-dev"));
2599 // Releases are imported over the REST API (not just their tags).
2600 assert.equal(done.summary.releases?.imported, 1, JSON.stringify(done.summary.releases));
2601 const releases = await ok("GET", `/repos/${owner}/imported-app/releases`);
2602 assert.deepEqual(releases.map((r) => r.tag_name), ["v1.0.0"]);
2603
2604 // Repository settings
2605 const repo = await ok("GET", `/repos/${owner}/imported-app`);
2606 assert.equal(repo.visibility, "private");
2607 assert.equal(repo.default_branch, "main");
2608 assert.equal(repo.description, "The app");
2609 assert.equal(repo.homepage, "https://app.example.com");
2610 assert.deepEqual(repo.topics, ["demo", "import"]);
2611
2612 // Git: branches, tags and pull request heads; no merge queue branches, merge refs or import refs.
2613 const refs = Object.fromEntries(
2614 git(work, ["ls-remote", `${base}/${owner}/imported-app.git`])
2615 .trim()
2616 .split("\n")
2617 .map((l) => l.split("\t").reverse()),
2618 );
2619 assert.equal(refs["refs/heads/main"], fx.mainSha);
2620 assert.equal(refs["refs/heads/feature"], fx.featureSha);
2621 assert.equal(refs["refs/heads/draft-work"], fx.draftSha);
2622 assert.ok(refs["refs/tags/v1.0"] && refs["refs/tags/v0.1"]);
2623 assert.equal(refs["refs/pull/2/head"], fx.featureSha);
2624 assert.equal(refs["refs/pull/5/head"], fx.draftSha);
2625 assert.equal(refs["refs/pull/6/head"], fx.forkSha);
2626 assert.ok(!Object.keys(refs).some((r) => r.startsWith("refs/heads/gh-readonly-queue/") || r.startsWith("refs/diffinery-import/") || r === "refs/pull/2/merge"), Object.keys(refs).join("\n"));
2627 const copy = join(work, "imported-app");
2628 git(work, ["clone", "-q", "--mirror", `${base}/${owner}/imported-app.git`, copy], token, { env: { ...process.env, GIT_LFS_SKIP_SMUDGE: "1", GIT_TERMINAL_PROMPT: "0" } });
2629 git(copy, ["fsck", "--no-progress"]);
2630 git(copy, ["cat-file", "-e", fx.forkSha]);
2631 // The LFS object is stored in Diffinery.
2632 const lfsRes = await fetch(`${base}/${owner}/imported-app.git/info/lfs/objects/batch`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/vnd.git-lfs+json" }, body: JSON.stringify({ operation: "download", objects: [{ oid: fx.asset.oid, size: fx.asset.data.length }] }) });
2633 const lfsBody = await lfsRes.json();
2634 assert.ok(lfsBody.objects[0].actions?.download, `${JSON.stringify(lfsBody)}\n${JSON.stringify(done.warnings)}\n${agent.out}\n${devLog().split("\n").filter((l) => /lfs|rror/i.test(l)).slice(-40).join("\n")}`);
2635 const blob = await fetch(lfsBody.objects[0].actions.download.href, { headers: { authorization: `Bearer ${token}` } });
2636 assert.equal(Buffer.from(await blob.arrayBuffer()).toString(), fx.asset.data.toString());
2637 // The push token is revoked.
2638 assert.equal((await api("GET", "/user", undefined, agent.pushToken)).status, 401);
2639
2640 // Issues keep their numbers, people, state and dates.
2641 const i1 = await ok("GET", `/repos/${owner}/imported-app/issues/1`);
2642 assert.equal(i1.title, "First bug");
2643 assert.equal(i1.user.login, owner, "a linked GitHub account maps to its Diffinery account");
2644 assert.deepEqual(i1.assignees.map((a) => a.login), [owner]);
2645 assert.deepEqual(i1.labels.map((l) => l.name), ["bug"]);
2646 assert.equal(i1.milestone.title, "v1");
2647 assert.equal(i1.created_at, t);
2648 const i3 = await ok("GET", `/repos/${owner}/imported-app/issues/3`);
2649 assert.equal(i3.state, "closed");
2650 assert.equal(i3.state_reason, "not_planned");
2651 assert.equal(i3.user.login, "github:alice");
2652 assert.equal((await api("GET", `/repos/${owner}/imported-app/issues/4`)).status, 404, "a deleted GitHub issue leaves its number unused");
2653 const c1 = await ok("GET", `/repos/${owner}/imported-app/issues/1/comments`);
2654 assert.deepEqual(c1.map((c) => [c.user.login, c.body, c.created_at]), [["github:alice", "I can reproduce this", "2024-01-03T00:00:00Z"], [owner, "Thanks!", "2024-01-04T00:00:00Z"]]);
2655 // Pull requests: merged state, who merged, reviews and line comments with replies.
2656 const p2 = await ok("GET", `/repos/${owner}/imported-app/pulls/2`);
2657 assert.equal(p2.merged, true);
2658 assert.equal(p2.merged_by.login, owner);
2659 assert.equal(p2.merge_commit_sha, fx.mergeSha);
2660 assert.equal(p2.head.ref, "feature");
2661 assert.equal(p2.head.sha, fx.featureSha);
2662 const reviews = await ok("GET", `/repos/${owner}/imported-app/pulls/2/reviews`);
2663 assert.deepEqual(reviews.map((r) => [r.user.login, r.state, r.body]), [["github:bob", "APPROVED", "Looks good"]]);
2664 const lineComments = await ok("GET", `/repos/${owner}/imported-app/pulls/2/comments`);
2665 assert.equal(lineComments.length, 2);
2666 assert.equal(lineComments[0].path, "feature.txt");
2667 assert.equal(lineComments[1].in_reply_to_id, lineComments[0].id);
2668 const p5 = await ok("GET", `/repos/${owner}/imported-app/pulls/5`);
2669 assert.equal(p5.draft, true);
2670 assert.equal(p5.state, "open");
2671 assert.deepEqual(p5.requested_reviewers.map((r) => r.login), ["github:bob"]);
2672 // M1: an imported review is history, not a vote — even when its author is a linked Diffinery account.
2673 const r5 = await ok("GET", `/repos/${owner}/imported-app/pulls/5/reviews`);
2674 assert.deepEqual(r5.map((r) => [r.user.login, r.state]), [[owner, "APPROVED"]], "the imported approval is kept as history");
2675 assert.equal(p5.approvals, 0, "an imported approval does not count toward the required approvals");
2676 assert.equal(p5.required_approvals, 1);
2677 const p6 = await ok("GET", `/repos/${owner}/imported-app/pulls/6`);
2678 assert.equal(p6.head.ref, "forker:patch");
2679 assert.equal(p6.head.sha, fx.forkSha);
2680 assert.equal(p6.merged, false);
2681 // A pull request from a fork runs the fork's code, so its jobs get what GitHub gives them:
2682 // a read-only token and no secrets.
2683 assert.equal((await api("PUT", `/repos/${owner}/imported-app/actions/secrets/DEPLOY_KEY`, { value: "never-for-forks" })).status, 204);
2684 await ok("PATCH", `/repos/${owner}/imported-app/pulls/6`, { state: "open" });
2685 const forkJob = await until("the fork pull request's job", async () => {
2686 const r = await runnerClaim(`/repos/${owner}/imported-app`, ["linux"]);
2687 return r.status === 200 ? r.json : null;
2688 });
2689 const forkSpec = await (await fetch(`${base}/runner/jobs/${forkJob.job_id}`, { headers: { authorization: `Bearer ${forkJob.token}` } })).json();
2690 assert.equal(forkSpec.github.event_name, "pull_request");
2691 assert.deepEqual(Object.keys(forkSpec.secrets).sort(), ["DIFFINERY_TOKEN", "GITHUB_TOKEN"]);
2692 assert.equal((await api("POST", `/repos/${owner}/imported-app/issues`, { title: "from a fork's job" }, forkJob.token)).status, 403);
2693 await fetch(`${base}/runner/jobs/${forkJob.job_id}/complete`, { method: "POST", headers: { authorization: `Bearer ${forkJob.token}`, "content-type": "application/json" }, body: JSON.stringify({ conclusion: "success", outputs: {} }) });
2694 await ok("PATCH", `/repos/${owner}/imported-app/pulls/6`, { state: "closed" });
2695 // New issues continue after the highest imported number.
2696 assert.equal((await ok("POST", `/repos/${owner}/imported-app/issues`, { title: "After import" })).number, 8);
2697 // Labels, milestones, protection, variables.
2698 const labels = await ok("GET", `/repos/${owner}/imported-app/labels`);
2699 {
2700 const bug = labels.find((l) => l.name === "bug");
2701 assert.deepEqual([bug.name, bug.color, bug.description], ["bug", "d73a4a", "Something isn't working"]);
2702 }
2703 const milestones = await ok("GET", `/repos/${owner}/imported-app/milestones?state=all`);
2704 assert.equal(milestones.length, 1);
2705 assert.equal(milestones[0].due_on, "2030-01-01T00:00:00Z");
2706 assert.equal(milestones[0].open_issues, 1);
2707 const protection = await ok("GET", `/repos/${owner}/imported-app/branches/main/protection`);
2708 assert.match(JSON.stringify(protection), /CI \/ build/);
2709 const vars = await ok("GET", `/repos/${owner}/imported-app/actions/variables`);
2710 assert.deepEqual(vars.variables.map((v) => [v.name, v.value]).sort(), [["DEPLOY_ENV", "staging"], ["REGION", "us"]]);
2711 assert.ok((await ok("GET", "/diffinery/imports")).some((x) => x.id === started.id));
2712
2713 // ------------------------------------------------------------ secrets policy "stop" fails with a clear message
2714 const strict = await ok("POST", "/diffinery/imports", { source: "octo/app", owner, name: "strict-app", github_token: GH_TOKEN, github_api_url: apiUrl, options: { secrets: "stop", issues: false } });
2715 const strictAgent = await transfer(strict.id);
2716 assert.equal(strictAgent.status, 1, strictAgent.out);
2717 assert.match(strictAgent.out, /secret/i);
2718 const strictDone = await finished(strict.id);
2719 assert.equal(strictDone.status, "failed");
2720 assert.match(strictDone.error, /secrets/);
2721
2722 // ------------------------------------------------------------ a whole organization, into an organization
2723 await ok("POST", "/user/orgs", { login: "acme-imports" });
2724 const bulk = await ok("POST", "/diffinery/imports", { source_owner: "octo", owner: "acme-imports", github_token: GH_TOKEN, github_api_url: apiUrl, concurrency: 2, options: { lfs: false } });
2725 assert.equal(bulk.kind, "organization");
2726 assert.deepEqual(bulk.children.map((ch) => ch.source).sort(), ["octo/app", "octo/lib"]);
2727 for (const ch of bulk.children) assert.equal((await transfer(ch.id)).status, 0);
2728 const bulkDone = await finished(bulk.id, 300_000);
2729 assert.equal(bulkDone.status, "succeeded", JSON.stringify(bulkDone, null, 2));
2730 assert.deepEqual(bulkDone.summary.orgSecretNames, ["ORG_DEPLOY_KEY"]);
2731 const orgVars = await ok("GET", "/orgs/acme-imports/actions/variables");
2732 assert.deepEqual(orgVars.variables.map((v) => [v.name, v.value]), [["ORG_REGION", "eu-west"]]);
2733 assert.ok(bulkDone.warnings.some((w) => /ORG_PRIVATE_HOST/.test(w)) && bulkDone.warnings.some((w) => /ORG_SELECTED_KEY/.test(w)), JSON.stringify(bulkDone.warnings));
2734 assert.equal((await ok("GET", "/repos/acme-imports/lib")).default_branch, "trunk");
2735 assert.equal((await ok("GET", "/repos/acme-imports/lib/issues/1")).title, "Lib issue");
2736 assert.equal((await ok("GET", "/repos/acme-imports/app/pulls/2")).merged, true);
2737
2738 // ------------------------------------------------------------ without a token: everything public comes across, variables are skipped
2739 // GitHub answers Actions variables, secrets and environments only with a token (401 otherwise).
2740 const anon = await ok("POST", "/diffinery/imports", { source: "octo/lib", owner, name: "anon-lib", github_api_url: apiUrl, options: { lfs: false } });
2741 assert.equal((await transfer(anon.id)).status, 0);
2742 const anonDone = await finished(anon.id);
2743 assert.equal(anonDone.status, "succeeded", JSON.stringify(anonDone, null, 2));
2744 const anonVars = anonDone.steps.find((st) => st.name === "variables");
2745 assert.equal(anonVars.status, "skipped", JSON.stringify(anonDone.steps));
2746 assert.match(anonVars.message, /needs a GitHub token/);
2747 assert.ok(anonDone.warnings.some((w) => /variables, secret names and environments were not imported/.test(w)), JSON.stringify(anonDone.warnings));
2748 assert.equal((await ok("GET", `/repos/${owner}/anon-lib/issues/1`)).title, "Lib issue");
2749 assert.equal((await ok("GET", `/repos/${owner}/anon-lib`)).default_branch, "trunk");
2750
2751 // ------------------------------------------------------------ an agent's organization import cannot touch variables (H1)
2752 const agentBulk = await api("POST", "/diffinery/imports", { source_owner: "octo", owner: "acme-imports", github_token: GH_TOKEN, github_api_url: apiUrl, concurrency: 1, options: { lfs: false } }, bot);
2753 assert.equal(agentBulk.status, 201, JSON.stringify(agentBulk.json));
2754 const agentBulkDone = await finished(agentBulk.json.id, 180_000);
2755 const orgStep = agentBulkDone.steps.find((s) => s.name === "organization");
2756 assert.equal(orgStep.status, "skipped", JSON.stringify(agentBulkDone.steps));
2757 assert.match(orgStep.message, /agents cannot manage variables/);
2758 // The organization's variable is untouched by the agent import.
2759 assert.deepEqual((await ok("GET", "/orgs/acme-imports/actions/variables")).variables.map((v) => v.name), ["ORG_REGION"]);
2760
2761 // ------------------------------------------------------------ a retry onto a repository adopted since is refused (H2)
2762 await ok("POST", `/repos/${owner}/strict-app/issues`, { title: "adopted after the failed import" });
2763 await ok("POST", `/diffinery/imports/${strict.id}/retry`, { github_token: GH_TOKEN });
2764 const reDone = await finished(strict.id);
2765 assert.equal(reDone.status, "failed");
2766 assert.match(reDone.error, /holds content|start a new import/);
2767
2768 // ------------------------------------------------------------ a stale (revoked) import push token cannot push in import mode (M4)
2769 const stalePush = gitFails(copy, ["push", `${base}/${owner}/imported-app.git`, "--push-option=diffinery-import", "refs/heads/main:refs/heads/stale-attempt"], agent.pushToken);
2770 assert.match(stalePush, /401|403|denied|forbidden|authentication|fatal/i, stalePush);
2771
2772 // ------------------------------------------------------------ an organization import holds each repository to the size limit
2773 listHuge = true;
2774 const hugeBulk = await ok("POST", "/diffinery/imports", { source_owner: "octo", repositories: ["huge"], owner: "acme-imports", github_token: GH_TOKEN, github_api_url: apiUrl, concurrency: 1, options: { lfs: false } });
2775 const hugeChild = await until("the oversized repository to be refused", async () => {
2776 const ch = (await ok("GET", `/diffinery/imports/${hugeBulk.id}`)).children?.find((c) => c.source === "octo/huge");
2777 return ch?.status === "failed" ? ch : ch?.git?.phase === "waiting" ? Promise.reject(new Error("the oversized repository was queued for transfer")) : null;
2778 }, 120_000);
2779 assert.match(hugeChild.error ?? (await ok("GET", `/diffinery/imports/${hugeChild.id}`)).error, /import limit/);
2780 assert.equal((await api("GET", "/repos/acme-imports/huge")).status, 404);
2781 await finished(hugeBulk.id);
2782
2783 // ------------------------------------------------------------ the web UI (signed in via DEV_AUTH)
2784 for (const path of ["/new/import", "/imports", `/imports/${started.id}`, `/imports/${started.id}/secrets`, `/imports/${bulk.id}`, "/settings/linked-accounts", `/${owner}/imported-app/issues/1`, `/${owner}/imported-app/pull/2`]) {
2785 const res = await fetch(`${base}${path}`);
2786 const html = await res.text();
2787 assert.equal(res.status, 200, `${path} -> ${res.status}\n${html.slice(0, 500)}`);
2788 assert.ok(!/<select|type="checkbox"|type="radio"/.test(html.replace(/<template[\s\S]*?<\/template>/g, "")) || path.startsWith(`/${owner}`), `${path} renders Kumo controls, not native ones`);
2789 }
2790 assert.match(await (await fetch(`${base}/imports/${started.id}`)).text(), /NPM_TOKEN/);
2791 assert.match(await (await fetch(`${base}/${owner}/imported-app/issues/1`)).text(), /v1/);
2792 assert.match(await (await fetch(`${base}/${owner}/imported-app/issues/3`)).text(), /alice/);
2793 await gh.close();
2794});
2795
2796test("scheduled workflows: the schedule fires without a cron trigger", async () => {
2797 assert.ok(tickRepo, "the schedule was registered");
2798 const runs = await until("a scheduled run", async () => {
2799 const r = await ok("GET", `/repos/${tickRepo}/actions/runs?event=schedule`);
2800 return r.total_count > 0 && r.workflow_runs;
2801 }, 150_000);
2802 assert.equal(runs[0].event, "schedule");
2803 assert.equal(runs[0].path, ".github/workflows/tick.yml");
2804 assert.equal(runs[0].actor.login, "diffinery-scheduler");
2805 // One run per tick, never two for the same minute.
2806 const minutes = runs.map((r) => r.created_at.slice(0, 16));
2807 assert.equal(new Set(minutes).size, minutes.length, `two runs in one tick: ${minutes.join(", ")}`);
2808 // Site admins can see the scheduler's state (the live test reports it when no run comes).
2809 const state = await ok("GET", "/diffinery/admin/scheduler");
2810 assert.equal(state.tick_minutes, 1);
2811 assert.ok(state.last_tick_at && state.covered_until, JSON.stringify(state));
2812 assert.ok(Date.parse(state.next_tick_at) > Date.parse(state.last_tick_at), JSON.stringify(state));
2813 // And the newest unexpected server errors; a request id that isn't kept is a 404.
2814 const errors = await ok("GET", "/diffinery/admin/errors?per_page=5");
2815 assert.ok(Array.isArray(errors) && errors.length <= 5, JSON.stringify(errors));
2816 assert.equal((await api("GET", "/diffinery/admin/errors/not-a-request-id")).status, 404);
2817 // A push without the schedule removes it.
2818 const src = join(work, "schedules");
2819 rmSync(join(src, ".github/workflows/tick.yml"));
2820 git(src, ["commit", "-q", "-am", "no schedule"]);
2821 git(src, ["push", "-q", `${base}/${tickRepo}.git`, "main"]);
2822});
2823
2824/**
2825 * `git` without blocking this process, so the tests below run side by side; it rejects with git's
2826 * output and, on a server error or after 10 minutes without finishing (the command is killed, so a
2827 * stuck push fails the test instead of the whole job), the tail of `log` and what `more` says.
2828 * A `tok` of null sends no credentials (for GitHub).
2829 */
2830function gitAsync(cwd, args, tok = token, log = devLog, more = () => "") {
2831 const auth = tok === null ? [] : ["-c", `http.extraHeader=Authorization: Basic ${Buffer.from(`x-token:${tok}`).toString("base64")}`];
2832 return new Promise((done, fail) => {
2833 const child = spawn("git", [...auth, "-c", "protocol.version=2", ...args], {
2834 cwd,
2835 stdio: ["ignore", "pipe", "pipe"],
2836 env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_AUTHOR_NAME: "E2E", GIT_AUTHOR_EMAIL: "e2e@example.com", GIT_COMMITTER_NAME: "E2E", GIT_COMMITTER_EMAIL: "e2e@example.com" },
2837 });
2838 let stdout = "";
2839 let stderr = "";
2840 let timedOut = false;
2841 const timer = setTimeout(() => {
2842 timedOut = true;
2843 child.kill("SIGKILL");
2844 }, 600_000);
2845 child.stdout.on("data", (d) => (stdout += d));
2846 child.stderr.on("data", (d) => (stderr += d));
2847 child.on("error", fail);
2848 child.on("close", (status) => {
2849 clearTimeout(timer);
2850 if (status === 0) return done(stdout);
2851 let message = `git ${args.join(" ")} ${timedOut ? "didn't finish in 10 minutes" : `exited ${status}`}\n${stderr}`;
2852 if (timedOut || /HTTP 5\d\d|Failed to connect/.test(stderr)) message += `\n${more()}\n--- wrangler log tail ---\n${log().slice(-4000)}`;
2853 fail(Object.assign(new Error(message), { stdout, stderr }));
2854 });
2855 });
2856}
2857
2858/**
2859 * `ok`, `git` and `gitFails` against `server` (startServer's, or the shared one), with git that doesn't
2860 * block this process: for the tests below that run side by side.
2861 */
2862function client(server) {
2863 const ok = async (method, path, body) => {
2864 const send = () => fetch(`${server.base}/api/v3${path}`, { method, headers: { authorization: `Bearer ${server.token}`, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
2865 // A GET goes again on a kept-alive connection the server closed meanwhile, as in api().
2866 const r = await send().catch((e) => (method === "GET" ? sleep(1000).then(send) : Promise.reject(e)));
2867 const text = await r.text();
2868 assert.ok(r.ok, `${method} ${path} -> ${r.status} ${text}`);
2869 return JSON.parse(text);
2870 };
2871 const git = (cwd, args) => gitAsync(cwd, args, server.token, server.log, () => `the Worker was at ${server.direct}; wrangler dev now names ${server.workerUrl?.() ?? "(the shared server)"}`);
2872 const gitFails = async (cwd, args) => {
2873 try {
2874 await git(cwd, args);
2875 } catch (e) {
2876 return `${e.stdout ?? ""}${e.stderr ?? ""}`;
2877 }
2878 assert.fail(`expected git ${args.join(" ")} to fail`);
2879 };
2880 // Git goes straight to the Worker: wrangler dev's own proxy drops large pushes and clones streaming
2881 // through it (see workerUrl), which isn't Diffinery and doesn't exist in production.
2882 assert.ok(server.direct, `the Worker's own address wasn't found in wrangler dev's debug log`);
2883 return { ...server, gitBase: server.direct, ok, git, gitFails };
2884}
2885const shared = () => client({ base, direct, token, log: devLog });
2886
2887/** Runs `fn` with a client of a server of its own, stopped afterwards. */
2888async function onOwnServer(name, fn, ready = Promise.resolve()) {
2889 const [server] = await Promise.all([startServer(name), ready]);
2890 try {
2891 assert.ok(server.direct && (await fetch(`${server.direct}/healthz`)).ok, `the Worker's own address (${server.direct}) doesn't answer`);
2892 return await fn(client(server));
2893 } finally {
2894 server.stop();
2895 }
2896}
2897
2898/**
2899 * A real project's history, pushed whole to a new repository on `server` and cloned back. Pinned
2900 * commits, so the packs are the same each run; cloned from GitHub without the Diffinery token.
2901 */
2902async function pushHistory({ gitBase, ok, git }, name, upstream) {
2903 const me = await ok("GET", "/user");
2904 await ok("POST", "/user/repos", { name });
2905 const remote = `${gitBase}/${me.login}/${name}.git`;
2906 // Test fixtures in these histories look like credentials (tornado has a test private key): pushed as an admin's bypass.
2907 await git(upstream, ["-c", "http.postBuffer=1048576", "push", "-q", "-o", "allow-secrets=e2e of a public history", remote, "main"]);
2908 const out = join(work, `${name}-clone`);
2909 await git(work, ["clone", "-q", "--bare", remote, out]);
2910 assert.equal((await git(out, ["rev-parse", "main"])).trim(), (await git(upstream, ["rev-parse", "main"])).trim());
2911 assert.equal((await git(out, ["rev-list", "--count", "main"])).trim(), (await git(upstream, ["rev-list", "--count", "main"])).trim());
2912 await git(out, ["fsck", "--full"]);
2913}
2914
2915// Two at a time, each on a server of its own (the lockfile's on the shared one): one big push keeps
2916// one server process busy, so on separate processes they use the runner's other cores; jquery's push
2917// takes about as long as the other three's together. Not all four: a local server's memory grows to
2918// 2 to 4 GB during such a push, and four at once ran a runner out of memory (the Workers runtime
2919// crashed mid-push); two at a time peak about 1 GB above one at a time. Git goes past wrangler dev's
2920// proxy (see client).
2921describe("real histories: whole projects, side by side", { concurrency: 2 }, () => {
2922 for (const [name, url, sha] of [
2923 // 37 MB: staged in R2 and unpacked in pieces.
2924 ["jquery", "https://github.com/jquery/jquery", "c2f27864e4ffc2d1409c289fcb9a42b6165dfeaf"],
2925 // About 12 MB each: too many objects for parsing whole in memory, so unpacked in pieces too.
2926 ["tornado", "https://github.com/tornadoweb/tornado", "056cacaefc7de31bda28363378c4ffc86b97d7e4"],
2927 ["flask", "https://github.com/pallets/flask", "d086db856be187255b8ec61ef409357393020f32"],
2928 ]) {
2929 test(`real histories: ${name}'s whole history goes in one push and clones back intact`, async () => {
2930 const upstream = join(work, `${name}-upstream.git`);
2931 const download = gitAsync(work, ["clone", "-q", "--bare", "--no-tags", url, upstream], null).then(() => gitAsync(upstream, ["update-ref", "refs/heads/main", sha], null));
2932 await onOwnServer(name, (c) => pushHistory(c, name, upstream), download);
2933 });
2934 }
2935
2936 test("real histories: a 2.6 MB lockfile's 60 versions, a chain of deltas, go in one small push", async () => {
2937 const upstream = join(work, "lockfile-upstream");
2938 mkdirSync(upstream, { recursive: true });
2939 git(upstream, ["init", "-q", "-b", "main"]);
2940 const versions = new Map();
2941 const pkgs = Array.from({ length: 11_000 }, (_, i) => `pkg-${String(i).padStart(5, "0")}`);
2942 pkgs.forEach((p, i) => versions.set(p, `1.${i % 51}.${i % 97}`));
2943 for (let c = 0; c < 60; c++) {
2944 for (let k = 0; k < 40; k++) versions.set(pkgs[(c * 7919 + k * 104729) % pkgs.length], `2.${c}.${k}`);
2945 const body = pkgs.map((p) => {
2946 const v = versions.get(p);
2947 return ` "node_modules/${p}": {\n "version": "${v}",\n "resolved": "https://registry.npmjs.org/${p}/-/${p}-${v}.tgz",\n "integrity": "sha512-${createHash("sha512").update(p + v).digest("hex").slice(0, 64)}"\n },\n`;
2948 });
2949 writeFileSync(join(upstream, "package-lock.json"), `{\n "lockfileVersion": 3,\n "packages": {\n${body.join("")} }\n}\n`);
2950 git(upstream, ["add", "-A"]);
2951 git(upstream, ["commit", "-q", "-m", `lockfile ${c}`]);
2952 }
2953 assert.ok(readFileSync(join(upstream, "package-lock.json")).length > 2_500_000);
2954 const packBytes = Number(execFileSync("bash", ["-c", "git pack-objects --revs --stdout -q <<<main | wc -c"], { cwd: upstream, encoding: "utf8" }).trim());
2955 assert.ok(packBytes < 16 * 1024 * 1024, `the pack is ${packBytes} bytes`);
2956 await pushHistory(shared(), "lockfile", upstream);
2957 });
2958});
2959
2960// Side by side, each on a server of its own, as the real histories above: about as long as the 40 MB
2961// history's pushes alone instead of the sum.
2962describe("large pushes: side by side, each on a server of its own", { concurrency: true }, () => {
2963 test("large files: a 40 MB file is pushed and cloned intact, and push protection still reads big text files", () =>
2964 onOwnServer("bigfile", async ({ gitBase, ok, git, gitFails }) => {
2965 const me = await ok("GET", "/user");
2966 await ok("POST", "/user/repos", { name: "bigfile" });
2967 const src = join(work, "bigfile");
2968 mkdirSync(src, { recursive: true });
2969 await git(src, ["init", "-q", "-b", "main"]);
2970 // Random bytes don't compress: the push is over 16 MB, so it goes through R2 on its way in.
2971 const data = randomBytes(40 * 1024 * 1024);
2972 writeFileSync(join(src, "big.bin"), data);
2973 await git(src, ["add", "-A"]);
2974 await git(src, ["commit", "-q", "-m", "a large file"]);
2975 await git(src, ["-c", "http.postBuffer=1048576", "push", "-q", `${gitBase}/${me.login}/bigfile.git`, "main"]);
2976 const out = join(work, "bigfile-clone");
2977 await git(work, ["clone", "-q", `${gitBase}/${me.login}/bigfile.git`, out]);
2978 assert.ok(readFileSync(join(out, "big.bin")).equals(data), "the cloned file is the pushed file");
2979 const wantBlob = (await git(src, ["rev-parse", "HEAD:big.bin"])).trim();
2980 assert.equal((await git(out, ["rev-parse", "HEAD:big.bin"])).trim(), wantBlob);
2981 // A large text file (scanned slice by slice) with a key near its end is still refused.
2982 // diffinery:allow-secret (a fake key)
2983 writeFileSync(join(src, "dump.sql"), `${"-- row\n".repeat(1024 * 1024)}aws_key = AKIAIOSFODNN7EXAMPL3\n`);
2984 await git(src, ["add", "-A"]);
2985 await git(src, ["commit", "-q", "-m", "a large dump"]);
2986 assert.match(await gitFails(src, ["push", "-q", `${gitBase}/${me.login}/bigfile.git`, "main"]), /possible secrets detected/);
2987 }));
2988
2989 test("large pushes: three large pushes into one repository at once all go in, and a fetch meanwhile works", () =>
2990 onOwnServer("pushes-at-once", async ({ gitBase, ok, git }) => {
2991 const me = await ok("GET", "/user");
2992 await ok("POST", "/user/repos", { name: "pushes-at-once" });
2993 const remote = `${gitBase}/${me.login}/pushes-at-once.git`;
2994 const src = join(work, "pushes-at-once");
2995 mkdirSync(src, { recursive: true });
2996 await git(src, ["init", "-q", "-b", "main"]);
2997 writeFileSync(join(src, "README.md"), "base\n");
2998 await git(src, ["add", "-A"]);
2999 await git(src, ["commit", "-q", "-m", "base"]);
3000 await git(src, ["push", "-q", remote, "main"]);
3001 // Each branch: many medium files over a few commits, so unpacking holds a lot. Two packs stay under
3002 // 16 MB (handed over in memory), one goes over (staged in R2), as when several agents push at once.
3003 const sizes = { a: 180, b: 180, c: 420 };
3004 const tips = {};
3005 for (const [branch, count] of Object.entries(sizes)) {
3006 await git(src, ["checkout", "-q", "-b", branch, "main"]);
3007 const files = Array.from({ length: count }, () => randomBytes(48 * 1024).toString("base64"));
3008 mkdirSync(join(src, branch), { recursive: true });
3009 for (let c = 0; c < 3; c++) {
3010 files.forEach((f, i) => writeFileSync(join(src, branch, `f${i}.txt`), `${f}\nrevision ${c}\n${randomBytes(1024).toString("hex")}\n`));
3011 await git(src, ["add", "-A"]);
3012 await git(src, ["commit", "-q", "-m", `${branch} ${c}`]);
3013 }
3014 tips[branch] = (await git(src, ["rev-parse", "HEAD"])).trim();
3015 }
3016 await git(src, ["checkout", "-q", "main"]);
3017 const push = (branch) => git(src, ["-c", "http.postBuffer=1048576", "push", "-q", remote, branch]);
3018 const fetchWhile = git(work, ["clone", "-q", remote, join(work, "pushes-at-once-early")]);
3019 await Promise.all([push("a"), push("b"), push("c"), fetchWhile]);
3020 const branches = (await ok("GET", `/repos/${me.login}/pushes-at-once/branches`)).map((b) => b.name).sort();
3021 assert.deepEqual(branches, ["a", "b", "c", "main"]);
3022 const out = join(work, "pushes-at-once-clone");
3023 await git(work, ["clone", "-q", "--mirror", remote, out]);
3024 for (const [branch, tip] of Object.entries(tips)) assert.equal((await git(out, ["rev-parse", `refs/heads/${branch}`])).trim(), tip);
3025 await git(out, ["fsck", "--full", "--strict"]);
3026 }));
3027
3028 test("large pushes: a 40 MB history of many files goes in one push, read from R2 in ranges, and is still checked", () =>
3029 onOwnServer("bighistory", async ({ gitBase, ok, git, gitFails }) => {
3030 const me = await ok("GET", "/user");
3031 await ok("POST", "/user/repos", { name: "bighistory" });
3032 const remote = `${gitBase}/${me.login}/bighistory.git`;
3033 const src = join(work, "bighistory");
3034 mkdirSync(join(src, "files"), { recursive: true });
3035 await git(src, ["init", "-q", "-b", "main"]);
3036 // Hundreds of medium files, each changed a little in later commits: a pack of deltas over 16 MB,
3037 // as a fork's pull request heads made one in jekyll/minima's import.
3038 const files = Array.from({ length: 400 }, () => randomBytes(96 * 1024).toString("base64"));
3039 for (let c = 0; c < 6; c++) {
3040 files.forEach((f, i) => writeFileSync(join(src, "files", `f${i}.txt`), `${f}\nrevision ${c} of file ${i}\n${randomBytes(2048).toString("hex")}\n`));
3041 await git(src, ["add", "-A"]);
3042 await git(src, ["commit", "-q", "-m", `revision ${c}`]);
3043 }
3044 const packBytes = Number(execFileSync("bash", ["-c", "git pack-objects --revs --stdout -q <<<main | wc -c"], { cwd: src, encoding: "utf8" }).trim());
3045 assert.ok(packBytes > 30 * 1024 * 1024, `the pack is ${packBytes} bytes`);
3046 await git(src, ["-c", "http.postBuffer=1048576", "push", "-q", remote, "main"]);
3047 const out = join(work, "bighistory-clone");
3048 await git(work, ["clone", "-q", remote, out]);
3049 assert.equal((await git(out, ["rev-parse", "HEAD"])).trim(), (await git(src, ["rev-parse", "HEAD"])).trim());
3050 await git(out, ["fsck", "--full", "--strict"]);
3051
3052 // A second large push builds on objects the repository has (a thin pack, its bases read from storage).
3053 files.forEach((f, i) => writeFileSync(join(src, "files", `f${i}.txt`), `${f}\nrevision 6 of file ${i}\n${randomBytes(2048).toString("hex")}\n`));
3054 writeFileSync(join(src, "new.bin"), randomBytes(20 * 1024 * 1024));
3055 await git(src, ["add", "-A"]);
3056 await git(src, ["commit", "-q", "-m", "revision 6"]);
3057 await git(src, ["-c", "http.postBuffer=1048576", "push", "-q", remote, "main"]);
3058 await git(out, ["pull", "-q", "--ff-only"]);
3059 assert.equal((await git(out, ["rev-parse", "HEAD"])).trim(), (await git(src, ["rev-parse", "HEAD"])).trim());
3060 await git(out, ["fsck", "--full", "--strict"]);
3061
3062 // A large push is checked like a small one: a key in one small file, or an unsafe .gitmodules, refuses all of it.
3063 await git(src, ["checkout", "-q", "-b", "leak"]);
3064 writeFileSync(join(src, "more.bin"), randomBytes(20 * 1024 * 1024));
3065 writeFileSync(join(src, "config.txt"), "aws_key = AKIAIOSFODNN7EXAMPL3\n"); // diffinery:allow-secret (a fake key; the pushed file doesn't carry the marker)
3066 await git(src, ["add", "-A"]);
3067 await git(src, ["commit", "-q", "-m", "a key"]);
3068 assert.match(await gitFails(src, ["-c", "http.postBuffer=1048576", "push", "-q", remote, "leak"]), /possible secrets detected/);
3069 await git(src, ["checkout", "-q", "main"]);
3070 await git(src, ["checkout", "-q", "-b", "modules"]);
3071 writeFileSync(join(src, "more.bin"), randomBytes(20 * 1024 * 1024));
3072 writeFileSync(join(src, ".gitmodules"), '[submodule "x"]\n\tpath = x\n\turl = --upload-pack=touch /tmp/pwned\n');
3073 await git(src, ["add", "-A"]);
3074 await git(src, ["commit", "-q", "-m", "an unsafe submodule"]);
3075 assert.match(await gitFails(src, ["-c", "http.postBuffer=1048576", "push", "-q", remote, "modules"]), /fsck error: \.gitmodules .*starts with '-'/);
3076 const branches = (await ok("GET", `/repos/${me.login}/bighistory/branches`)).map((b) => b.name);
3077 assert.deepEqual(branches, ["main"]);
3078 }));
3079});