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.

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