// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; const testWebConfig = { nodeEnv: "test", sessionSecret: "dGVzdC1zZXNzaW9uLXNlY3JldC13aXRoLWVub3VnaC1lbnRyb3B5LTEyMzQ1Njc4OTA=", i18n: { enabledLocales: ["de", "en"] as const }, routing: { appBaseDomain: "localhost", protocol: "http" as const, }, crisp: { chatWebsiteId: undefined }, webPush: { vapidPublicKey: undefined }, }; vi.doMock("@hivegrid/config", async () => { const actual = await vi.importActual("@hivegrid/config"); return { ...actual, loadRequiredWebConfig: () => testWebConfig, }; }); vi.mock("./db/tenants.db.server", () => ({ getMyTenants: vi.fn(), getTenant: vi.fn(), })); vi.mock("./db/users.db.server", () => ({ getUser: vi.fn(), })); const authStoreMock = vi.hoisted(() => ({ getActiveSessionByToken: vi.fn() })); const sessionLifecycleMock = vi.hoisted(() => ({ endServerSession: vi.fn(), startServerSession: vi.fn() })); vi.mock("~/services/auth/sessionStore.server", () => ({ getActiveSessionByToken: (...args: unknown[]) => authStoreMock.getActiveSessionByToken(...args), })); vi.mock("~/services/auth/sessionLifecycle.server", () => ({ endServerSession: (...args: unknown[]) => sessionLifecycleMock.endServerSession(...args), startServerSession: (...args: unknown[]) => sessionLifecycleMock.startServerSession(...args), })); vi.mock("@hivegrid/db/auth-boundary.server", () => ({ getAuthUserWithoutPasswordById: vi.fn(), getTenantById: vi.fn(), })); vi.mock("~/locale/i18next.server", () => ({ enabledLocales: ["de", "en"], i18nCookie: { serialize: vi.fn(async () => "i18n=de") }, remixI18Next: { getLocale: vi.fn(async () => "de") }, })); vi.mock("~/modules/featureFlags/services/FeatureFlagsService", () => ({ default: { getCurrentFeatureFlags: vi.fn(async () => []) }, })); vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn(async () => ({ time: async (value: T | Promise) => value, getServerTimingHeader: () => ({ "Server-Timing": "test" }), })), })); vi.mock("~/utils/analyticsCookie.server", () => ({ commitAnalyticsSession: vi.fn(async () => "analytics=session"), destroyAnalyticsSession: vi.fn(async () => "analytics=; Max-Age=0"), generateAnalyticsUserId: vi.fn(() => "analytics-user-1"), getAnalyticsSession: vi.fn(async () => { const values = new Map(); return { get: (key: string) => values.get(key), set: (key: string, value: string) => values.set(key, value), }; }), })); vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn(async () => ({ analytics: { enabled: false }, app: { theme: "light" }, featureFlags: { enabled: false }, metrics: { enabled: false, logToConsole: false, saveToDatabase: false, ignoreUrls: [] }, })), })); vi.mock("~/utils/helpers/.server/AnalyticsService", () => ({ default: { getFromRequest: vi.fn() }, })); const { IMPERSONATION_SESSION_TTL_MS, createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, logout, requireUserId, storage, validateAdminImpersonationSessionState, validateImpersonationSessionState, } = await import("./session.server"); const { getAuthUserWithoutPasswordById } = await import("@hivegrid/db/auth-boundary.server"); const { loadRootData } = await import("./data/.server/rootData"); const now = new Date("2026-01-01T12:00:00.000Z"); const freshStartedAt = new Date(now.getTime() - 5 * 60 * 1000).toISOString(); const currentFreshStartedAt = new Date(Date.now() - 5 * 60 * 1000).toISOString(); const rootTestUsers = { "admin-1": { id: "admin-1", email: "admin@example.test", firstName: "Admin", lastName: "User" }, "user-1": { id: "user-1", email: "user@example.test", firstName: "Target", lastName: "User" }, }; async function requestFromSession(sessionValues: Record) { const session = await storage.getSession(); const values = { ...sessionValues }; if (typeof values.userId === "string" && values.sessionToken === undefined) { const ownerUserId = typeof values.impersonatingFromUserId === "string" ? values.impersonatingFromUserId : values.userId; values.sessionToken = `tok:${ownerUserId}`; } for (const [key, value] of Object.entries(values)) { session.set(key, value); } return new Request("https://example.test/app", { headers: { Cookie: (await storage.commitSession(session)).split(";")[0] }, }); } beforeEach(() => { authStoreMock.getActiveSessionByToken.mockReset(); authStoreMock.getActiveSessionByToken.mockImplementation(async (rawToken: string) => ({ id: `session:${rawToken}`, userId: rawToken.startsWith("tok:") ? rawToken.slice(4) : "unknown", })); sessionLifecycleMock.endServerSession.mockReset(); sessionLifecycleMock.endServerSession.mockResolvedValue(undefined); sessionLifecycleMock.startServerSession.mockReset(); sessionLifecycleMock.startServerSession.mockImplementation(async ({ userId }: { userId: string }) => `tok:${userId}`); }); describe("impersonation session TTL", () => { it("accepts only complete, fresh admin impersonation state", () => { expect( validateAdminImpersonationSessionState( { impersonatingFromAdminUserId: "admin-1", impersonatingFromAdminEmail: "admin@example.test", impersonatingStartedAt: freshStartedAt, userId: "user-1", }, now ) ).toBe(true); expect( validateAdminImpersonationSessionState( { impersonatingFromAdminUserId: "admin-1", impersonatingStartedAt: freshStartedAt, userId: "user-1", }, now ) ).toBe(false); }); it("fails closed instead of restoring a tenant target from stale admin impersonation state", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingFromAdminUserId: "admin-1", impersonatingFromAdminEmail: "admin@example.test", impersonatingStartedAt: new Date(Date.now() - IMPERSONATION_SESSION_TTL_MS - 1).toISOString(), }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: null, impersonatingFromAdminUserId: undefined, impersonatingFromAdminEmail: undefined, impersonatingStartedAt: undefined, }); }); it("creates a target-owned tenant session with an auditable admin banner marker", async () => { const startedAt = createImpersonationStartedAt(new Date()); const response = await createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], impersonatingFromAdminUserId: "admin-1", impersonatingFromAdminEmail: "admin@example.test", impersonatingStartedAt: startedAt, }, "/app", { request: new Request("https://example.test/admin/impersonate") } ); const request = new Request("https://example.test/app", { headers: { Cookie: (response.headers.get("Set-Cookie") ?? "").split(";")[0] }, }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1", impersonatingFromAdminUserId: "admin-1", impersonatingFromAdminEmail: "admin@example.test", impersonatingStartedAt: startedAt, }); expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({ request: expect.any(Request), userId: "user-1", }); }); it("accepts fresh impersonation state", () => { expect( validateImpersonationSessionState( { impersonatingFromUserId: "admin-1", impersonatingStartedAt: freshStartedAt, userId: "user-1" }, { now } ) ).toEqual({ valid: true, reason: "valid", actorUserId: "admin-1", startedAt: freshStartedAt }); }); it("rejects missing actor state", () => { expect(validateImpersonationSessionState({ impersonatingStartedAt: freshStartedAt }, { now })).toMatchObject({ valid: false, reason: "missing_actor", }); }); it("rejects missing timestamp state", () => { expect(validateImpersonationSessionState({ impersonatingFromUserId: "admin-1" }, { now })).toMatchObject({ valid: false, reason: "missing_started_at", }); }); it("rejects malformed timestamp state without throwing", () => { expect( validateImpersonationSessionState({ impersonatingFromUserId: "admin-1", impersonatingStartedAt: "not-a-date" }, { now }) ).toMatchObject({ valid: false, reason: "malformed_started_at" }); }); it("rejects future timestamp state", () => { expect( validateImpersonationSessionState( { impersonatingFromUserId: "admin-1", impersonatingStartedAt: new Date(now.getTime() + 1).toISOString() }, { now } ) ).toMatchObject({ valid: false, reason: "future_started_at" }); }); it("rejects stale timestamp state", () => { expect( validateImpersonationSessionState( { impersonatingFromUserId: "admin-1", impersonatingStartedAt: new Date(now.getTime() - IMPERSONATION_SESSION_TTL_MS - 1).toISOString() }, { now } ) ).toMatchObject({ valid: false, reason: "stale_started_at" }); }); it("caps the impersonation window at 30 minutes (AK-P19 DoD #4)", () => { expect(IMPERSONATION_SESSION_TTL_MS).toBe(30 * 60 * 1000); // 29 minutes in: still valid; 31 minutes in: stale. const at = (minutes: number) => validateImpersonationSessionState( { impersonatingFromUserId: "admin-1", impersonatingStartedAt: new Date(now.getTime() - minutes * 60 * 1000).toISOString() }, { now } ); expect(at(29)).toMatchObject({ valid: true }); expect(at(31)).toMatchObject({ valid: false, reason: "stale_started_at" }); }); it("rejects wrong actor state", () => { expect( validateImpersonationSessionState( { impersonatingFromUserId: "admin-1", impersonatingStartedAt: freshStartedAt }, { now, expectedActorUserId: "admin-2" } ) ).toMatchObject({ valid: false, reason: "wrong_actor" }); }); it("preserves only fresh impersonation state in getUserInfo", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: currentFreshStartedAt, }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: currentFreshStartedAt, }); }); it("restores the actor instead of degrading invalid impersonation state into a target session", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: "not-a-date", }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "admin-1", impersonatingFromUserId: undefined, impersonatingStartedAt: undefined, }); }); it("restores the actor in requireUserId after the impersonation TTL expires", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: new Date(Date.now() - IMPERSONATION_SESSION_TTL_MS - 1).toISOString(), }); await expect(requireUserId(request)).resolves.toBe("admin-1"); }); it("fails closed when invalid impersonation state has no actor to restore", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingStartedAt: "not-a-date", }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: null, impersonatingFromUserId: undefined, impersonatingStartedAt: undefined, }); }); it("requires createUserSession impersonation callers to provide an issue timestamp", async () => { const response = await createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], impersonatingFromUserId: "admin-1", }, "/app", { request: new Request("https://example.test/admin/impersonate") }, ); const cookie = response.headers.get("Set-Cookie") ?? ""; const request = new Request("https://example.test/app", { headers: { Cookie: cookie.split(";")[0] } }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "admin-1", impersonatingFromUserId: undefined, impersonatingStartedAt: undefined, }); }); it("serializes fresh impersonation timestamps without leaking secrets", async () => { const response = await createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", csrf: "csrf-secret-token", cookies: [], impersonatingFromUserId: "admin-1", impersonatingStartedAt: createImpersonationStartedAt(now), }, "/app", { request: new Request("https://example.test/admin/impersonate") }, ); const cookie = response.headers.get("Set-Cookie") ?? ""; expect(cookie).toContain("hivegrid_app_session="); expect(cookie).not.toContain("csrf-secret-token"); expect(cookie).not.toContain("password"); expect(cookie).not.toContain("totp"); expect(cookie).not.toContain("recovery"); }); it("preserves fresh impersonation metadata and password-policy flags in new sessions", async () => { const startedAt = createImpersonationStartedAt(new Date()); const response = await createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], impersonatingFromUserId: "admin-1", impersonatingStartedAt: startedAt, passwordPolicyOutdated: true, }, "/app", { request: new Request("https://example.test/admin/impersonate") }, ); const request = new Request("https://example.test/app", { headers: { Cookie: (response.headers.get("Set-Cookie") ?? "").split(";")[0] }, }); await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: startedAt, passwordPolicyOutdated: true, }); expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({ request: expect.any(Request), userId: "admin-1", }); }); it("reuses an active actor-owned token when switching into impersonation", async () => { const startedAt = createImpersonationStartedAt(new Date()); const request = new Request("https://example.test/admin/impersonate"); const response = await createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], sessionToken: "tok:admin-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: startedAt, }, "/app", { request }, ); expect(response.status).toBe(302); expect(authStoreMock.getActiveSessionByToken).toHaveBeenCalledWith("tok:admin-1"); expect(sessionLifecycleMock.startServerSession).not.toHaveBeenCalled(); }); it("rejects an impersonation cookie backed by a token owned by the target", async () => { const startedAt = createImpersonationStartedAt(new Date()); await expect( createUserSession( { userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], sessionToken: "tok:user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: startedAt, }, "/app", { request: new Request("https://example.test/admin/impersonate") }, ), ).rejects.toThrow("owner-mismatch"); }); it("clears impersonation state on logout", async () => { const request = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: freshStartedAt, }); const response = await logout(request); const cookie = response.headers.get("Set-Cookie") ?? ""; const loggedOutSession = await storage.getSession(cookie.split(";")[0]); expect(loggedOutSession.get("impersonatingFromUserId")).toBeUndefined(); expect(loggedOutSession.get("impersonatingStartedAt")).toBeUndefined(); expect((await getUserSession(new Request("https://example.test", { headers: { Cookie: cookie.split(";")[0] } }))).get("userId")).toBeUndefined(); }); it("exposes fresh impersonation state in root data", async () => { vi.mocked(getAuthUserWithoutPasswordById).mockImplementation(async (userId) => rootTestUsers[userId as keyof typeof rootTestUsers] as never); const request = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: currentFreshStartedAt, }); const response = await loadRootData({ request, params: {} }); const data = await response.json(); expect(data.userSession).toMatchObject({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: currentFreshStartedAt, }); expect(data.impersonatingSession).toEqual({ fromUser: rootTestUsers["admin-1"], toUser: rootTestUsers["user-1"] }); }); it("omits stale or malformed impersonation metadata from root data", async () => { vi.mocked(getAuthUserWithoutPasswordById).mockImplementation(async (userId) => rootTestUsers[userId as keyof typeof rootTestUsers] as never); const staleStartedAt = new Date(Date.now() - IMPERSONATION_SESSION_TTL_MS - 1).toISOString(); const staleRequest = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: staleStartedAt, }); const malformedRequest = await requestFromSession({ userId: "user-1", impersonatingFromUserId: "admin-1", impersonatingStartedAt: "not-a-date", }); const staleData = await (await loadRootData({ request: staleRequest, params: {} })).json(); const malformedData = await (await loadRootData({ request: malformedRequest, params: {} })).json(); expect(staleData.userSession.impersonatingFromUserId).toBeUndefined(); expect(staleData.userSession.impersonatingStartedAt).toBeUndefined(); expect(staleData.userSession.userId).toBe("admin-1"); expect(staleData.impersonatingSession).toBeNull(); expect(malformedData.userSession.impersonatingFromUserId).toBeUndefined(); expect(malformedData.userSession.impersonatingStartedAt).toBeUndefined(); expect(malformedData.userSession.userId).toBe("admin-1"); expect(malformedData.impersonatingSession).toBeNull(); }); });