test(e2e): drive backup and restore end to end through the settings surfaces

One journey across the whole path: an account writes readings in three
domains and files a PDF, downloads its own record as the passphrase-sealed
archive, an admin snapshots it from the backups console, and the snapshot is
restored over an account that has since lost a reading and a dose and gained
one the snapshot never saw.

The assertions address what the documentation promises rather than what the
implementation happens to do. The archive is checked byte by byte against the
HLX1 header in src/lib/export/passphrase-archive.ts — magic, version, KDF id
and the Argon2 cost the file carries — because "a file arrived" is equally
true of plaintext JSON under a new extension. The restored reading and dose
are checked by their ORIGINAL ids, because a restore that re-created them
under fresh ones would have written a different record that reads the same.
The reading created after the snapshot is asserted GONE: the runbook says the
restore replaces the account's data tables, and replacing is not merging.

Two refusing controls. A stored copy with one flipped ciphertext byte is
refused with the route's decrypt failure and leaves the record untouched — the
envelope is AES-256-GCM and its tag covers every byte, so the flip is caught
before the transaction opens. A delegate holding whole-record READ inside the
account gets the not-covered panel instead of the export card, never reaches
the console, and is refused 403 by the list, the manual run and the restore,
the last of them naming the real snapshot so the refusal cannot be mistaken
for a missing row.

Waiting is on the job's own evidence: the console's endpoint is polled until
this account's stored copy is newer than the click, so nothing in the file
guesses at a queue. The journey has its own account, its own delegate and its
own cookie jars; only the reset between repetitions and the deliberate
corruption reach Postgres directly, because a browser cannot express either.

