Browse Source

test(auth): add session expiration and rotation edge case coverage

ding113 1 week ago
parent
commit
3f2803f2cd

+ 1 - 0
tests/security/session-cookie-hardening.test.ts

@@ -31,6 +31,7 @@ vi.mock("@/lib/auth", () => ({
   getSessionTokenMode: mockGetSessionTokenMode,
   clearAuthCookie: mockClearAuthCookie,
   getLoginRedirectTarget: mockGetLoginRedirectTarget,
+  toKeyFingerprint: vi.fn().mockResolvedValue("sha256:mock"),
   withNoStoreHeaders: realWithNoStoreHeaders,
 }));
 

+ 2 - 1
tests/security/session-fixation-rotation.test.ts

@@ -77,7 +77,7 @@ function makeLogoutRequest(): NextRequest {
 }
 
 async function loadLogoutPost(): Promise<(request: NextRequest) => Promise<Response>> {
-  const mod = await import("../../src/app/api/auth/logout/route");
+  const mod = await import("@/app/api/auth/logout/route");
   return mod.POST;
 }
 
@@ -91,6 +91,7 @@ async function simulatePostLoginSessionRotation(
 
 describe("session fixation rotation and logout revocation", () => {
   beforeEach(() => {
+    vi.resetModules();
     vi.clearAllMocks();
     mockRedisSessionStoreCtor.mockImplementation(function RedisSessionStoreMock() {
       return {

+ 23 - 0
tests/security/session-store.test.ts

@@ -236,4 +236,27 @@ describe("RedisSessionStore", () => {
     expect(rotated?.keyFingerprint).toBe(oldSession.keyFingerprint);
     expect(loggerMock.warn).toHaveBeenCalled();
   });
+
+  it("rotate() returns null for already-expired session", async () => {
+    const { RedisSessionStore } = await import("@/lib/auth-session-store/redis-session-store");
+
+    const expiredSession = {
+      sessionId: "bbb-expired-session",
+      keyFingerprint: "fp-expired",
+      userId: 6,
+      userRole: "user",
+      createdAt: Date.now() - 120_000,
+      expiresAt: Date.now() - 1_000,
+    };
+    redis.store.set(`cch:session:${expiredSession.sessionId}`, JSON.stringify(expiredSession));
+
+    const store = new RedisSessionStore();
+    const rotated = await store.rotate(expiredSession.sessionId);
+
+    expect(rotated).toBeNull();
+    expect(loggerMock.warn).toHaveBeenCalledWith(
+      "[AuthSessionStore] Cannot rotate expired session",
+      expect.objectContaining({ sessionId: expiredSession.sessionId })
+    );
+  });
 });