Files
HealthLog/src/lib/__tests__/moodlog-secret.test.ts
T
Marc-André BombeckandClaude Opus 4.7 909c572bfd fix(auth): reject moodLog webhook secrets that fail envelope decryption
`readMoodLogSecret()` previously caught every decrypt failure and
returned the stored bytes verbatim, on the theory that legacy
plaintext rows should keep working through the migration grace
period. That fallback is correct for genuinely unprefixed legacy
values, but it also swallowed two failure modes that should never
silently succeed:

- An envelope-shaped row (`<keyId>.<payload>`) whose key id is no
  longer in the live `ENCRYPTION_KEYS` map. Returning the literal
  `v1.<base64-ciphertext>` as if it were the plaintext secret would
  cause every webhook attempt against that row to compare a known-bad
  literal — and worse, lock the user into a state where rotating the
  key out of the env quietly broke their integration.
- A row whose envelope bytes were tampered with directly in the
  column (SQL injection, restored-from-backup-with-tamper, leaked DB
  credentials). The catch-all returned the attacker-chosen value as
  the active secret; the webhook would then accept whatever the
  attacker sent over the wire.

The fix routes the envelope-shape check through `extractKeyId()` and
only catches the failure for the genuinely legacy path. Envelope
rows that fail to decrypt now throw — operators see the rotation gap
or the tampered row instead of running on a quietly-broken secret.

`isLegacyPlaintext()` simplifies to the same shape check: anything
with an envelope prefix is encrypted (even if currently undecryptable),
so it should not be re-rotated as if it were plaintext.

Two new test cases pin the contract for envelope-shape failures
(unknown key id; tampered ciphertext under a known key).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 00:08:56 +02:00

107 lines
3.9 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from "vitest";
import {
encryptMoodLogSecret,
readMoodLogSecret,
isLegacyPlaintext,
rotateLegacyMoodLogSecrets,
} from "../moodlog-secret";
const ORIGINAL_ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;
beforeEach(() => {
process.env.ENCRYPTION_KEY = "a".repeat(64);
});
afterEach(() => {
if (ORIGINAL_ENCRYPTION_KEY === undefined) delete process.env.ENCRYPTION_KEY;
else process.env.ENCRYPTION_KEY = ORIGINAL_ENCRYPTION_KEY;
});
// V3 audit STILL-V2-C-2: mood_log_webhook_secret was stored in plaintext.
// The new contract encrypts at rest with AES-256-GCM and tolerates legacy
// plaintext rows during the transition window.
describe("moodLog secret encrypt-at-rest", () => {
it("encrypts and decrypts a generated secret round-trip", () => {
const plaintext = "mb_" + "f".repeat(64);
const encrypted = encryptMoodLogSecret(plaintext);
expect(encrypted).not.toBe(plaintext);
expect(readMoodLogSecret(encrypted)).toBe(plaintext);
});
it("treats unrecognised values as legacy plaintext (transitional grace)", () => {
expect(readMoodLogSecret("mb_legacyplaintextsecret")).toBe(
"mb_legacyplaintextsecret",
);
});
it("returns null for null/empty stored values", () => {
expect(readMoodLogSecret(null)).toBeNull();
expect(readMoodLogSecret("")).toBeNull();
});
it("isLegacyPlaintext detects rotation status correctly", () => {
const enc = encryptMoodLogSecret("mb_test");
expect(isLegacyPlaintext(enc)).toBe(false);
expect(isLegacyPlaintext("mb_test")).toBe(true);
expect(isLegacyPlaintext(null)).toBe(false);
});
it("throws when an envelope-shaped row fails to decrypt (tamper or stale key)", () => {
// `<keyId>.<payload>` shape but the keyId is unknown to the live
// config — must surface as an error, not silently return the
// ciphertext as if it were the plaintext secret.
expect(() => readMoodLogSecret("v9.AAAAAAAAAAAAAAAAAAAAAAA=")).toThrow();
});
it("treats envelope-shaped tampered ciphertext as a hard failure", () => {
// Round-trip an encrypted value, then flip a byte in the payload.
// The shape stays envelope-like, so decrypt must throw (AES-GCM
// auth-tag mismatch) instead of falling back to plaintext.
const enc = encryptMoodLogSecret("mb_test");
const dot = enc.indexOf(".");
const tampered = `${enc.slice(0, dot + 1)}AA${enc.slice(dot + 3)}`;
expect(() => readMoodLogSecret(tampered)).toThrow();
});
it("rotateLegacyMoodLogSecrets encrypts only legacy rows and is idempotent", async () => {
const enc = encryptMoodLogSecret("mb_alreadyencrypted");
const rows = [
{ id: "u1", moodLogWebhookSecret: "mb_legacy1" },
{ id: "u2", moodLogWebhookSecret: enc },
{ id: "u3", moodLogWebhookSecret: "mb_legacy3" },
{ id: "u4", moodLogWebhookSecret: null },
];
const updates: Array<{ id: string; encrypted: string }> = [];
const rotated = await rotateLegacyMoodLogSecrets({
findLegacy: async () => rows,
rotate: async (id, encrypted) => {
updates.push({ id, encrypted });
},
});
expect(rotated).toBe(2);
expect(updates.map((u) => u.id).sort()).toEqual(["u1", "u3"]);
for (const update of updates) {
// Each rotation must produce a value that decrypts back to the
// original legacy plaintext — no data loss.
const original = rows.find(
(r) => r.id === update.id,
)!.moodLogWebhookSecret;
expect(readMoodLogSecret(update.encrypted)).toBe(original);
}
// Re-running on the now-encrypted store rotates nothing.
const next = await rotateLegacyMoodLogSecrets({
findLegacy: async () => [
{ id: "u1", moodLogWebhookSecret: updates[0].encrypted },
{ id: "u2", moodLogWebhookSecret: enc },
],
rotate: async () => {
throw new Error("should not be called");
},
});
expect(next).toBe(0);
});
});