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

A stranger cut off during a one-click start can resume it with the resumeKey #14910 issues #15139

Merged opened this

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

Merged

mason/forge:mason/15126-a-stranger-cut-off-during-a-one-click-st → main 9 commits fork 3 threads · 3 unresolved

  • Merged. mason/15126-a-stranger-cut-off-during-a-one-click-st was merged into main as bb6dbd7.

Review

Sign in to review this change.
8 files changed +294 −10
src/tui/screens/startforge.ts +41 −1
@@ -6,9 +6,14 @@
66 * one of the fixed sentences the home page shows (`web/start_refusal.ts`); a
77 * made forge's claim link is shown once and kept nowhere. Signed in, "New
88 * forge" is the fuller form, so this command is a guest's.
9 * Each name is sent with a resume key this SSH session keeps (#15126), so a
10 * start cut off before the forge is made is finished by pressing Enter again
11 * in the same session, and by nobody else. The key is never shown; a session
12 * holds keys for its last `RESUME_NAMES` names.
913 */
1014
1115 import { notePeer } from "../../http/peer.ts";
16 import { secret } from "../../kernel/id.ts";
1217 import { spawnDoor } from "../../spawn/door.ts";
1318 import { START_REFUSALS, startRefusalOf, startRefusalWords, startWaitOf } from "../../web/start_refusal.ts";
1419 import type { Ctx, Screen } from "../app/app.ts";
@@ -21,6 +26,37 @@ import { linkScreen, runAsync } from "./common.ts";
2126
2227 const HINT = "Lowercase letters, digits and dashes. Enter starts it.";
2328
29 /** The most names one session holds a resume key for; past it the oldest is dropped. */
30 export const RESUME_NAMES = 8;
outdated

This Map is unbounded per session: every name a guest types adds a key. Cap its size and drop the oldest, with a test.

31
32 /**
33 * Each session's resume keys, by forge name: kept until that forge is made, gone with the session.
34 */
35 const resumeKeys = new WeakMap<Session, Map<string, string>>();
36
37 /**
38 * The key `keys` holds for `name`, or a fresh one from `make` it keeps. Insertion order is age, so
39 * a new name past `RESUME_NAMES` drops the oldest and the map stays bounded.
40 */
41 export function keptResumeKey(keys: Map<string, string>, name: string, make: () => string): string {
42 const held = keys.get(name);
43 if (held !== undefined) return held;
44 const key = make();
45 keys.set(name, key);
46 for (const old of keys.keys()) {
47 if (keys.size <= RESUME_NAMES) break;
48 keys.delete(old);
49 }
50 return key;
51 }
52
53 /** The key this session sends for `name`: the one it already holds, or a fresh one it keeps. */
54 function resumeKeyOf(f: Session, name: string): string {
55 let keys = resumeKeys.get(f);
56 if (keys === undefined) resumeKeys.set(f, (keys = new Map()));
57 return keptResumeKey(keys, name, secret);
58 }
59
2460 export function startForgeScreen(f: Session, ctx: Ctx): Screen {
2561 let name = "";
2662 let error: string | undefined;
@@ -36,7 +72,11 @@ export function startForgeScreen(f: Session, ctx: Ctx): Screen {
3672 const request = new Request(new URL("/forges/start", url).href, { method: "POST" });
3773 notePeer(request, f.identity.remoteAddress);
3874 const hctx = { app: f.app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" as const }, theme: undefined };
39 const made = await spawnDoor(hctx, undefined, { name: name.trim().toLowerCase(), dryRun: false });
75 const asked = name.trim().toLowerCase();
76 // Held before the door is asked: a start that stops part way leaves the key here for Enter
77 // again.
78 const made = await spawnDoor(hctx, undefined, { name: asked, dryRun: false, resumeKey: resumeKeyOf(f, asked) });
79 if (made.status < 400) resumeKeys.get(f)?.delete(asked);
4080 const link = made.body["claimUrl"];
4181 if (made.status >= 400 || typeof link !== "string") {
4282 error = made.status >= 400 ? startRefusalWords(startRefusalOf(made), startWaitOf(made)) : START_REFUSALS.taken;
src/web/pages/start-forge.ts +31 −5
@@ -6,16 +6,19 @@
66 * answers (`web/forge_made.ts`), in a no-store body. The answer does not wait
77 * on the first reach proof: the page shows the start itself.
88 * A signed-in person is sent to the fuller `/forges/new`, which keeps its form.
9 * The door is sent a resume key this browser keeps (`web/resume_cookie.ts`, #15126), so a start
10 * cut off before the forge is made is finished by pressing it again here, and by nobody else.
911 */
1012 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1113 import type { Ctx } from "../../http/context.ts";
12 import { spawnDoor } from "../../spawn/door.ts";
14 import { spawnDoor, type Door } from "../../spawn/door.ts";
1315 import { noteForgeMade } from "../funnel_door.ts";
1416 import { field, readForm, refused } from "../form.ts";
1517 import { agentsPage } from "./agents.ts";
1618 import { madeBody, madeJs } from "../forge_made.ts";
1719 import { page, redirect } from "../layout.ts";
1820 import { notFoundPage } from "../chrome.ts";
21 import { dropResumeKey, keepResumeKey, resumeKeyFor } from "../resume_cookie.ts";
1922 import { startRefusalHref, startRefusalOf, startRefusalWords, startWaitOf } from "../start_refusal.ts";
2023
2124 /** The home's live name check: asks `GET /forges/name/<name>` and says free, taken, or the route's own reason; a 429 or a failure says nothing. */
@@ -44,21 +47,44 @@ export async function startForgeSubmit(ctx: Ctx): Promise<Response> {
4447 const typed = field(form, "name").trim();
4548 const name = typed.toLowerCase();
4649 if (user !== undefined) return redirect(SLUG.test(name) ? `/forges/new?name=${encodeURIComponent(name)}` : "/forges/new");
47 const door = await spawnDoor(ctx, undefined, { name, dryRun: false }, { page: true });
50 const resumeKey = resumeKeyFor(ctx.request, name);
51 const door = await startDoor(ctx, name, resumeKey);
4852 if (door.status >= 400) {
4953 const why = startRefusalOf(door);
5054 const wait = startWaitOf(door);
55 // Kept on every refusal: a start that stopped part way is this browser's to finish.
56 const kept = keepResumeKey(name, resumeKey, ctx.url, ctx.app.config.url);
5157 // The /agents form is answered on /agents, the name kept and the reason beside it.
52 if (field(form, "from") === "agents") return agentsPage(ctx, refused(form, { name: startRefusalWords(why, wait) }));
58 if (field(form, "from") === "agents") return withCookie(await agentsPage(ctx, refused(form, { name: startRefusalWords(why, wait) })), kept);
5359 // Said on the home page, with the name kept (#11238).
54 return redirect(startRefusalHref(why, typed, wait));
60 return withCookie(redirect(startRefusalHref(why, typed, wait)), kept);
5561 }
62 const done = dropResumeKey(name, ctx.url, ctx.app.config.url);
5663 const link = door.body["claimUrl"];
57 if (typeof link !== "string") return redirect(startRefusalHref("taken", name));
64 if (typeof link !== "string") return withCookie(redirect(startRefusalHref("taken", name)), done);
5865 noteForgeMade(ctx);
5966 // Made for themselves: its own account screen, never the one for a link someone sent.
6067 const body = madeBody({ name, link: link.replace(/\/claim#/, "/welcome#"), own: true });
6168 const response = page({ ctx, title: "Your new forge", body, scriptJs: madeJs });
6269 response.headers.set("cache-control", "no-store");
70 return withCookie(response, done);
71 }
72
73 /**
74 * The door, as a stranger holding `resumeKey`. A start that throws part way may leave its forge
75 * unfinished: it is answered as a failed start, so the browser still gets the key that resumes it.
76 */
77 async function startDoor(ctx: Ctx, name: string, resumeKey: string): Promise<Door> {
78 try {
79 return await spawnDoor(ctx, undefined, { name, dryRun: false, resumeKey }, { page: true });
80 } catch (error) {
81 ctx.app.log.error("a home page start failed part way", { name, error: String(error) });
82 return { status: 500, body: { error: "failed", message: "the forge could not be made" } };
83 }
84 }
85
86 /** `response` with the resume key's cookie line (`web/resume_cookie.ts`), when there is one. */
87 function withCookie(response: Response, resumeLine: string | undefined): Response {
88 if (resumeLine !== undefined) response.headers.append("set-cookie", resumeLine);
6389 return response;
6490 }
src/web/start_refusal.ts +7 −1
@@ -6,7 +6,9 @@
66 * except the name, escaped, back in its field.
77 */
88
9 export type StartRefusal = "rate" | "taken" | "name" | "full" | "queued" | "other";
9 import { NOT_YOURS } from "../actions/spawn.ts";
10
11 export type StartRefusal = "rate" | "taken" | "not_yours" | "name" | "full" | "queued" | "other";
1012
1113 /** A queued spawn's place in line and the seconds to wait before pressing again. */
1214 export interface StartWait {
@@ -17,6 +19,7 @@ export interface StartWait {
1719 export const START_REFUSALS: Readonly<Record<StartRefusal, string>> = {
1820 rate: "Too many forges have been started from your connection lately. Wait a few minutes, or try again tomorrow, and press Start my forge again.",
outdated

Principles 1 and 8: this says it twice. Make it one plain sentence, e.g. "Someone else is making a forge by that name. Pick another name and press Start my forge again."

1921 taken: "That name is already taken. Change it a little, for example add your own name or a number, and press Start my forge again.",
22 not_yours: "Someone else is making a forge by that name. Pick another name and press Start my forge again.",
2023 name: "That name can't be used. Use 1 to 39 lowercase letters, digits or dashes, not starting or ending with a dash, and press Start my forge again.",
2124 queued: "Many forges are being made right now. Wait a minute, then press Start my forge again.",
2225 full: "This forge has no room for another forge right now. Try again later, or come back tomorrow.",
@@ -29,6 +32,9 @@ export function startRefusalOf(door: { readonly status: number; readonly body: R
2932 const message = String(door.body["message"] ?? "");
3033 if (door.status === 429 || error === "rate_limited") return "rate";
3134 if (error === "queued") return "queued";
35 // #14910's `not_yours`: an unfinished forge this caller did not start. Matched on the door's own
outdated

Fragile: this matches on the wording of the door's message. Use a stable code or the shared NOT_YOURS constant instead, so a reword cannot silently turn this into "other".

36 // `NOT_YOURS` sentence, after its name, so a reword there moves both.
37 if (error === "refused" && message.endsWith(NOT_YOURS(""))) return "not_yours";
3238 if (error === "exists" || (error === "refused" && /already exists|being made/.test(message))) return "taken";
3339 if (error === "invalid" && /^name: /.test(message)) return "name";
3440 if (error === "refused" && /forges sent|room|quota|deep|capacity|limit/i.test(message)) return "full";
test/start-forge-resume.test.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * A stranger cut off during a one-click start resumes it, and nobody else does (#15126): the home
3 * page's **Start my forge** keeps #14910's resume key in an HttpOnly cookie named for the forge,
4 * the terminal's keeps it for the SSH session, and each sends it back on the retry. A retry with no
5 * key or the wrong one is told #14910's `not_yours`, in plain words.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { NOT_YOURS } from "../src/actions/spawn.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { usePlacement, useProbe } from "../src/spawn/door.ts";
15 import { hostedPlacement } from "../src/spawn/placement.ts";
16 import { resetAnonSpawns } from "../src/spawn/rate.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { RESUME_NAMES, keptResumeKey, startForgeScreen } from "../src/tui/screens/startforge.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { START_REFUSALS, startRefusalOf } from "../src/web/start_refusal.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 let dir: string;
27 let app: App;
28 let servers: Servers;
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-start-resume-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 servers = await serve(app);
33 useProbe(app, () => async () => true);
34 usePlacement(app, hostedPlacement({ host: "forge.test" }));
35 });
36 afterAll(async () => {
37 await servers.stop?.();
38 app.close();
39 await rm(dir, { recursive: true, force: true });
40 });
41
42 /** The next start of `name` stops right after its ledger is written, as a process cut off would. */
43 function cutOffOnce(): void {
44 const append = app.bus.append.bind(app.bus);
45 const cut: typeof app.bus.append = (...args) => {
46 if (args[0].kind !== "forge.spawn.started") return append(...args);
47 app.bus.append = append;
48 throw new Error("cut off");
49 };
50 app.bus.append = cut;
51 }
52
53 const ledger = async (name: string) => JSON.parse(await Bun.file(join(dir, "spawn", `${name}.json`)).text()) as { done: boolean };
54
55 const start = (name: string, cookie?: string) =>
56 fetch(`${servers.url}/forges/start`, {
57 method: "POST",
58 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url, ...(cookie === undefined ? {} : { cookie }) },
59 body: new URLSearchParams({ name }),
60 redirect: "manual",
61 });
62
63 test("the home page: a cut-off start leaves its key in a cookie, which resumes it; no key or another is not_yours", async () => {
64 resetAnonSpawns(app.db);
65 cutOffOnce();
66 const first = await start("cut-web");
67 expect(first.status).toBe(303);
68 expect(first.headers.get("location")).toStartWith("/?start=other");
69 expect((await ledger("cut-web")).done).toBe(false);
70 const line = first.headers.getSetCookie().find((c) => c.startsWith("forge_resume_cut-web=")) ?? "";
71 const flags = line.split(";").map((f) => f.trim());
72 expect(flags).toContain("HttpOnly");
73 expect(flags).toContain("SameSite=Lax");
74 expect(flags).toContain("Path=/forges/start");
75 const cookie = flags[0]!;
76 // The key is never in the address or the page.
77 const key = cookie.split("=")[1]!;
78 expect(key).toMatch(/^[A-Za-z0-9_-]{32,128}$/);
79 expect(first.headers.get("location")).not.toContain(key);
80
81 for (const other of [undefined, `forge_resume_cut-web=${"x".repeat(43)}`]) {
82 const refused = await start("cut-web", other);
83 expect(refused.status).toBe(303);
84 expect(refused.headers.get("location")).toStartWith("/?start=not_yours&name=cut-web");
85 const home = await (await fetch(`${servers.url}${refused.headers.get("location")}`)).text();
86 expect(home.replaceAll("&#39;", "'")).toContain(START_REFUSALS.not_yours);
87 expect(home).not.toContain(key);
88 }
89
90 const resumed = await start("cut-web", cookie);
91 const body = await resumed.text();
92 expect(resumed.status).toBe(200);
93 expect(body).toMatch(/href="[^"]*cut-web--[^"]*\/welcome#[A-Za-z0-9_-]{43}"/);
94 expect(body).not.toContain(key);
95 expect((await ledger("cut-web")).done).toBe(true);
96 // Made: the browser forgets the key.
97 expect(resumed.headers.getSetCookie().find((c) => c.startsWith("forge_resume_cut-web="))).toContain("Max-Age=0");
98 });
99
100 test("the terminal: Enter again in the same session resumes a cut-off start; another session is not_yours", async () => {
101 resetAnonSpawns(app.db);
102 const identity = (remoteAddress: string) => ({ sshUsername: "git", remoteAddress, fingerprint: "SHA256:test", user: undefined });
103 const open = async (remoteAddress: string) => {
104 const terminal = headlessTerminal(120, 30);
105 const { app: tui, session } = createForgeApp(app, identity(remoteAddress), { terminal, exitHooks: false });
106 tui.start();
107 tui.ctx.push(startForgeScreen(session, tui.ctx));
108 await settleApp(tui);
109 return { tui, terminal };
110 };
111 const mine = await open("203.0.113.10");
112 const theirs = await open("203.0.113.11");
113 try {
114 cutOffOnce();
115 mine.terminal.feed("cut-tty\r");
116 await settleApp(mine.tui);
117 expect((await ledger("cut-tty")).done).toBe(false);
118
119 theirs.terminal.feed("cut-tty\r");
120 await settleApp(theirs.tui);
121 expect(theirs.tui.screen.toText().replace(/\s+/g, " ")).toContain(START_REFUSALS.not_yours.slice(0, 60));
122 expect((await ledger("cut-tty")).done).toBe(false);
123
124 // The same session, the name still in its field: Enter again finishes it and shows its link.
125 mine.terminal.feed("\r");
126 await settleApp(mine.tui);
127 expect(mine.tui.screen.toText()).toMatch(/https?:\/\/cut-tty--[^/\s]*\/claim#/);
128 expect((await ledger("cut-tty")).done).toBe(true);
129 } finally {
130 mine.tui.stop?.();
131 theirs.tui.stop?.();
132 }
133 });
134
135 test("the door's not_yours is its own plain sentence, not 'taken'", () => {
136 const door = { status: 409, body: { error: "refused", message: NOT_YOURS("kid") } };
137 expect(startRefusalOf(door)).toBe("not_yours");
138 expect(START_REFUSALS.not_yours).toBe("Someone else is making a forge by that name. Pick another name and press Start my forge again.");
139 // Another refusal that merely mentions a start is not not_yours.
140 expect(startRefusalOf({ status: 409, body: { error: "refused", message: "kid is being made" } })).toBe("taken");
141 });
142
143 test("a terminal session holds resume keys for its last 8 names, dropping the oldest", () => {
144 const keys = new Map<string, string>();
145 let n = 0;
146 const make = (): string => `key-${n++}`;
147 const first = keptResumeKey(keys, "name-0", make);
148 expect(keptResumeKey(keys, "name-0", make)).toBe(first);
149 for (let i = 1; i <= RESUME_NAMES; i++) keptResumeKey(keys, `name-${i}`, make);
150 expect(RESUME_NAMES).toBe(8);
151 expect(keys.size).toBe(RESUME_NAMES);
152 expect(keys.has("name-0")).toBe(false);
153 expect(keys.get("name-1")).toBe("key-1");
154 expect(keys.get(`name-${RESUME_NAMES}`)).toBe(`key-${RESUME_NAMES}`);
155 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs