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

Only the person who started a child forge can resume it and receive its claim link #14999

Merged opened this

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

Merged

scout/forge:scout/14910-only-the-person-who-started-a-child-forg → main 4 commits fork

  • Merged. scout/14910-only-the-person-who-started-a-child-forg was merged into main as f813815.

Review

Sign in to review this change.
5 files changed +254 −0
src/actions/spawn.ts +48
@@ -16,6 +16,7 @@ import { nameShapeVerdict, nameVerdict, suggestNames, takenWords, type NameVerdi
1616 import { readdirSync, readFileSync } from "node:fs";
1717 import { mkdir, readdir, rm } from "node:fs/promises";
1818 import { join } from "node:path";
19 import { timingSafeEqual } from "node:crypto";
1920 import { createApp, type App } from "../app.ts";
2021 import { tellPlan } from "../billing/notice.ts";
2122 import {
@@ -94,8 +95,20 @@ export interface Spawned {
9495 * keeps only its hash (`spawn/claim.ts`).
9596 */
9697 readonly claimUrl?: string;
98 /**
99 * A stranger's child only: the key that resumes it if the making is cut off, given to its first
100 * caller and demanded again (the ledger keeps only its hash). Absent for a signed-in person's.
101 */
102 readonly resumeKey?: string;
97103 }
98104
105 /** The shape of a resume key a caller may choose: a `secret()` or something as long and plain. */
106 export const RESUME_KEY = /^[A-Za-z0-9_-]{32,128}$/;
107
108 /** Said to anyone but the starter who asks to resume an unfinished child. */
109 export const NOT_YOURS = (name: string): string =>
110 `${name} is being made by someone else; only the person who started it can resume it`;
111
99112 export type SpawnError =
100113 | { readonly kind: "unauthorized" | "forbidden" | "cross_origin" }
101114 | { readonly kind: "invalid"; readonly field: string; readonly reason: string }
@@ -128,6 +141,11 @@ export interface SpawnDeps {
128141 * series.
129142 */
130143 readonly drill?: boolean;
144 /**
145 * A stranger's resume key (`RESUME_KEY`): on a new child it is the one kept, so a caller cut off
146 * before the answer still holds it; on an unfinished one it must match.
147 */
148 readonly resumeKey?: string;
131149 }
132150
133151 interface Ledger {
@@ -176,6 +194,28 @@ interface Ledger {
176194 * child holds the same one in its `parent.json`. Never in an answer.
177195 */
178196 beatKey?: string;
197 /** A stranger's child: the hash of the key that resumes it (`Spawned.resumeKey`). */
198 readonly resumeHash?: string;
199 }
200
201 /**
202 * The key a new child keeps: none for a signed-in owner, else the stranger's own or a fresh one.
203 */
204 function newResumeKey(owner: User | undefined, chosen: string | undefined): string | undefined {
205 if (owner !== undefined) return undefined;
206 return chosen !== undefined && RESUME_KEY.test(chosen) ? chosen : secret();
207 }
208
209 /**
210 * Whether this caller started the unfinished child: its owner, or, for a stranger's, whoever holds
211 * the resume key. A ledger from before the key, with no owner, resumes for nobody.
212 */
213 function startedBy(ledger: Ledger, owner: User | undefined, resumeKey: string | undefined): boolean {
214 if (ledger.ownerId !== undefined) return owner !== undefined && owner.id === ledger.ownerId;
215 if (owner !== undefined || ledger.resumeHash === undefined || resumeKey === undefined) return false;
216 const a = Buffer.from(sha256(resumeKey));
217 const b = Buffer.from(ledger.resumeHash);
218 return a.length === b.length && timingSafeEqual(a, b);
179219 }
180220
181221 const SAFE_ID = /^[A-Za-z0-9_-]{1,80}$/;
@@ -346,9 +386,14 @@ async function make(
346386 let ledger = await readLedger(app, plan.name);
347387 // Only a child this call began is removed on failure; a resumed one is left for the retry.
348388 const began = ledger === undefined;
389 // A stranger's: the key that resumes this child, said back with it.
390 let resumeKey = owner === undefined ? deps.resumeKey : undefined;
349391 if (ledger) {
350392 if (ledger.planHash !== planHash)
351393 return err({ kind: "invalid", field: "name", reason: await takenReason(app, plan.name) });
394 // Resuming mints a new claim link: only the one who started the child may (#14910).
395 if (!ledger.done && !startedBy(ledger, owner, deps.resumeKey))
396 return err({ kind: "refused", reason: "not_yours", message: NOT_YOURS(plan.name) });
352397 // The plan names that there is a key, never which: a retry with another
353398 // key is refused plainly rather than quietly keeping the first.
354399 if (deps.modelKey !== undefined) {
@@ -388,6 +433,7 @@ async function make(
388433 }
389434 const over = quotaRefusal(app.config.dataDir, plan.size ?? DEFAULT_SIZE);
390435 if (over !== undefined) return err({ kind: "refused", reason: "quota", message: over });
436 resumeKey = newResumeKey(owner, deps.resumeKey);
391437 const placed = await deps.placement.place(plan);
392438 if (!placed.ok) return err({ kind: "refused", ...placed.error });
393439 if (!SAFE_ID.test(placed.value.bodyId)) {
@@ -404,6 +450,7 @@ async function make(
404450 apps: plan.apps.map((a) => a.ref),
405451 createdAt: new Date().toISOString(),
406452 ...(owner === undefined ? {} : { ownerId: owner.id }),
453 ...(resumeKey === undefined ? {} : { resumeHash: sha256(resumeKey) }),
407454 size: plan.size ?? DEFAULT_SIZE,
408455 ...(plan.admin === undefined ? {} : { admin: plan.admin }),
409456 ...(plan.domain === undefined ? {} : { domain: plan.domain }),
@@ -443,6 +490,7 @@ async function make(
443490 placement: ledger.placement ?? "hosted",
444491 existed: false,
445492 claimUrl,
493 ...(resumeKey === undefined ? {} : { resumeKey }),
446494 });
447495 }
448496
src/spawn/door.ts +6
@@ -19,6 +19,7 @@ import {
1919 founderClash,
2020 previewReissue,
2121 reissueClaim,
22 RESUME_KEY,
2223 spawnForge,
2324 takenReason,
2425 type SpawnError,
@@ -324,6 +325,10 @@ export async function spawnDoor(
324325 "modelKey",
325326 "anonymous spawns carry no model key; open the forge as yours and add one there",
326327 );
328 // A stranger's resume key (#14910): their own, so a cut-off answer still leaves them holding it.
329 const resumeKey = raw["resumeKey"];
330 if (resumeKey !== undefined && (!anon || typeof resumeKey !== "string" || !RESUME_KEY.test(resumeKey)))
331 return invalid("resumeKey", anon ? "must be 32 to 128 letters, digits, - or _" : "is for a stranger's forge; yours resumes by your sign-in");
327332 // The child's model key: a key or subscription token with a whole-life budget, or none. A
328333 // subscription token is a person's own plan and never travels.
329334 const modelEndpointRaw = raw["modelEndpoint"];
@@ -505,6 +510,7 @@ export async function spawnDoor(
505510 url: ctx.url,
506511 ...(typeof modelKey === "string" ? { modelKey } : {}),
507512 ...(modelEndpoint === undefined ? {} : { modelEndpoint }),
513 ...(typeof resumeKey === "string" ? { resumeKey } : {}),
508514 });
509515 born = made.ok && !made.value.existed;
510516 if (made.ok && gift !== undefined && !made.value.existed) {
test/spawn-resume-door.test.ts added +65
@@ -0,0 +1,65 @@
1 // The door's check on `resumeKey` (#14910): only a stranger may send one, in the shape
2 // `RESUME_KEY` names, and a good one reaches `spawnForge` and comes back in the answer.
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createUser, type User } from "../src/core/users.ts";
9 import type { Ctx } from "../src/http/context.ts";
10 import { spawnDoor, usePlacement, useProbe } from "../src/spawn/door.ts";
11 import { hostedPlacement } from "../src/spawn/placement.ts";
12
13 let dir: string;
14 let app: App;
15 let carol: User;
16 const ctx = (user?: User): Ctx => ({
17 app,
18 request: new Request("https://forge.test/api/v1/forges", { method: "POST", headers: { origin: "https://forge.test" } }),
19 url: new URL("https://forge.test/api/v1/forges"),
20 params: {},
21 auth: { user, scope: undefined, via: user === undefined ? "none" : "session" },
22 theme: undefined,
23 });
24 const ask = (user: User | undefined, resumeKey: unknown, name = "door-kid") =>
25 spawnDoor(ctx(user), user, { name, apps: [], crew: [], dryRun: false, resumeKey });
26 const onKey = (door: { status: number; body: Record<string, unknown> }) => {
27 expect(door.status).toBe(422);
28 expect(String(door.body["message"])).toStartWith("resumeKey:");
29 };
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-spawn-resume-door-"));
33 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
34 const r = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", isAdmin: true });
35 if (!r.ok) throw new Error(r.error);
36 carol = r.value;
37 useProbe(app, () => async () => true);
38 usePlacement(app, hostedPlacement({ host: "forge.test" }));
39 });
40 afterAll(async () => {
41 app.close();
42 await rm(dir, { recursive: true, force: true });
43 });
44
45 test("a stranger's malformed key is invalid on resumeKey: too short, or outside A-Za-z0-9_-", async () => {
46 onKey(await ask(undefined, "short"));
47 onKey(await ask(undefined, `${"a".repeat(40)}!`));
48 onKey(await ask(undefined, "a".repeat(129)));
49 });
50
51 test("a signed-in caller sending a key is invalid on resumeKey", async () => {
52 onKey(await ask(carol, "k".repeat(40)));
53 });
54
55 test("a key that is not a string is refused", async () => {
56 onKey(await ask(undefined, 12345678901234567890));
57 onKey(await ask(undefined, ["k".repeat(40)]));
58 });
59
60 test("a stranger's good key reaches spawnForge and comes back in the answer", async () => {
61 const key = "Good_key-".repeat(4);
62 const door = await ask(undefined, key, "door-good");
63 expect(door.status).toBe(201);
64 expect(door.body["resumeKey"]).toBe(key);
65 });
test/spawn-resume.test.ts added +118
@@ -0,0 +1,118 @@
1 // Only the one who started an unfinished child may resume it and be handed a fresh claim link
2 // (#14910): its owner by sign-in, a stranger by the resume key the first answer gave them.
3 import { afterEach, beforeEach, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { NOT_YOURS, spawnForge, type SpawnDeps } from "../src/actions/spawn.ts";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { repoDir } from "../src/git/repos.ts";
12 import { commitFiles } from "../src/git/write.ts";
13 import { hostedPlacement } from "../src/spawn/placement.ts";
14 import type { SpawnSource } from "../src/spawn/plan.ts";
15
16 let dir: string;
17 let app: App;
18 let alice: User;
19 let bob: User;
20 let deps: SpawnDeps;
21 let source: SpawnSource;
22 const input = { name: "kid", org: "kids", apps: ["alice/notes"], carryBriefs: false, carrySubscriptions: false };
23
24 async function person(username: string, isAdmin: boolean): Promise<User> {
25 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@x.invalid`, isAdmin });
26 if (!made.ok) throw new Error("user");
27 return made.value;
28 }
29
30 beforeEach(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-spawn-resume-"));
32 app = createApp({ dataDir: dir, url: "https://forge.test" });
33 alice = await person("alice", true);
34 bob = await person("bob", false);
35 const repo = await createRepo(app, alice, { name: "notes", visibility: "public" });
36 if (!repo.ok) throw new Error("repo");
37 const c = await commitFiles(repoDir(app.reposRoot, "alice", "notes"), {
38 branch: "main",
39 message: "one",
40 files: [{ path: "one.txt", content: "one" }],
41 author: { name: "a", email: "[email protected]" },
42 });
43 if (!c.ok) throw new Error("commit");
44 source = { catalog: [{ ref: "alice/notes", readable: true, bytes: 10, forgeJsonBytes: 0 }], briefs: [], subscriptions: [] };
45 deps = {
46 placement: hostedPlacement({ host: "forge.test" }),
47 request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }),
48 url: new URL("https://forge.test/spawn"),
49 };
50 });
51
52 afterEach(async () => {
53 app.close();
54 await rm(dir, { recursive: true, force: true });
55 });
56
57 const spawn = (actor: User | undefined, more: Partial<SpawnDeps> = {}) =>
58 spawnForge(app, actor, input, source, { ...deps, ...more });
59
60 /** The child as a cut-off making leaves it: its ledger written, not yet done. */
61 async function cutOff(): Promise<void> {
62 const path = join(dir, "spawn", "kid.json");
63 const ledger = JSON.parse(await Bun.file(path).text());
64 await Bun.write(path, JSON.stringify({ ...ledger, done: false }));
65 }
66
67 test("the owner resumes their unfinished child; a stranger and an anonymous caller are refused", async () => {
68 const first = await spawn(alice);
69 if (!first.ok) throw new Error(JSON.stringify(first.error));
70 expect(first.value.resumeKey).toBeUndefined();
71 await cutOff();
72
73 const stranger = await spawn(bob);
74 expect(stranger).toEqual({ ok: false, error: { kind: "refused", reason: "not_yours", message: NOT_YOURS("kid") } });
75 const anon = await spawn(undefined, { resumeKey: "x".repeat(43) });
76 expect(anon).toEqual({ ok: false, error: { kind: "refused", reason: "not_yours", message: NOT_YOURS("kid") } });
77
78 const again = await spawn(alice);
79 if (!again.ok) throw new Error(JSON.stringify(again.error));
80 expect(again.value.claimUrl).toContain("claim");
81 });
82
83 test("a stranger's child resumes only with the key its first answer gave", async () => {
84 const first = await spawn(undefined);
85 if (!first.ok) throw new Error(JSON.stringify(first.error));
86 const key = first.value.resumeKey!;
87 expect(key).toMatch(/^[A-Za-z0-9_-]{43}$/);
88 // The parent keeps its hash only.
89 expect(await Bun.file(join(dir, "spawn", "kid.json")).text()).not.toContain(key);
90 await cutOff();
91
92 expect((await spawn(undefined)).ok).toBe(false);
93 expect((await spawn(undefined, { resumeKey: "y".repeat(43) })).ok).toBe(false);
94 // A signed-in person is not the stranger who began it, key or none.
95 expect((await spawn(bob, { resumeKey: key })).ok).toBe(false);
96
97 const again = await spawn(undefined, { resumeKey: key });
98 if (!again.ok) throw new Error(JSON.stringify(again.error));
99 expect(again.value.claimUrl).toContain("claim");
100 });
101
102 test("a stranger's own key is the one kept, so a cut-off answer still leaves them holding it", async () => {
103 const mine = "m".repeat(40);
104 const first = await spawn(undefined, { resumeKey: mine });
105 if (!first.ok) throw new Error(JSON.stringify(first.error));
106 expect(first.value.resumeKey).toBe(mine);
107 await cutOff();
108 expect((await spawn(undefined, { resumeKey: mine })).ok).toBe(true);
109 });
110
111 test("a finished child is answered as before, to anyone, with no claim link", async () => {
112 const first = await spawn(alice);
113 if (!first.ok) throw new Error(JSON.stringify(first.error));
114 const seen = await spawn(bob);
115 if (!seen.ok) throw new Error(JSON.stringify(seen.error));
116 expect(seen.value.existed).toBe(true);
117 expect(seen.value.claimUrl).toBeUndefined();
118 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs