Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+1
-1
@@ -40,7 +40,7 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
|
||||
import { getUserByEmail } from "~/utils/db/users.db.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
+203
-14
@@ -29,6 +29,9 @@ vi.mock("~/utils/session.server", () => ({
|
||||
setLoggedUser: vi.fn().mockResolvedValue({ userId: "u1", defaultTenantId: "t1", defaultTenant: { id: "t1", slug: "t1" } }),
|
||||
validateCSRFToken: vi.fn(),
|
||||
commitPendingMfaLoginCookie: vi.fn().mockResolvedValue("hivegrid_session=pending; Path=/; HttpOnly"),
|
||||
isPendingMfaLoginFresh: vi.fn().mockReturnValue(true),
|
||||
isPendingMfaPrimaryMethod: vi.fn((value: unknown) => ["admin-sso", "password", "magic-link", "password-reset", "invitation"].includes(String(value))),
|
||||
PENDING_MFA_PRIMARY_METHOD_KEY: "pendingMfaPrimaryMethod",
|
||||
}));
|
||||
vi.mock("~/services/auth/sessionLifecycle.server", () => ({ startServerSession: vi.fn().mockResolvedValue("server-token") }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn().mockResolvedValue({ id: "t1", slug: "t1" }) }));
|
||||
@@ -36,6 +39,14 @@ vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: v
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({ verifyPassword: vi.fn().mockResolvedValue({ valid: true, rehashedHash: null }) }));
|
||||
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({ default: { log: vi.fn().mockResolvedValue(null) } }));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({ validatePassword: vi.fn().mockResolvedValue({ valid: true, errors: [] }) }));
|
||||
vi.mock("~/services/auth/admin-fallback.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/auth/admin-fallback.server")>("~/services/auth/admin-fallback.server");
|
||||
return {
|
||||
...actual,
|
||||
assertAdminFallbackLoginAllowedForIdentity: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("~/modules/admin-sso/audit.server", () => ({ writeAdminSsoAuditEvent: vi.fn() }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockReturnValue(0),
|
||||
@@ -57,7 +68,7 @@ vi.mock("~/utils/auth/mfa/challenge-rate-limit.server", () => ({
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/trusted-device.server", () => ({
|
||||
isTrustedDevice: vi.fn().mockResolvedValue(false),
|
||||
rememberDeviceForUser: vi.fn().mockResolvedValue("hivegrid_trusted_device=marker; Path=/; HttpOnly"),
|
||||
rememberDeviceForUser: vi.fn().mockResolvedValue("__Host-hivegrid_trusted_device=marker; Path=/; HttpOnly; Secure"),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
||||
@@ -65,17 +76,26 @@ vi.mock("@hivegrid/config", async () => {
|
||||
...actual,
|
||||
loadRequiredWebConfig: () => ({
|
||||
nodeEnv: "test",
|
||||
routing: { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", protocol: "https" },
|
||||
routing: {
|
||||
appBaseDomain: "example.com",
|
||||
webAppHost: "app.example.com",
|
||||
adminAppHost: "admin.example.com",
|
||||
apiHost: "api.example.com",
|
||||
protocol: "https",
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
|
||||
import { getUserByEmail, getUser, getUserTotpStatus, getActiveTotpSecretEncrypted, consumeUserMfaRecoveryCode } from "~/utils/db/users.db.server";
|
||||
import { createUserSession, getUserSession, commitPendingMfaLoginCookie } from "~/utils/session.server";
|
||||
import { createUserSession, getUserSession, commitPendingMfaLoginCookie, isPendingMfaLoginFresh } from "~/utils/session.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { checkMfaChallengeRateLimit, recordFailedMfaChallengeAttempt, resetMfaChallengeRateLimit } from "~/utils/auth/mfa/challenge-rate-limit.server";
|
||||
import { isTrustedDevice, rememberDeviceForUser } from "~/utils/auth/mfa/trusted-device.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { AdminFallbackLoginRejected, assertAdminFallbackLoginAllowedForIdentity } from "~/services/auth/admin-fallback.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
const getUserByEmailMock = vi.mocked(getUserByEmail);
|
||||
@@ -86,9 +106,13 @@ const consumeUserMfaRecoveryCodeMock = vi.mocked(consumeUserMfaRecoveryCode);
|
||||
const createUserSessionMock = vi.mocked(createUserSession);
|
||||
const getUserSessionMock = vi.mocked(getUserSession);
|
||||
const commitPendingMfaLoginCookieMock = vi.mocked(commitPendingMfaLoginCookie);
|
||||
const isPendingMfaLoginFreshMock = vi.mocked(isPendingMfaLoginFresh);
|
||||
const verifyTotpCodeMock = vi.mocked(verifyTotpCode);
|
||||
const checkMfaChallengeRateLimitMock = vi.mocked(checkMfaChallengeRateLimit);
|
||||
const isTrustedDeviceMock = vi.mocked(isTrustedDevice);
|
||||
const verifyPasswordMock = vi.mocked(verifyPassword);
|
||||
const assertAdminFallbackLoginAllowedForIdentityMock = vi.mocked(assertAdminFallbackLoginAllowedForIdentity);
|
||||
const writeAdminSsoAuditEventMock = vi.mocked(writeAdminSsoAuditEvent);
|
||||
|
||||
const baseUser = { id: "u1", email: "alice@example.com", passwordHash: "hash", admin: null, locale: "de", defaultTenantId: "t1" };
|
||||
|
||||
@@ -116,6 +140,7 @@ beforeEach(() => {
|
||||
createUserSessionMock.mockImplementation(async () => redirectResponse());
|
||||
isTrustedDeviceMock.mockResolvedValue(false);
|
||||
checkMfaChallengeRateLimitMock.mockResolvedValue({ allowed: true, remaining: 5, resetAt: new Date() } as never);
|
||||
isPendingMfaLoginFreshMock.mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe("loginFromRequest — 2FA gate", () => {
|
||||
@@ -129,50 +154,214 @@ describe("loginFromRequest — 2FA gate", () => {
|
||||
expect(body.requiresMfa).toBe(true);
|
||||
expect(body.mfaVerifyPath).toBe("/login-mfa");
|
||||
expect(response.headers.get("Set-Cookie")).toContain("hivegrid_session=pending");
|
||||
expect(commitPendingMfaLoginCookieMock).toHaveBeenCalledWith(expect.any(Request), { userId: "u1", redirectTo: "" });
|
||||
expect(commitPendingMfaLoginCookieMock).toHaveBeenCalledWith(expect.any(Request), {
|
||||
userId: "u1",
|
||||
redirectTo: "",
|
||||
primaryMethod: "password",
|
||||
});
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips the gate for a trusted device and issues a normal session", async () => {
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
|
||||
isTrustedDeviceMock.mockResolvedValue(true);
|
||||
const request = new Request("https://app.example.com/login", { method: "POST" });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const response = await AuthService.loginFromRequest(request, loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("logs a non-TOTP user straight in (regression: branch is additive)", async () => {
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: false } as never);
|
||||
const request = new Request("https://app.example.com/login", { method: "POST" });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const response = await AuthService.loginFromRequest(request, loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("blocks a resolved AdminUser on the public app host when emergency fallback is disabled", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
assertAdminFallbackLoginAllowedForIdentityMock.mockImplementationOnce(() => {
|
||||
throw new AdminFallbackLoginRejected("disabled");
|
||||
});
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const body = (await response.json()) as Record<string, unknown>;
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body.error).toBe("api.errors.invalidPassword");
|
||||
expect(getUserTotpStatusMock).not.toHaveBeenCalled();
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", reason: "disabled" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("allows an allowlisted AdminUser and audits only the completed session", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: false } as never);
|
||||
createUserSessionMock.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { Location: "https://admin.example.com/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; HttpOnly; Secure" },
|
||||
})
|
||||
);
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://admin.example.com/login", { method: "POST" }), loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).toHaveBeenCalledWith(expect.objectContaining({ email: "alice@example.com" }));
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", severity: "warn" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps wrong-password responses identity-agnostic before evaluating admin fallback", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
verifyPasswordMock.mockResolvedValueOnce({ valid: false, rehashedHash: null });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyMfaLoginFromRequest", () => {
|
||||
beforeEach(() => {
|
||||
getUserSessionMock.mockResolvedValue(sessionMock({ pendingMfaUserId: "u1", pendingMfaRedirectTo: "" }) as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "password",
|
||||
}) as never
|
||||
);
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
|
||||
});
|
||||
|
||||
it("rejects an expired pending challenge before checking a second factor", async () => {
|
||||
isPendingMfaLoginFreshMock.mockReturnValueOnce(false);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
await expect(AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form)).rejects.toMatchObject({
|
||||
status: 302,
|
||||
});
|
||||
|
||||
expect(getUserMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("completes the login on a valid TOTP code", async () => {
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
const request = new Request("https://app.example.com/login-mfa", { method: "POST" });
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(request, form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(verifyTotpCodeMock).toHaveBeenCalledWith("enc-secret", "123456");
|
||||
expect(resetMfaChallengeRateLimit).toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("re-checks a password-fallback AdminUser after MFA and blocks a policy revoked during the challenge", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
assertAdminFallbackLoginAllowedForIdentityMock.mockImplementationOnce(() => {
|
||||
throw new AdminFallbackLoginRejected("disabled");
|
||||
});
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
await expect(AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form)).rejects.toMatchObject({
|
||||
status: 302,
|
||||
});
|
||||
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", stage: "mfa-complete", reason: "disabled" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("audits a completed allowlisted magic-link AdminUser MFA session", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "magic-link",
|
||||
}) as never
|
||||
);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
createUserSessionMock.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { Location: "https://admin.example.com/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; HttpOnly; Secure" },
|
||||
})
|
||||
);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://admin.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "magic-link", mfa: true, severity: "warn" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("allows signed Authentik MFA assurance without applying fallback policy", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "admin-sso",
|
||||
}) as never
|
||||
);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(verifyTotpCodeMock).toHaveBeenCalledWith("enc-secret", "123456");
|
||||
expect(resetMfaChallengeRateLimit).toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("completes the login on a valid recovery code when TOTP fails", async () => {
|
||||
@@ -200,7 +389,7 @@ describe("verifyMfaLoginFromRequest", () => {
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(rememberDeviceForUser).toHaveBeenCalledWith({ request: expect.any(Request), userId: "u1" });
|
||||
expect(response.headers.getSetCookie?.().some((c) => c.includes("hivegrid_trusted_device")) ?? true).toBe(true);
|
||||
expect(response.headers.getSetCookie?.().some((c) => c.includes("__Host-hivegrid_trusted_device")) ?? true).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a wrong code without issuing a session", async () => {
|
||||
|
||||
+7
-2
@@ -49,8 +49,13 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockResolvedValue(0),
|
||||
loginRequiresCaptcha: vi.fn().mockReturnValue(false),
|
||||
recordFailedLogin: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({
|
||||
validatePassword: vi.fn(),
|
||||
}));
|
||||
|
||||
+55
-2
@@ -48,16 +48,24 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockResolvedValue(0),
|
||||
loginRequiresCaptcha: vi.fn().mockReturnValue(false),
|
||||
recordFailedLogin: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getUserByEmail } from "~/utils/db/users.db.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { recordFailedLogin } from "~/services/auth/login-captcha-gate.server";
|
||||
import { setLoggedUser } from "~/utils/session.server";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
const getUserByEmailMock = vi.mocked(getUserByEmail);
|
||||
const verifyPasswordMock = vi.mocked(verifyPassword);
|
||||
const recordFailedLoginMock = vi.mocked(recordFailedLogin);
|
||||
const setLoggedUserMock = vi.mocked(setLoggedUser);
|
||||
|
||||
function buildForm(): FormData {
|
||||
@@ -98,6 +106,8 @@ describe("AuthService magic-link-only account guard (#20)", () => {
|
||||
const body = await result.json();
|
||||
// Anti-enumeration: identical to the unknown-email / wrong-password path.
|
||||
expect(body.error).toBe("api.errors.invalidPassword");
|
||||
expect(body.fields).toEqual({ email: "invited@example.com" });
|
||||
expect(JSON.stringify(body)).not.toContain("anything-they-typed");
|
||||
expect(body.requiresMagicLink).toBeUndefined();
|
||||
expect(body.magicLinkHref).toBeUndefined();
|
||||
// Timing side-channel closed: the dummy-hash comparison runs anyway.
|
||||
@@ -105,4 +115,47 @@ describe("AuthService magic-link-only account guard (#20)", () => {
|
||||
// Critical: must never have created a session on a null-hash row.
|
||||
expect(setLoggedUserMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a disabled account generically before creating a session", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({
|
||||
id: "u-disabled",
|
||||
email: "invited@example.com",
|
||||
passwordHash: "$argon2id$valid",
|
||||
firstName: "Disabled",
|
||||
lastName: "User",
|
||||
active: false,
|
||||
pendingDeletion: false,
|
||||
pseudonymized: false,
|
||||
admin: null,
|
||||
locale: null,
|
||||
} as unknown as Awaited<ReturnType<typeof getUserByEmail>>);
|
||||
|
||||
const req = new Request("https://app.example.com/login", { method: "POST" });
|
||||
const result = (await AuthService.loginFromRequest(req, buildForm())) as Response;
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
await expect(result.json()).resolves.toMatchObject({
|
||||
error: "api.errors.invalidPassword",
|
||||
fields: { email: "invited@example.com" },
|
||||
});
|
||||
expect(verifyPasswordMock).toHaveBeenCalledTimes(1);
|
||||
expect(recordFailedLoginMock).toHaveBeenCalledWith({
|
||||
request: req,
|
||||
identifier: "invited@example.com",
|
||||
});
|
||||
expect(setLoggedUserMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not expose an unexpected IP logging error to the user", async () => {
|
||||
getUserByEmailMock.mockResolvedValue(null);
|
||||
vi.mocked(IpAddressServiceServer.log).mockRejectedValueOnce(new Error("database connection details"));
|
||||
|
||||
const result = (await AuthService.loginFromRequest(
|
||||
new Request("https://app.example.com/login", { method: "POST" }),
|
||||
buildForm()
|
||||
)) as Response;
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
await expect(result.json()).resolves.toEqual({ error: "shared.unexpectedError" });
|
||||
});
|
||||
});
|
||||
+793
-73
File diff suppressed because it is too large.
Load diff
+416
-86
@@ -1,9 +1,21 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { createLogLogin } from "~/utils/db/logs.db.server";
|
||||
import { getUserByEmail, getUser, getUserTotpStatus, getActiveTotpSecretEncrypted, consumeUserMfaRecoveryCode } from "~/utils/db/users.db.server";
|
||||
import { setLoggedUser, createUserSession, getUserInfo, getUserSession, validateCSRFToken, commitPendingMfaLoginCookie } from "~/utils/session.server";
|
||||
import { startServerSession } from "~/services/auth/sessionLifecycle.server";
|
||||
import {
|
||||
setLoggedUser,
|
||||
createUserSession,
|
||||
getUserInfo,
|
||||
getUserSession,
|
||||
validateCSRFToken,
|
||||
commitPendingMfaLoginCookie,
|
||||
isPendingMfaLoginFresh,
|
||||
isPendingMfaPrimaryMethod,
|
||||
PENDING_MFA_PRIMARY_METHOD_KEY,
|
||||
} from "~/utils/session.server";
|
||||
import { updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import {
|
||||
@@ -14,10 +26,16 @@ import {
|
||||
} from "~/utils/auth/mfa/challenge-rate-limit.server";
|
||||
import { isTrustedDevice, rememberDeviceForUser } from "~/utils/auth/mfa/trusted-device.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getRegistrationFormData, validateRegistration, createRegistrationForm } from "~/utils/services/authService";
|
||||
import { getRegistrationByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import {
|
||||
createRegistrationForm,
|
||||
getRegistrationFormData,
|
||||
isSignupCreationRequestKey,
|
||||
RegistrationValidationError,
|
||||
resolvePendingRegistrationResendRecovery,
|
||||
validateRegistration,
|
||||
} from "~/utils/services/authService";
|
||||
import { getRegistrationVerificationStateByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import { Params, redirect } from "react-router";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
import { isCanonicalAdminHostRoute } from "~/utils/app/HostRouting.server";
|
||||
@@ -29,10 +47,28 @@ import { clearFailedLogins, getFailedLoginCount, loginRequiresCaptcha, recordFai
|
||||
import { getSecret, getSitekey, isCaptchaConfigured, resolveCaptchaConfig, verifyCaptchaToken } from "@hivegrid/captcha";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import {
|
||||
AdminFallbackLoginRejected,
|
||||
assertAdminFallbackLoginAllowedForIdentity,
|
||||
isCompletedAdminFallbackLoginResponse,
|
||||
} from "~/services/auth/admin-fallback.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import { deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
|
||||
import {
|
||||
clearRegistrationResendRecovery,
|
||||
commitRegistrationResendRecovery,
|
||||
readRegistrationResendRecovery,
|
||||
} from "~/services/auth/registration-resend-recovery.server";
|
||||
|
||||
const authLogger = createScopedLogger("auth");
|
||||
|
||||
const DUMMY_PASSWORD_HASH = "$2a$10$7EqJtq98hPqEX7fNZaFWoOhi8VfIf6z9SjG8/aYx8vvjE5LiE3D0C";
|
||||
const DUMMY_PASSWORD_HASH = "$argon2id$v=19$m=19456,t=2,p=1$CGZ841jS/Rerhh41+cREiw$piaCzFMbzHjq946K2t0iN7iMI/389iUpLNm2HROGO4Y";
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT = 5;
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
function registrationVerifyRateLimitIdentifier(token: string): string {
|
||||
return createHash("sha256").update("registration-verify:v1\0").update(token).digest("hex");
|
||||
}
|
||||
|
||||
// D1 — tenant-faehige Verify-Route, an die das Login nach Passwort-OK fuer den zweiten Faktor
|
||||
// weiterleitet (siehe routeModules/auth/login-mfa).
|
||||
@@ -56,38 +92,48 @@ function translateIpAddressError(t: (key: string) => string, error: string): str
|
||||
if (error === "unauthorized") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return error;
|
||||
return t("shared.unexpectedError");
|
||||
}
|
||||
|
||||
// The demo-login gate is a RUNTIME switch, not a seeding switch. It used to ride
|
||||
// on SEED_DEMO_DATA / ALLOW_STAGING_DEMO_SEED / SEED_DEMO_PRO_MANAGED, but the
|
||||
// RLS deploy contract forbids every SEED_*-prefixed key on a runtime resource
|
||||
// (`assert-runtime-db-env` rejects them, and seeding is not approved under forced
|
||||
// RLS). Carrying the gate on those names made the staging demo accounts
|
||||
// unreachable the moment the contract was enforced. It now has its own name, so
|
||||
// enabling demo logins never implies enabling a seed path.
|
||||
//
|
||||
// SENTRY_ENVIRONMENT is still required to be `staging`: the flag alone must not be
|
||||
// able to unlock a demo account in production, even if someone sets it there.
|
||||
type DemoLoginEnvironment = {
|
||||
ALLOW_STAGING_DEMO_SEED?: string;
|
||||
SEED_DEMO_DATA?: string;
|
||||
SENTRY_ENVIRONMENT?: string;
|
||||
STAGING_DEMO_LOGIN_ENABLED?: string;
|
||||
};
|
||||
|
||||
export function isStagingDemoLoginAllowed(env?: DemoLoginEnvironment) {
|
||||
const demoLoginEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
return demoLoginEnv.SEED_DEMO_DATA === "true" && demoLoginEnv.ALLOW_STAGING_DEMO_SEED === "true";
|
||||
return demoLoginEnv.SENTRY_ENVIRONMENT?.trim() === "staging" && demoLoginEnv.STAGING_DEMO_LOGIN_ENABLED?.trim() === "true";
|
||||
}
|
||||
|
||||
export function isProductionTestAccountBlocked(email: string, env?: DemoLoginEnvironment) {
|
||||
const runtimeEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
if (blockedProductionSeedAccountEmails.has(email)) {
|
||||
return true;
|
||||
}
|
||||
if (guardedStagingDemoAccountEmails.has(email)) {
|
||||
return !isStagingDemoLoginAllowed(env);
|
||||
if (guardedStagingDemoAccountEmails.has(email) || email.endsWith("@mitarbeiter.example.test")) {
|
||||
return !isStagingDemoLoginAllowed(runtimeEnv);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenantId: string; request: Request }) {
|
||||
async function getHome({ isAdmin, tenantSlug, request }: { isAdmin: boolean; tenantSlug?: string | null; request: Request }) {
|
||||
let appHome = "";
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (isAdmin) {
|
||||
appHome = absoluteAdminPath(loadRequiredWebConfig().routing, "dashboard");
|
||||
} else if (appConfiguration.app.features.tenantHome === "/:tenant/") {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (tenant) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenant.slug, "dashboard");
|
||||
if (tenantSlug) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "dashboard");
|
||||
} else {
|
||||
appHome = absoluteAppRootPath(loadRequiredWebConfig().routing);
|
||||
}
|
||||
@@ -97,6 +143,22 @@ async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenan
|
||||
return appHome;
|
||||
}
|
||||
|
||||
function getRegistrationBillingDestination(
|
||||
tenantSlug: string,
|
||||
selectedSubscriptionPriceId: string,
|
||||
selectedOfficeSeatQuantity?: number,
|
||||
selectedFieldSeatQuantity?: number
|
||||
): string {
|
||||
const destination = new URL(absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "settings/billing"));
|
||||
destination.searchParams.set("subscription_required", "1");
|
||||
destination.searchParams.set("selected_price", selectedSubscriptionPriceId);
|
||||
if (selectedOfficeSeatQuantity !== undefined && selectedFieldSeatQuantity !== undefined) {
|
||||
destination.searchParams.set("office_seats", String(selectedOfficeSeatQuantity));
|
||||
destination.searchParams.set("field_seats", String(selectedFieldSeatQuantity));
|
||||
}
|
||||
return destination.toString();
|
||||
}
|
||||
|
||||
function isSafeRelativeRedirect(redirectTo: string) {
|
||||
return redirectTo.startsWith("/") && !redirectTo.startsWith("//") && !redirectTo.includes("\\");
|
||||
}
|
||||
@@ -125,11 +187,13 @@ export async function getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin,
|
||||
defaultTenantId,
|
||||
defaultTenantSlug,
|
||||
fallback,
|
||||
}: {
|
||||
redirectTo: string;
|
||||
isAdmin: boolean;
|
||||
defaultTenantId: string;
|
||||
defaultTenantSlug?: string | null;
|
||||
fallback: string;
|
||||
}) {
|
||||
if (!redirectTo || !isSafeRelativeRedirect(redirectTo)) {
|
||||
@@ -149,8 +213,7 @@ export async function getSafeLoginRedirect({
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const defaultTenant = defaultTenantId ? await getTenant(defaultTenantId) : null;
|
||||
const tenantSlug = defaultTenant?.slug;
|
||||
const tenantSlug = defaultTenantSlug ?? undefined;
|
||||
const targetsDefaultTenantId = Boolean(defaultTenantId && (redirectTo === `/${defaultTenantId}` || redirectTo.startsWith(`/${defaultTenantId}/`)));
|
||||
if (targetsDefaultTenantId) {
|
||||
return fallback;
|
||||
@@ -191,14 +254,16 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
throw new Error(t("auth:errors.invalidFormData"));
|
||||
}
|
||||
|
||||
const fields = { email, password };
|
||||
// Never return the submitted password in action data. React Router hydrates
|
||||
// error responses into the document, so only non-secret fields may be echoed.
|
||||
const fields = { email };
|
||||
const fieldErrors = {
|
||||
email: !UserValidationUtils.validateEmail(email) ? t("auth:errors.invalidEmail") : undefined,
|
||||
password: !UserValidationUtils.validatePassword(password) ? t("auth:errors.invalidPassword") : undefined,
|
||||
};
|
||||
if (Object.values(fieldErrors).some(Boolean)) return Response.json({ fieldErrors, fields }, { status: 400 });
|
||||
|
||||
const rateLimit = checkAuthRateLimit({
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "login",
|
||||
identifier: email,
|
||||
@@ -212,7 +277,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// Brute-force soft gate: after repeated failures per IP+email, require the
|
||||
// configured self-hosted captcha before checking the password.
|
||||
const captchaConfig = resolveCaptchaConfig(process.env);
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(getFailedLoginCount({ request, identifier: email }))) {
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(await getFailedLoginCount({ request, identifier: email }))) {
|
||||
const captchaOk = await verifyCaptchaToken({
|
||||
token: form.get("cap-token")?.toString() ?? form.get("mcaptcha__token")?.toString() ?? form.get("captchaToken")?.toString(),
|
||||
sitekey: getSitekey(captchaConfig, "login"),
|
||||
@@ -238,7 +303,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
if (isProductionTestAccountBlocked(email)) {
|
||||
return Response.json({ fields: { email, password }, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
return Response.json({ fields, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
// Phase 01 / #20 — Magic-link-only accounts have `passwordHash = null`
|
||||
@@ -252,11 +317,38 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// false for a null-hash row, so no session is ever issued. The magic-link
|
||||
// hint is surfaced generically on the /forgot-password flow, not here.
|
||||
const { valid: isCorrectPassword, rehashedHash } = await verifyPassword(password, user?.passwordHash ?? DUMMY_PASSWORD_HASH);
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword) {
|
||||
recordFailedLogin({ request, identifier: email });
|
||||
// Keep disabled identities on the same generic credentials path so they
|
||||
// cannot be enumerated and never receive an immediately unusable session.
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword || user.active === false) {
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
// Admin identities may only use a password as the explicitly enabled,
|
||||
// allowlisted emergency fallback. This identity-based check also prevents
|
||||
// an AdminUser from bypassing the admin-host policy through an app-host
|
||||
// login; the resulting app cookie remains host-isolated from admin.
|
||||
const isAdminFallbackLogin = Boolean(user.admin);
|
||||
if (isAdminFallbackLogin) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { reason: error.reason, email, method: "password" },
|
||||
});
|
||||
// Preserve the same public response as invalid credentials so resolving
|
||||
// an AdminUser never becomes an account-enumeration oracle.
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
if (rehashedHash) {
|
||||
// Drain a legacy bcrypt user to argon2 transparently on successful login.
|
||||
// Best-effort: never block the login on a rehash-persist failure.
|
||||
@@ -275,7 +367,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
// Erfolgreicher Login: Brute-Force-Failure-Counter zuruecksetzen (Captcha-Gate faellt wieder weg).
|
||||
clearFailedLogins({ request, identifier: email });
|
||||
await clearFailedLogins({ request, identifier: email });
|
||||
|
||||
// D1 (Produktentscheidung 18.06.) — 2FA-Login-Gate: TOTP-Nutzer erhalten mit Passwort allein
|
||||
// KEINE Session. Stattdessen wird ein signierter Pending-MFA-Zustand ins Cookie geschrieben
|
||||
@@ -283,26 +375,24 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// vertrauenswuerdig markiertes Geraet (Trust-Device-Cookie) ueberspringt den zweiten Faktor.
|
||||
const totpStatus = await getUserTotpStatus(user.id);
|
||||
if (totpStatus?.enabled && !(await isTrustedDevice(request, user.id))) {
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo });
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo, primaryMethod: "password" });
|
||||
authLogger.info({ op: "login.mfaRequired", userId: user.id }, "Password accepted; awaiting second factor before issuing a session.");
|
||||
return Response.json(
|
||||
{ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH },
|
||||
{ status: 200, headers: { "Set-Cookie": setCookie } }
|
||||
);
|
||||
return Response.json({ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH }, { status: 200, headers: { "Set-Cookie": setCookie } });
|
||||
}
|
||||
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
// const tenant = await getTenant(userSession.defaultTenantId);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({
|
||||
isAdmin: !!user.admin,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
tenantSlug: defaultTenant?.slug,
|
||||
request,
|
||||
});
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
// Phase 01 / #27 — soft-check the submitted password against the current
|
||||
@@ -333,19 +423,32 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
"Password policy soft-check raised; falling back to policyOutdated=false."
|
||||
);
|
||||
}
|
||||
// R-P2a S4b — serverseitige Session-Zeile additiv anlegen (best-effort; ein Store-Fehler darf
|
||||
// den Login nicht blockieren) und ihren Token ins Cookie geben.
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
passwordPolicyOutdated: passwordPolicyOutdated || undefined,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
isAdminFallbackLogin
|
||||
? {
|
||||
request,
|
||||
rotate: true,
|
||||
adminAuthenticationMethods: ["local-development", "mfa"],
|
||||
adminMfaAssuredAt: new Date(),
|
||||
}
|
||||
: { request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackLogin && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { email, severity: "warn", method: "password" },
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,7 +467,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const { t } = await getTranslations(request);
|
||||
const session = await getUserSession(request);
|
||||
const pendingMfaUserId = session.get("pendingMfaUserId");
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0) {
|
||||
const pendingMfaStartedAt = session.get("pendingMfaStartedAt");
|
||||
const rawPendingMfaPrimaryMethod = session.get(PENDING_MFA_PRIMARY_METHOD_KEY);
|
||||
const pendingMfaPrimaryMethod = isPendingMfaPrimaryMethod(rawPendingMfaPrimaryMethod) ? rawPendingMfaPrimaryMethod : undefined;
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0 || !isPendingMfaLoginFresh(pendingMfaStartedAt)) {
|
||||
// Kein laufender 2FA-Login (Cookie fehlt/abgelaufen) -> sauber zurueck zur Anmeldung.
|
||||
throw redirect("/login");
|
||||
}
|
||||
@@ -381,7 +487,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const rateLimitKey = mfaChallengeRateLimitKey(request, user.id);
|
||||
const rateLimit = await checkMfaChallengeRateLimit(rateLimitKey);
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json({ error: t("account.loginMfa.errors.tooManyAttempts") }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } });
|
||||
return Response.json(
|
||||
{ error: t("account.loginMfa.errors.tooManyAttempts") },
|
||||
{ status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } }
|
||||
);
|
||||
}
|
||||
|
||||
let verified = false;
|
||||
@@ -410,28 +519,70 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
|
||||
await resetMfaChallengeRateLimit(rateLimitKey);
|
||||
|
||||
// The pending cookie is signed and records which primary factor established
|
||||
// the challenge. Authentik is the only AdminUser path that may finish
|
||||
// without the emergency fallback policy; every other path is re-checked at
|
||||
// the last possible point so disabling/removing the allowlist during the MFA
|
||||
// challenge prevents a real admin session from being issued.
|
||||
const isAdminFallbackMfa = Boolean(user.admin && pendingMfaPrimaryMethod !== "admin-sso");
|
||||
if (isAdminFallbackMfa) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
reason: error.reason,
|
||||
email: user.email,
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
stage: "mfa-complete",
|
||||
},
|
||||
});
|
||||
throw redirect("/login?error=fallback_disabled");
|
||||
}
|
||||
}
|
||||
|
||||
// Ab hier identisch zum normalen Login-Abschluss in loginFromRequest.
|
||||
const userInfo = await getUserInfo(request);
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantId: userSession.defaultTenantId, request });
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantSlug: defaultTenant?.slug, request });
|
||||
const rawRedirectTo = session.get("pendingMfaRedirectTo");
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo: typeof rawRedirectTo === "string" ? rawRedirectTo : "",
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackMfa && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
email: user.email,
|
||||
severity: "warn",
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
mfa: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Trust-Device: dieses Geraet kuenftig ohne zweiten Faktor zulassen. Legt eine widerrufbare
|
||||
// TrustedDevice-Zeile an und gibt den Token als zusaetzliches Set-Cookie aus.
|
||||
@@ -444,84 +595,263 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
async function registerFromRequest(request: Request) {
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
let creationRequestKey: string | undefined;
|
||||
let verificationFlowAttempted = false;
|
||||
let verificationEmail: string | undefined;
|
||||
let shouldResetCaptcha = false;
|
||||
try {
|
||||
await validateCSRFToken(request);
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
const result = await validateRegistration({ request, registrationData, addToTrialOrFreePlan: true });
|
||||
shouldResetCaptcha = registrationData.intent !== "resendVerification";
|
||||
if (registrationData.creationRequestKey && isSignupCreationRequestKey(registrationData.creationRequestKey)) {
|
||||
creationRequestKey = registrationData.creationRequestKey;
|
||||
}
|
||||
const isResendVerification = registrationData.intent === "resendVerification";
|
||||
let resendRecovery: { registrationId: string; catchUpOnly: boolean } | undefined;
|
||||
if (isResendVerification && registrationData.email) {
|
||||
const signedRecovery = await readRegistrationResendRecovery(request);
|
||||
if (signedRecovery?.email === registrationData.email.trim().toLowerCase()) {
|
||||
const resolvedRecovery = await resolvePendingRegistrationResendRecovery(signedRecovery);
|
||||
if (resolvedRecovery) {
|
||||
registrationData.creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
resendRecovery = {
|
||||
registrationId: resolvedRecovery.registrationId,
|
||||
catchUpOnly: resolvedRecovery.catchUpOnly,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isResendVerification && (!registrationData.acceptTerms || !registrationData.acceptPrivacy)) {
|
||||
throw new RegistrationValidationError("account.register.errors.acceptTermsAndPrivacy");
|
||||
}
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
...(isResendVerification ? { captchaAlreadyVerified: true } : {}),
|
||||
});
|
||||
if (result.verificationRequired) {
|
||||
await createRegistrationForm({ ...registrationData, email: result.email, ipAddress: result.ipAddress, recreateToken: false, request });
|
||||
return Response.json({ verificationEmailSent: true });
|
||||
verificationFlowAttempted = true;
|
||||
verificationEmail = result.email;
|
||||
if (!creationRequestKey) {
|
||||
throw new RegistrationValidationError("auth:errors.invalidFormData");
|
||||
}
|
||||
const createdRegistration = await createRegistrationForm({
|
||||
...registrationData,
|
||||
email: result.email,
|
||||
ipAddress: result.ipAddress,
|
||||
resendOnly: isResendVerification,
|
||||
request,
|
||||
creationRequestKey,
|
||||
selectedSubscriptionPriceId: result.selectedSubscriptionPriceId,
|
||||
selectedOfficeSeatQuantity: result.selectedOfficeSeatQuantity,
|
||||
selectedFieldSeatQuantity: result.selectedFieldSeatQuantity,
|
||||
...(resendRecovery ? { resendRecovery } : {}),
|
||||
});
|
||||
creationRequestKey = createdRegistration.creationRequestKey;
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
} else if (result.registered) {
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const home = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
request,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const home = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
home
|
||||
home,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
}
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
} catch (e: any) {
|
||||
return Response.json(
|
||||
{
|
||||
error: t("shared.unknownError"),
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
// Intentionally do NOT log e.message verbatim — auth flow errors may
|
||||
// contain user-provided email/registration tokens. Log only the error
|
||||
// class and a short tag so we can still investigate via Sentry.
|
||||
authLogger.warn(
|
||||
{
|
||||
err: { name: e?.name ?? "Error", message: typeof e?.message === "string" ? "[redacted]" : "[unknown]" },
|
||||
err: { name: e instanceof Error ? e.name : "Error", message: e instanceof Error ? "[redacted]" : "[unknown]" },
|
||||
op: "verifyAndRegister",
|
||||
},
|
||||
"Auth verify-and-register failed"
|
||||
);
|
||||
return Response.json({ error: t(e.message) }, { status: 400 });
|
||||
if (verificationFlowAttempted && isHiddenRegistrationExistenceConflict(e) && creationRequestKey) {
|
||||
authLogger.info(
|
||||
{
|
||||
op: "registration.existence_hidden",
|
||||
reason: e instanceof RegistrationValidationError ? "registered" : "pending-conflict",
|
||||
},
|
||||
"Registration existence response normalized"
|
||||
);
|
||||
if (verificationEmail) {
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
}
|
||||
}
|
||||
const publicError =
|
||||
e instanceof RegistrationValidationError ? t(e.i18nKey, e.i18nArgs ?? {}) : e instanceof CatalogError ? t(e.i18nKey) : t("shared.unknownError");
|
||||
return Response.json(
|
||||
{
|
||||
error: publicError,
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
// CAP proofs are single-use. Any later validation failure after a
|
||||
// successful verification has consumed the proof as well, so every
|
||||
// failed initial registration must mount a fresh challenge for retry.
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function registrationVerificationResponse(email: string, creationRequestKey: string): Promise<Response> {
|
||||
return Response.json(
|
||||
{ verificationEmailSent: true, creationRequestKey },
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Set-Cookie": await commitRegistrationResendRecovery({ email, creationRequestKey }),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function clearRegistrationRecoveryOnSessionResponse(response: Response): Promise<Response> {
|
||||
response.headers.append("Set-Cookie", await clearRegistrationResendRecovery());
|
||||
return response;
|
||||
}
|
||||
|
||||
function isHiddenRegistrationExistenceConflict(error: unknown): boolean {
|
||||
return (
|
||||
(error instanceof RegistrationValidationError && error.i18nKey === "api.errors.userAlreadyRegistered") ||
|
||||
(error instanceof CatalogError && error.code === "foundation.idempotency_conflict")
|
||||
);
|
||||
}
|
||||
|
||||
async function verifyFromRequest({ request, params }: { request: Request; params: Params }) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const verificationToken = params.id ?? "";
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "registration-verify",
|
||||
identifier: registrationVerifyRateLimitIdentifier(verificationToken),
|
||||
limit: REGISTRATION_VERIFY_RATE_LIMIT,
|
||||
windowMs: REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{ error: t("api.errors.tooManyRequests") },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Retry-After": String(rateLimit.retryAfterSeconds),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const registration = await getRegistrationByToken(params.id ?? "");
|
||||
if (!registration || registration.createdTenantId) {
|
||||
return Response.json({ error: t("api.errors.userAlreadyRegistered") }, { status: 400 });
|
||||
const verificationState = await getRegistrationVerificationStateByToken(verificationToken);
|
||||
if (verificationState.status !== "pending") {
|
||||
const errorKey =
|
||||
verificationState.status === "expired"
|
||||
? "account.verify.expiredLink"
|
||||
: verificationState.status === "used"
|
||||
? "account.verify.usedLink"
|
||||
: "account.verify.invalidLink";
|
||||
return Response.json({ error: t(errorKey) }, { status: 400 });
|
||||
}
|
||||
const registration = verificationState.registration;
|
||||
|
||||
let creationRequestKey: string | undefined;
|
||||
try {
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
registrationData.leadId = registration.leadConversionLeadId ?? undefined;
|
||||
registrationData.leadToken = registration.leadConversionToken ?? undefined;
|
||||
registrationData.leadPlanId = registration.leadConversionPlanId ?? undefined;
|
||||
const result = await validateRegistration({ request, registrationData, checkEmailVerification: false, addToTrialOrFreePlan: true });
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
const submittedData = await getRegistrationFormData(request);
|
||||
const expectedCreationRequestKey = deriveVerificationCreationRequestKey(registration.id);
|
||||
if (
|
||||
!submittedData.creationRequestKey ||
|
||||
!isSignupCreationRequestKey(submittedData.creationRequestKey) ||
|
||||
submittedData.creationRequestKey !== expectedCreationRequestKey
|
||||
) {
|
||||
throw new Error("Invalid verification creation request key");
|
||||
}
|
||||
await updateRegistration(registration.id, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const appHome = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
creationRequestKey = expectedCreationRequestKey;
|
||||
// The URL token selects the persisted registration. Only the password and
|
||||
// captcha proof may come from the browser; identity and lead fields are
|
||||
// immutable here so hidden-form tampering cannot change the new account.
|
||||
const registrationData = {
|
||||
email: registration.email,
|
||||
password: submittedData.password,
|
||||
company: registration.company ?? undefined,
|
||||
firstName: registration.firstName,
|
||||
lastName: registration.lastName,
|
||||
slug: registration.slug ?? undefined,
|
||||
leadId: registration.leadConversionLeadId ?? undefined,
|
||||
leadToken: registration.leadConversionToken ?? undefined,
|
||||
leadPlanId: registration.leadConversionPlanId ?? undefined,
|
||||
selectedSubscriptionPriceId: registration.selectedSubscriptionPriceId ?? undefined,
|
||||
selectedOfficeSeatQuantity: registration.selectedOfficeSeatQuantity ?? undefined,
|
||||
selectedFieldSeatQuantity: registration.selectedFieldSeatQuantity ?? undefined,
|
||||
creationRequestKey,
|
||||
captchaToken: submittedData.captchaToken,
|
||||
};
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
checkEmailVerification: false,
|
||||
captchaAlreadyVerified: true,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
requireRegistrationSeatQuantities: registration.selectedOfficeSeatQuantity !== null && registration.selectedFieldSeatQuantity !== null,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
// The compare-and-set below is the intentional replay boundary. Before it
|
||||
// commits, response-loss may safely retry the same key/payload. Afterwards
|
||||
// the token stays consumed; the committed password account recovers via
|
||||
// normal login instead of turning this verification URL into a login link.
|
||||
await updateRegistration(registration.id, { expectedToken: verificationToken }, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const appHome = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
appHome
|
||||
appHome,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
} catch {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user