From d3f087475cfc65224df9188fe84df2d0e2c34bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Thu, 10 Sep 2026 05:25:30 +0200 Subject: [PATCH] fix(backup): refuse a stored copy that will not open with 422 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `DataBackup` row that fails to decrypt answered 500 on the restore, the download and the preview. It is not a server fault: either the key that wrote the copy is no longer in `ENCRYPTION_KEYS` — a rotation that dropped the legacy entry before the script reported zero rows, the case the rotation runbook warns about — or the stored bytes are not the ones that were written. Every other bad-input arm on those routes already answers 4xx, and the 500 also paged the error reporter as if the process had broken. All three now answer 422 with `meta.errorCode = backup.payload.undecryptable` and one shared sentence, so the three routes cannot drift into three wordings for one condition. The download's second 500 stays: a payload this instance wrote and cannot parse really is a fault here. The two routes that open a stored copy move from the unpublished list into the contract, because the refusal is now a promise an operator can look up rather than whatever the handler happened to answer. The restore publishes its `Idempotency-Key` header with them. --- docs/api/openapi.yaml | 212 ++++++++++++++++++ e2e/backup-restore-journey.spec.ts | 12 +- .../idempotency-contract-publication.test.ts | 5 +- .../openapi-route-coverage-guard.test.ts | 12 +- .../api/admin/backups/[id]/download/route.ts | 17 +- .../api/admin/backups/[id]/restore/route.ts | 15 +- .../[id]/summary/__tests__/route.test.ts | 10 +- .../api/admin/backups/[id]/summary/route.ts | 13 +- src/lib/export/backup-blob.ts | 22 ++ src/lib/openapi/routes/admin-backups.ts | 173 ++++++++++++++ src/lib/openapi/routes/index.ts | 7 + 11 files changed, 471 insertions(+), 27 deletions(-) create mode 100644 src/lib/openapi/routes/admin-backups.ts diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index d5b69b924..b4f88ebde 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -19817,6 +19817,119 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" + /api/admin/backups/{id}/download: + get: + tags: + - Admin + summary: Download one stored backup as JSON + description: "Decrypts one stored copy and returns the backup document itself, with `Content-Disposition: attachment` + and `Cache-Control: no-store`. The response is the raw document, not the standard envelope — it is the artefact + an operator keeps. The ciphertext stays in the database. Admin session cookie required; Bearer tokens cannot + reach admin endpoints." + parameters: + - in: path + name: id + schema: + type: string + description: "`DataBackup.id`." + required: true + description: "`DataBackup.id`." + responses: + "200": + description: The decrypted backup document. + content: + application/json: + schema: + $ref: "#/components/schemas/AdminBackupDocument" + "403": &a43 + description: Caller is not an admin. `requireAdmin()` is cookie-only, so a Bearer token lands here whatever its scope. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "404": &a44 + description: No stored copy with this id. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "422": + description: "The stored copy could not be opened: either the key that wrote it is no longer in `ENCRYPTION_KEYS` (a + rotation that dropped the legacy entry too early), or the stored bytes are not the ones that were written. + `meta.errorCode` = `backup.payload.undecryptable`. Nothing was changed." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "500": + description: The copy decrypted and then failed schema validation — a document this instance wrote and cannot parse. + This one genuinely is a server fault, and is reported as one. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + /api/admin/backups/{id}/restore: + post: + tags: + - Admin + summary: Restore one stored backup over its owner's record + description: "Replaces the snapshot owner's data tables from the stored copy, in one transaction, under the ids the file + carries. Replacing is not merging: every row the account gained after the snapshot was taken is deleted with the + rest of its class. The target is the account the snapshot was taken for, never the admin running it, and a + payload declaring a different owner than the stored row is refused. Admin session cookie required; Bearer tokens + cannot reach admin endpoints." + parameters: + - in: path + name: id + schema: + type: string + description: "`DataBackup.id`." + required: true + description: "`DataBackup.id`." + - *a6 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/AdminBackupRestoreRequest" + responses: + "200": + description: The restore ran. + content: + application/json: + schema: + $ref: "#/components/schemas/AdminBackupRestoreResponse" + "400": + description: Body was not JSON. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "403": *a43 + "404": *a44 + "409": + description: Either the payload declares a different owner than the stored row, or a request under the same + `Idempotency-Key` is still in flight. Nothing was changed. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "413": + description: Body exceeds 64 KiB. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "422": + description: "The request or the file was refused before anything was written: `confirm` missing, the copy undecryptable + (`meta.errorCode` = `backup.payload.undecryptable`), the payload failing schema validation, an unsupported + `schemaVersion`, a section the file's own manifest says it carries and does not (`meta.errorCode` = + `backup.section.missing`), a metadata-only document entry, or an owner who no longer exists here." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" /api/bugreport: post: security: [] @@ -28915,6 +29028,21 @@ components: the same plausibility range the interactive create paths use. `idempotencyKey` is an identity, not a windowed replay token: it is stored on the row forever and matched by equality, so a key that rotates per client launch never matches its own earlier row and every re-sync logs the dose again." + AdminBackupRestoreRequest: + type: object + properties: + confirm: + type: string + const: RESTORE + restoreInstanceSettings: + type: boolean + required: + - confirm + description: "`confirm` is the literal typed gate; anything else is refused with 422 and nothing is read. + `restoreInstanceSettings` defaults to false: the restore then replaces the snapshot owner's data tables and + leaves the singleton instance settings — registration, MFA requirement, default locale and timezone, module + availability, notification and AI configuration, document cap and quota — exactly as they are. Send `true` only + when rebuilding a host from a snapshot, because those settings apply to every account on the installation." MedicationTreatmentClass: type: string enum: @@ -68370,6 +68498,90 @@ components: - data - error additionalProperties: false + AdminBackupDocument: + type: object + propertyNames: + type: string + additionalProperties: {} + description: "The backup payload as the writer serialised it: `schemaVersion`, `exportedAt`, `userId`, and one array or + object per serialised class." + AdminBackupRestoreResponse: + type: object + properties: + data: + $ref: "#/components/schemas/AdminBackupRestoreResult" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + AdminBackupRestoreResult: + type: object + properties: + restored: + type: boolean + const: true + summary: + type: object + propertyNames: + type: string + additionalProperties: {} + skipped: + type: object + properties: + catalogueKeys: + type: array + items: + $ref: "#/components/schemas/AdminBackupRestoreSkipEntry" + links: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - catalogueKeys + - links + additionalProperties: false + cleared: + type: object + propertyNames: + type: string + additionalProperties: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - restored + - summary + - skipped + - cleared + additionalProperties: false + description: What the transaction wrote. `cleared` counts the rows each class held before it was rebuilt from the file, + `summary` counts what the file carried, and `skipped.links` is the number of links dropped because a catalogue + key in the file does not exist here — zero is the normal answer. + AdminBackupRestoreSkipEntry: + type: object + properties: + catalogue: + type: string + key: + type: string + links: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - catalogue + - key + - links + additionalProperties: false + description: One catalogue key the file referenced and this instance could not resolve, with the number of links it cost. __schema0: anyOf: - type: string diff --git a/e2e/backup-restore-journey.spec.ts b/e2e/backup-restore-journey.spec.ts index e54acbbcd..5d02c395f 100644 --- a/e2e/backup-restore-journey.spec.ts +++ b/e2e/backup-restore-journey.spec.ts @@ -385,12 +385,16 @@ test.describe("Backup and restore, through the settings surfaces", () => { const response = await restoreThroughDialog(page, tamperedId); // The envelope is AES-256-GCM and its tag covers every ciphertext byte, so - // the flip is caught before the transaction opens. 500 with this sentence - // is what the route answers on a payload it could not decrypt. - expect(response.status()).toBe(500); + // the flip is caught before the transaction opens. 422 and + // `backup.payload.undecryptable` are the refusal the route documents — + // `docs/api/openapi.yaml`, and `docs/ops/backup-restore.md` for the + // operator reading it after a key rotation — rather than whatever the + // handler happened to answer. The code is asserted and not the sentence: + // the sentence is prose that may be reworded, the code is the contract. + expect(response.status()).toBe(422); expect(await response.json()).toMatchObject({ data: null, - error: "Failed to decrypt backup payload", + meta: { errorCode: "backup.payload.undecryptable" }, }); // A refusal that still wrote something would be worse than no refusal. diff --git a/src/__tests__/idempotency-contract-publication.test.ts b/src/__tests__/idempotency-contract-publication.test.ts index 442aadbbd..74af2402a 100644 --- a/src/__tests__/idempotency-contract-publication.test.ts +++ b/src/__tests__/idempotency-contract-publication.test.ts @@ -124,10 +124,7 @@ function idempotentOperationsFromContract(): Set { * Listed rather than filtered silently, so the exclusion stays visible in the * file that would otherwise claim full coverage. */ -const UNPUBLISHED_PATHS: Readonly> = { - "/api/admin/backups/{id}/restore": - "Admin surface: cookie-only by construction, so arguably out of scope for a client contract.", -}; +const UNPUBLISHED_PATHS: Readonly> = {}; describe("idempotency — the contract matches the wrapper", () => { it("finds idempotent operations in the source tree at all", () => { diff --git a/src/__tests__/openapi-route-coverage-guard.test.ts b/src/__tests__/openapi-route-coverage-guard.test.ts index 82480859c..2b28e2a3b 100644 --- a/src/__tests__/openapi-route-coverage-guard.test.ts +++ b/src/__tests__/openapi-route-coverage-guard.test.ts @@ -217,14 +217,10 @@ const UNPUBLISHED: Readonly> = { "/api/admin/backups": { kind: "adminConsole", methods: ["GET"] }, "/api/admin/backups/run": { kind: "adminConsole", methods: ["POST"] }, "/api/admin/backups/upload": { kind: "adminConsole", methods: ["POST"] }, - "/api/admin/backups/{id}/download": { - kind: "adminConsole", - methods: ["GET"], - }, - "/api/admin/backups/{id}/restore": { - kind: "adminConsole", - methods: ["POST"], - }, + // `/api/admin/backups/{id}/download` and `/api/admin/backups/{id}/restore` + // are published rather than exempted: both open the encrypted stored copy, + // and the refusal they answer when it will not open is a promise an operator + // needs to be able to look up. See `src/lib/openapi/routes/admin-backups.ts`. "/api/admin/backups/{id}/summary": { kind: "adminConsole", methods: ["GET"] }, "/api/admin/central-codex": { kind: "adminConsole", diff --git a/src/app/api/admin/backups/[id]/download/route.ts b/src/app/api/admin/backups/[id]/download/route.ts index 0e55b6f7c..644313726 100644 --- a/src/app/api/admin/backups/[id]/download/route.ts +++ b/src/app/api/admin/backups/[id]/download/route.ts @@ -19,7 +19,11 @@ import { prisma } from "@/lib/db"; import { apiHandler, HttpError, requireAdmin } from "@/lib/api-handler"; import { apiError, getClientIp } from "@/lib/api-response"; import { auditLog } from "@/lib/auth/audit"; -import { unpackBackupBlob } from "@/lib/export/backup-blob"; +import { + BACKUP_UNDECRYPTABLE_CODE, + BACKUP_UNDECRYPTABLE_ERROR, + unpackBackupBlob, +} from "@/lib/export/backup-blob"; import { annotate } from "@/lib/logging/context"; import { parseBackupPayload } from "@/lib/validations/backup"; @@ -54,9 +58,10 @@ export const GET = apiHandler( try { plaintext = unpackBackupBlob(backup.data); } catch (err) { - // Decryption failure is rare but real — a rotated/missing key, or a - // corrupted blob from a partially-failed write. Surface it as a 500 - // and audit the event so the admin has something to investigate. + // A rotated or dropped key, or a stored copy that is no longer the one + // that was written. Both are bad stored input rather than a fault in + // this process, so the answer is 422 with a reason the operator can act + // on — and the audit row keeps the underlying message. await auditLog("admin.backups.download.failed", { userId: admin.id, ipAddress: getClientIp(request), @@ -66,7 +71,9 @@ export const GET = apiHandler( reason: err instanceof Error ? err.message : "decrypt_failed", }, }); - return apiError("Failed to decrypt backup payload", 500); + return apiError(BACKUP_UNDECRYPTABLE_ERROR, 422, { + errorCode: BACKUP_UNDECRYPTABLE_CODE, + }); } // Validate the payload BEFORE handing it back. This catches the diff --git a/src/app/api/admin/backups/[id]/restore/route.ts b/src/app/api/admin/backups/[id]/restore/route.ts index d775e8411..409a5b345 100644 --- a/src/app/api/admin/backups/[id]/restore/route.ts +++ b/src/app/api/admin/backups/[id]/restore/route.ts @@ -23,7 +23,11 @@ import { prisma, toJson } from "@/lib/db"; import { apiHandler, HttpError, requireAdmin } from "@/lib/api-handler"; import { apiError, apiSuccess, getClientIp } from "@/lib/api-response"; import { auditLog } from "@/lib/auth/audit"; -import { unpackBackupBlob } from "@/lib/export/backup-blob"; +import { + BACKUP_UNDECRYPTABLE_CODE, + BACKUP_UNDECRYPTABLE_ERROR, + unpackBackupBlob, +} from "@/lib/export/backup-blob"; import { encryptNote } from "@/lib/crypto/note-cipher"; import { encryptToBytes } from "@/lib/ai/coach/bytes-codec"; import { encryptContextToBytes } from "@/lib/labs/biomarker-store"; @@ -204,7 +208,14 @@ const handler = apiHandler( reason: err instanceof Error ? err.message : "decrypt_failed", }, }); - return apiError("Failed to decrypt backup payload", 500); + // Bad stored input, not a broken server: a copy written under a key the + // operator has since dropped, or one whose bytes have changed. Every + // other bad-input arm on this route answers 4xx, and a 500 here would + // also page the error reporter for a rotation mistake. Refused above the + // transaction, so nothing was touched. + return apiError(BACKUP_UNDECRYPTABLE_ERROR, 422, { + errorCode: BACKUP_UNDECRYPTABLE_CODE, + }); } // Parsed once and kept, because the schema's per-section `.default([])` diff --git a/src/app/api/admin/backups/[id]/summary/__tests__/route.test.ts b/src/app/api/admin/backups/[id]/summary/__tests__/route.test.ts index 51441643c..766e0d4de 100644 --- a/src/app/api/admin/backups/[id]/summary/__tests__/route.test.ts +++ b/src/app/api/admin/backups/[id]/summary/__tests__/route.test.ts @@ -81,12 +81,18 @@ describe("GET /api/admin/backups/[id]/summary", () => { await expect(GET(request, params)).rejects.toMatchObject({ status: 404 }); }); - it("degrades to an error response when the file cannot be decrypted", async () => { + it("refuses a file it cannot decrypt with the documented 422", async () => { decryptMock.mockImplementation(() => { throw new Error("bad key"); }); const res = await GET(request, params); - expect(res.status).toBe(500); + // Bad stored input — a key dropped from `ENCRYPTION_KEYS`, or bytes that + // are not the ones written — and not a fault in this process, so it does + // not answer 500 and does not reach the error reporter as one. + expect(res.status).toBe(422); + expect(await res.json()).toMatchObject({ + meta: { errorCode: "backup.payload.undecryptable" }, + }); }); it("422s a file that fails schema validation", async () => { diff --git a/src/app/api/admin/backups/[id]/summary/route.ts b/src/app/api/admin/backups/[id]/summary/route.ts index 3ae840d80..4b79fcc79 100644 --- a/src/app/api/admin/backups/[id]/summary/route.ts +++ b/src/app/api/admin/backups/[id]/summary/route.ts @@ -16,7 +16,11 @@ import { NextRequest } from "next/server"; import { prisma } from "@/lib/db"; import { apiHandler, HttpError, requireAdmin } from "@/lib/api-handler"; import { apiError, apiSuccess } from "@/lib/api-response"; -import { unpackBackupBlob } from "@/lib/export/backup-blob"; +import { + BACKUP_UNDECRYPTABLE_CODE, + BACKUP_UNDECRYPTABLE_ERROR, + unpackBackupBlob, +} from "@/lib/export/backup-blob"; import { annotate } from "@/lib/logging/context"; import { isCompatibleSchemaVersion, @@ -46,7 +50,12 @@ export const GET = apiHandler( try { plaintext = unpackBackupBlob(backup.data); } catch { - return apiError("Failed to decrypt backup payload", 500); + // Same refusal the restore and the download give, for the same reason: + // a copy this instance cannot open is bad stored input, and the preview + // is the first place an operator meets it. + return apiError(BACKUP_UNDECRYPTABLE_ERROR, 422, { + errorCode: BACKUP_UNDECRYPTABLE_CODE, + }); } let payload; diff --git a/src/lib/export/backup-blob.ts b/src/lib/export/backup-blob.ts index 79dbf1e04..a05760650 100644 --- a/src/lib/export/backup-blob.ts +++ b/src/lib/export/backup-blob.ts @@ -223,6 +223,28 @@ export async function packBackupBlobStreaming( return pieces.join(""); } +/** + * The refusal a caller gets when a stored copy will not open, as one string. + * + * Two causes, one answer, because the envelope cannot tell them apart and the + * operator's next step is the same either way: the key that wrote the copy is + * no longer in `ENCRYPTION_KEYS` (a rotation that dropped the legacy entry too + * early — the case `docs/ops/encryption-key-rotation.md` warns about), or the + * stored bytes are not the bytes that were written. Neither is a server fault, + * so neither is a 500: it is bad stored input, refused with 422 like every + * other bad input on these routes, and it never reaches the error reporter as + * if the process had broken. + * + * Shared rather than retyped, so the three routes that decrypt a stored copy — + * restore, download, summary — cannot drift into three different sentences for + * the same condition. + */ +export const BACKUP_UNDECRYPTABLE_ERROR = + "Backup payload could not be decrypted — either the key that wrote this copy is no longer in ENCRYPTION_KEYS, or the stored copy is not the one that was written. Nothing was changed."; + +/** The stable machine-readable half of {@link BACKUP_UNDECRYPTABLE_ERROR}. */ +export const BACKUP_UNDECRYPTABLE_CODE = "backup.payload.undecryptable"; + /** * A stored `DataBackup.data` string → the backup JSON. * diff --git a/src/lib/openapi/routes/admin-backups.ts b/src/lib/openapi/routes/admin-backups.ts new file mode 100644 index 000000000..aea64243b --- /dev/null +++ b/src/lib/openapi/routes/admin-backups.ts @@ -0,0 +1,173 @@ +/** + * OpenAPI route table — the two backups-console routes that read a stored copy. + * + * Part of the OpenAPI route table; aggregated in `./index.ts`. + * + * Most of `/api/admin/backups/*` is deliberately unpublished: it is a + * cookie-only console, `requireAdmin()` refuses every Bearer caller, and a + * contract nobody can call against is a contract nobody reads. These two are + * here for the opposite reason. Both open the encrypted copy in + * `data_backups.data`, and both therefore have a refusal an operator meets on + * the day a key rotation went one step too far — the case + * `docs/ops/encryption-key-rotation.md` warns about. That refusal is a promise + * (422, `backup.payload.undecryptable`, nothing changed) rather than whatever + * the handler happens to answer, and a promise belongs somewhere it can be + * quoted from. + */ +import { z } from "zod/v4"; +import type { ZodOpenApiObject } from "zod-openapi"; + +import { dataEnvelope, errorEnvelope, idempotencyKeyParameter } from "./shared"; + +const restoreRequest = z + .object({ + confirm: z.literal("RESTORE"), + restoreInstanceSettings: z.boolean().optional(), + }) + .meta({ + id: "AdminBackupRestoreRequest", + description: + "`confirm` is the literal typed gate; anything else is refused with 422 and nothing is read. `restoreInstanceSettings` defaults to false: the restore then replaces the snapshot owner's data tables and leaves the singleton instance settings — registration, MFA requirement, default locale and timezone, module availability, notification and AI configuration, document cap and quota — exactly as they are. Send `true` only when rebuilding a host from a snapshot, because those settings apply to every account on the installation.", + }); + +const restoreSkipEntry = z + .object({ + catalogue: z.string(), + key: z.string(), + links: z.number().int(), + }) + .meta({ + id: "AdminBackupRestoreSkipEntry", + description: + "One catalogue key the file referenced and this instance could not resolve, with the number of links it cost.", + }); + +const restoreResult = z + .object({ + restored: z.literal(true), + summary: z.record(z.string(), z.unknown()), + skipped: z.object({ + catalogueKeys: z.array(restoreSkipEntry), + links: z.number().int(), + }), + cleared: z.record(z.string(), z.number().int()), + }) + .meta({ + id: "AdminBackupRestoreResult", + description: + "What the transaction wrote. `cleared` counts the rows each class held before it was rebuilt from the file, `summary` counts what the file carried, and `skipped.links` is the number of links dropped because a catalogue key in the file does not exist here — zero is the normal answer.", + }); + +/** + * The one refusal both routes share, worded once. + * + * A stored copy that will not open is bad stored input, not a fault in the + * server: either the key that wrote it is no longer in `ENCRYPTION_KEYS`, or + * the stored bytes are not the bytes that were written. It answers 422 like + * every other bad input on these routes, and never as a 500. + */ +const undecryptableResponse = { + description: + "The stored copy could not be opened: either the key that wrote it is no longer in `ENCRYPTION_KEYS` (a rotation that dropped the legacy entry too early), or the stored bytes are not the ones that were written. `meta.errorCode` = `backup.payload.undecryptable`. Nothing was changed.", + content: { "application/json": { schema: errorEnvelope } }, +}; + +const adminOnlyResponse = { + description: + "Caller is not an admin. `requireAdmin()` is cookie-only, so a Bearer token lands here whatever its scope.", + content: { "application/json": { schema: errorEnvelope } }, +}; + +const notFoundResponse = { + description: "No stored copy with this id.", + content: { "application/json": { schema: errorEnvelope } }, +}; + +export const adminBackupPaths: NonNullable = { + "/api/admin/backups/{id}/download": { + get: { + tags: ["Admin"], + summary: "Download one stored backup as JSON", + description: + "Decrypts one stored copy and returns the backup document itself, with `Content-Disposition: attachment` and `Cache-Control: no-store`. The response is the raw document, not the standard envelope — it is the artefact an operator keeps. The ciphertext stays in the database. Admin session cookie required; Bearer tokens cannot reach admin endpoints.", + requestParams: { + path: z.object({ + id: z.string().meta({ description: "`DataBackup.id`." }), + }), + }, + responses: { + "200": { + description: "The decrypted backup document.", + content: { + "application/json": { + schema: z.record(z.string(), z.unknown()).meta({ + id: "AdminBackupDocument", + description: + "The backup payload as the writer serialised it: `schemaVersion`, `exportedAt`, `userId`, and one array or object per serialised class.", + }), + }, + }, + }, + "403": adminOnlyResponse, + "404": notFoundResponse, + "422": undecryptableResponse, + "500": { + description: + "The copy decrypted and then failed schema validation — a document this instance wrote and cannot parse. This one genuinely is a server fault, and is reported as one.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, + "/api/admin/backups/{id}/restore": { + post: { + tags: ["Admin"], + summary: "Restore one stored backup over its owner's record", + description: + "Replaces the snapshot owner's data tables from the stored copy, in one transaction, under the ids the file carries. Replacing is not merging: every row the account gained after the snapshot was taken is deleted with the rest of its class. The target is the account the snapshot was taken for, never the admin running it, and a payload declaring a different owner than the stored row is refused. Admin session cookie required; Bearer tokens cannot reach admin endpoints.", + requestParams: { + path: z.object({ + id: z.string().meta({ description: "`DataBackup.id`." }), + }), + }, + // The one write here, and the destructive one: the console sends a + // per-row key so a double-click replays the first answer instead of + // running the transaction twice. + parameters: [idempotencyKeyParameter], + requestBody: { + required: true, + content: { "application/json": { schema: restoreRequest } }, + }, + responses: { + "200": { + description: "The restore ran.", + content: { + "application/json": { + schema: dataEnvelope(restoreResult, "AdminBackupRestoreResponse"), + }, + }, + }, + "400": { + description: "Body was not JSON.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "403": adminOnlyResponse, + "404": notFoundResponse, + "409": { + description: + "Either the payload declares a different owner than the stored row, or a request under the same `Idempotency-Key` is still in flight. Nothing was changed.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "422": { + description: + "The request or the file was refused before anything was written: `confirm` missing, the copy undecryptable (`meta.errorCode` = `backup.payload.undecryptable`), the payload failing schema validation, an unsupported `schemaVersion`, a section the file's own manifest says it carries and does not (`meta.errorCode` = `backup.section.missing`), a metadata-only document entry, or an owner who no longer exists here.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, +}; diff --git a/src/lib/openapi/routes/index.ts b/src/lib/openapi/routes/index.ts index df326ba58..c1a5a0a21 100644 --- a/src/lib/openapi/routes/index.ts +++ b/src/lib/openapi/routes/index.ts @@ -28,6 +28,7 @@ import { recordScopeParameter, } from "./account-sharing"; import { adminDiagnosticPaths, adminInvitePaths } from "./admin"; +import { adminBackupPaths } from "./admin-backups"; import { allergyPaths } from "./allergies"; import { analyticsPaths } from "./analytics"; import { authPaths } from "./auth"; @@ -163,6 +164,12 @@ export const openApiPaths: NonNullable = { ...awardsPaths, ...environmentPaths, ...ingestPaths, + // The two backups-console routes that open a stored copy. The rest of the + // family stays unpublished — it is a cookie-only console — but these two + // carry a refusal an operator has to be able to look up rather than + // discover: a copy this instance can no longer decrypt (appended, spread + // order is load-bearing). + ...adminBackupPaths, // The environmental-context overview. Its own module because nothing else // owns the surface (appended, spread order is load-bearing). //