From 8e14b0f55e13bf990a2c98daa9f54a71799573fb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 11:33:15 +0000 Subject: [PATCH] fix(reader-access): make session management test suite pass The session suite merged in #647 failed on main (66/140), which made the "No new test failures" check fail for every PR that merged main. Implementation: - store.listSessionsByEmail: accept the real Netlify Blobs list() result ({ blobs: [{ key }] }) as well as a plain key array, and filter keys by the reader's prefix. Previously the real Blobs shape made createSession throw, and a prefix-ignoring adapter leaked other readers' sessions into the device count. - createSession: do not count the device being re-verified towards MAX_CONCURRENT_DEVICES (its session is replaced in place), and serialise creations per reader so concurrent requests cannot all pass the check. Tests (no skips, no removals): - session.test.ts: in-memory Blobs double instead of an auto-mocked store; persist the expiry in the expired-session case. - Await rejects assertions; step past the renewal coalesce window with a faked Date instead of sleeping inside it; expire beyond clock-skew tolerance; measure the rolling window from renewedAt. - security.test.ts: reset rate-limiter state between tests; unpadded base64url fixture; empty tokens must not match; timing tests compare warmed-up interleaved medians (tests/session/helpers/timing.ts). - New regression test for re-verifying on a registered device at the limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZe8PHngjvTuY2dcfYm --- CHANGELOG.md | 1 + netlify/lib/blobs.ts | 6 +- netlify/lib/reader-access/session-service.ts | 54 +++++++++++- netlify/lib/reader-access/store.ts | 38 ++++++-- tests/session/device-limit-tests.test.ts | 29 ++++++- tests/session/helpers/timing.ts | 66 ++++++++++++++ tests/session/security.test.ts | 91 +++++++++----------- tests/session/session-expiry.test.ts | 40 +++++++-- tests/session/session-logout.test.ts | 6 +- tests/session/session-persistence.test.ts | 6 +- tests/session/session-renewal.test.ts | 39 ++++++--- tests/session/session.test.ts | 76 ++++++++++------ 12 files changed, 339 insertions(+), 113 deletions(-) create mode 100644 tests/session/helpers/timing.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b18f19e..79ef7c5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Reader access session management test suite** — The session suite merged in PR #647 failed on `main` (66 of 140 tests), so every PR that merged `main` failed the "No new test failures" check. Implementation fixes: `listSessionsByEmail` now reads both the Netlify Blobs `list()` result shape (`{ blobs: [{ key }] }`) and a plain key array, and filters keys by the reader's prefix itself. Before this, the real Blobs result made session creation throw, and an adapter that ignored `prefix` counted other readers' sessions towards the device limit. `createSession` no longer counts the device being re-verified towards `MAX_CONCURRENT_DEVICES`, and it serialises creations per reader so concurrent requests cannot all pass the limit check together. Test fixes: replaced the auto-mocked store in `session.test.ts` with an in-memory Blobs double; awaited `rejects` assertions; stepped the clock past the renewal coalesce window instead of sleeping inside it; set expired sessions beyond the clock-skew tolerance; measured the rolling window from `renewedAt`; reset rate-limiter state between tests; removed base64 padding from a base64url token fixture; required two empty tokens not to match; and made timing tests compare warmed-up medians. No tests were skipped or removed. - **Corrupted package-lock.json** — The merge in `161ed46` truncated `package-lock.json` into invalid JSON, so `npm ci` failed with `EUSAGE` in every workflow. Regenerated the lockfile from the last valid copy (`7db390c`) with `npm install --package-lock-only --ignore-scripts`; `package.json` is unchanged. - **CI: Removed unused Playwright browser install from Vitest job** — The `Install Playwright browsers` step in `tests.yml` stalled on the runner's apt mirror (~20 s per package, 49 packages), causing both matrix jobs to time out at 20 minutes and the "No new test failures" comparison to fail closed. The Vitest suite runs in a plain Node environment and needs no browser binaries. Removing the step unblocks the Tests workflow without affecting test coverage. - **Netlify deployment configuration** — Removed duplicate `public/_redirects` file that conflicted with redirect rules defined in `netlify.toml`, resolving validation failures for header rules, redirect rules, and pages changed checks diff --git a/netlify/lib/blobs.ts b/netlify/lib/blobs.ts index 5a94ba36..3d737aaa 100644 --- a/netlify/lib/blobs.ts +++ b/netlify/lib/blobs.ts @@ -18,7 +18,11 @@ export interface BlobStore { set(key: string, value: string): Promise; get(key: string): Promise; delete(key: string): Promise; - list?(options?: { prefix?: string }): Promise; + /** + * Netlify Blobs resolves to `{ blobs: [{ key, etag }], directories }`; + * simpler adapters may resolve to a plain array of keys. + */ + list?(options?: { prefix?: string }): Promise; } /** diff --git a/netlify/lib/reader-access/session-service.ts b/netlify/lib/reader-access/session-service.ts index fb5bc737..e4b2ae98 100644 --- a/netlify/lib/reader-access/session-service.ts +++ b/netlify/lib/reader-access/session-service.ts @@ -60,6 +60,20 @@ export async function createSession( email: string, verificationCode: string, deviceFingerprint: FingerprintInput +): Promise { + // Serialise creations per reader so the device-limit check and the write + // happen together. Without this, concurrent requests all read the same + // "active count" before any of them stores a session (check-then-act race) + // and every one of them is allowed through. + return withEmailLock(email, () => + createSessionUnlocked(email, verificationCode, deviceFingerprint) + ); +} + +async function createSessionUnlocked( + email: string, + verificationCode: string, + deviceFingerprint: FingerprintInput ): Promise { // TODO: T006a - Validate verification code (Phase 2 integration) // - Lookup verification code in Phase 2 storage @@ -71,10 +85,13 @@ export async function createSession( // Generate device fingerprint hash const deviceId = generateDeviceFingerprint(deviceFingerprint); - // Check concurrent device limit (T006b) + // Check concurrent device limit (T006b). + // A session for this same device is stored under the same key and is + // replaced by the new one, so it must not count towards the limit: + // re-verifying on a device the reader already uses is not a new device. const activeSessions = await listSessionsByEmail(email); const activeCount = activeSessions.filter( - (s) => s.status === 'active' && s.terminatedAt === null + (s) => s.status === 'active' && s.terminatedAt === null && s.deviceId !== deviceId ).length; if (activeCount >= MAX_CONCURRENT_DEVICES) { @@ -109,6 +126,39 @@ export async function createSession( return session; } +/** + * Pending session-creation work per reader, used by withEmailLock(). + * + * This only serialises work inside one function instance. Requests handled by + * different instances can still race; closing that gap needs a conditional + * write in Blobs (or a per-reader session index guarded by an ETag). + */ +const emailLocks = new Map>(); + +/** + * Run `task` after any earlier task for the same reader has settled. + * + * @param email Reader's email (case-insensitive key) + * @param task Work to run while holding the reader's lock + * @returns The task's result + */ +async function withEmailLock(email: string, task: () => Promise): Promise { + const key = email.toLowerCase(); + const previous = emailLocks.get(key) ?? Promise.resolve(); + const run = previous.catch(() => undefined).then(task); + const tail = run.catch(() => undefined); + emailLocks.set(key, tail); + + try { + return await run; + } finally { + // Drop the entry once nothing newer has queued behind us. + if (emailLocks.get(key) === tail) { + emailLocks.delete(key); + } + } +} + /** * Validate a session from a sessionId token. * diff --git a/netlify/lib/reader-access/store.ts b/netlify/lib/reader-access/store.ts index 47c4012c..f02d3410 100644 --- a/netlify/lib/reader-access/store.ts +++ b/netlify/lib/reader-access/store.ts @@ -178,16 +178,21 @@ export async function listSessionsByEmail(email: string): Promise { // Build prefix for all sessions for this email const prefix = buildSessionKey(email, ''); - // List all keys starting with prefix - // Note: This assumes Blobs supports list() with prefix filtering - // If not available, we may need to store a separate session index - const keys = await (store as any).list?.({ prefix }); - - if (!keys) { + // List all keys starting with prefix. + // Netlify Blobs resolves list() to `{ blobs: [{ key, etag }], directories }`, + // while simple adapters (and test doubles) may resolve to a plain string[]. + // Normalise both shapes, then filter by prefix ourselves so an adapter that + // ignores the prefix option can never leak another reader's sessions into + // this reader's device count. + if (typeof store.list !== 'function') { // Fallback: return empty array if list() not available return []; } + const keys = extractListKeys(await store.list({ prefix })).filter((key) => + key.startsWith(prefix) + ); + // Fetch each session in parallel const sessions = await Promise.all( keys.map(async (key: string) => { @@ -207,6 +212,27 @@ export async function listSessionsByEmail(email: string): Promise { } } +/** + * Normalise the result of a Blobs list() call into an array of keys. + * + * @param result Either a string[] or a Netlify Blobs ListResult + * @returns Array of blob keys (empty for unrecognised shapes) + */ +function extractListKeys(result: unknown): string[] { + if (Array.isArray(result)) { + return result.filter((key): key is string => typeof key === 'string'); + } + + const blobs = (result as { blobs?: unknown } | null | undefined)?.blobs; + if (Array.isArray(blobs)) { + return blobs + .map((blob) => (blob as { key?: unknown } | null)?.key) + .filter((key): key is string => typeof key === 'string'); + } + + return []; +} + /** * Build a composite session storage key. * Format: session:${email}:${deviceId} diff --git a/tests/session/device-limit-tests.test.ts b/tests/session/device-limit-tests.test.ts index a6c70b9f..eefb16a9 100644 --- a/tests/session/device-limit-tests.test.ts +++ b/tests/session/device-limit-tests.test.ts @@ -117,9 +117,9 @@ describe('Device Limit Enforcement - T099-T102 (US4)', () => { } // Next attempt should fail - expect(async () => { - await createSession(testEmail, testCode, devices[MAX_CONCURRENT_DEVICES]); - }).rejects.toThrow(); + await expect( + createSession(testEmail, testCode, devices[MAX_CONCURRENT_DEVICES]) + ).rejects.toThrow('Device limit exceeded'); }); it('should return 409 Conflict when limit exceeded', async () => { @@ -144,6 +144,29 @@ describe('Device Limit Enforcement - T099-T102 (US4)', () => { }); }); + describe('T100: Re-verifying on a registered device', () => { + it('should allow a new session on an already-registered device at the limit', async () => { + const testEmail = `${testEmailBase}-reverify`; + const devices = Array.from({ length: MAX_CONCURRENT_DEVICES }, (_, i) => ({ + userAgent: `Device${i + 1}`, + ipAddress: `192.168.1.${i + 1}`, + timezone: 'UTC', + })); + + const sessions = []; + for (const device of devices) { + sessions.push(await createSession(testEmail, testCode, device)); + } + + // Same device again: replaces its own session, so it is not a new device + const replacement = await createSession(testEmail, testCode, devices[0]); + + expect(replacement.deviceId).toBe(sessions[0].deviceId); + expect(replacement.sessionId).not.toBe(sessions[0].sessionId); + expect(await getActiveSessionCount(testEmail)).toBe(MAX_CONCURRENT_DEVICES); + }); + }); + describe('T101: Device termination and freeing slots', () => { it('should allow creation after terminating a device', async () => { const testEmail = `${testEmailBase}-free-slot`; diff --git a/tests/session/helpers/timing.ts b/tests/session/helpers/timing.ts new file mode 100644 index 00000000..6381bdc1 --- /dev/null +++ b/tests/session/helpers/timing.ts @@ -0,0 +1,66 @@ +/** + * Timing helpers for constant-time / timing-attack tests. + * + * Single wall-clock samples are dominated by JIT warm-up, GC pauses and + * scheduler noise, so comparing one sample (or a mean that includes outliers) + * against another makes these tests fail at random on CI. These helpers warm + * the code path up, interleave the cases being compared, and report medians, + * which are robust to the occasional outlier. + */ + +/** Median of a list of numbers (does not mutate the input). */ +export function median(values: number[]): number { + if (values.length === 0) { + throw new Error('median() needs at least one value'); + } + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]; +} + +/** + * Time one call in nanoseconds. Works for sync and async functions; a sync + * result is not awaited, so no microtask overhead is added to its measurement. + */ +async function timeOnce(fn: () => unknown): Promise { + const start = process.hrtime.bigint(); + const result = fn(); + if (result && typeof (result as PromiseLike).then === 'function') { + await result; + } + return Number(process.hrtime.bigint() - start); +} + +/** + * Measure several cases with interleaved runs and return each case's median + * duration in nanoseconds, in the same order as `cases`. + * + * @param cases Functions to compare (sync or async) + * @param iterations Measured runs per case + * @param warmup Unmeasured runs per case before measuring + */ +export async function medianTimingsNs( + cases: Array<() => unknown>, + iterations = 200, + warmup = 50 +): Promise { + for (let i = 0; i < warmup; i++) { + for (const fn of cases) { + await fn(); + } + } + + const samples: number[][] = cases.map(() => []); + for (let i = 0; i < iterations; i++) { + for (let c = 0; c < cases.length; c++) { + samples[c].push(await timeOnce(cases[c])); + } + } + + return samples.map(median); +} + +/** Ratio of the larger to the smaller value (always >= 1). */ +export function spreadRatio(a: number, b: number): number { + return Math.max(a, b) / Math.min(a, b); +} diff --git a/tests/session/security.test.ts b/tests/session/security.test.ts index 5be366c6..02dad342 100644 --- a/tests/session/security.test.ts +++ b/tests/session/security.test.ts @@ -8,6 +8,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { constantTimeTokenCompare, isValidSessionToken } from '../../netlify/lib/reader-access/crypto'; import { checkRateLimit, getRateLimitStatus, resetRateLimit, RATE_LIMIT_PRESETS } from '../../netlify/lib/reader-access/rate-limiter'; +import { medianTimingsNs, spreadRatio } from './helpers/timing'; describe('Session Security - Constant-Time Comparison', () => { describe('constantTimeTokenCompare', () => { @@ -29,57 +30,35 @@ describe('Session Security - Constant-Time Comparison', () => { }); it('should handle empty string tokens', () => { - expect(constantTimeTokenCompare('', '')).toBe(true); + // Two empty tokens must NOT match: an empty stored token compared with an + // empty cookie would otherwise authenticate a request with no credential. + expect(constantTimeTokenCompare('', '')).toBe(false); expect(constantTimeTokenCompare('', 'token')).toBe(false); expect(constantTimeTokenCompare('token', '')).toBe(false); }); - it('should use constant-time comparison (no timing leaks)', () => { + it('should use constant-time comparison (no timing leaks)', async () => { // Measure comparison time for correct vs incorrect tokens const correctToken = 'a'.repeat(43); // base64url token length const wrongShorter = 'b'.repeat(10); const wrongLonger = 'c'.repeat(100); const wrongSameLength = 'x'.repeat(43); - // Run multiple times to get statistical average - const iterations = 1000; - const timings: Record = { - correct: [], - wrongShorter: [], - wrongLonger: [], - wrongSameLength: [], - }; - - for (let i = 0; i < iterations; i++) { - const start1 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, correctToken); - const time1 = Number(process.hrtime.bigint() - start1); - timings.correct.push(time1); - - const start2 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongShorter); - const time2 = Number(process.hrtime.bigint() - start2); - timings.wrongShorter.push(time2); - - const start3 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongLonger); - const time3 = Number(process.hrtime.bigint() - start3); - timings.wrongLonger.push(time3); - - const start4 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongSameLength); - const time4 = Number(process.hrtime.bigint() - start4); - timings.wrongSameLength.push(time4); - } - - // Calculate averages - const avgCorrect = timings.correct.reduce((a, b) => a + b, 0) / iterations; - const avgWrongSameLength = - timings.wrongSameLength.reduce((a, b) => a + b, 0) / iterations; + // Warm up, interleave the cases and compare medians: means over raw + // samples are skewed by JIT warm-up and GC pauses. + const [medianCorrect, , , medianWrongSameLength] = await medianTimingsNs( + [ + () => constantTimeTokenCompare(correctToken, correctToken), + () => constantTimeTokenCompare(correctToken, wrongShorter), + () => constantTimeTokenCompare(correctToken, wrongLonger), + () => constantTimeTokenCompare(correctToken, wrongSameLength), + ], + 1000, + 200 + ); // For same-length tokens, timing should be nearly identical (constant-time) - const timingRatio = Math.max(avgCorrect, avgWrongSameLength) / - Math.min(avgCorrect, avgWrongSameLength); + const timingRatio = spreadRatio(medianCorrect, medianWrongSameLength); // Allow up to 1.5x variance for constant-time comparison expect(timingRatio).toBeLessThan(1.5); @@ -88,7 +67,9 @@ describe('Session Security - Constant-Time Comparison', () => { describe('isValidSessionToken', () => { it('should validate correct token format', () => { - const validToken = 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY3ODk='; // 48 chars base64 + // Session tokens are unpadded base64url (see generateSessionToken), so the + // fixture must not carry a trailing '=' padding character. + const validToken = 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY3ODk'; // 47 chars base64url expect(isValidSessionToken(validToken)).toBe(true); }); @@ -127,8 +108,13 @@ describe('Session Security - Constant-Time Comparison', () => { describe('Session Security - Rate Limiting', () => { beforeEach(() => { - // Reset rate limit store before each test + // Reset rate limit store before each test. The limiter keeps its state in + // a module-level Map, so attempts from earlier tests would otherwise carry + // over to later tests that reuse the same identifier. vi.clearAllMocks(); + for (const email of ['test@example.com', 'user1@example.com', 'user2@example.com']) { + resetRateLimit(email, RATE_LIMIT_PRESETS.SESSION_CREATION.keyPrefix); + } }); describe('checkRateLimit', () => { @@ -268,7 +254,7 @@ describe('Session Security - Rate Limiting', () => { }); describe('Session Security - Timing Attack Resistance', () => { - it('should resist timing attacks on session validation', () => { + it('should resist timing attacks on session validation', async () => { // Test that validation time is consistent regardless of token similarity // This is implementation detail, but important for security @@ -278,16 +264,17 @@ describe('Session Security - Timing Attack Resistance', () => { tokens.push('a'.repeat(40 + i)); // Varying lengths } - const timings: number[] = []; - - tokens.forEach(token => { - const start = process.hrtime.bigint(); - // Try to compare with another token of same length - const reference = 'x'.repeat(token.length); - constantTimeTokenCompare(token, reference); - const duration = Number(process.hrtime.bigint() - start); - timings.push(duration); - }); + // One median per token length, from warmed-up interleaved runs. A single + // sample per token mostly measures JIT warm-up of the first call. + const timings = await medianTimingsNs( + tokens.map((token) => { + // Compare with another token of the same length + const reference = 'x'.repeat(token.length); + return () => constantTimeTokenCompare(token, reference); + }), + 200, + 50 + ); // Check variance in timing (should be low for constant-time) const avg = timings.reduce((a, b) => a + b, 0) / timings.length; diff --git a/tests/session/session-expiry.test.ts b/tests/session/session-expiry.test.ts index 51cff7cc..764524b8 100644 --- a/tests/session/session-expiry.test.ts +++ b/tests/session/session-expiry.test.ts @@ -5,9 +5,22 @@ * User Story 2: 30-Day Rolling Session Renewal */ -import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { createSession, validateSession, renewSession } from '../../netlify/lib/reader-access/session-service'; -import { SESSION_LIFETIME_DAYS, CLOCK_SKEW_TOLERANCE_MS } from '../../netlify/lib/reader-access/session-config'; +import { + SESSION_LIFETIME_DAYS, + CLOCK_SKEW_TOLERANCE_MS, + RENEWAL_COALESCE_WINDOW_MS, +} from '../../netlify/lib/reader-access/session-config'; + +/** + * Advance the (faked) clock by `ms`. Only Date is faked, so real timers keep + * working. Used to step past the renewal coalesce window without sleeping. + */ +function advanceClock(ms: number) { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + ms); +} vi.mock('../../netlify/lib/blobs', () => { const store = new Map(); @@ -35,6 +48,10 @@ describe('Session Expiry - T083 (US2)', () => { vi.clearAllMocks(); }); + afterEach(() => { + vi.useRealTimers(); + }); + describe('Expiry calculation precision', () => { it('should calculate expiresAt exactly 30 days from creation', async () => { const before = Date.now(); @@ -92,7 +109,9 @@ describe('Session Expiry - T083 (US2)', () => { // Mock an expired session by manually setting expiresAt to past const { updateSession } = await import('../../netlify/lib/reader-access/store'); - const pastDate = new Date(Date.now() - 1000).toISOString(); // 1 second ago + // Clearly past expiry: beyond CLOCK_SKEW_TOLERANCE_MS, which still accepts + // a session that expired up to that long ago. + const pastDate = new Date(Date.now() - CLOCK_SKEW_TOLERANCE_MS - 5000).toISOString(); await updateSession(testEmail, session.deviceId, { expiresAt: pastDate }); const result = await validateSession(session.sessionId, testEmail, session.deviceId); @@ -133,8 +152,8 @@ describe('Session Expiry - T083 (US2)', () => { const session = await createSession(testEmail, testCode, fingerprint); const originalExpiresAt = new Date(session.expiresAt).getTime(); - // Wait a bit - await new Promise((resolve) => setTimeout(resolve, 100)); + // Move past the renewal coalesce window, otherwise renewal is skipped + advanceClock(RENEWAL_COALESCE_WINDOW_MS + 100); const before = Date.now(); const renewed = await renewSession(testEmail, session.deviceId); @@ -192,16 +211,19 @@ describe('Session Expiry - T083 (US2)', () => { let current = session; for (let i = 0; i < 3; i++) { - await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for coalesce window + advanceClock(RENEWAL_COALESCE_WINDOW_MS * 2); // Step past coalesce window const renewed = await renewSession(testEmail, current.deviceId); - const createdTime = new Date(renewed.createdAt).getTime(); + // The window is rolling: it is measured from the latest renewal, not + // from createdAt (which stays fixed while expiresAt moves forward). + const renewedTime = new Date(renewed.renewedAt).getTime(); const expiresTime = new Date(renewed.expiresAt).getTime(); - const windowSize = expiresTime - createdTime; + const windowSize = expiresTime - renewedTime; // Should still be ~30 days - expect(Math.abs(windowSize - thirtyDaysInMs)).toBeLessThan(2000); + expect(renewedTime).toBeGreaterThan(new Date(current.renewedAt).getTime()); + expect(Math.abs(windowSize - thirtyDaysInMs)).toBeLessThan(1000); current = renewed; } diff --git a/tests/session/session-logout.test.ts b/tests/session/session-logout.test.ts index 09d13df0..07426e64 100644 --- a/tests/session/session-logout.test.ts +++ b/tests/session/session-logout.test.ts @@ -168,9 +168,9 @@ describe('Session Logout - T103 (US5)', () => { describe('Error cases', () => { it('should throw when terminating non-existent session', async () => { - expect(async () => { - await terminateSession('nonexistent@example.com', 'nonexistent-device'); - }).rejects.toThrow(); + await expect( + terminateSession('nonexistent@example.com', 'nonexistent-device') + ).rejects.toThrow('Session not found'); }); }); diff --git a/tests/session/session-persistence.test.ts b/tests/session/session-persistence.test.ts index 21c40902..73cba2ac 100644 --- a/tests/session/session-persistence.test.ts +++ b/tests/session/session-persistence.test.ts @@ -185,9 +185,9 @@ describe('Session Persistence - T079 (US1)', () => { }); it('should not throw on missing session', async () => { - expect(async () => { - await getSession('nonexistent@example.com', 'nonexistent-device'); - }).not.toThrow(); + await expect( + getSession('nonexistent@example.com', 'nonexistent-device') + ).resolves.toBeNull(); }); }); }); diff --git a/tests/session/session-renewal.test.ts b/tests/session/session-renewal.test.ts index f56ed46d..ce7940e6 100644 --- a/tests/session/session-renewal.test.ts +++ b/tests/session/session-renewal.test.ts @@ -5,9 +5,23 @@ * User Story 2: 30-Day Rolling Session Renewal */ -import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { createSession, renewSession } from '../../netlify/lib/reader-access/session-service'; -import { SESSION_LIFETIME_DAYS } from '../../netlify/lib/reader-access/session-config'; +import { + SESSION_LIFETIME_DAYS, + RENEWAL_COALESCE_WINDOW_MS, +} from '../../netlify/lib/reader-access/session-config'; + +/** + * Move the clock past the renewal coalesce window. renewSession deliberately + * returns the stored session unchanged when the last renewal was less than + * RENEWAL_COALESCE_WINDOW_MS ago, so a renewal straight after creation is a + * no-op by design. Only Date is faked; timers keep running normally. + */ +function advancePastCoalesceWindow() { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + RENEWAL_COALESCE_WINDOW_MS + 1); +} vi.mock('../../netlify/lib/blobs', () => { const store = new Map(); @@ -35,6 +49,10 @@ describe('Session Renewal - T082 (US2)', () => { vi.clearAllMocks(); }); + afterEach(() => { + vi.useRealTimers(); + }); + describe('Basic renewal', () => { it('should renew active session', async () => { const created = await createSession(testEmail, testCode, fingerprint); @@ -48,8 +66,8 @@ describe('Session Renewal - T082 (US2)', () => { it('should update renewedAt timestamp on renewal', async () => { const created = await createSession(testEmail, testCode, fingerprint); - // Wait a bit to ensure time difference - await new Promise((resolve) => setTimeout(resolve, 10)); + // Renew after the coalesce window, otherwise the renewal is skipped + advancePastCoalesceWindow(); const renewed = await renewSession(testEmail, created.deviceId); @@ -74,6 +92,7 @@ describe('Session Renewal - T082 (US2)', () => { it('should change expiresAt timestamp from original', async () => { const created = await createSession(testEmail, testCode, fingerprint); + advancePastCoalesceWindow(); const renewed = await renewSession(testEmail, created.deviceId); expect(renewed.expiresAt).not.toBe(created.expiresAt); @@ -145,9 +164,9 @@ describe('Session Renewal - T082 (US2)', () => { describe('Error cases', () => { it('should throw when renewing non-existent session', async () => { - expect(async () => { - await renewSession('nonexistent@example.com', 'nonexistent-device'); - }).rejects.toThrow(); + await expect( + renewSession('nonexistent@example.com', 'nonexistent-device') + ).rejects.toThrow('Session not found'); }); it('should throw when renewing terminated session', async () => { @@ -157,9 +176,9 @@ describe('Session Renewal - T082 (US2)', () => { const created = await createSession(testEmail, testCode, fingerprint); await terminateSession(testEmail, created.deviceId); - expect(async () => { - await renewSession(testEmail, created.deviceId); - }).rejects.toThrow(); + await expect(renewSession(testEmail, created.deviceId)).rejects.toThrow( + 'Cannot renew terminated session' + ); }); }); diff --git a/tests/session/session.test.ts b/tests/session/session.test.ts index db29f81c..94193171 100644 --- a/tests/session/session.test.ts +++ b/tests/session/session.test.ts @@ -16,10 +16,37 @@ import { } from '../../netlify/lib/reader-access/session-service'; import { FingerprintInput } from '../../netlify/lib/reader-access/session'; import { generateSessionToken } from '../../netlify/lib/reader-access/crypto'; -import { SESSION_LIFETIME_DAYS } from '../../netlify/lib/reader-access/session-config'; - -// Mock store operations -vi.mock('../../netlify/lib/reader-access/store'); +import { + SESSION_LIFETIME_DAYS, + RENEWAL_COALESCE_WINDOW_MS, +} from '../../netlify/lib/reader-access/session-config'; +import { updateSession } from '../../netlify/lib/reader-access/store'; +import { medianTimingsNs, spreadRatio } from './helpers/timing'; + +// In-memory Netlify Blobs double. The session service needs a stateful store +// (terminate-then-validate, renew-then-read), so the real store adapter runs +// on top of this Map instead of being auto-mocked to return undefined. +const blobData = vi.hoisted(() => new Map()); + +vi.mock('../../netlify/lib/blobs', () => ({ + getStore: () => ({ + get: (key: string) => Promise.resolve(blobData.get(key) ?? null), + set: (key: string, value: string) => { + blobData.set(key, value); + return Promise.resolve(); + }, + delete: (key: string) => { + blobData.delete(key); + return Promise.resolve(); + }, + list: ({ prefix = '' }: { prefix?: string } = {}) => + Promise.resolve({ + blobs: [...blobData.keys()] + .filter((key) => key.startsWith(prefix)) + .map((key) => ({ key, etag: 'test' })), + }), + }), +})); describe('Session Service - Core Operations', () => { const testEmail = 'reader@example.com'; @@ -32,10 +59,12 @@ describe('Session Service - Core Operations', () => { beforeEach(() => { vi.clearAllMocks(); + blobData.clear(); }); afterEach(() => { vi.clearAllMocks(); + vi.useRealTimers(); }); describe('createSession', () => { @@ -112,21 +141,15 @@ describe('Session Service - Core Operations', () => { const correctToken = testSession.sessionId; const wrongToken = 'wrong' + 'x'.repeat(correctToken.length - 5); - const start1 = process.hrtime.bigint(); - await validateSession(correctToken, testEmail, testSession.deviceId); - const end1 = process.hrtime.bigint(); - - const start2 = process.hrtime.bigint(); - await validateSession(wrongToken, testEmail, testSession.deviceId); - const end2 = process.hrtime.bigint(); + // Compare medians of warmed-up, interleaved runs: a single sample of + // each is dominated by JIT warm-up and scheduler noise. + const [timing1, timing2] = await medianTimingsNs([ + () => validateSession(correctToken, testEmail, testSession.deviceId), + () => validateSession(wrongToken, testEmail, testSession.deviceId), + ]); + const timingRatio = spreadRatio(timing1, timing2); - // Timing should be similar (constant-time) - // Note: This is a statistical test; exact timing varies by CPU - const timing1 = Number(end1 - start1); - const timing2 = Number(end2 - start2); - const timingRatio = Math.max(timing1, timing2) / Math.min(timing1, timing2); - - // Allow up to 2x variance (should be much closer in constant-time impl) + // Allow up to 2.5x variance (should be much closer in constant-time impl) expect(timingRatio).toBeLessThan(2.5); }); @@ -145,14 +168,14 @@ describe('Session Service - Core Operations', () => { }); it('should reject expired session', async () => { - // Create session with past expiry - const expiredSession = { - ...testSession, - expiresAt: new Date(Date.now() - 1000).toISOString(), - }; + // Persist a past expiry beyond the clock-skew tolerance. Changing a local + // copy of the session has no effect: validateSession reads from storage. + await updateSession(testEmail, testSession.deviceId, { + expiresAt: new Date(Date.now() - 60 * 1000).toISOString(), + }); const result = await validateSession( - expiredSession.sessionId, + testSession.sessionId, testEmail, testSession.deviceId ); @@ -170,6 +193,11 @@ describe('Session Service - Core Operations', () => { }); it('should extend expiry to 30 days from renewal time', async () => { + // Step past the coalesce window (only Date is faked), otherwise the + // renewal is skipped and renewedAt keeps the creation timestamp. + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + RENEWAL_COALESCE_WINDOW_MS + 1); + const beforeRenewal = new Date(); const renewed = await renewSession(testEmail, testSession.deviceId); const afterRenewal = new Date();