Files
HealthLog/tests/integration/note-encryption-backfill.test.ts
T
Marc-André Bombeck 4d3a02cc1a feat(security): add second-factor schema and encrypt free-text health notes at rest
Lay the account-security and data-sovereignty substrate for v1.23. No
user-facing behaviour yet — schema, crypto registry, redaction, and the
note-encryption data path only.

Schema + migrations:
- 0199 — User totp_secret_encrypted / totp_confirmed_at / mfa_enforced /
  passkey_upgrade_nudge_dismissed; Session mfa_verified_at / last_active_at;
  Passkey last_used_at. All additive, nullable / defaulted.
- 0200 — mfa_challenges (single-use step-up ticket; only the ticket hash is
  stored, so no session or token is ever minted before the second factor),
  mfa_recovery_codes (Argon2id at rest), webauthn_mfa_credentials (second-factor
  keys, kept separate from passkeys, which remain the passwordless-primary set).
- 0201 — mood_entries.note_encrypted + measurements.notes_encrypted (BYTEA),
  matching the existing free-text encrypted-note convention.

Free-text health notes:
- New writes encrypt the mood / measurement note into the *_encrypted column and
  null the legacy plaintext column; reads prefer the ciphertext and fall back to
  plaintext only for not-yet-migrated rows, via a single read/write helper.
- A boot-time job migrates existing plaintext rows in an idempotent,
  transactional, fail-closed pass (encrypt, then null the plaintext, per row in
  one transaction; safe to re-run; a row with content is never left both-null).
- The legacy plaintext columns are kept this release and dropped in a follow-up
  once the backfill reports zero remaining rows — the same boundary the
  key-rotation playbook uses before dropping a legacy key.

Crypto coverage:
- Register the three new encrypted columns and wire them into the key-rotation
  script so a rotation never orphans them.
- Extend the observability and log redaction denylists so TOTP secrets, MFA /
  recovery / backup codes, and export passphrases never reach a wide event.
2026-06-27 19:33:10 +02:00

125 lines
4.1 KiB
TypeScript

/**
* v1.23 — free-text health-note encryption backfill (real Postgres).
*
* Seeds legacy plaintext rows (note in the plaintext column, ciphertext null),
* runs the per-user backfill, and asserts:
* - the plaintext is encrypted into `*Encrypted` and the plaintext column is
* nulled, in one transaction (no row left both-null when it had content);
* - the ciphertext decrypts back to the original (no data loss);
* - a note-less row is untouched;
* - a second run is a no-op (idempotent).
*/
import { beforeEach, describe, expect, it } from "vitest";
import { readNote } from "@/lib/crypto/note-cipher";
import { runNoteEncryptionBackfillForUser } from "@/lib/jobs/note-encryption-backfill";
import { getPrismaClient, truncateAllTables } from "./setup";
const TEST_USER_ID = "user-note-backfill";
beforeEach(async () => {
await truncateAllTables(getPrismaClient());
await getPrismaClient().user.create({
data: {
id: TEST_USER_ID,
username: "note-backfill",
email: "note-backfill@example.test",
timezone: "Europe/Berlin",
},
});
});
describe("note-encryption backfill (real Postgres)", () => {
it("migrates legacy plaintext notes to ciphertext and nulls the plaintext", async () => {
const prisma = getPrismaClient();
// Legacy rows: plaintext present, ciphertext null (the pre-v1.23 shape).
const withNote = await prisma.measurement.create({
data: {
userId: TEST_USER_ID,
type: "WEIGHT",
value: 80,
unit: "kg",
measuredAt: new Date("2026-05-16T08:00:00.000Z"),
notes: "felt dizzy after",
},
});
const noNote = await prisma.measurement.create({
data: {
userId: TEST_USER_ID,
type: "WEIGHT",
value: 81,
unit: "kg",
measuredAt: new Date("2026-05-17T08:00:00.000Z"),
notes: null,
},
});
const mood = await prisma.moodEntry.create({
data: {
userId: TEST_USER_ID,
date: "2026-05-16",
tz: "Europe/Berlin",
mood: "OKAY",
score: 3,
moodLoggedAt: new Date("2026-05-16T08:00:00.000Z"),
note: "rough night",
},
});
const summary = await runNoteEncryptionBackfillForUser(TEST_USER_ID);
expect(summary.measurementsMigrated).toBe(1);
expect(summary.moodEntriesMigrated).toBe(1);
const m = await prisma.measurement.findUnique({
where: { id: withNote.id },
});
expect(m?.notes).toBeNull();
expect(m?.notesEncrypted).not.toBeNull();
expect(readNote(m?.notesEncrypted ?? null, null)).toBe("felt dizzy after");
const untouched = await prisma.measurement.findUnique({
where: { id: noNote.id },
});
expect(untouched?.notes).toBeNull();
expect(untouched?.notesEncrypted).toBeNull();
const x = await prisma.moodEntry.findUnique({ where: { id: mood.id } });
expect(x?.note).toBeNull();
expect(readNote(x?.noteEncrypted ?? null, null)).toBe("rough night");
});
it("is idempotent: a second run migrates zero rows and preserves the data", async () => {
const prisma = getPrismaClient();
const row = await prisma.measurement.create({
data: {
userId: TEST_USER_ID,
type: "WEIGHT",
value: 80,
unit: "kg",
measuredAt: new Date("2026-05-16T08:00:00.000Z"),
notes: "side effect note",
},
});
await runNoteEncryptionBackfillForUser(TEST_USER_ID);
const first = await prisma.measurement.findUnique({
where: { id: row.id },
});
const firstCipher = Buffer.from(first?.notesEncrypted ?? new Uint8Array());
const second = await runNoteEncryptionBackfillForUser(TEST_USER_ID);
expect(second.measurementsMigrated).toBe(0);
const after = await prisma.measurement.findUnique({
where: { id: row.id },
});
// Same ciphertext, plaintext still null, note still recoverable.
expect(Buffer.from(after?.notesEncrypted ?? new Uint8Array())).toEqual(
firstCipher,
);
expect(after?.notes).toBeNull();
expect(readNote(after?.notesEncrypted ?? null, null)).toBe(
"side effect note",
);
});
});