227 lines
9.6 KiB
TypeScript
227 lines
9.6 KiB
TypeScript
import { memoryAdapter } from "better-auth/adapters/memory";
|
|
import { expect, test, vi } from "vitest";
|
|
|
|
import { POST } from "@/app/api/auth/[...all]/route";
|
|
|
|
import { createPortalAuth, createRegistrationIngress } from "./auth";
|
|
import { CURRENT_TERMS_VERSION } from "./registration";
|
|
|
|
test("allows the trusted registration service ingress while rejecting public direct sign-up", async () => {
|
|
const registrationRepository = {
|
|
createEditorial: vi.fn(),
|
|
markPendingApproval: vi.fn(),
|
|
removeUnverifiedAuthIdentity: vi.fn(),
|
|
recordRegistrationCompensationFailure: vi.fn(),
|
|
recordVerificationInconsistency: vi.fn(),
|
|
canCreateSession: vi.fn().mockResolvedValue(false),
|
|
};
|
|
const { registrationService } = createPortalAuth({
|
|
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
|
|
mailerService: {
|
|
sendPasswordReset: vi.fn(),
|
|
sendVerification: vi.fn(),
|
|
},
|
|
registrationRepository,
|
|
});
|
|
|
|
await expect(
|
|
registrationService.register({
|
|
companyName: "Registration GmbH",
|
|
contactName: "Registration Service",
|
|
email: "registration@example.com",
|
|
password: "sicheres-passwort-123",
|
|
billingAddress: {
|
|
addressLine1: "Presseweg 1",
|
|
postalCode: "10115",
|
|
city: "Berlin",
|
|
countryCode: "DE",
|
|
},
|
|
actsForBusiness: true,
|
|
termsVersion: CURRENT_TERMS_VERSION,
|
|
privacyAcknowledged: true,
|
|
}),
|
|
).resolves.toEqual({ status: "pending_email" });
|
|
|
|
expect(registrationRepository.createEditorial).toHaveBeenCalledTimes(1);
|
|
|
|
const response = await POST(
|
|
new Request("http://localhost:3000/api/auth/sign-up/email", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({
|
|
email: "bypass@example.com",
|
|
name: "Bypass",
|
|
password: "sicheres-passwort-123",
|
|
}),
|
|
}),
|
|
{ params: Promise.resolve({ all: ["sign-up", "email"] }) },
|
|
);
|
|
|
|
expect(response.status).toBe(403);
|
|
});
|
|
|
|
test("rate-limits registration by a hashed email and proxy identity before sign-up", async () => {
|
|
const register = vi.fn();
|
|
const consume = vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 120 });
|
|
const ingress = createRegistrationIngress({ register, consumeRateLimit: consume });
|
|
|
|
await expect(
|
|
ingress(
|
|
{
|
|
companyName: "Beispiel GmbH",
|
|
contactName: "Max Beispiel",
|
|
email: "Redaktion@Example.com",
|
|
password: "sicheres-passwort-123",
|
|
billingAddress: {
|
|
addressLine1: "Presseweg 1",
|
|
postalCode: "10115",
|
|
city: "Berlin",
|
|
countryCode: "DE",
|
|
},
|
|
actsForBusiness: true,
|
|
termsVersion: CURRENT_TERMS_VERSION,
|
|
privacyAcknowledged: true,
|
|
},
|
|
new Headers({ "x-real-ip": "203.0.113.8" }),
|
|
),
|
|
).rejects.toMatchObject({ name: "RateLimitExceededError", retryAfterSeconds: 120 });
|
|
|
|
expect(consume).toHaveBeenCalledWith(expect.stringMatching(/^registration:[a-f0-9]{64}$/), expect.any(Object));
|
|
expect(register).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("keeps Better Auth login limits separate for clients forwarded by Zoraxy", async () => {
|
|
const registrationRepository = {
|
|
createEditorial: vi.fn(),
|
|
markPendingApproval: vi.fn(),
|
|
removeUnverifiedAuthIdentity: vi.fn(),
|
|
recordRegistrationCompensationFailure: vi.fn(),
|
|
recordVerificationInconsistency: vi.fn(),
|
|
canCreateSession: vi.fn().mockResolvedValue(false),
|
|
};
|
|
const { auth } = createPortalAuth({
|
|
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
|
|
mailerService: { sendPasswordReset: vi.fn(), sendVerification: vi.fn() },
|
|
registrationRepository,
|
|
});
|
|
const signIn = (forwardedFor: string) =>
|
|
auth.handler(
|
|
new Request("http://localhost:3000/api/auth/sign-in/email", {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
"x-forwarded-for": forwardedFor,
|
|
},
|
|
body: JSON.stringify({ email: "nobody@example.com", password: "invalid-password" }),
|
|
}),
|
|
);
|
|
|
|
for (let attempt = 0; attempt < 5; attempt += 1) await signIn("203.0.113.10");
|
|
const otherClient = await signIn("203.0.113.11");
|
|
|
|
expect(otherClient.status).not.toBe(429);
|
|
});
|
|
|
|
test("Better Auth grants admin access only to the session that completed MFA", async () => {
|
|
const password = "dummy-admin-password";
|
|
const email = "mfa-admin@example.test";
|
|
const userId = crypto.randomUUID();
|
|
const { hashPassword, symmetricDecrypt } = await import("better-auth/crypto");
|
|
const { createPrincipalGuard } = await import("./principal");
|
|
const state = {
|
|
user: [{ id: userId, email, name: "Test Admin", role: "ADMIN" as const, emailVerified: true,
|
|
twoFactorEnabled: false, createdAt: new Date(), updatedAt: new Date() }],
|
|
account: [{ id: crypto.randomUUID(), userId, providerId: "credential", accountId: userId,
|
|
password: await hashPassword(password), createdAt: new Date(), updatedAt: new Date() }],
|
|
session: [],
|
|
verification: [],
|
|
twoFactor: [] as Array<{ secret: string }>,
|
|
};
|
|
const sendPasswordReset = vi.fn<(input: { to: string; resetUrl: string }) => Promise<void>>();
|
|
const { auth } = createPortalAuth({
|
|
database: memoryAdapter(state),
|
|
mailerService: { sendPasswordReset, sendVerification: vi.fn() },
|
|
registrationRepository: {
|
|
createEditorial: vi.fn(), markPendingApproval: vi.fn(), removeUnverifiedAuthIdentity: vi.fn(),
|
|
recordRegistrationCompensationFailure: vi.fn(), recordVerificationInconsistency: vi.fn(),
|
|
canCreateSession: vi.fn().mockResolvedValue(true),
|
|
},
|
|
});
|
|
const post = (path: string, body: object, cookie?: string) =>
|
|
auth.handler(new Request(`http://localhost:3000/api/auth/${path}`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
|
|
body: JSON.stringify(body),
|
|
}));
|
|
function responseCookie(response: Response, name: string) {
|
|
const header = response.headers.getSetCookie().find((value) => value.startsWith(`better-auth.${name}=`));
|
|
expect(header).toBeDefined();
|
|
return header!.split(";")[0];
|
|
}
|
|
const headers = (cookie: string) => new Headers({ cookie });
|
|
const guard = createPrincipalGuard({
|
|
async getSession(requestHeaders) {
|
|
const session = await auth.api.getSession({ headers: requestHeaders });
|
|
return session?.user.role === "ADMIN"
|
|
? { ...session, user: { ...session.user, role: "ADMIN", twoFactorEnabled: session.user.twoFactorEnabled === true } }
|
|
: null;
|
|
},
|
|
getAccount: async () => null,
|
|
});
|
|
const login = () => post("sign-in/email", { email, password });
|
|
const first = responseCookie(await login(), "session_token");
|
|
const second = responseCookie(await login(), "session_token");
|
|
expect(first).not.toEqual(second);
|
|
const setup = await post("two-factor/enable", { password, method: "totp" }, first);
|
|
expect(setup.status).toBe(200);
|
|
const { method, backupCodes } = await setup.json();
|
|
expect(method).toBe("totp");
|
|
const secret = await symmetricDecrypt({
|
|
key: (await auth.$context).secretConfig, data: state.twoFactor[0].secret,
|
|
});
|
|
const { code } = await auth.api.generateTOTP({ body: { secret } });
|
|
const verified = await post("two-factor/verify-totp", { code }, first);
|
|
expect(verified.status).toBe(200);
|
|
const rotated = responseCookie(verified, "session_token");
|
|
|
|
await expect(guard.requireAdmin(headers(rotated))).resolves.toMatchObject({ userId });
|
|
await expect(guard.requireAdmin(headers(second))).rejects.toMatchObject({ code: "AUTHENTICATION_REQUIRED" });
|
|
expect((await post("two-factor/disable", { password }, second)).status).toBe(401);
|
|
|
|
const challenge = await login();
|
|
expect(await challenge.clone().json()).toMatchObject({ twoFactorRedirect: true });
|
|
const challengeCookie = responseCookie(challenge, "two_factor");
|
|
const signedIn = await post("two-factor/verify-totp", { code }, challengeCookie);
|
|
expect(signedIn.status).toBe(200);
|
|
const signedInCookie = responseCookie(signedIn, "session_token");
|
|
await expect(guard.requireAdmin(headers(signedInCookie))).resolves.toMatchObject({ userId });
|
|
|
|
const backupChallenge = responseCookie(await login(), "two_factor");
|
|
const backup = await post("two-factor/verify-backup-code", { code: backupCodes[0] }, backupChallenge);
|
|
expect(backup.status).toBe(200);
|
|
await expect(guard.requireAdmin(headers(responseCookie(backup, "session_token"))))
|
|
.resolves.toMatchObject({ userId });
|
|
|
|
const disabled = await post("two-factor/disable", { password }, signedInCookie);
|
|
expect(disabled.status).toBe(200);
|
|
expect(await auth.api.getSession({ headers: headers(rotated) })).toBeNull();
|
|
const preResetCookie = responseCookie(disabled, "session_token");
|
|
|
|
const resetRequest = await post("request-password-reset", {
|
|
email, redirectTo: "http://localhost:3000/passwort-zuruecksetzen",
|
|
});
|
|
expect(resetRequest.status).toBe(200);
|
|
expect(sendPasswordReset).toHaveBeenCalledOnce();
|
|
const resetUrl = new URL(sendPasswordReset.mock.calls[0][0].resetUrl);
|
|
const token = resetUrl.pathname.split("/").at(-1);
|
|
const newPassword = "dummy-updated-admin-password";
|
|
expect((await post("reset-password", { token, newPassword })).status).toBe(200);
|
|
expect(await auth.api.getSession({ headers: headers(preResetCookie) })).toBeNull();
|
|
|
|
const afterReset = responseCookie(await post("sign-in/email", { email, password: newPassword }), "session_token");
|
|
const signedOut = await post("sign-out", {}, afterReset);
|
|
expect(signedOut.status).toBe(200);
|
|
await expect(signedOut.json()).resolves.toMatchObject({ success: true });
|
|
expect(await auth.api.getSession({ headers: headers(afterReset) })).toBeNull();
|
|
});
|