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

An admin runs a restore drill on demand: the newest snapshot restored into an empty directory, opened, counted, and its verdict on the Backups page #1580

Closed opened this
Closed without merging

scout/forge:scout/1568-an-admin-runs-a-restore-drill-on-demand → main 5 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +486 −1
README.md +1 −1
@@ -424,7 +424,7 @@ holds, where it goes, and the one command that restores it.
424424
425425 A snapshot uploads eight objects at a time. Run logs older than a day go up
426426 bundled per day (cut at 4 MB, so a long history is several objects, never one
427 huge one); restore unpacks them. While one runs, progress shows on
427 huge one); restore unpacks them. An admin's **Run a drill** on the Backups page restores the newest snapshot into a scratch directory, opens it, counts repositories and issues, unseals one secret, deletes the directory, and shows the verdict there (one drill at a time; it needs `FORGE_SNAPSHOT_PASSPHRASE` for the key to travel). While one runs, progress shows on
428428 **Settings → Backups** and as a line in the log every 500 objects or minute.
429429 The terminal has no backups view, so it has no readout.
430430
docs/SNAPSHOT.md +4
@@ -98,3 +98,7 @@ sealed variable and an app's SQLite is snapshotted, restored into an empty
9898 directory with the passphrase and booted there as the same forge; restored
9999 without it, the repositories come back and the sealed variable is reported by
100100 name. It also checks that the raw key is in no file of the store.
101
102 ## Drill
103
104 On the Backups page an admin can run a restore drill: the newest snapshot restored into a scratch directory under `FORGE_APP_DATA/drill`, opened, counted and one sealed value unsealed, then the directory is deleted. The verdict (green, or red with the step it stopped at) stays on that page. Without `FORGE_SNAPSHOT_PASSPHRASE` the key is not in the snapshot and the drill says so.
scripts/gate.ts +1
@@ -128,6 +128,7 @@ export const GATE: readonly string[] = [
128128 "test/helpers.test.ts",
129129 "test/shards.test.ts",
130130 "test/snapshot-store.test.ts",
131 "test/snapshot-drill.test.ts",
131132 "test/migrate.test.ts",
132133 "test/schema-additive.test.ts",
133134 "test/schema-migrations.test.ts",
src/core/schema.ts +16
@@ -1631,6 +1631,22 @@ export const migrations: readonly string[] = [
16311631 scopes TEXT NOT NULL
16321632 );
16331633 `,
1634 // 78 — a restore drill (#1568): the newest snapshot restored into an
1635 // empty directory, opened and counted. One row per drill; `step` names
1636 // where a red one stopped, '' for a green one.
1637 `
1638 CREATE TABLE drill (
1639 id TEXT PRIMARY KEY,
1640 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1641 snapshot TEXT NOT NULL DEFAULT '',
1642 duration_ms INTEGER NOT NULL DEFAULT 0,
1643 repos INTEGER NOT NULL DEFAULT 0,
1644 issues INTEGER NOT NULL DEFAULT 0,
1645 ok INTEGER NOT NULL DEFAULT 0,
1646 step TEXT NOT NULL DEFAULT '',
1647 detail TEXT NOT NULL DEFAULT ''
1648 );
1649 `,
16341650 ];
16351651
16361652 /**
src/http/server.ts +2
@@ -96,6 +96,7 @@ import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
9696 import {
9797 backupsClear,
9898 backupsDestination,
99 backupsDrill,
99100 backupsNow,
100101 backupsPage,
101102 backupsTest,
@@ -671,6 +672,7 @@ export function buildRouter(): Router<Handler> {
671672 router.add("POST", "/admin/limits", limitsSet);
672673 router.add("GET", "/settings/backups", backupsPage);
673674 router.add("POST", "/settings/backups/now", backupsNow);
675 router.add("POST", "/settings/backups/drill", backupsDrill);
674676 router.add("POST", "/settings/backups/destination", backupsDestination);
675677 router.add("POST", "/settings/backups/test", backupsTest);
676678 router.add("POST", "/settings/backups/clear", backupsClear);
src/snapshot/drill.ts added +229
@@ -0,0 +1,229 @@
1 /**
2 * A restore drill: the newest snapshot restored into a fresh directory,
3 * opened, counted, one sealed value unsealed, and the directory deleted.
4 * A backup nobody has restored is a hope; this is the restore, run on
5 * demand, with its verdict kept as one row.
6 *
7 * Steps, in order: `list`, `restore`, `open`, `count`, `unseal`. A red
8 * verdict names the step it stopped at; a hang past the timeout is red at
9 * the step it hung in.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { mkdirSync, readdirSync, rmSync } from "node:fs";
14 import { join } from "node:path";
15 import { id } from "../kernel/id.ts";
16 import { forgetKey, open } from "../kernel/secret.ts";
17 import { restoreSnapshot } from "./restore.ts";
18 import { listSnapshots } from "./snapshot.ts";
19 import type { Store } from "./store.ts";
20
21 export const DRILL_TIMEOUT_MS = 10 * 60 * 1000;
22
23 export type DrillStep = "list" | "restore" | "open" | "count" | "unseal";
24
25 export interface Drill {
26 readonly id: string;
27 readonly at: string;
28 readonly snapshot: string;
29 readonly durationMs: number;
30 readonly repos: number;
31 readonly issues: number;
32 readonly ok: boolean;
33 /** Where a red drill stopped; empty when green. */
34 readonly step: DrillStep | "";
35 readonly detail: string;
36 }
37
38 interface Row {
39 id: string;
40 at: string;
41 snapshot: string;
42 duration_ms: number;
43 repos: number;
44 issues: number;
45 ok: number;
46 step: string;
47 detail: string;
48 }
49
50 const toDrill = (r: Row): Drill => ({
51 id: r.id,
52 at: r.at,
53 snapshot: r.snapshot,
54 durationMs: r.duration_ms,
55 repos: r.repos,
56 issues: r.issues,
57 ok: r.ok === 1,
58 step: r.step as Drill["step"],
59 detail: r.detail,
60 });
61
62 /** The most recent drill, if any has run. */
63 export function lastDrill(db: Database): Drill | undefined {
64 const row = db
65 .query<Row, []>("SELECT * FROM drill ORDER BY at DESC, id DESC LIMIT 1")
66 .get();
67 return row ? toDrill(row) : undefined;
68 }
69
70 export interface DrillOptions {
71 readonly db: Database;
72 readonly dataDir: string;
73 readonly store: Store;
74 readonly passphrase?: string | undefined;
75 readonly timeoutMs?: number;
76 }
77
78 class Stop extends Error {
79 constructor(
80 readonly step: DrillStep,
81 message: string,
82 ) {
83 super(message);
84 }
85 }
86
87 let inFlight: Promise<Drill> | undefined;
88 let cleaning: Promise<void> = Promise.resolve();
89
90 /** Resolves once every scratch directory a drill made has been removed. */
91 export const drillIdle = (): Promise<void> => cleaning;
92
93 /**
94 * Restore the newest snapshot into a scratch directory and record the
95 * verdict. One drill at a time per process: a second call joins the first.
96 */
97 export function runDrill(options: DrillOptions): Promise<Drill> {
98 inFlight ??= drill(options).finally(() => {
99 inFlight = undefined;
100 });
101 return inFlight;
102 }
103
104 async function drill(options: DrillOptions): Promise<Drill> {
105 // A restored forge is plaintext: sweep what a crashed or abandoned drill left.
106 const root = join(options.dataDir, "drill");
107 try {
108 for (const name of readdirSync(root))
109 rmSync(join(root, name), { recursive: true, force: true });
110 } catch {
111 // no drill directory yet
112 }
113 const started = Date.now();
114 const drillId = id();
115 const dir = join(options.dataDir, "drill", drillId);
116 const counts = { repos: 0, issues: 0 };
117 let snapshot = "";
118 let step: DrillStep = "list";
119 let timer: ReturnType<typeof setTimeout> | undefined;
120
121 const work = async (): Promise<void> => {
122 const newest = (await listSnapshots(options.store))[0];
123 if (newest === undefined) throw new Stop("list", "the store holds no snapshot");
124 snapshot = newest.name;
125 step = "restore";
126 mkdirSync(dir, { recursive: true });
outdated

Medium: when the snapshot carried no key (no FORGE_SNAPSHOT_PASSPHRASE), open → loadKey generates a fresh secret.key here, and the drill reports "will not open with the restored key". Branch on restored.key === "missing" and give the true reason, using restored.sealedMissing.

127 const restored = await restoreSnapshot(options.store, newest.name, dir, {
128 passphrase: options.passphrase,
129 });
130 counts.repos = restored.repos;
131 if (restored.key === "missing")
132 throw new Stop(
133 "restore",
134 `the key does not travel with snapshots without FORGE_SNAPSHOT_PASSPHRASE; ${restored.sealedMissing.length} sealed value(s) would need setting again`,
135 );
136 step = "open";
137 const { Database } = await import("bun:sqlite");
138 const db = new Database(join(dir, "forge.db"), { readonly: true });
139 try {
140 step = "count";
141 const n = (table: string): number =>
142 db.query<{ n: number }, []>(`SELECT count(*) AS n FROM ${table}`).get()!
143 .n;
144 counts.repos = n("repo");
145 counts.issues = n("issue");
146 step = "unseal";
147 const sealed = db
148 .query<{ name: string; scope: string; value_enc: string }, []>(
outdated

High: the race does not cancel work(). After a timeout, restoreSnapshot keeps writing into dir (it runs mkdir -p for each file), after the finally below has already removed it. A decrypted forge.db, ssh keys and possibly secret.key then stay in FORGE_APP_DATA/drill/<id> for good. Remove the directory only once work() settles, or make restore stoppable.

149 "SELECT name, scope, value_enc FROM secret ORDER BY scope, name LIMIT 1",
150 )
151 .get();
152 if (sealed) {
153 forgetKey(dir);
154 try {
155 const opened = open(
156 dir,
157 sealed.value_enc,
158 `secret:${sealed.scope}:${sealed.name}`,
159 );
160 if (!opened.ok)
161 throw new Stop(
162 "unseal",
163 `${sealed.name} (${sealed.scope} secret) will not open with the restored key`,
outdated

This runs before the still-running restore finishes, so the directory can come back. Also sweep any stale drill/* at the start of a drill.

164 );
165 } finally {
166 forgetKey(dir);
167 }
168 }
169 } finally {
170 db.close();
171 }
172 };
173
174 let failure: { step: DrillStep; detail: string } | undefined;
175 // The scratch directory goes only once the restore has stopped writing:
176 // a timeout ends the verdict, not the restore.
177 const running = work();
178 cleaning = running
179 .catch(() => {})
180 .then(() => rmSync(dir, { recursive: true, force: true }));
181 try {
182 await Promise.race([
183 running,
184 new Promise<never>((_, reject) => {
185 timer = setTimeout(
186 () => reject(new Stop(step, "timed out")),
187 options.timeoutMs ?? DRILL_TIMEOUT_MS,
188 );
189 }),
190 ]);
191 } catch (error) {
192 failure = {
193 step: error instanceof Stop ? error.step : step,
194 detail: String(error instanceof Error ? error.message : error).slice(0, 500),
195 };
196 } finally {
197 clearTimeout(timer);
198 rmSync(dir, { recursive: true, force: true });
199 }
200
201 const drill: Drill = {
202 id: drillId,
203 at: new Date().toISOString(),
204 snapshot,
205 durationMs: Date.now() - started,
206 repos: counts.repos,
207 issues: counts.issues,
208 ok: failure === undefined,
209 step: failure?.step ?? "",
210 detail: failure?.detail ?? "",
211 };
212 options.db
213 .query(
214 `INSERT INTO drill (id, at, snapshot, duration_ms, repos, issues, ok, step, detail)
215 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
216 )
217 .run(
218 drill.id,
219 drill.at,
220 drill.snapshot,
221 drill.durationMs,
222 drill.repos,
223 drill.issues,
224 drill.ok ? 1 : 0,
225 drill.step,
226 drill.detail,
227 );
228 return drill;
229 }
src/web/pages/backups.ts +51
@@ -15,6 +15,7 @@ import {
1515 type DestinationInput,
1616 } from "../../actions/destination.ts";
1717 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
18 import { lastDrill, runDrill, type Drill } from "../../snapshot/drill.ts";
1819 import { keyOf } from "../../snapshot/snapshot.ts";
1920 import { snapshotsOf } from "../../snapshot/service.ts";
2021 import type { Ctx } from "../../http/context.ts";
@@ -153,6 +154,10 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
153154 variant: "primary",
154155 icon: "download",
155156 })}
157 </form>
158 ${drillLine(lastDrill(ctx.app.db))}
159 <form method="post" action="/settings/backups/drill" class="backups-now">
160 ${btn("Run a drill", { type: "submit", icon: "history" })}
156161 </form>`,
157162 {
158163 head: html`${icon("download")}
@@ -209,6 +214,25 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
209214 );
210215 }
211216
217 /** The last restore drill in one line, green or red with the step it stopped at. */
218 function drillLine(d: Drill | undefined): Html {
219 if (d === undefined)
220 return html`<p class="muted">
221 No restore drill has run. A backup nobody has restored is a hope.
222 </p>`;
223 const secs = (d.durationMs / 1000).toFixed(1);
224 return d.ok
225 ? html`<p class="backups-drill">
226 ${icon("check")} Restore drill ${time(d.at)}: ${d.snapshot} restored in
227 ${secs} s — ${d.repos} repositories, ${d.issues} issues.
228 </p>`
229 : html`<p class="backups-error">
230 ${icon("alert")} Restore drill ${time(d.at)} failed at
231 <strong>${d.step}</strong>${d.snapshot ? html` (${d.snapshot})` : ""}:
232 ${d.detail}
233 </p>`;
234 }
235
212236 const SOURCE: Record<string, string> = {
213237 sealed: "sealed in this forge (set here)",
214238 dir: "the directory named by FORGE_SNAPSHOT_DIR",
@@ -367,3 +391,30 @@ export async function backupsNow(ctx: Ctx): Promise<Response> {
367391 });
368392 }
369393 }
394
395 /** POST /settings/backups/drill — restore the newest snapshot into a scratch directory and say what came of it. */
396 export async function backupsDrill(ctx: Ctx): Promise<Response> {
397 const denied = requireAdmin(ctx);
398 if (denied) return denied;
399 const form = await readForm(ctx, "admin");
400 if (form instanceof Response) return form;
401 const store = snapshotsOf(ctx.app)?.store;
402 if (store === undefined)
403 return flashTo(ctx, "/settings/backups", {
404 tone: "danger",
405 message: "This forge has no snapshots to drill.",
406 });
407 const d = await runDrill({

Medium: a 10-minute restore runs inline on the request, with no guard against a second concurrent drill. Allow one drill in flight at a time.

408 db: ctx.app.db,
409 dataDir: ctx.app.config.dataDir,
410 store,
411 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
412 });
413 return flashTo(
414 ctx,
415 "/settings/backups",
416 d.ok
417 ? { message: `Drill green: ${d.snapshot} restored.` }
418 : { tone: "danger", message: `Drill red at ${d.step}: ${d.detail}` },
419 );
420 }
test/asks-rank.test.ts +4
@@ -34,6 +34,7 @@ import {
3434 askLinesFor,
3535 recordAskLedger,
3636 } from "../src/web/studio/asks.ts";
37 import { resetRefusedInternal } from "../src/kernel/internal_refused.ts";
3738 import { quietLogs } from "./helpers/globals.ts";
3839
3940 quietLogs();
@@ -138,6 +139,9 @@ describe("asks that earn their place", () => {
138139 };
139140
140141 beforeAll(async () => {
142 // Refusals are counted per process; an earlier suite in this shard may
143 // have left some, and the forge's own card would then join the asks.
144 resetRefusedInternal();
141145 dataDir = await mkdtemp(join(tmpdir(), "forge-asks-rank-"));
142146 app = createApp({ dataDir, port: 0 });
143147 servers = await serve(app);
test/snapshot-drill.test.ts added +178
@@ -0,0 +1,178 @@
1 /**
2 * The restore drill (#1568): the newest snapshot of a seeded forge restores
3 * into a scratch directory, opens, counts and unseals green; a corrupt one
4 * is red naming the step; the scratch directory is gone either way.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { existsSync, mkdirSync, mkdtempSync, readdirSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { setSecret } from "../src/core/secret_store.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { drillIdle, lastDrill, runDrill } from "../src/snapshot/drill.ts";
16 import { takeSnapshot } from "../src/snapshot/snapshot.ts";
17 import { dirStore, type Store } from "../src/snapshot/store.ts";
18
19 const PASS = "correct horse battery staple";
20 let root: string;
21 let app: App;
22 let store: Store;
23
24 const drillDirs = (): string[] => {
25 const dir = join(app.config.dataDir, "drill");
26 return existsSync(dir) ? readdirSync(dir) : [];
27 };
28 const options = (s: Store, extra = {}) => ({
29 db: app.db,
30 dataDir: app.config.dataDir,
31 store: s,
32 passphrase: PASS,
33 ...extra,
34 });
35
36 beforeAll(async () => {
37 root = mkdtempSync(join(tmpdir(), "forge-drill-"));
38 app = createApp({ dataDir: join(root, "live"), port: 0 });
39 const u = await createUser(app.db, {
40 trusted: true,
41 username: "alice",
42 email: "[email protected]",
43 password: "a-good-passphrase",
44 adminIfFirst: true,
45 });
46 if (!u.ok) throw new Error(u.error);
47 const repo = await createRepo(app, u.value, { name: "notes", visibility: "private" });
48 if (!repo.ok) throw new Error(String(repo.error));
49 const c = await commitToBranch(app, u.value, repo.value, {
50 message: "first",
51 files: [{ path: "README.md", content: "# notes\n" }],
52 });
53 if (!c.ok) throw new Error(JSON.stringify(c.error));
54 const s = setSecret(app.db, app.config.dataDir, "forge", "", "TOKEN", "hunter2");
55 if (!s.ok) throw new Error(s.error);
56 store = dirStore(join(root, "store"));
57 await takeSnapshot(
58 {
59 db: app.db,
60 dataDir: app.config.dataDir,
61 reposRoot: app.reposRoot,
62 version: "t",
63 passphrase: PASS,
64 },
65 store,
66 new Date("2026-09-22T08:00:00Z"),
67 );
68 });
69
70 afterAll(async () => {
71 app.close();
72 await rm(root, { recursive: true, force: true });
73 });
74
75 test("a snapshot of a seeded forge drills green with the right counts", async () => {
76 const live = {
77 repos: app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM repo").get()!.n,
78 issues: app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM issue").get()!.n,
79 };
80 expect(live.repos).toBe(1);
81 const d = await runDrill(options(store));
82 expect(d.ok).toBe(true);
83 expect(d.step).toBe("");
84 expect(d.snapshot).toBe("2026-09-22T08-00-00Z");
85 expect(d.repos).toBe(live.repos);
86 expect(d.issues).toBe(live.issues);
87 expect(lastDrill(app.db)?.id).toBe(d.id);
88 expect(drillDirs()).toEqual([]);
89 });
90
91 test("a wrong passphrase is red at restore, and nothing is left behind", async () => {
92 const d = await runDrill(options(store, { passphrase: "not it" }));
93 expect(d.ok).toBe(false);
94 expect(d.step).toBe("restore");
95 expect(d.detail).toContain("passphrase");
96 expect(drillDirs()).toEqual([]);
97 });
98
99 test("a corrupt snapshot is red naming the step", async () => {
100 const bad = dirStore(join(root, "bad"));
101 const objects = await store.list("");
102 for (const key of objects) {
103 const body = await store.get(key);
104 if (body === undefined) continue;
105 await bad.put(key, key.endsWith("forge.db") ? body.subarray(0, 10) : body);
106 }
107 const d = await runDrill(options(bad));
108 expect(d.ok).toBe(false);
109 expect(d.step).toBe("restore");
110 expect(lastDrill(app.db)?.ok).toBe(false);
111 expect(drillDirs()).toEqual([]);
112 });
113
114 test("a store with no snapshot is red at list", async () => {
115 const d = await runDrill(options(dirStore(join(root, "empty"))));
116 expect(d.ok).toBe(false);
117 expect(d.step).toBe("list");
118 });
119
120 test("a hang ends as a red verdict naming the step", async () => {
121 const slow: Store = {
122 ...store,
123 get: () => new Promise(() => {}),
124 };
125 const d = await runDrill(options(slow, { timeoutMs: 50 }));
126 expect(d.ok).toBe(false);
127 expect(d.detail).toBe("timed out");
128 expect(["list", "restore"]).toContain(d.step);
129 expect(drillDirs()).toEqual([]);
130 });
131
132 test("a restore that finishes after the timeout leaves nothing behind", async () => {
133 const slow: Store = {
134 ...store,
135 get: async (key) => {
136 await new Promise((r) => setTimeout(r, 150));
137 return store.get(key);
138 },
139 };
140 const d = await runDrill(options(slow, { timeoutMs: 50 }));
141 expect(d.detail).toBe("timed out");
142 await drillIdle();
143 expect(drillDirs()).toEqual([]);
144 });
145
146 test("a stale scratch directory is swept at the start of a drill", async () => {
147 const stale = join(app.config.dataDir, "drill", "old");
148 mkdirSync(stale, { recursive: true });
149 await Bun.write(join(stale, "forge.db"), "plaintext");
150 const d = await runDrill(options(store));
151 expect(d.ok).toBe(true);
152 expect(drillDirs()).toEqual([]);
153 });
154
155 test("a snapshot taken without a passphrase is red for the true reason", async () => {
156 const bare = dirStore(join(root, "bare"));
157 await takeSnapshot(
158 {
159 db: app.db,
160 dataDir: app.config.dataDir,
161 reposRoot: app.reposRoot,
162 version: "t",
163 },
164 bare,
165 new Date("2026-09-23T08:00:00Z"),
166 );
167 const d = await runDrill(options(bare, { passphrase: undefined }));
168 expect(d.ok).toBe(false);
169 expect(d.step).toBe("restore");
170 expect(d.detail).toContain("key does not travel");
171 expect(d.detail).not.toContain("restored key");
172 expect(drillDirs()).toEqual([]);
173 });
174
175 test("two drills at once are one drill", async () => {
176 const [a, b] = await Promise.all([runDrill(options(store)), runDrill(options(store))]);
177 expect(b.id).toBe(a.id);
178 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs