mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
A Guardian signed in through single sign-on with a second factor enrolled could not hand a managed profile over once five minutes had passed since sign-in: the handover answered 401 auth.stepup.required, and the panel printed "Confirm your second factor, then try again" with no way to do so. The same held for every action behind requireFreshMfa: creating, editing and ending a managed profile, adding and removing a Guardian, disabling the second factor, rotating recovery codes, removing a security key or a passkey, changing the password, the data wipe, account deletion and the key rotation. The recent-proof routes had the dialog; these had text. - requireFreshMfa names the proofs that clear a stale stamp in meta.methods (the possession proofs the account holds, never a password, which stamps reproofAt only). - The re-proof flow treats that refusal like auth.reproof.required: open the dialog, post the proof to /api/auth/reproof, send the request once more. The flow moves into a React-free module so it can be driven in tests; the hook binds it to the dialog. - The managed-profile mutation hooks take a required proof guard, and every caller passes recentProof.run. The other surfaces wrap their requests in recentProof.run; disabling the second factor asks before its confirmation opens, so the code typed there is not spent twice. - An account with nothing to re-prove in place (single sign-on only, no factor) is told to sign in again when adding a factor, instead of being offered a password it does not have. - step-up-web-caller-guard freezes the gated route methods and fails when a web request to one of them runs outside the flow. An account whose only second factor is the identity provider's is still asked for an app factor on the managed-profile acts: the app cannot see the provider's factor. Enrolling right after a sign-in needs no further proof, and the confirmation stamps the session, so the act follows. Refs #959
135 lines
4.8 KiB
TypeScript
135 lines
4.8 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
// Mirror require-fresh-mfa.test.ts mocking so the api-handler module loads
|
|
// without a live DB / request scope.
|
|
vi.mock("@/lib/db", () => ({
|
|
prisma: {
|
|
session: { findUnique: vi.fn() },
|
|
apiToken: { findUnique: vi.fn(), update: vi.fn() },
|
|
user: { findUnique: vi.fn() },
|
|
webauthnMfaCredential: { count: vi.fn() },
|
|
// The stale refusal names the proofs the account holds, passkeys among them.
|
|
passkey: { count: vi.fn() },
|
|
},
|
|
}));
|
|
|
|
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
|
vi.mock("@/lib/auth/hmac", () => ({ hashToken: vi.fn(() => "hash") }));
|
|
vi.mock("@/lib/auth/audit", () => ({
|
|
auditLog: vi.fn().mockResolvedValue(undefined),
|
|
}));
|
|
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
|
|
|
const headersGet = vi.fn<(name: string) => string | null>();
|
|
vi.mock("next/headers", () => ({
|
|
headers: vi.fn(async () => ({ get: headersGet })),
|
|
cookies: vi.fn(async () => ({
|
|
get: () => undefined,
|
|
set: () => {},
|
|
delete: () => {},
|
|
})),
|
|
}));
|
|
|
|
import {
|
|
requireFreshMfaIfEnrolled,
|
|
StepUpRequiredError,
|
|
HttpError,
|
|
MFA_STEP_UP_MAX_AGE_SECONDS,
|
|
} from "../api-handler";
|
|
import { getSession } from "@/lib/auth/session";
|
|
import { prisma } from "@/lib/db";
|
|
import { headers } from "next/headers";
|
|
import { auditLog } from "@/lib/auth/audit";
|
|
|
|
const MFA_USER = {
|
|
id: "user-1",
|
|
role: "USER" as const,
|
|
username: "u",
|
|
totpConfirmedAt: new Date("2020-01-01"),
|
|
};
|
|
const PLAIN_USER = { ...MFA_USER, totpConfirmedAt: null };
|
|
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
headersGet.mockReturnValue(null);
|
|
// resetAllMocks wipes the inline mock factory implementation too; restore
|
|
// the headers() wrapper so requireAuth's Bearer branch can read the header.
|
|
vi.mocked(headers).mockImplementation(
|
|
async () => ({ get: headersGet }) as never,
|
|
);
|
|
// resetAllMocks wipes the factory mockResolvedValue; auditLog is awaited
|
|
// via `.catch(...)` in the Bearer path, so it must return a thenable.
|
|
vi.mocked(auditLog).mockResolvedValue(undefined);
|
|
// Default: no registered security key, so a TOTP-less account is genuinely
|
|
// unenrolled and passes straight through.
|
|
vi.mocked(prisma.webauthnMfaCredential.count).mockResolvedValue(0 as never);
|
|
});
|
|
|
|
function mockCookieSession(user: unknown) {
|
|
vi.mocked(getSession).mockResolvedValue({
|
|
session: { id: "sess-1", expiresAt: new Date(Date.now() + 1e6) },
|
|
user,
|
|
} as never);
|
|
}
|
|
|
|
describe("requireFreshMfaIfEnrolled", () => {
|
|
it("passes a non-MFA user straight through without a freshness read", async () => {
|
|
mockCookieSession(PLAIN_USER);
|
|
const ctx = await requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS);
|
|
expect(ctx.user.id).toBe("user-1");
|
|
expect(prisma.session.findUnique).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("gates a security-key-only user (no TOTP) on step-up too", async () => {
|
|
mockCookieSession(PLAIN_USER);
|
|
vi.mocked(prisma.webauthnMfaCredential.count).mockResolvedValue(1 as never);
|
|
vi.mocked(prisma.session.findUnique).mockResolvedValue({
|
|
mfaVerifiedAt: null,
|
|
} as never);
|
|
await expect(
|
|
requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS),
|
|
).rejects.toBeInstanceOf(StepUpRequiredError);
|
|
});
|
|
|
|
it("passes an MFA user with a fresh verification", async () => {
|
|
mockCookieSession(MFA_USER);
|
|
vi.mocked(prisma.session.findUnique).mockResolvedValue({
|
|
mfaVerifiedAt: new Date(Date.now() - 60_000),
|
|
} as never);
|
|
const ctx = await requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS);
|
|
expect(ctx.user.id).toBe("user-1");
|
|
});
|
|
|
|
it("blocks an MFA user without a fresh verification", async () => {
|
|
mockCookieSession(MFA_USER);
|
|
vi.mocked(prisma.session.findUnique).mockResolvedValue({
|
|
mfaVerifiedAt: null,
|
|
} as never);
|
|
await expect(
|
|
requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS),
|
|
).rejects.toBeInstanceOf(StepUpRequiredError);
|
|
});
|
|
|
|
it("a Bearer token can never satisfy step-up for an MFA-enrolled account", async () => {
|
|
// requireAuth resolves the Bearer caller (no cookie), but the step-up read
|
|
// is cookie-only — getSession returns null inside requireFreshMfa.
|
|
vi.mocked(getSession).mockResolvedValue(null as never);
|
|
headersGet.mockImplementation((n) =>
|
|
n.toLowerCase() === "authorization" ? "Bearer hlk_xyz" : null,
|
|
);
|
|
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
|
|
id: "tok-1",
|
|
userId: "user-1",
|
|
permissions: ["*"],
|
|
revoked: false,
|
|
expiresAt: null,
|
|
} as never);
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue(MFA_USER as never);
|
|
vi.mocked(prisma.apiToken.update).mockResolvedValue({} as never);
|
|
|
|
await expect(
|
|
requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS),
|
|
).rejects.toBeInstanceOf(HttpError);
|
|
});
|
|
});
|