|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +const { mockGetRedisClient, redis } = vi.hoisted(() => { |
| 7 | + const redis = { |
| 8 | + get: vi.fn(), |
| 9 | + set: vi.fn(), |
| 10 | + } |
| 11 | + return { mockGetRedisClient: vi.fn(), redis } |
| 12 | +}) |
| 13 | + |
| 14 | +vi.mock('@/lib/core/config/redis', () => ({ |
| 15 | + getRedisClient: mockGetRedisClient, |
| 16 | +})) |
| 17 | + |
| 18 | +import { buildRedisRateLimitStorage } from '@/lib/auth/rate-limit-storage' |
| 19 | + |
| 20 | +describe('buildRedisRateLimitStorage', () => { |
| 21 | + beforeEach(() => { |
| 22 | + vi.clearAllMocks() |
| 23 | + mockGetRedisClient.mockReturnValue(redis) |
| 24 | + }) |
| 25 | + |
| 26 | + it('returns undefined when Redis is not configured (falls back to in-memory)', () => { |
| 27 | + mockGetRedisClient.mockReturnValue(null) |
| 28 | + expect(buildRedisRateLimitStorage()).toBeUndefined() |
| 29 | + }) |
| 30 | + |
| 31 | + it('reads and parses a stored counter', async () => { |
| 32 | + const storage = buildRedisRateLimitStorage() |
| 33 | + redis.get.mockResolvedValue(JSON.stringify({ key: 'k', count: 4, lastRequest: 123 })) |
| 34 | + const value = await storage?.get('k') |
| 35 | + expect(redis.get).toHaveBeenCalledWith('auth-rl:k') |
| 36 | + expect(value).toEqual({ key: 'k', count: 4, lastRequest: 123 }) |
| 37 | + }) |
| 38 | + |
| 39 | + it('returns undefined when no counter is stored', async () => { |
| 40 | + const storage = buildRedisRateLimitStorage() |
| 41 | + redis.get.mockResolvedValue(null) |
| 42 | + expect(await storage?.get('missing')).toBeUndefined() |
| 43 | + }) |
| 44 | + |
| 45 | + it('writes the counter with a bounding TTL', async () => { |
| 46 | + const storage = buildRedisRateLimitStorage() |
| 47 | + await storage?.set('k', { key: 'k', count: 1, lastRequest: 999 }) |
| 48 | + expect(redis.set).toHaveBeenCalledWith( |
| 49 | + 'auth-rl:k', |
| 50 | + JSON.stringify({ key: 'k', count: 1, lastRequest: 999 }), |
| 51 | + 'EX', |
| 52 | + 3600 |
| 53 | + ) |
| 54 | + }) |
| 55 | + |
| 56 | + it('fails open on a read error (allows the request)', async () => { |
| 57 | + const storage = buildRedisRateLimitStorage() |
| 58 | + redis.get.mockRejectedValue(new Error('redis down')) |
| 59 | + expect(await storage?.get('k')).toBeUndefined() |
| 60 | + }) |
| 61 | + |
| 62 | + it('swallows write errors so a Redis outage never blocks auth', async () => { |
| 63 | + const storage = buildRedisRateLimitStorage() |
| 64 | + redis.set.mockRejectedValue(new Error('redis down')) |
| 65 | + await expect(storage?.set('k', { key: 'k', count: 1, lastRequest: 1 })).resolves.toBeUndefined() |
| 66 | + }) |
| 67 | +}) |
0 commit comments