/** * Integration test : verifie que le rate limit s'applique sur /api/v1/* et * PAS sur /api/health, /api/ready, /api/webhooks/*. Et que l'invalidation * cache est declenchee apres POST/PATCH/PUT/DELETE sur les routes mutation. * * On reconstitue une mini app proche de buildApp() (sans serve()) avec un * fake Redis qui compte les calls invalidatePattern + checkRateLimit. */ import { Decimal } from 'decimal.js'; import { Hono } from 'hono'; import { afterEach, describe, expect, it } from 'vitest'; import type { RedisCache } from '../../src/adapters/redis-cache.js'; import type { Personne } from '../../src/domain/personne.js'; import { setContainer } from '../../src/lib/container.js'; import { logger } from '../../src/lib/logger.js'; import { type AuthVariables, authMiddleware } from '../../src/middleware/auth.js'; import { errorHandler } from '../../src/middleware/error-handler.js'; import { defaultRateLimitKey, rateLimit } from '../../src/middleware/rate-limit.js'; import { attributionsRoutes } from '../../src/routes/attributions.js'; import { interventionsRoutes } from '../../src/routes/interventions.js'; import { modulesRoutes } from '../../src/routes/modules.js'; import { personnesRoutes } from '../../src/routes/personnes.js'; import { webhooksRoutes } from '../../src/routes/webhooks.js'; import { buildFakeRepos } from '../helpers/fake-repos.js'; import { makeAttribution, makePersonne } from '../helpers/fixtures.js'; const TABLE_IDS = { personne: 1, formation: 2, bloc: 3, module: 4, attribution: 5, client: 6, projet: 7, tache: 8, intervention: 9, } as const; class FakeRedis { public invalidations: string[] = []; public rateChecks: Array<{ key: string; max: number }> = []; public counts = new Map(); public eventIds = new Set(); async invalidatePattern(pattern: string): Promise { this.invalidations.push(pattern); return 1; } async checkRateLimit(key: string, max: number, _window: number): Promise { this.rateChecks.push({ key, max }); const next = (this.counts.get(key) ?? 0) + 1; this.counts.set(key, next); return next <= max; } async checkAndStoreEventId(id: string): Promise { if (this.eventIds.has(id)) return true; this.eventIds.add(id); return false; } } const READ_TOKEN = 'brg_read'; const WRITE_TOKEN = 'brg_write'; function installContainer(redis: FakeRedis, opts: { globalMax: number; mutationMax: number }) { const personne = makePersonne({ id: 1, roles: ['formateur'] }); const attribution = makeAttribution({ id: 500 }); const repos = buildFakeRepos({ personnes: [personne], attributions: [attribution] }); setContainer({ config: { nodeEnv: 'test', port: 0, logLevel: 'fatal', baserowApiUrl: 'http://localhost', baserowApiToken: 'fake', redisUrl: 'redis://localhost', baserowWebhookSecret: 'fake-secret-at-least-16-chars-long', docmostWebhookSecret: undefined, bridgeApiTokens: undefined, authStrictMapping: true, rateLimitGlobalMax: opts.globalMax, rateLimitGlobalWindow: 60, rateLimitMutationMax: opts.mutationMax, rateLimitMutationWindow: 60, }, // biome-ignore lint/suspicious/noExplicitAny: stubs baserow: {} as any, redis: redis as unknown as RedisCache, repos, tokens: new Map([ [READ_TOKEN, { token: READ_TOKEN, name: 'reader', scopes: ['read:personnes'] }], [ WRITE_TOKEN, { token: WRITE_TOKEN, name: 'writer', scopes: ['write:attributions', 'admin:*'] }, ], ]), tableIds: TABLE_IDS, oidc: null, groupsScopesMap: {}, logger, }); return repos; } function buildAppWithRateLimit(redis: FakeRedis, opts: { globalMax: number; mutationMax: number }) { const app = new Hono<{ Variables: AuthVariables }>(); app.onError(errorHandler); app.get('/api/health', (c) => c.json({ status: 'ok' })); app.get('/api/ready', (c) => c.json({ status: 'ok' })); app.route('/api/webhooks', webhooksRoutes); const v1 = new Hono<{ Variables: AuthVariables }>(); v1.use( '*', authMiddleware({ tokens: new Map([ [READ_TOKEN, { token: READ_TOKEN, name: 'reader', scopes: ['read:personnes'] }], [ WRITE_TOKEN, { token: WRITE_TOKEN, name: 'writer', scopes: ['write:attributions', 'admin:*'] }, ], ]), oidc: null, groupsScopesMap: {}, strictMapping: true, cache: { get: async () => null, set: async () => {}, }, finder: { findByEmail: async (): Promise => null }, logger, }), ); v1.use('*', rateLimit(redis, { maxRequests: opts.globalMax, windowSeconds: 60 })); const mutLimiter = rateLimit(redis, { maxRequests: opts.mutationMax, windowSeconds: 60, keyFrom: (c) => `${defaultRateLimitKey(c)}:mut`, }); v1.use('*', async (c, next) => { const m = c.req.method.toUpperCase(); if (m === 'POST' || m === 'PATCH' || m === 'PUT' || m === 'DELETE') { return mutLimiter(c, next); } await next(); }); v1.route('/personnes', personnesRoutes); v1.route('/modules', modulesRoutes); v1.route('/interventions', interventionsRoutes); v1.route('/attributions', attributionsRoutes); app.route('/api/v1', v1); return app; } afterEach(() => setContainer(null)); describe('Rate limit application sur /api/v1/*', () => { it('GET /api/health : pas de rate limit (route publique)', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 1, mutationMax: 1 }); const app = buildAppWithRateLimit(redis, { globalMax: 1, mutationMax: 1 }); const r1 = await app.request('/api/health'); const r2 = await app.request('/api/health'); const r3 = await app.request('/api/health'); expect(r1.status).toBe(200); expect(r2.status).toBe(200); expect(r3.status).toBe(200); expect(redis.rateChecks).toHaveLength(0); }); it('GET /api/ready : pas de rate limit', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 1, mutationMax: 1 }); const app = buildAppWithRateLimit(redis, { globalMax: 1, mutationMax: 1 }); await app.request('/api/ready'); await app.request('/api/ready'); expect(redis.rateChecks).toHaveLength(0); }); it('POST /api/webhooks/baserow : pas de rate limit (HMAC + idempotence couvrent)', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 1, mutationMax: 1 }); const app = buildAppWithRateLimit(redis, { globalMax: 1, mutationMax: 1 }); // Sans signature : 401, mais sans avoir consomme le rate limit. const r = await app.request('/api/webhooks/baserow', { method: 'POST', body: '{}' }); expect(r.status).toBe(401); expect(redis.rateChecks).toHaveLength(0); }); it('GET /api/v1/personnes : rate limit consomme', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 100, mutationMax: 100 }); const app = buildAppWithRateLimit(redis, { globalMax: 100, mutationMax: 100 }); const r = await app.request('/api/v1/personnes', { headers: { Authorization: `Bearer ${READ_TOKEN}` }, }); expect(r.status).toBe(200); expect(redis.rateChecks).toHaveLength(1); expect(redis.rateChecks[0]?.key).toBe('token:reader'); }); it('GET au-dela de globalMax -> 429', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 2, mutationMax: 100 }); const app = buildAppWithRateLimit(redis, { globalMax: 2, mutationMax: 100 }); const headers = { Authorization: `Bearer ${READ_TOKEN}` }; const r1 = await app.request('/api/v1/personnes', { headers }); const r2 = await app.request('/api/v1/personnes', { headers }); const r3 = await app.request('/api/v1/personnes', { headers }); expect(r1.status).toBe(200); expect(r2.status).toBe(200); expect(r3.status).toBe(429); }); it('PATCH attribution : applique mutation rate limit + invalide le cache', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 100, mutationMax: 100 }); const app = buildAppWithRateLimit(redis, { globalMax: 100, mutationMax: 100 }); const r = await app.request('/api/v1/attributions/500/heures-realisees', { method: 'PATCH', headers: { Authorization: `Bearer ${WRITE_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ heures_realisees: 4 }), }); expect(r.status).toBe(200); // Deux compteurs Redis distincts : token:writer et token:writer:mut. const keys = redis.rateChecks.map((c) => c.key); expect(keys).toContain('token:writer'); expect(keys).toContain('token:writer:mut'); // Cache invalidation : attribution row + list + cascade module + personne. expect(redis.invalidations).toContain('bridge:attribution:list:*'); expect(redis.invalidations).toContain('bridge:attribution:row:500'); expect(redis.invalidations).toContain('bridge:module:list:*'); expect(redis.invalidations).toContain('bridge:personne:list:*'); }); it('mutation au-dela de mutationMax -> 429 meme si globalMax pas atteint', async () => { const redis = new FakeRedis(); installContainer(redis, { globalMax: 100, mutationMax: 1 }); const app = buildAppWithRateLimit(redis, { globalMax: 100, mutationMax: 1 }); const headers = { Authorization: `Bearer ${WRITE_TOKEN}`, 'Content-Type': 'application/json' }; const body = JSON.stringify({ heures_realisees: new Decimal(1).toNumber() }); const r1 = await app.request('/api/v1/attributions/500/heures-realisees', { method: 'PATCH', headers, body, }); const r2 = await app.request('/api/v1/attributions/500/heures-realisees', { method: 'PATCH', headers, body, }); expect(r1.status).toBe(200); expect(r2.status).toBe(429); }); });