Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/auth/mfa/recovery-codes.fault.server.test.ts
T
2026-07-08 16:15:37 +02:00

64 lines
2.5 KiB
TypeScript

// @vitest-environment node
//
// Fault-injection coverage for the hard-to-reach failure branches in
// recovery-codes.server: the HMAC-secret resolution (CRYPTO_SECRET vs the
// SESSION_SECRET fallback vs neither) and the "could not generate unique
// codes after retry" guard. Both need control over `@hivegrid/config` /
// `node:crypto`, so they live in a dedicated file with their own mocks
// instead of the env-driven happy-path suite.
import { describe, expect, test, vi } from "vitest";
const state = vi.hoisted(() => ({
secret: { cryptoSecret: "fault-crypto-secret", sessionSecret: "" } as { cryptoSecret?: string; sessionSecret?: string },
collapseEntropy: false,
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => state.secret,
};
});
vi.mock("node:crypto", async () => {
const actual = await vi.importActual<typeof import("node:crypto")>("node:crypto");
return {
...actual,
// When collapsed, every random byte is 0 → every generated character is the
// first alphabet entry → all codes are identical → the uniqueness retry
// loop is exhausted. Real HMAC/equality stay intact via `actual`.
randomBytes: (size: number) =>
state.collapseEntropy ? Buffer.alloc(size, 0) : (actual.randomBytes as (n: number) => Buffer)(size),
};
});
import { generateRecoveryCodes, hashRecoveryCode } from "./recovery-codes.server";
describe("recovery-codes.server (fault injection)", () => {
test("falls back to SESSION_SECRET when CRYPTO_SECRET is unset", () => {
state.secret = { cryptoSecret: "", sessionSecret: "session-fallback-secret" };
const hash = hashRecoveryCode("2345-6789-ABCD");
expect(hash).toMatch(/^[a-f0-9]{64}$/);
});
test("throws a configuration error when neither CRYPTO_SECRET nor SESSION_SECRET is set", () => {
state.secret = { cryptoSecret: "", sessionSecret: "" };
expect(() => hashRecoveryCode("2345-6789-ABCD")).toThrow("CRYPTO_SECRET or SESSION_SECRET env variable not set");
});
test("throws when unique recovery codes cannot be generated after the retry budget is exhausted", () => {
state.secret = { cryptoSecret: "fault-crypto-secret", sessionSecret: "" };
state.collapseEntropy = true;
try {
expect(() => generateRecoveryCodes({ count: 2 })).toThrow(
"Failed to generate unique recovery codes after retry; suspected entropy source failure.",
);
} finally {
state.collapseEntropy = false;
}
});
});