The backups console gains data-testid hooks and a data-backup-id on each row
so the spec addresses controls rather than translated labels.
This commit is contained in:
Marc-André Bombeck committed 2026-09-10 04:53:03 +02:00
1 parent 297395372b
commit 5cb5c7df44
5 files changed
+963 -4

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
/**
* Database-side fixture for the backup/restore journey.
*
* Everything the journey WRITES it writes through the browser: the readings,
* the medication and its dose, the mood entry, the document, the snapshot, the
* deletions and the restore all ride the app's own routes. What lives here is
* only what a browser has no way to express — clearing the account back to a
* known state so the file survives `--repeat-each`, and corrupting one stored
* copy so the restore path has an authenticated envelope to refuse.
*
* Raw SQL through `pg` for the same reason `global-setup.ts` uses it:
* Playwright's TS loader does not handle the generated Prisma client's
* `import.meta.url` indirection.
*/
import pg from "pg";
import { E2E_BACKUP_ADMIN, E2E_BACKUP_DELEGATE } from "./global-setup";
/** One row of the account's readings, as the journey needs to compare it. */
export interface StoredMeasurement {
id: string;
type: string;
value: number;
deletedAt: string | null;
}
async function withPool<T>(fn: (pool: pg.Pool) => Promise<T>): Promise<T> {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error(
"DATABASE_URL is unset — the backup journey needs the same database the app is running against.",
);
}
const pool = new pg.Pool({ connectionString });
try {
return await fn(pool);
} finally {
await pool.end();
}
}
/** The journey account's id, resolved by username rather than assumed. */
export async function backupAccountId(): Promise<string> {
return withPool(async (pool) => {
const { rows } = await pool.query<{ id: string }>(
`SELECT id FROM users WHERE username = $1`,
[E2E_BACKUP_ADMIN.username],
);
if (rows.length !== 1) {
throw new Error(
`expected exactly one ${E2E_BACKUP_ADMIN.username} row, found ${rows.length}`,
);
}
return rows[0].id;
});
}
/**
* Put the account back where the journey expects to find it.
*
* Deletes only what this file's account holds, and only the classes the
* journey writes. The stored snapshots go too: a row left behind from the
* previous repetition is indistinguishable from the one this repetition is
* about to take, and the whole journey turns on picking the right one.
*
* The rate buckets are cleared for the same reason `global-setup.ts` clears
* the login bucket: the manual-run and upload endpoints allow three calls a
* minute each and the export bucket ten an hour, which are the right
* production numbers and fewer than three repetitions of this file need.
*/
export async function resetBackupJourney(): Promise<void> {
await withPool(async (pool) => {
const { rows } = await pool.query<{ id: string }>(
`SELECT id FROM users WHERE username = ANY($1)`,
[[E2E_BACKUP_ADMIN.username, E2E_BACKUP_DELEGATE.username]],
);
const ids = rows.map((row) => row.id);
// Intake events before medications: the child rows carry the foreign key.
await pool.query(
`DELETE FROM medication_intake_events WHERE user_id = ANY($1)`,
[ids],
);
await pool.query(`DELETE FROM medications WHERE user_id = ANY($1)`, [ids]);
await pool.query(`DELETE FROM measurements WHERE user_id = ANY($1)`, [ids]);
await pool.query(`DELETE FROM mood_entries WHERE user_id = ANY($1)`, [ids]);
await pool.query(`DELETE FROM inbound_documents WHERE user_id = ANY($1)`, [
ids,
]);
await pool.query(`DELETE FROM data_backups WHERE user_id = ANY($1)`, [ids]);
// The delegate is switched back out of the record; the refusal control
// switches in and a stamp that outlived a repetition would start the next
// one already inside.
await pool.query(
`UPDATE sessions SET acting_as_user_id = NULL WHERE user_id = ANY($1)`,
[ids],
);
for (const id of ids) {
await pool.query(
`DELETE FROM rate_limits
WHERE key IN ($1, $2, $3)`,
[
`admin-backups-run:${id}`,
`admin-backups-upload:${id}`,
`export:${id}`,
],
);
}
});
}
/**
* Copy one stored snapshot and flip a single character of its ciphertext.
*
* `DataBackup.data` is `~hlgcm1.<keyId>.<base64(iv | ciphertext | authTag)>`
* (see `src/lib/crypto.ts`), so the flip lands four fifths of the way in —
* well past the header, inside the ciphertext the tag covers. The replacement
* stays inside the base64 alphabet, so what the restore meets is a
* well-formed envelope whose authentication tag no longer matches, and not a
* decoder error standing in for one.
*
* A COPY rather than the row itself: the journey still needs the good
* snapshot afterwards, and a control that destroys its own subject can only
* be run once.
*/
export async function storeTamperedCopy(backupId: string): Promise<string> {
return withPool(async (pool) => {
const { rows } = await pool.query<{
user_id: string;
data: string;
}>(`SELECT user_id, data FROM data_backups WHERE id = $1`, [backupId]);
if (rows.length !== 1) {
throw new Error(`no stored backup ${backupId} to copy`);
}
const stored = rows[0].data;
const at = Math.floor(stored.length * 0.8);
const original = stored[at];
if (!/[A-Za-z0-9+/]/.test(original)) {
throw new Error(
`the byte at ${at} of the stored blob is '${original}', not ciphertext base64`,
);
}
const flipped = original === "A" ? "B" : "A";
const tampered = stored.slice(0, at) + flipped + stored.slice(at + 1);
if (tampered === stored) {
throw new Error("the tamper changed nothing");
}
const { rows: created } = await pool.query<{ id: string }>(
`INSERT INTO data_backups (id, user_id, type, data, created_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id`,
[
`c${Date.now().toString(36)}tampered${Math.floor(Math.random() * 1e6)}`,
rows[0].user_id,
`MANUAL_UPLOAD_${Date.now()}`,
tampered,
],
);
return created[0].id;
});
}
/** Every reading the account holds, tombstoned ones included. */
export async function storedMeasurements(): Promise<StoredMeasurement[]> {
const userId = await backupAccountId();
return withPool(async (pool) => {
const { rows } = await pool.query<{
id: string;
type: string;
value: string;
deleted_at: Date | null;
}>(
`SELECT id, type, value, deleted_at
FROM measurements WHERE user_id = $1 ORDER BY measured_at ASC`,
[userId],
);
return rows.map((row) => ({
id: row.id,
type: row.type,
value: Number(row.value),
deletedAt: row.deleted_at ? row.deleted_at.toISOString() : null,
}));
});
}
/** Every dose the account holds, tombstoned ones included. */
export async function storedIntakeIds(): Promise<
Array<{ id: string; deletedAt: string | null }>
> {
const userId = await backupAccountId();
return withPool(async (pool) => {
const { rows } = await pool.query<{ id: string; deleted_at: Date | null }>(
`SELECT id, deleted_at FROM medication_intake_events
WHERE user_id = $1 ORDER BY scheduled_for ASC`,
[userId],
);
return rows.map((row) => ({
id: row.id,
deletedAt: row.deleted_at ? row.deleted_at.toISOString() : null,
}));
});
}
+120 -2
View File
@@ -71,6 +71,39 @@ export const E2E_OWNER = {
*/
export const E2E_OWNER_FULL_NAME = "Test Full Name";
/**
* The backup/restore journey's own account.
*
* Its own account, and an administrative one, because the restore path is
* admin-only by construction (`requireAdmin()` is cookie-only) and because the
* journey is destructive on purpose: it deletes rows, restores an earlier
* snapshot over them, and asserts what came back. Pointing that at an account
* any other spec reads would make every one of them depend on where this
* journey happens to be.
*/
export const E2E_BACKUP_ADMIN = {
email: "e2e-backup-admin@healthlog.test",
username: "e2e-backup-admin",
password: "Hw3!Tq7vZm2xRb8L",
role: "ADMIN",
} as const;
/**
* The read-level delegate on that account's record.
*
* The refusing half of the journey needs somebody who is inside the record and
* still has no business taking or replaying a copy of it. A separate account
* rather than one of the existing delegates: this one is granted READ over the
* whole record above, and reusing a delegate would change what the scoped
* journeys see.
*/
export const E2E_BACKUP_DELEGATE = {
email: "e2e-backup-delegate@healthlog.test",
username: "e2e-backup-delegate",
password: "Ld6!Yn4kW9pJc3Vt",
role: "USER",
} as const;
/**
* v1.37.0 — the account that creates and administers managed profiles.
*
@@ -250,6 +283,23 @@ export const CROSS_TAB_STORAGE_STATE_PATH = resolve(
"e2e/setup/storageStateCrossTab.json",
);
/** The backup/restore journey's jar, for the account it owns outright. */
export const BACKUP_STORAGE_STATE_PATH = resolve(
process.cwd(),
"e2e/setup/storageStateBackup.json",
);
/**
* The read-level delegate's jar for that journey. Its own session row, like
* every other switching spec's — the refusal control switches into the
* journey's record, and the switch is stamped on the row rather than held in
* the tab.
*/
export const BACKUP_DELEGATE_STORAGE_STATE_PATH = resolve(
process.cwd(),
"e2e/setup/storageStateBackupDelegate.json",
);
/**
* The banner-geometry spec's jar, and the reason it exists is a release-shaped
* one rather than a load-shaped one.
@@ -647,7 +697,7 @@ export default async function globalSetup(config: FullConfig): Promise<void> {
WHERE key LIKE 'sharing:%'`,
);
// The login bucket, for the same reason. This setup signs in TEN times now
// The login bucket, for the same reason. This setup signs in TWELVE times now
// (the shared jar, the owner, and one jar apiece for every spec that moves
// a session's record selector), and the ceiling is five attempts per IP per
// quarter-hour — so two local runs in a row would otherwise end with a 429
@@ -707,6 +757,70 @@ export default async function globalSetup(config: FullConfig): Promise<void> {
["e2e-level-write"],
);
// ── the backup/restore journey's pair ────────────────────────────────
//
// The account the journey owns, with the three modules its readings need
// switched on, and the delegate that holds READ over the whole record.
// Both are re-seeded here rather than in the spec so the journey never
// spends a login on a surface the setup already owns.
for (const account of [E2E_BACKUP_ADMIN, E2E_BACKUP_DELEGATE] as const) {
await pool.query(
`INSERT INTO users
(id, username, email, password_hash, role, created_at, updated_at,
onboarding_completed_at, onboarding_tour_completed,
module_preferences_json)
VALUES ($1, $2, $3, $4, $5, $6, $6, $6, true, $7::jsonb)
ON CONFLICT (username) DO UPDATE SET
email = EXCLUDED.email,
password_hash = EXCLUDED.password_hash,
role = EXCLUDED.role,
updated_at = EXCLUDED.updated_at,
onboarding_completed_at = EXCLUDED.onboarding_completed_at,
onboarding_tour_completed = EXCLUDED.onboarding_tour_completed,
module_preferences_json = EXCLUDED.module_preferences_json,
totp_confirmed_at = NULL`,
[
cuid(),
account.username,
account.email,
await hashPassword(account.password),
account.role,
now,
JSON.stringify({
medications: true,
mood: true,
inboundDocuments: true,
}),
],
);
}
// Grant hygiene before the grant, for the reason the sharing fixture
// states above: a grant and a switch stamp both outlive a run.
await pool.query(
`DELETE FROM account_grants
WHERE grantor_id IN (SELECT id FROM users WHERE username = ANY($1))
OR grantee_id IN (SELECT id FROM users WHERE username = ANY($1))`,
[[E2E_BACKUP_ADMIN.username, E2E_BACKUP_DELEGATE.username]],
);
await pool.query(
`UPDATE sessions SET acting_as_user_id = NULL
WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1))`,
[[E2E_BACKUP_ADMIN.username, E2E_BACKUP_DELEGATE.username]],
);
// Whole-record READ: `scope_json` NULL is the un-narrowed grant, which is
// the strongest read a delegate can hold and therefore the honest subject
// for "and still cannot take or replay a copy".
await pool.query(
`INSERT INTO account_grants
(id, grantor_id, grantee_id, access, scope_json, invited_at,
accepted_at, created_at)
SELECT $1, owner.id, delegate.id, 'READ', NULL, $2, $2, $2
FROM users owner, users delegate
WHERE owner.username = $3 AND delegate.username = $4`,
[cuid(), now, E2E_BACKUP_ADMIN.username, E2E_BACKUP_DELEGATE.username],
);
// Console (instead of structured logging) is intentional here —
// global-setup runs outside the app's logging context, and the
// line is useful when debugging a CI failure where the seed didn't
@@ -727,7 +841,7 @@ export default async function globalSetup(config: FullConfig): Promise<void> {
* Log one account in, clearing the login bucket first.
*
* The ceiling is FIVE attempts per IP per quarter-hour and this setup now
* signs in ten times, so clearing once before the batch is no longer
* signs in twelve times, so clearing once before the batch is no longer
* enough — the sixth would be answered by the fixture's own 429 rather
* than by the product. Only the auth surfaces' buckets are touched, and
* only between logins this setup is itself performing.
@@ -766,6 +880,10 @@ export default async function globalSetup(config: FullConfig): Promise<void> {
await capture(E2E_SCOPE_DELEGATE, CROSS_TAB_STORAGE_STATE_PATH);
await capture(E2E_SCOPE_DELEGATE, SEAM_BANNERS_STORAGE_STATE_PATH);
// The backup/restore journey's pair.
await capture(E2E_BACKUP_ADMIN, BACKUP_STORAGE_STATE_PATH);
await capture(E2E_BACKUP_DELEGATE, BACKUP_DELEGATE_STORAGE_STATE_PATH);
// v1.37.0 — the guardian's jar, and only then its second factor.
//
// Order is the whole of it. `requireFreshMfa` refuses an account with no