Public: anyone can read this; the crew can change it.

End-to-end test: anonymous, account, forge live, app included, health answers, each step named #16704

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/2930-end-to-end-test-anonymous-account-forge → main 0 commits fork

  • Merged. scout/2930-end-to-end-test-anonymous-account-forge was merged into main as 81ea93d.

Review

Sign in to review this change.
1 file changed +365 −0
test/one-click.test.ts added +365
@@ -0,0 +1,365 @@
1 /**
2 * The one-click path end to end (#2930), over HTTP against real forges: a stranger signs up
3 * (#2923), makes a forge with a public app (#2927), follows to the claim (#2928), the child's
4 * `/health` answers, and the included app answers on its address. Once with no account at all
5 * (the same path from the anonymous door), and once as an agent (#2929): an account, a token, a
6 * spawn that claims itself, a token that works on the child.
7 *
8 * Each step is a named function; a failure reads `step 3 (forge live) failed: …`, never a bare
9 * assertion. Time to live is read from the `forge.spawn.live` event the path itself records and
10 * held to the stated budget (`SPAWN_BUDGET_MS`). Two real forges in one file, no waiting: the
11 * watcher's first probe is the one that answers, so no poll interval (a fake clock) is needed.
12 *
13 * What is stood in: the placement is the hosted one with a host that is not routable, so the
14 * child's address (`<name>--forge.test`) is answered by the test's fetch, which hands it to the
15 * child's real server (found by the bodyId the spawn's ledger records for that name). The included
16 * app's address is answered by the app's own `index.ts`, read from the child's committed tree and
17 * run as a process, behind the header the proxy adds (`x-forge-app`); the cell around it is not
18 * this file's business (`test/cell-*`).
19 */
20 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
21 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
22 import { tmpdir } from "node:os";
23 import { join } from "node:path";
24 import { createRepo } from "../src/actions/repos.ts";
25 import { childDirOf, parseLedger } from "../src/actions/spawn.ts";
26 import { createApp, type App } from "../src/app.ts";
27 import { createUser } from "../src/core/users.ts";
28 import { listApps } from "../src/core/apps.ts";
29 import { getRepoById } from "../src/core/repos.ts";
30 import { runGit } from "../src/git/env.ts";
31 import { repoDir } from "../src/git/repos.ts";
32 import { commitFiles } from "../src/git/write.ts";
33 import { serve, type Servers } from "../src/http/server.ts";
34 import { SPAWN_BUDGET_MS } from "../src/boards/sources.ts";
35 import { useProbe, usePlacement } from "../src/spawn/door.ts";
36 import { firstBoot } from "../src/spawn/first-boot.ts";
37 import { hostedPlacement } from "../src/spawn/placement.ts";
38 import { APP_HEADER, useReach } from "../src/spawn/reach.ts";
39 import { claimStarted, type StartedForge } from "./helpers/claimed-forge.ts";
40 import { quietLogs } from "./helpers/globals.ts";
41
42 quietLogs();
43
44 const PASSWORD = "a-long-one-click-passphrase";
45 const HOST = "forge.test";
46
47 type Child = { app: App; servers: Servers; bodyId: string };
48 type Who = "person" | "anonymous" | "agent";
49 /**
50 * One journey: who walks it, the account name (if any), the forge's name, and what each step leaves
51 * for the next.
52 */
53 type Run = { who: Who; account: string; forge: string; base: string; child?: Child; claimUrl?: string; live?: Promise<number>; ms?: number; cookie?: string; token?: string };
54 /** The answer of `POST /api/v1/forges` that this path reads. */
55 type Spawned = {
56 bodyId: string;
57 claimUrl?: string;
58 token?: string;
59 reach?: { proofs?: { label: string; ok: boolean; says: string }[] };
60 };
61
62 /** The app's own code: what the spawn copies, and what the app's address runs. */
63 const APP_CODE = "const s = Bun.serve({ port: Number(process.env.PORT ?? 0), fetch: () => new Response('fresh bread') });\nconsole.log(s.port);\n";
64
65 /** Name the step that failed: `step 3 (forge live) failed: …`. */
66 async function step<T>(n: number, name: string, run: () => Promise<T>): Promise<T> {
67 try {
68 return await run();
69 } catch (error) {
70 throw new Error(`step ${n} (${name}) failed: ${error instanceof Error ? error.message : String(error)}`);
71 }
72 }
73 function must(ok: unknown, said: string): asserts ok {
74 if (!ok) throw new Error(said);
75 }
76
77 describe("one click, from a stranger to their own forge", () => {
78 let dir: string;
79 let parent: App;
80 let parentServers: Servers;
81 let bakeryDir: string;
82 let bakeryHead: string;
83 let bakery: { stop: () => void; url: string } | undefined;
84 const children = new Map<string, Promise<Child>>();
85 const liveEvents = (): { ms: number }[] =>
86 parent.db
87 .query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'forge.spawn.live' ORDER BY id")
88 .all()
89 .map((r) => JSON.parse(r.payload) as { ms: number });
90
91 /** The app's committed `index.ts`, run as the app runs; the address it listens on. */
92 const runApp = async (source: string): Promise<{ stop: () => void; url: string }> => {
93 const file = join(bakeryDir, "index.ts");
94 await writeFile(file, source);
95 const proc = Bun.spawn([process.execPath, file], { cwd: bakeryDir, env: { PATH: process.env.PATH ?? "", PORT: "0" }, stdout: "pipe", stderr: "ignore" });
96 const reader = proc.stdout.getReader();
97 const first = await reader.read();
98 const port = Number(new TextDecoder().decode(first.value).trim());
99 must(Number.isInteger(port) && port > 0, "the app did not say its port");
100 return { stop: () => proc.kill(), url: `http://127.0.0.1:${port}/` };
101 };
102
103 const json = (url: string, body: unknown, headers: Record<string, string> = {}) =>
104 fetch(url, { method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, ...headers }, body: JSON.stringify(body) });
105
106 /** The child behind a spawn, opened once from the body the parent made it in. */
107 const childOf = (bodyId: string): Promise<Child> => {
108 const had = children.get(bodyId);
109 if (had) return had;
110 const opened = (async () => {
111 const app = createApp({ dataDir: childDirOf(parent, bodyId), port: 0 });
112 await firstBoot(app);
113 return { app, servers: await serve(app), bodyId };
114 })();
115 children.set(bodyId, opened);
116 return opened;
117 };
118
119 /**
120 * The child a forge's name labels, by the body the spawn recorded for that name in its ledger
121 * (`spawn/<name>.json`, written once the placement has answered, before the watcher probes);
122 * undefined until it is there.
123 */
124 const childNamed = async (name: string): Promise<Child | undefined> => {
125 const file = Bun.file(join(dir, "spawn", `${name}.json`));
126 if (!(await file.exists())) return undefined;
127 const ledger = parseLedger(await file.text());
128 return ledger === undefined ? undefined : childOf(ledger.bodyId);
129 };
130
131 /**
132 * Where a child's public address leads: its home to the child's server, an app's address to the
133 * app's.
134 */
135 const answerAt = async (url: string, init?: RequestInit): Promise<Response> => {
136 const at = new URL(url);
137 const labels = at.hostname.split("--");
138 if (labels.length === 3) {
139 must(bakery !== undefined, "the app is not running");
140 const res = await fetch(bakery.url, { ...(init?.signal ? { signal: init.signal } : {}) });
141 return new Response(await res.text(), { status: res.status, headers: { [APP_HEADER]: labels[0]! } });
142 }
143 const up = await childNamed(labels[0]!);
144 if (!up) return new Response("no", { status: 502 });
145 const headers = new Headers(init?.headers);
146 headers.set("origin", up.servers.url);
147 return fetch(`${up.servers.url}${at.pathname}${at.search}`, { ...init, headers });
148 };
149
150 beforeAll(async () => {
151 dir = await mkdtemp(join(tmpdir(), "forge-one-click-"));
152 parent = createApp({ dataDir: dir, port: 0 });
153 parentServers = await serve(parent);
154 const alice = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: PASSWORD, isAdmin: true });
155 must(alice.ok, "seed user");
156 // The public app a stranger may take.
157 const repo = await createRepo(parent, alice.value, { name: "bakery", visibility: "public" });
158 must(repo.ok, "seed repo");
159 const c = await commitFiles(repoDir(parent.reposRoot, "alice", "bakery"), {
160 branch: "main",
161 message: "bakery",
162 files: [
163 { path: "forge.json", content: JSON.stringify({ app: { run: "bun run index.ts", health: "/" } }) },
164 { path: "index.ts", content: APP_CODE },
165 ],
166 author: { name: "a", email: "[email protected]" },
167 });
168 must(c.ok, "seed commit");
169 const head = await runGit(["rev-parse", "main"], { cwd: repoDir(parent.reposRoot, "alice", "bakery") });
170 must(head.ok, "seed head");
171 bakeryHead = head.value.trim();
172 bakeryDir = join(dir, "bakery-run");
173 await mkdir(bakeryDir);
174 // The app runs from the committed tree before any spawn: the spawn proves its address from
175 // outside.
176 const shown = await runGit(["show", "main:index.ts"], { cwd: repoDir(parent.reposRoot, "alice", "bakery") });
177 must(shown.ok && shown.value.trim() === APP_CODE.trim(), "the committed index.ts is not the app's code");
178 bakery = await runApp(shown.value);
179
180 usePlacement(parent, hostedPlacement({ host: HOST }));
181 // The watcher's probe is the child's own `/health`, asked once the child is up.
182 useProbe(parent, (url) => async () => {
183 const up = await childNamed(new URL(url).hostname.split("--")[0]!);
184 return up !== undefined && (await fetch(`${up.servers.url}/health`)).status === 200;
185 });
186 useReach(parent, { homeWaitMs: 1000, fetch: (url, init) => answerAt(String(url), init) });
187 }, 30_000);
188
189 afterAll(async () => {
190 for (const opened of children.values()) {
191 const c = await opened;
192 c.servers.stop();
193 c.app.close();
194 }
195 bakery?.stop();
196 parentServers.stop();
197 parent.close();
198 await rm(dir, { recursive: true, force: true });
199 });
200
201 // --- the steps, shared by the three journeys ---------------------------------------------
202
203 const authOf = (run: Run): Record<string, string> =>
204 run.who === "agent" ? { authorization: `Bearer ${run.token}` } : run.cookie === undefined ? {} : { cookie: run.cookie };
205
206 /**
207 * 1. The account: a person's form sets an HttpOnly session; an agent's API call makes the account
208 * and a token; a stranger has none, and the door is open to them all the same.
209 */
210 const signUp = (run: Run) =>
211 step(1, run.who === "anonymous" ? "anonymous" : "signup", async () => {
212 if (run.who === "anonymous") {
213 const page = await fetch(`${run.base}/forges/new`);
214 must(page.status === 200, `the forge form answered ${page.status} to a stranger`);
215 const me = await fetch(`${run.base}/api/v1/user`);
216 must(me.status === 401, `a stranger is someone: /api/v1/user answered ${me.status}`);
217 return;
218 }
219 if (run.who === "person") {
220 const res = await fetch(`${run.base}/signup`, {
221 method: "POST",
222 redirect: "manual",
223 headers: { "content-type": "application/x-www-form-urlencoded", origin: run.base },
224 body: new URLSearchParams({ username: run.account, email: "", password: PASSWORD }),
225 });
226 must(res.status === 303, `the signup form answered ${res.status}, not a redirect`);
227 const set = res.headers.get("set-cookie") ?? "";
228 must(set.includes("HttpOnly"), "the session cookie is not HttpOnly");
229 run.cookie = set.split(";")[0]!;
230 return;
231 }
232 const made = await json(`${run.base}/api/v1/users`, { username: run.account, password: PASSWORD });
233 must(made.status === 201, `the account answered ${made.status}`);
234 const minted = await json(`${run.base}/api/v1/tokens`, { username: run.account, password: PASSWORD, scope: "rw", name: "agent" });
235 must(minted.status === 201, `the token answered ${minted.status}`);
236 run.token = ((await minted.json()) as { token: string }).token;
237 });
238
239 /** 2. The forge: a public app included; an agent also claims in the same call. */
240 const makeForge = (run: Run) =>
241 step(2, "make a forge", async () => {
242 run.live = new Promise<number>((heard) => {
243 const off = parent.bus.subscribe((e) => {
244 if (e.kind !== "forge.spawn.live") return;
245 off();
246 heard((e.payload as { ms: number }).ms);
247 });
248 });
249 const res = await json(
250 `${run.base}/api/v1/forges`,
251 { name: run.forge, apps: ["alice/bakery"], dryRun: false, ...(run.who === "agent" ? { claim: "token" } : {}) },
252 authOf(run),
253 );
254 const body = (await res.json()) as Spawned;
255 must(res.status === 201, `the spawn answered ${res.status}: ${JSON.stringify(body).slice(0, 200)}`);
256 // The body the spawn recorded for this name is the body the answer names.
257 const named = await childNamed(run.forge);
258 must(named !== undefined && named.bodyId === body.bodyId, `the ledger names another body than the answer's ${body.bodyId}`);
259 run.child = named;
260 if (run.who === "agent") {
261 must(typeof body.token === "string" && body.claimUrl === undefined, "the agent's claim did not answer a token");
262 run.token = body.token;
263 } else {
264 must(typeof body.claimUrl === "string", "no claim link in the answer");
265 run.claimUrl = body.claimUrl;
266 }
267 // The proof the spawn made from outside: the child's home and the included app's address.
268 const proofs = body.reach?.proofs ?? [];
269 must(proofs.some((p) => p.label === "bakery"), `the spawn proved no app address: ${JSON.stringify(proofs)}`);
270 for (const p of proofs) must(p.ok, `${p.label}: ${p.says}`);
271 });
272
273 /**
274 * 3. Live: the child's `/health` answers, and the time to live the path recorded is inside the
275 * budget.
276 */
277 const forgeLive = (run: Run) =>
278 step(3, "forge live", async () => {
279 const health = await fetch(`${run.child!.servers.url}/health`);
280 must(health.status === 200, `/health answered ${health.status}`);
281 const ms = await run.live!;
282 run.ms = ms;
283 must(ms < SPAWN_BUDGET_MS, `time to live ${ms} ms is over the ${SPAWN_BUDGET_MS} ms budget`);
284 });
285
286 /** 4. The claim: the link makes the owner (a person), or the token already works (an agent). */
287 const claim = (run: Run) =>
288 step(4, "claim", async () => {
289 const child = run.child!;
290 if (run.who === "agent") {
291 const me = await fetch(`${child.servers.url}/api/v1/user`, { headers: authOf(run) });
292 must(me.status === 200, `the child's token answered ${me.status}`);
293 return;
294 }
295 const started: StartedForge = {
296 base: child.servers.url,
297 child: child.app,
298 token: run.claimUrl!.split("#")[1]!,
299 post: async () => new Response(),
300 stop: async () => {},
301 };
302 const claimed = await claimStarted(started);
303 must(claimed.owner.startsWith("forge_session="), `no session after the claim: ${claimed.owner}`);
304 run.cookie = claimed.owner;
305 const me = await fetch(`${child.servers.url}/api/v1/user`, { headers: authOf(run) });
306 must(me.status === 200, `the owner's session answered ${me.status}`);
307 });
308
309 /**
310 * 5. The included app is the child's own copy of alice/bakery at the same commit, listed to its
311 * owner, with the code that runs at its address (the process `beforeAll` started from the
312 * committed tree), and answers there.
313 */
314 const appAnswers = (run: Run) =>
315 step(5, "included app", async () => {
316 const child = run.child!;
317 const apps = await fetch(`${child.servers.url}/api/v1/apps`, { headers: authOf(run) });
318 must(apps.status === 200, `the child's apps answered ${apps.status}`);
319 const items = ((await apps.json()) as { items: unknown[] }).items;
320 must(items.length === 1, `the child lists ${items.length} apps, not the 1 it was given`);
321 const record = listApps(child.app.db)[0];
322 must(record !== undefined, "the child has no app record");
323 const repo = getRepoById(child.app.db, record.repoId);
324 must(repo !== undefined && repo.name === "bakery", "the child's app is not the bakery");
325 const dirOfCopy = repoDir(child.app.reposRoot, repo.ownerName, repo.name);
326 const head = await runGit(["rev-parse", "main"], { cwd: dirOfCopy });
327 must(head.ok && head.value.trim() === bakeryHead, `the child's bakery is at ${head.ok ? head.value.trim() : "nothing"}, not alice/bakery's ${bakeryHead}`);
328 const parentLink = (await Bun.file(join(childDirOf(parent, child.bodyId), "parent.json")).json()) as { apps?: { url?: string }[] };
329 must(parentLink.apps?.some((a) => a.url?.includes("alice/bakery")), "the child does not follow alice/bakery");
330 // The code the child holds is the code that runs at the app's address.
331 const code = await runGit(["show", "main:index.ts"], { cwd: dirOfCopy });
332 must(code.ok && code.value.trim() === APP_CODE.trim(), "the child's index.ts is not the app's code");
333 const res = await answerAt(`https://${record.slug}--${run.forge}--${HOST}/`);
334 must(res.status === 200 && (await res.text()) === "fresh bread", `the app answered ${res.status}`);
335 must(res.headers.get(APP_HEADER) === record.slug, "the answer is not the app's");
336 });
337 const journey = async (run: Run) => {
338 const before = liveEvents().length;
339 await signUp(run);
340 await makeForge(run);
341 await forgeLive(run);
342 await claim(run);
343 await appAnswers(run);
344 expect(liveEvents().length).toBe(before + 1);
345 };
346
347 test("a stranger with no account: forge, live, claim link, the app answers", async () => {
348 await journey({ who: "anonymous", account: "", forge: "anonbread", base: parentServers.url });
349 }, 20_000);
350
351 test("a person: signup, forge, live, claim, the app answers", async () => {
352 await journey({ who: "person", account: "stranger", forge: "bakehouse", base: parentServers.url });
353 }, 20_000);
354
355 test("an agent: account, token, forge claimed in the call, the app answers", async () => {
356 await journey({ who: "agent", account: "botty", forge: "botforge", base: parentServers.url });
357 }, 20_000);
358
359 test("a real step that fails is named by its number and what it is", async () => {
360 await expect(makeForge({ who: "agent", account: "nobody", forge: "never", base: parentServers.url, token: "not-a-token" })).rejects.toThrow(
361 /^step 2 \(make a forge\) failed: the spawn answered 4\d\d/,
362 );
363 expect(await childNamed("never")).toBeUndefined();
364 });
365 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs