feat(admin): replace the key backup step with a recovery kit

The step confirmed one key, the active application key. A restore needs
more: off-host copies are sealed under BACKUP_ENCRYPTION_KEY, a copy
written before a rotation needs the retired application key it was
written under, and every session, token and share link hangs off
API_TOKEN_HMAC_KEY. An operator could do everything the step asked and
still be unable to read a single backup.

The recovery kit lists every key a restore of this server needs, by id
and fingerprint, never key material:

- each id in ENCRYPTION_KEYS, plus any retired id a stored copy
  (innerKeyIds) or an off-host object inside the bucket's retention
  (OffhostBackupKeyUse) still lists, also once the server dropped it;
- BACKUP_ENCRYPTION_KEY and each BACKUP_ENCRYPTION_PREVIOUS_KEYS entry,
  named by the id their objects record;
- API_TOKEN_HMAC_KEY.

Confirming records the set the admin was shown and refuses a stale one
with 409 recovery.kit.stale. The kit is due again as soon as a key it
lists is not in that set (a rotation, a new backup key, a re-keyed
install); a key that merely drops out does not make it due. "Check my
copy" now checks any key in the kit.

Migration 0487 carries a confirmation given under the old step forward
as a kit holding that key, so that part stays confirmed, and drops the
four app_settings columns. It also creates the two tables the readiness
evaluation uses (restore_drill_outcomes, recovery_readiness_notices).

The routes move to /api/admin/recovery-kit; the reader of the keys the
backups still need moves out of the encryption status route into
src/lib/recovery/backup-key-needs.ts so the kit and the status view
share one definition.
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 13:32:29 +01:00
1 parent 953c64f7a4
commit d3c672cc3f
56 files changed
+3042 -1611

No files matched your search

@@ -0,0 +1,60 @@
/**
* POST /api/admin/recovery-kit/confirm { entries: [{ kind, id, fingerprint }] }
*
* The admin states that a copy of every key in the kit is kept outside the
* server. The body is the kit as the admin was shown it; when that is no
* longer the kit (a rotation, a new backup key, a restart with other keys
* since the page loaded) the answer is 409 `recovery.kit.stale` with the
* current kit, and nothing is recorded. No step-up: confirming is a low-risk
* write that reveals nothing.
*/
import type { NextRequest } from "next/server";
import { apiHandler, requireAdmin } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { parseJsonBody } from "@/lib/api/body";
import { auditLog } from "@/lib/auth/audit";
import { annotate } from "@/lib/logging/context";
import { confirmRecoveryKit } from "@/lib/recovery/kit";
import {
kitConfirmationSchema,
RECOVERY_KIT_STALE_CODE,
} from "@/lib/recovery/kit-rules";
export const dynamic = "force-dynamic";
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAdmin();
annotate({ action: { name: "admin.recoveryKit.confirm" } });
const parsed = await parseJsonBody(request, kitConfirmationSchema, {
maxBytes: 8 * 1024,
});
if (!parsed.ok) return parsed.error;
const result = await confirmRecoveryKit({
shown: parsed.data.entries,
userId: user.id,
});
if (!result.ok) {
annotate({ meta: { recovery_kit_stale: true } });
return apiError(
"The recovery kit changed since this page was loaded. Reload, check the keys it lists now, and confirm again.",
409,
{ errorCode: RECOVERY_KIT_STALE_CODE },
);
}
await auditLog("recovery.kit.confirmed", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
keys: result.kit.keys.map(({ kind, id, fingerprint }) => ({
kind,
id,
fingerprint,
})),
},
});
return apiSuccess(result.kit);
});
+29
View File
@@ -0,0 +1,29 @@
/**
* GET /api/admin/recovery-kit
*
* The recovery kit: every key a restore of this instance needs (the
* application keys, including retired ones a backup still lists, the off-host
* backup keys and the token key), each with its fingerprint and why it is
* needed, and whether the admin's confirmation covers it. Ids and
* fingerprints only, never key material. Cookie-only admin.
*/
import { apiHandler, requireAdmin } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { readRecoveryKit } from "@/lib/recovery/kit";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async () => {
await requireAdmin();
annotate({ action: { name: "admin.recoveryKit.status" } });
const kit = await readRecoveryKit();
annotate({
meta: {
recovery_kit_due: kit.due,
recovery_kit_keys: kit.keys.length,
recovery_kit_unconfirmed: kit.unconfirmed.length,
},
});
return apiSuccess(kit);
});
@@ -0,0 +1,70 @@
/**
* POST /api/admin/recovery-kit/verify { kind, id, keyCopy }
*
* "Check my copy": the admin pastes the copy of one key the kit lists and
* learns whether it is that key. The value is compared in memory (constant
* time on the compared bytes) and dropped. It is never stored, never logged,
* never echoed: the Zod issue list is not returned for this body (a
* validation failure is a plain 422), and the field name is on the
* observability denylist.
*
* A boolean answer is no oracle against a 256-bit key; the 5 per minute limit
* per admin is there to keep the route from being anyone's busy loop. Over
* plain HTTP the value crosses the network in clear, as the admin's password
* does; the client says so before sending.
*/
import type { NextRequest } from "next/server";
import { z } from "zod/v4";
import { apiHandler, requireAdmin } from "@/lib/api-handler";
import { apiError, apiSuccess, safeJson } from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { verifyKitKey } from "@/lib/recovery/kit";
import { KIT_KEY_KINDS } from "@/lib/recovery/kit-rules";
export const dynamic = "force-dynamic";
const KIT_VERIFY_LIMIT = 5;
const KIT_VERIFY_WINDOW_MS = 60 * 1000;
const verifySchema = z
.object({
kind: z.enum(KIT_KEY_KINDS),
id: z.string().min(1).max(64),
keyCopy: z.string().min(1).max(512),
})
.strict();
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAdmin();
annotate({ action: { name: "admin.recoveryKit.verify" } });
const limit = await checkRateLimit(
`recovery-kit-verify:${user.id}`,
KIT_VERIFY_LIMIT,
KIT_VERIFY_WINDOW_MS,
);
if (!limit.allowed) {
return apiError("Too many checks. Try again in a minute.", 429);
}
const body = await safeJson(request, { maxBytes: 2048 });
if (body.error) return body.error;
const parsed = verifySchema.safeParse(body.data);
if (!parsed.success) {
// Deliberately not `returnAllZodIssues`: nothing derived from this body
// goes back over the wire.
return apiError("Paste the key exactly as it is set.", 422);
}
const { kind, id } = parsed.data;
const matches = verifyKitKey({ kind, id, value: parsed.data.keyCopy });
annotate({ meta: { recovery_kit_verify_matches: matches } });
await auditLog("recovery.kit.verified", {
userId: user.id,
details: { kind, keyId: id, matches },
});
return apiSuccess({ matches, kind, id });
});