545 lines
24 KiB
TypeScript
545 lines
24 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(async () => ({
|
|
t: (key: string) =>
|
|
({
|
|
"shared.invalidForm": "Form not submitted correctly.",
|
|
"shared.unexpectedError": "Unexpected error",
|
|
"settings.profile.errors.firstNameRequired": "First name required",
|
|
"settings.profile.errors.invalidPassword": "Invalid password.",
|
|
"settings.profile.errors.passwordMinLength": "Passwords must have least 6 characters.",
|
|
"settings.profile.errors.currentPasswordRequired": "Current password is required.",
|
|
"settings.profile.errors.cannotDeleteAdmin": "Cannot delete an admin",
|
|
"settings.profile.passwordUpdated": "Password updated",
|
|
"settings.profile.mfa.enrollmentStarted": "Authenticator enrollment started",
|
|
"settings.profile.mfa.enabled": "Authenticator enabled",
|
|
"settings.profile.mfa.disabled": "Authenticator disabled",
|
|
"settings.profile.mfa.enterCode": "Enter the 6-digit authenticator code.",
|
|
"settings.profile.mfa.noPendingEnrollment": "No pending authenticator enrollment found.",
|
|
"settings.profile.mfa.invalidCode": "Invalid authenticator code.",
|
|
})[key] ?? key,
|
|
})),
|
|
}));
|
|
vi.mock("~/utils/loaders.middleware", () => ({
|
|
requireAuth: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({
|
|
getUserInfo: vi.fn(),
|
|
getUserSession: vi.fn(),
|
|
storage: { destroySession: vi.fn() },
|
|
validateCSRFToken: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/services/.server/urlService", () => ({
|
|
getTenantIdFromUrl: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/db/tenants.db.server", () => ({
|
|
getTenant: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/db.server", () => ({
|
|
db: {
|
|
user: {
|
|
findUnique: vi.fn(),
|
|
},
|
|
},
|
|
}));
|
|
vi.mock("~/utils/db/users.db.server", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("~/utils/db/users.db.server")>();
|
|
return {
|
|
...actual,
|
|
activateUserTotpPendingSecret: vi.fn(),
|
|
disableUserTotp: vi.fn(),
|
|
getUserTotpPendingEnrollment: vi.fn(),
|
|
getUserTotpStatus: vi.fn(),
|
|
setUserMfaRecoveryCodes: vi.fn(),
|
|
setUserTotpPendingSecret: vi.fn(),
|
|
updateUserPassword: vi.fn(),
|
|
updateUserProfile: vi.fn(),
|
|
};
|
|
});
|
|
vi.mock("~/services/auth/totp.server", () => ({
|
|
startTotpEnrollment: vi.fn(),
|
|
verifyTotpCode: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/auth/mfa/recovery-codes.server", () => ({
|
|
generateRecoveryCodes: vi.fn(),
|
|
}));
|
|
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
|
default: { create: vi.fn() },
|
|
}));
|
|
vi.mock("bcryptjs", () => ({
|
|
default: { compare: vi.fn(), hash: vi.fn() },
|
|
}));
|
|
vi.mock("~/utils/auth/passwordHasher.server", () => ({
|
|
hashPassword: vi.fn(async () => "new-hash"),
|
|
verifyPassword: vi.fn(async () => ({ valid: true })),
|
|
}));
|
|
vi.mock("~/services/auth/password-policy.server", () => ({
|
|
validatePassword: vi.fn(async () => ({ valid: true, errors: [] })),
|
|
loadPasswordPolicy: vi.fn(() => ({
|
|
minLength: 1,
|
|
requireUpper: false,
|
|
requireLower: false,
|
|
requireDigit: false,
|
|
requireSpecial: false,
|
|
hibpCheck: false,
|
|
hibpMaxOccurrences: 0,
|
|
})),
|
|
MIN_PASSWORD_LENGTH: 12,
|
|
}));
|
|
vi.mock("~/utils/integrations/storageService", () => ({ storeFile: vi.fn() }));
|
|
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
|
|
|
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
|
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
|
import EventsService from "~/modules/events/services/.server/EventsService";
|
|
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
|
import { startTotpEnrollment, verifyTotpCode } from "~/services/auth/totp.server";
|
|
import { db } from "~/utils/db.server";
|
|
import {
|
|
activateUserTotpPendingSecret,
|
|
disableUserTotp,
|
|
getUserTotpPendingEnrollment,
|
|
getUserTotpStatus,
|
|
setUserMfaRecoveryCodes,
|
|
setUserTotpPendingSecret,
|
|
updateUserPassword,
|
|
updateUserProfile,
|
|
} from "~/utils/db/users.db.server";
|
|
import { getTenant } from "~/utils/db/tenants.db.server";
|
|
import { requireAuth } from "~/utils/loaders.middleware";
|
|
import { getUserInfo, getUserSession, storage } from "~/utils/session.server";
|
|
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
|
import { storeFile } from "~/utils/integrations/storageService";
|
|
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
|
import { action, loader } from "./profile";
|
|
import { appendCSRFToken } from "~/utils/csrf";
|
|
|
|
const params = { tenant: "acme" };
|
|
const user = {
|
|
id: "user_1",
|
|
email: "ada@example.com",
|
|
passwordHash: "hashed-password",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
admin: null,
|
|
};
|
|
const tenant = { id: "tenant_1", slug: "acme" };
|
|
const disabledStatus = { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null };
|
|
const pendingStatus = { enabled: false, pending: true, enabledAt: null, pendingCreatedAt: new Date("2026-05-08T12:00:00.000Z") };
|
|
const enabledStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:05:00.000Z"), pendingCreatedAt: null };
|
|
const recoveryGeneratedAt = new Date("2026-05-08T12:05:01.000Z");
|
|
const recoveryCodes = ["ABCD-EFGH-JKLM", "NPQR-STUV-WXYZ"];
|
|
const recoveryEntries = recoveryCodes.map((code, index) => ({ hash: `hash-${index + 1}`, usedAt: null, createdAt: recoveryGeneratedAt }));
|
|
|
|
function postRequest(form: FormData) {
|
|
return new Request("https://app.example.test/acme/settings/profile", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams(form as unknown as Record<string, string>),
|
|
});
|
|
}
|
|
|
|
function formWithAction(actionName: string, values: Record<string, string> = {}) {
|
|
const form = new FormData();
|
|
appendCSRFToken(form);
|
|
form.set("action", actionName);
|
|
Object.entries(values).forEach(([key, value]) => form.set(key, value));
|
|
return form;
|
|
}
|
|
|
|
async function callAction(form: FormData) {
|
|
return action({
|
|
request: postRequest(form),
|
|
params,
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/settings/profile",
|
|
} as ActionFunctionArgs) as Promise<Response>;
|
|
}
|
|
|
|
async function json(response: Response) {
|
|
return response.json() as Promise<Record<string, unknown>>;
|
|
}
|
|
|
|
function expectNoSecretLeak(payload: unknown) {
|
|
const serialized = JSON.stringify(payload);
|
|
expect(serialized).not.toContain("RAWSECRET");
|
|
expect(serialized).not.toContain("encrypted-secret");
|
|
expect(serialized).not.toContain("encrypted-pending");
|
|
expect(serialized).not.toContain("123456");
|
|
expect(serialized).not.toContain("password-123");
|
|
expect(serialized).not.toContain("totpSecretEncrypted");
|
|
expect(serialized).not.toContain("secret");
|
|
expect(serialized).not.toContain("ABCD-EFGH-JKLM");
|
|
expect(serialized).not.toContain("NPQR-STUV-WXYZ");
|
|
expect(serialized).not.toContain("hash-1");
|
|
expect(serialized).not.toContain("hash-2");
|
|
}
|
|
|
|
describe("profile MFA route actions", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.mocked(requireAuth).mockResolvedValue(undefined as never);
|
|
vi.mocked(getUserInfo).mockResolvedValue({ userId: user.id } as never);
|
|
vi.mocked(getUserSession).mockResolvedValue({ id: "session_1", get: vi.fn(), set: vi.fn(), unset: vi.fn() } as never);
|
|
vi.mocked(storage.destroySession).mockResolvedValue("RJ_session=; Max-Age=0; Path=/; HttpOnly" as never);
|
|
vi.mocked(getTenantIdFromUrl).mockResolvedValue(tenant.id);
|
|
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
|
vi.mocked(db.user.findUnique).mockResolvedValue(user as never);
|
|
vi.mocked(updateUserProfile).mockResolvedValue({ ...user, avatar: "stored-avatar" } as never);
|
|
vi.mocked(updateUserPassword).mockResolvedValue({ ...user, passwordHash: "new-hash" } as never);
|
|
vi.mocked(storeFile).mockResolvedValue("stored-avatar" as never);
|
|
vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [{ id: tenant.id, name: "Acme" }] } as never);
|
|
vi.mocked(getUserTotpStatus).mockResolvedValue(disabledStatus);
|
|
vi.mocked(verifyPassword).mockResolvedValue({ valid: true });
|
|
vi.mocked(startTotpEnrollment).mockReturnValue({
|
|
secret: "RAWSECRET",
|
|
encryptedSecret: "encrypted-secret",
|
|
otpauthUri: "otpauth://totp/ToolCTRL:ada@example.com?secret=RAWSECRET&issuer=ToolCTRL",
|
|
qrValue: "otpauth://totp/ToolCTRL:ada@example.com?secret=RAWSECRET&issuer=ToolCTRL",
|
|
});
|
|
vi.mocked(verifyTotpCode).mockReturnValue(true);
|
|
vi.mocked(getUserTotpPendingEnrollment).mockResolvedValue({
|
|
totpPendingSecretEncrypted: "encrypted-pending",
|
|
totpPendingCreatedAt: pendingStatus.pendingCreatedAt,
|
|
});
|
|
vi.mocked(generateRecoveryCodes).mockReturnValue({
|
|
codes: recoveryCodes,
|
|
entries: recoveryEntries,
|
|
generatedAt: recoveryGeneratedAt,
|
|
});
|
|
});
|
|
|
|
it("loader exposes only non-secret MFA status for the current user", async () => {
|
|
const response = await loader({
|
|
request: new Request("https://app.example.test/acme/settings/profile"),
|
|
params,
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/settings/profile",
|
|
} as LoaderFunctionArgs);
|
|
|
|
expect(requireAuth).toHaveBeenCalled();
|
|
expect(getUserTotpStatus).toHaveBeenCalledWith(user.id);
|
|
expect(response).toMatchObject({ mfaStatus: disabledStatus });
|
|
expect(response).not.toHaveProperty("recoveryCodes");
|
|
expectNoSecretLeak(response);
|
|
});
|
|
|
|
it("starts TOTP enrollment after validating the current password", async () => {
|
|
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(disabledStatus).mockResolvedValueOnce(pendingStatus);
|
|
|
|
const response = await callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
|
expect(setUserTotpPendingSecret).toHaveBeenCalledWith(user.id, "encrypted-secret");
|
|
expect(body).toEqual({
|
|
success: "Authenticator enrollment started",
|
|
mfaStatus: { ...pendingStatus, pendingCreatedAt: pendingStatus.pendingCreatedAt?.toISOString() },
|
|
otpauthUri: expect.stringContaining("otpauth://"),
|
|
});
|
|
expect(JSON.stringify(body)).not.toContain("encrypted-secret");
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects start enrollment with a bad password without persisting pending state", async () => {
|
|
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
|
|
|
const response = await callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Invalid password." });
|
|
expect(setUserTotpPendingSecret).not.toHaveBeenCalled();
|
|
expectNoSecretLeak(body);
|
|
});
|
|
|
|
it("confirms pending TOTP enrollment and returns one-time recovery codes", async () => {
|
|
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(pendingStatus).mockResolvedValueOnce(enabledStatus);
|
|
|
|
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456", userId: "attacker" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(verifyTotpCode).toHaveBeenCalledWith("encrypted-pending", "123456");
|
|
expect(activateUserTotpPendingSecret).toHaveBeenCalledWith(user.id, "encrypted-pending");
|
|
expect(generateRecoveryCodes).toHaveBeenCalledTimes(1);
|
|
expect(setUserMfaRecoveryCodes).toHaveBeenCalledWith(user.id, recoveryEntries, recoveryGeneratedAt);
|
|
expect(JSON.stringify(vi.mocked(activateUserTotpPendingSecret).mock.calls)).not.toContain("attacker");
|
|
expect(body).toEqual({
|
|
success: "Authenticator enabled",
|
|
mfaStatus: { ...enabledStatus, enabledAt: enabledStatus.enabledAt?.toISOString() },
|
|
recoveryCodes,
|
|
});
|
|
expect(JSON.stringify(body)).not.toContain("hash-1");
|
|
expect(JSON.stringify(body)).not.toContain("hash-2");
|
|
const enabledEvent = vi.mocked(EventsService.create).mock.calls.at(-1)?.[0];
|
|
expect(enabledEvent?.data).toMatchObject({
|
|
recoveryCodes: { generatedCount: 2, remainingCount: 2, generatedAt: recoveryGeneratedAt },
|
|
});
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects invalid or missing TOTP codes before verification", async () => {
|
|
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "12ab56" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Enter the 6-digit authenticator code." });
|
|
expect(verifyTotpCode).not.toHaveBeenCalled();
|
|
expect(generateRecoveryCodes).not.toHaveBeenCalled();
|
|
expect(setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
|
expectNoSecretLeak(body);
|
|
});
|
|
|
|
it("rejects confirmation without a pending secret", async () => {
|
|
vi.mocked(getUserTotpPendingEnrollment).mockResolvedValue({ totpPendingSecretEncrypted: null, totpPendingCreatedAt: null });
|
|
|
|
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "No pending authenticator enrollment found." });
|
|
expect(activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
|
expectNoSecretLeak(body);
|
|
});
|
|
|
|
it("rejects invalid confirmation codes without activating pending state", async () => {
|
|
vi.mocked(verifyTotpCode).mockReturnValue(false);
|
|
|
|
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Invalid authenticator code." });
|
|
expect(activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
|
expect(generateRecoveryCodes).not.toHaveBeenCalled();
|
|
expect(setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
|
expectNoSecretLeak(body);
|
|
});
|
|
|
|
it("disables TOTP only after validating the current password", async () => {
|
|
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(enabledStatus).mockResolvedValueOnce(disabledStatus);
|
|
|
|
const response = await callAction(formWithAction("disableTotpEnrollment", { passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
|
expect(disableUserTotp).toHaveBeenCalledWith(user.id);
|
|
expect(body).toEqual({ success: "Authenticator disabled", mfaStatus: disabledStatus });
|
|
expectNoSecretLeak(body);
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects disabling without a password", async () => {
|
|
const response = await callAction(formWithAction("disableTotpEnrollment"));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Current password is required." });
|
|
expect(disableUserTotp).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("propagates unauthenticated rejection before reading or mutating MFA state", async () => {
|
|
const rejection = new Response(null, { status: 302, headers: { Location: "/login" } });
|
|
vi.mocked(requireAuth).mockRejectedValueOnce(rejection as never);
|
|
|
|
await expect(callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }))).rejects.toBe(rejection);
|
|
expect(getUserInfo).not.toHaveBeenCalled();
|
|
expect(setUserTotpPendingSecret).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("updates profile fields for the authenticated user and ignores tampered form user IDs", async () => {
|
|
const response = await callAction(
|
|
formWithAction("profile", {
|
|
userId: "attacker",
|
|
firstName: "Grace",
|
|
lastName: "Hopper",
|
|
avatar: "data:image/png;base64,avatar",
|
|
passwordCurrent: "password-123",
|
|
})
|
|
);
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(storeFile).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
bucket: "users-icons",
|
|
content: "data:image/png;base64,avatar",
|
|
id: user.id,
|
|
scan: expect.objectContaining({ context: "avatar", filename: `${user.id}.avatar` }),
|
|
})
|
|
);
|
|
expect(updateUserProfile).toHaveBeenCalledWith({ firstName: "Grace", lastName: "Hopper", avatar: "stored-avatar" }, user.id);
|
|
expect(JSON.stringify(vi.mocked(updateUserProfile).mock.calls)).not.toContain("attacker");
|
|
expect(body).toEqual({ success: "shared.updated" });
|
|
expect(vi.mocked(EventsService.create).mock.calls.at(-1)?.[0]).toMatchObject({
|
|
event: "user.profile.updated",
|
|
userId: user.id,
|
|
data: {
|
|
email: user.email,
|
|
new: { firstName: "Grace", lastName: "Hopper" },
|
|
old: { firstName: user.firstName, lastName: user.lastName },
|
|
userId: user.id,
|
|
},
|
|
});
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects invalid profile payloads before updating the authenticated user", async () => {
|
|
const response = await callAction(formWithAction("profile", { firstName: "A", lastName: "Hopper", userId: "attacker" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Form not submitted correctly.", fields: { firstName: "First name required" } });
|
|
expect(updateUserProfile).not.toHaveBeenCalled();
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("changes password only after comparing the current password and hashes the submitted new password", async () => {
|
|
// hashPassword mock is already set to return "new-hash" globally.
|
|
|
|
const response = await callAction(
|
|
formWithAction("password", {
|
|
userId: "attacker",
|
|
passwordCurrent: "password-123",
|
|
passwordNew: "new-password",
|
|
passwordNewConfirm: "new-password",
|
|
})
|
|
);
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
|
expect(hashPassword).toHaveBeenCalledWith("new-password");
|
|
expect(updateUserPassword).toHaveBeenCalledWith({ passwordHash: "new-hash" }, user.id);
|
|
expect(JSON.stringify(vi.mocked(updateUserPassword).mock.calls)).not.toContain("attacker");
|
|
expect(body).toEqual({ passwordSuccess: "Password updated" });
|
|
expect(vi.mocked(EventsService.create).mock.calls.at(-1)?.[0]).toMatchObject({
|
|
event: "user.password.updated",
|
|
userId: user.id,
|
|
data: { user: { id: user.id, email: user.email } },
|
|
});
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects bad current passwords before hashing or updating the password", async () => {
|
|
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
|
|
|
const response = await callAction(
|
|
formWithAction("password", { passwordCurrent: "password-123", passwordNew: "new-password", passwordNewConfirm: "new-password" })
|
|
);
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Invalid password." });
|
|
expect(hashPassword).not.toHaveBeenCalled();
|
|
expect(updateUserPassword).not.toHaveBeenCalled();
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects invalid password fields before comparing passwords", async () => {
|
|
vi.mocked(validatePolicyPassword).mockResolvedValueOnce({
|
|
valid: false,
|
|
errors: [{ code: "auth.password.errors.tooShort", args: { minLength: 12 } }],
|
|
});
|
|
const response = await callAction(formWithAction("password", { passwordCurrent: "password-123", passwordNew: "short", passwordNewConfirm: "short" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "auth.password.errors.tooShort" });
|
|
expect(verifyPassword).not.toHaveBeenCalled();
|
|
expect(updateUserPassword).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("deletes only the authenticated non-admin user and keeps deletion events redacted", async () => {
|
|
const response = await callAction(formWithAction("deleteAccount", { userId: "attacker", passwordCurrent: "password-123" }));
|
|
|
|
expect(response.status).toBe(302);
|
|
expect(response.headers.get("Location")).toBe("/login");
|
|
expect(getUserSession).toHaveBeenCalled();
|
|
expect(storage.destroySession).toHaveBeenCalledWith(expect.objectContaining({ id: "session_1" }));
|
|
expect(response.headers.get("Set-Cookie")).toContain("Max-Age=0");
|
|
expect(deleteUserWithItsTenants).toHaveBeenCalledWith(user.id);
|
|
expect(JSON.stringify(vi.mocked(deleteUserWithItsTenants).mock.calls)).not.toContain("attacker");
|
|
expect(vi.mocked(EventsService.create).mock.calls).toHaveLength(2);
|
|
expect(vi.mocked(EventsService.create).mock.calls[0][0]).toMatchObject({
|
|
event: "account.deleted",
|
|
userId: null,
|
|
data: { tenant: { id: tenant.id, name: "Acme" }, user: { id: user.id, email: user.email } },
|
|
});
|
|
expect(vi.mocked(EventsService.create).mock.calls[1][0]).toMatchObject({
|
|
event: "user.profile.deleted",
|
|
userId: null,
|
|
data: { id: user.id, email: user.email, firstName: user.firstName, lastName: user.lastName },
|
|
});
|
|
expectNoSecretLeak(vi.mocked(EventsService.create).mock.calls);
|
|
});
|
|
|
|
it("rejects account deletion without the current password", async () => {
|
|
const response = await callAction(formWithAction("deleteAccount"));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Current password is required." });
|
|
expect(verifyPassword).not.toHaveBeenCalled();
|
|
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects account deletion with an invalid current password", async () => {
|
|
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
|
|
|
const response = await callAction(formWithAction("deleteAccount", { passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Invalid password." });
|
|
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
|
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns an error when the deletion service fails after password validation", async () => {
|
|
vi.mocked(deleteUserWithItsTenants).mockRejectedValueOnce(new Error("delete failed") as never);
|
|
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
|
|
|
const response = await callAction(formWithAction("deleteAccount", { passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Unexpected error" });
|
|
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
expect(storage.destroySession).not.toHaveBeenCalled();
|
|
expect(consoleError).toHaveBeenCalledWith(expect.any(Error));
|
|
consoleError.mockRestore();
|
|
});
|
|
|
|
it("rejects admin account deletion before deleting user data", async () => {
|
|
vi.mocked(db.user.findUnique).mockResolvedValueOnce({ ...user, admin: { id: "admin_1" } } as never);
|
|
|
|
const response = await callAction(formWithAction("deleteAccount", { userId: "attacker", passwordCurrent: "password-123" }));
|
|
const body = await json(response);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(body).toEqual({ error: "Cannot delete an admin" });
|
|
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
|
expect(EventsService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("propagates unauthenticated rejection before profile, password, or delete mutations", async () => {
|
|
const rejection = new Response(null, { status: 302, headers: { Location: "/login" } });
|
|
vi.mocked(requireAuth).mockRejectedValueOnce(rejection as never);
|
|
|
|
await expect(callAction(formWithAction("profile", { firstName: "Grace", lastName: "Hopper" }))).rejects.toBe(rejection);
|
|
expect(getUserInfo).not.toHaveBeenCalled();
|
|
expect(updateUserProfile).not.toHaveBeenCalled();
|
|
expect(updateUserPassword).not.toHaveBeenCalled();
|
|
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
|
});
|
|
});
|