|
| 1 | +import type { NextFunction, Request, Response } from 'express' |
| 2 | +import { RateLimiterRes } from 'rate-limiter-flexible' |
| 3 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 4 | + |
| 5 | +import { rateLimitApi } from '../../middleware/rate-limit' |
| 6 | + |
| 7 | +const mocks = vi.hoisted(() => ({ |
| 8 | + rateLimiterRedis: { |
| 9 | + consume: vi.fn(), |
| 10 | + }, |
| 11 | + logger: { |
| 12 | + warn: vi.fn(), |
| 13 | + error: vi.fn(), |
| 14 | + }, |
| 15 | + createRedisClient: vi.fn(), |
| 16 | +})) |
| 17 | + |
| 18 | +vi.mock('rate-limiter-flexible', async (importOriginal) => { |
| 19 | + const actual = await importOriginal<typeof import('rate-limiter-flexible')>() |
| 20 | + return { |
| 21 | + ...actual, |
| 22 | + RateLimiterRedis: vi.fn(function () { |
| 23 | + return mocks.rateLimiterRedis |
| 24 | + }), |
| 25 | + } |
| 26 | +}) |
| 27 | + |
| 28 | +vi.mock('@/helpers/logger', () => ({ |
| 29 | + default: mocks.logger, |
| 30 | +})) |
| 31 | + |
| 32 | +vi.mock('@/config/redis', () => ({ |
| 33 | + createRedisClient: mocks.createRedisClient, |
| 34 | + REDIS_DB_INDEX: { |
| 35 | + RATE_LIMIT: 'rate-limit', |
| 36 | + }, |
| 37 | +})) |
| 38 | + |
| 39 | +describe('Rate Limiting Middleware', () => { |
| 40 | + let mockReq: Partial<Request> |
| 41 | + let mockRes: Partial<Response> |
| 42 | + let mockNext: NextFunction |
| 43 | + |
| 44 | + beforeEach(() => { |
| 45 | + mockReq = { |
| 46 | + headers: {}, |
| 47 | + socket: { |
| 48 | + remoteAddress: '127.0.0.1', |
| 49 | + } as any, |
| 50 | + context: { |
| 51 | + currentUser: { |
| 52 | + id: 'test-user-id', |
| 53 | + |
| 54 | + } as any, |
| 55 | + isAdminOperation: false, |
| 56 | + } as any, |
| 57 | + } |
| 58 | + |
| 59 | + mockRes = { |
| 60 | + status: vi.fn().mockReturnThis(), |
| 61 | + json: vi.fn(), |
| 62 | + } as Partial<Response> |
| 63 | + |
| 64 | + mockNext = vi.fn() |
| 65 | + |
| 66 | + vi.clearAllMocks() |
| 67 | + }) |
| 68 | + |
| 69 | + afterEach(() => { |
| 70 | + vi.restoreAllMocks() |
| 71 | + }) |
| 72 | + |
| 73 | + describe('rateLimitApi', () => { |
| 74 | + it('should allow request when under rate limit', async () => { |
| 75 | + mocks.rateLimiterRedis.consume.mockResolvedValueOnce({}) |
| 76 | + |
| 77 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 78 | + |
| 79 | + expect(mocks.rateLimiterRedis.consume).toHaveBeenCalledWith( |
| 80 | + 'test-user-id', |
| 81 | + ) |
| 82 | + expect(mockNext).toHaveBeenCalledOnce() |
| 83 | + expect(mockRes.status).not.toHaveBeenCalled() |
| 84 | + }) |
| 85 | + |
| 86 | + it('should use user ID for rate limiting when user is authenticated', async () => { |
| 87 | + mocks.rateLimiterRedis.consume.mockResolvedValueOnce({}) |
| 88 | + |
| 89 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 90 | + |
| 91 | + expect(mocks.rateLimiterRedis.consume).toHaveBeenCalledWith( |
| 92 | + 'test-user-id', |
| 93 | + ) |
| 94 | + expect(mockNext).toHaveBeenCalledOnce() |
| 95 | + }) |
| 96 | + |
| 97 | + it('should use IP address when user is not authenticated', async () => { |
| 98 | + mockReq.context = { |
| 99 | + currentUser: null, |
| 100 | + isAdminOperation: false, |
| 101 | + } as any |
| 102 | + mockReq.socket = { |
| 103 | + remoteAddress: '192.168.1.1', |
| 104 | + } as any |
| 105 | + |
| 106 | + mocks.rateLimiterRedis.consume.mockResolvedValueOnce({}) |
| 107 | + |
| 108 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 109 | + |
| 110 | + expect(mocks.rateLimiterRedis.consume).toHaveBeenCalledWith('192.168.1.1') |
| 111 | + expect(mockNext).toHaveBeenCalledOnce() |
| 112 | + }) |
| 113 | + |
| 114 | + it('should use Cloudflare IP when available', async () => { |
| 115 | + mockReq.context = { |
| 116 | + currentUser: null, |
| 117 | + isAdminOperation: false, |
| 118 | + } as any |
| 119 | + mockReq.headers = { |
| 120 | + 'cf-connecting-ip': '203.0.113.42', |
| 121 | + } |
| 122 | + |
| 123 | + mocks.rateLimiterRedis.consume.mockResolvedValueOnce({}) |
| 124 | + |
| 125 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 126 | + |
| 127 | + expect(mocks.rateLimiterRedis.consume).toHaveBeenCalledWith( |
| 128 | + '203.0.113.42', |
| 129 | + ) |
| 130 | + expect(mockNext).toHaveBeenCalledOnce() |
| 131 | + }) |
| 132 | + |
| 133 | + it('should return 429 when rate limit is exceeded', async () => { |
| 134 | + const rateLimitError = Object.assign(new RateLimiterRes(), { |
| 135 | + msBeforeNext: 5000, |
| 136 | + }) |
| 137 | + |
| 138 | + mocks.rateLimiterRedis.consume.mockRejectedValueOnce(rateLimitError) |
| 139 | + |
| 140 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 141 | + |
| 142 | + expect(mockRes.status).toHaveBeenCalledWith(429) |
| 143 | + expect(mockRes.json).toHaveBeenCalledWith({ |
| 144 | + error: 'Too many requests', |
| 145 | + message: 'Rate limit exceeded. Please try again later.', |
| 146 | + }) |
| 147 | + expect(mockNext).not.toHaveBeenCalled() |
| 148 | + }) |
| 149 | + |
| 150 | + it('should log rate limit violations', async () => { |
| 151 | + const rateLimitError = Object.assign(new RateLimiterRes(), { |
| 152 | + msBeforeNext: 3000, |
| 153 | + }) |
| 154 | + |
| 155 | + mocks.rateLimiterRedis.consume.mockRejectedValueOnce(rateLimitError) |
| 156 | + |
| 157 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 158 | + |
| 159 | + expect(mocks.logger.warn).toHaveBeenCalledWith( |
| 160 | + 'API endpoint rate limited', |
| 161 | + expect.objectContaining({ |
| 162 | + event: 'api-rate-limited', |
| 163 | + userId: 'test-user-id', |
| 164 | + remainingMs: 3000, |
| 165 | + }), |
| 166 | + ) |
| 167 | + }) |
| 168 | + |
| 169 | + it('should handle errors gracefully and continue', async () => { |
| 170 | + const genericError = new Error('Redis connection failed') |
| 171 | + mocks.rateLimiterRedis.consume.mockRejectedValueOnce(genericError) |
| 172 | + |
| 173 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 174 | + |
| 175 | + expect(mocks.logger.error).toHaveBeenCalledWith( |
| 176 | + 'Error in rate limiting middleware', |
| 177 | + { error: genericError }, |
| 178 | + ) |
| 179 | + expect(mockNext).toHaveBeenCalledOnce() |
| 180 | + expect(mockRes.status).not.toHaveBeenCalled() |
| 181 | + }) |
| 182 | + |
| 183 | + it('should use IP fallback when no user is available', async () => { |
| 184 | + mockReq.context = { |
| 185 | + currentUser: null, |
| 186 | + isAdminOperation: false, |
| 187 | + } as any |
| 188 | + mockReq.socket = { |
| 189 | + remoteAddress: '10.0.0.1', |
| 190 | + } as any |
| 191 | + mockReq.headers = {} |
| 192 | + |
| 193 | + mocks.rateLimiterRedis.consume.mockResolvedValueOnce({}) |
| 194 | + |
| 195 | + await rateLimitApi(mockReq as Request, mockRes as Response, mockNext) |
| 196 | + |
| 197 | + expect(mocks.rateLimiterRedis.consume).toHaveBeenCalledWith('10.0.0.1') |
| 198 | + expect(mockNext).toHaveBeenCalledOnce() |
| 199 | + }) |
| 200 | + }) |
| 201 | +}) |
0 commit comments