feat(backup): encrypted on-site DB backup engine + local target

The SQLite DB is the signed append-only ledger, so a disk failure / stolen or
destroyed PC means total revenue-history loss (open-question #5). This is the first
slice of the backup-recovery design: the engine + a local/mounted target + a daily
timer + a manual route.

Engine (apps/server/src/backup.ts):
- Consistent online copy of the live WAL DB via better-sqlite3's native .backup()
  (not a raw file copy, which can capture a torn WAL) — the restored copy is a
  byte-identical, queryable DB.
- AES-256-GCM with a scrypt-derived key from BACKUP_KEY; self-describing header
  (magic|version|salt|iv|...|authTag) so a restore tool needs only the key + file.
  Zero new dependencies (Node crypto).
- The plaintext intermediate is kept in scratch (not the removable/network target)
  and wiped in a finally, success or fail.
- Retention: keep-last-N + one-per-day within N days.

Wiring:
- BackupService (env config, single in-flight guard, last-success/last-error).
- routes/backup.ts: GET /api/backup/status (backup:read), POST /api/backup/run
  (backup:create), 409 when unconfigured. No restore route — restore is an
  out-of-band runbook action on a fresh appliance, not a console call.
- New  permission resource in @parking/shared.
- server.ts: an unref'd daily timer, a no-op until BACKUP_TARGET_DIR + BACKUP_KEY
  are set, deliberately not run at startup (a just-power-cut booth shouldn't write
  to a possibly-unmounted disk).
- openRawDb() added to @parking/db/testing (open a file without migrating, for
  restore-verification tests).

BACKUP_KEY is deliberately SEPARATE from EVENT_SIGNING_KEY (independent rotation;
backups travel, the signing key shouldn't). SMB/NFS work as mount paths; SFTP +
admin UI + restore runbook are deferred slices. Tests: round-trip byte-identical,
GCM tamper/wrong-key fail, short-key rejected, scratch cleaned, route auth/RBAC +
409. build/lint/test green (212 server tests). Wiki + open-question #5 updated.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-29 11:59:45 +02:00
parent 9e442586af
commit 0c218179c4
12 changed files with 750 additions and 7 deletions
@@ -0,0 +1,92 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { type Db } from "@parking/db";
import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { seedUser, login } from "../test-helpers.js";
// HTTP integration for the backup routes — the security seam + the unconfigured-state
// behaviour. The booted test app has no BACKUP_TARGET_DIR/BACKUP_KEY, so the service is
// "not configured": status reports it, and a manual run is a clean 409 (not a 500).
// See wiki/concepts/backup-recovery.md.
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
});
afterEach(async () => {
await app.close();
close();
});
describe("GET /api/backup/status", () => {
it("401 without a session", async () => {
const res = await app.inject({ method: "GET", url: "/api/backup/status" });
expect(res.statusCode).toBe(401);
});
it("403 for a user lacking backup:read", async () => {
const { username, password } = await seedUser(db, {
username: "viewer", roleId: "viewer", permissions: ["site:read"],
});
const { cookie } = await login(app, username, password);
const res = await app.inject({ method: "GET", url: "/api/backup/status", headers: { cookie } });
expect(res.statusCode).toBe(403);
});
it("an admin sees the (unconfigured) status shape", async () => {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
const { cookie } = await login(app, username, password);
const res = await app.inject({ method: "GET", url: "/api/backup/status", headers: { cookie } });
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body).toMatchObject({
configured: false,
running: false,
lastSuccessAt: null,
lastError: null,
});
});
});
describe("POST /api/backup/run", () => {
it("403 for a user lacking backup:create", async () => {
const { username, password } = await seedUser(db, {
username: "viewer", roleId: "viewer", permissions: ["backup:read"], // read but not create
});
const { cookie, csrf } = await login(app, username, password);
const res = await app.inject({
method: "POST", url: "/api/backup/run",
headers: { cookie, "x-csrf-token": csrf },
});
expect(res.statusCode).toBe(403);
});
it("requires CSRF on the mutation", async () => {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
const { cookie } = await login(app, username, password);
const res = await app.inject({
method: "POST", url: "/api/backup/run",
headers: { cookie }, // no csrf header
});
expect(res.statusCode).toBe(403);
});
it("returns 409 backup_not_configured when no target/key is set (not a 500)", async () => {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
const { cookie, csrf } = await login(app, username, password);
const res = await app.inject({
method: "POST", url: "/api/backup/run",
headers: { cookie, "x-csrf-token": csrf },
});
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: "backup_not_configured" });
});
});