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

First-admin recovery for a child forge trusts nothing in the child's own data directory #15052

Merged opened this

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

Merged

scout/forge:scout/15040-first-admin-recovery-for-a-child-forge-t → main 1 commit fork

  • Merged. scout/15040-first-admin-recovery-for-a-child-forge-t was merged into main as db01fb1.

Review

Sign in to review this change.
2 files changed +81 −7
src/core/first_admin_cli.ts +33 −7
@@ -8,7 +8,11 @@
88 *
99 * `--child <name>` mints for a child this forge hosts (`<data>/children/…`,
1010 * found through the spawn ledger), so the operator of the parent can hand
11 * a child its first admin without its claim link.
11 * a child its first admin without its claim link. Nothing in the child's
12 * own directory is trusted: its `parent.json` is the child's to write, so
13 * the address printed is the parent's own idea of the child's
14 * (`childPublicUrl`), and a `forge.db` that is a link, to the parent's
15 * database or anywhere else, is refused rather than followed.
1216 *
1317 * On a forge whose admins all lost their way in (`adminCanSignIn` is false:
1418 * typically a headless first admin whose token lapsed) it mints a recovery
@@ -17,11 +21,11 @@
1721 */
1822
1923 import { Database } from "bun:sqlite";
20 import { existsSync, readFileSync } from "node:fs";
24 import { lstatSync, readFileSync } from "node:fs";
2125 import { join } from "node:path";
2226 import { applyPragmas } from "../kernel/db.ts";
2327 import { dataDirOf } from "../kernel/preflight.ts";
24 import { CHILD_NAME } from "../spawn/placement.ts";
28 import { CHILD_NAME, childPublicUrl } from "../spawn/placement.ts";
2529 import { hasAdmin } from "../spawn/claim.ts";
2630 import {
2731 adminCanSignIn,
@@ -53,6 +57,25 @@ const readJson = (path: string): Record<string, unknown> | undefined => {
5357 }
5458 };
5559
60 /**
61 * Why `file` (and its `-wal`, `-shm`) is no plain database to open, or undefined when it is one.
62 * Checked without following links: a child can make its own files point anywhere.
63 */
64 const notPlainDb = (file: string): string | undefined => {
65 for (const path of [file, `${file}-wal`, `${file}-shm`]) {
66 let kind: "file" | "link" | "other" | "none";
67 try {
68 const st = lstatSync(path);
69 kind = st.isSymbolicLink() ? "link" : st.isFile() ? "file" : "other";
70 } catch {
71 kind = "none";
72 }
73 if (kind === "none" && path === file) return `no forge database at ${file}: start the forge once, then run this`;
74 if (kind === "link" || kind === "other") return `${path} is not a plain file: refused, no code was made`;
75 }
76 return undefined;
77 };
78
5679 const originOf = (raw: unknown): string | undefined => {
5780 if (typeof raw !== "string" || raw.trim() === "") return undefined;
5881 const url = URL.parse(raw.trim());
@@ -88,7 +111,8 @@ export function firstAdminCli(
88111 dir = join(dir, "children", bodyId);
89112 }
90113 const file = join(dir, "forge.db");
91 if (!existsSync(file)) return refuse(`no forge database at ${file}: start the forge once, then run this`);
114 const unsafe = notPlainDb(file);
115 if (unsafe !== undefined) return refuse(unsafe);
92116
93117 const db = new Database(file, { readwrite: true, strict: true });
94118 let minted: { code: string; expiresAt: string } | undefined;
@@ -119,11 +143,13 @@ export function firstAdminCli(
119143 }
120144 if (minted === undefined) return refuse(`${dir}: no code was made.`);
121145
146 const own = originOf(env.FORGE_APP_URL) ?? originOf(env.FORGE_URL) ?? `http://localhost:${env.PORT ?? 3000}`;
122147 const base =
123148 originOf(url) ??
124 originOf(readJson(join(dir, "parent.json"))?.url) ??
125 (child === undefined ? (originOf(env.FORGE_APP_URL) ?? originOf(env.FORGE_URL)) : undefined) ??
126 `http://localhost:${env.PORT ?? 3000}`;
149 (child === undefined
150 ? (originOf(readJson(join(dir, "parent.json"))?.url) ?? own)
151 : // The child's address as this forge gives it, never as the child's own files say.
152 childPublicUrl(child, own));
127153 const minutes = Math.round(FIRST_ADMIN_TTL_MS / 60_000);
128154 if (recovering !== undefined)
129155 return {
test/first-admin.test.ts +48
@@ -8,6 +8,7 @@
88 */
99
1010 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
11 import { mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
1112 import { mkdtemp, rm } from "node:fs/promises";
1213 import { tmpdir } from "node:os";
1314 import { join } from "node:path";
@@ -463,6 +464,37 @@ describe("the operator's command: --first-admin", () => {
463464 });
464465 });
465466
467 describe("--child refuses a child's forge.db that is a link", () => {
468 for (const which of ["forge.db", "forge.db-wal"] as const)
469 test(`${which} a symlink to another forge's database: refused, and nothing is minted there`, async () => {
470 const { dir: victimDir, app: victim } = await fresh();
471 try {
472 const parentDir = await mkdtemp(join(tmpdir(), "forge-first-admin-link-"));
473 dirs.push(parentDir);
474 mkdirSync(join(parentDir, "spawn"));
475 writeFileSync(join(parentDir, "spawn", "eve.json"), JSON.stringify({ name: "eve", bodyId: "body-1", done: true }));
476 const childDir = join(parentDir, "children", "body-1");
477 mkdirSync(childDir, { recursive: true });
478 if (which === "forge.db") symlinkSync(join(victimDir, "forge.db"), join(childDir, "forge.db"));
479 else {
480 const own = createApp({ dataDir: childDir, port: 0 });
481 own.close();
482 await rm(join(childDir, "forge.db-wal"), { force: true });
483 symlinkSync(join(victimDir, "forge.db-wal"), join(childDir, "forge.db-wal"));
484 }
485 const settings = () => JSON.stringify(victim.db.query("SELECT * FROM forge_setting ORDER BY key").all());
486 const before = settings();
487 const answer = firstAdminCli(["--child", "eve"], { FORGE_DATA: parentDir });
488 expect(answer.exit).toBe(1);
489 expect(answer.out).toHaveLength(0);
490 expect(answer.err[0]).toContain("not a plain file");
491 expect(settings()).toBe(before);
492 } finally {
493 victim.close();
494 }
495 });
496 });
497
466498 describe("a spawned child, made admin by its parent's operator", () => {
467499 let parentDir = "";
468500 let parent: App;
@@ -505,6 +537,22 @@ describe("a spawned child, made admin by its parent's operator", () => {
505537 parent.close();
506538 });
507539
540 test("--child prints the child's address as the parent knows it, never the one the child's parent.json names", () => {
541 const file = join(child.config.dataDir, "parent.json");
542 const before = readFileSync(file, "utf8");
543 try {
544 writeFileSync(file, JSON.stringify({ ...JSON.parse(before), url: "https://evil.test" }));
545 const answer = firstAdminCli(["--child", "maria"], { FORGE_DATA: parentDir, FORGE_URL: "https://forge.test" });
546 expect(answer.exit).toBe(0);
547 const text = answer.out.join("\n");
548 expect(text).not.toContain("evil.test");
549 expect(text).toMatch(/https:\/\/maria--forge\.test\/first-admin#[A-Za-z0-9_-]{43}/);
550 expect(text).toContain("POST https://maria--forge.test/api/v1/first-admin ");
551 } finally {
552 writeFileSync(file, before);
553 }
554 });
555
508556 test("--child mints in the child's database, at the child's address, and the child's org is handed over", async () => {
509557 const answer = firstAdminCli(["--child", "maria"], { FORGE_DATA: parentDir, FORGE_URL: "https://forge.test" });
510558 expect(answer.exit).toBe(0);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs