/** * 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. * * R1 — Reecrit pour /api/v1/tables/:id/rows (proxy generique). */ import { Hono } from 'hono'; import { afterEach, describe, expect, it } from 'vitest'; import type { RedisCache } from '../../src/adapters/redis-cache.js'; import { Row } from '../../src/domain/row.js'; import type { RepoSet } from '../../src/lib/container.js'; import { setContainer } from '../../src/lib/container.js'; import { errors } from '../../src/lib/errors.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 { tablesRoutes } from '../../src/routes/tables.js'; import { webhooksRoutes } from '../../src/routes/webhooks.js'; 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; } } class FakeRowsRepo { async list(tableId: number) { return { items: [new Row({ id: 1, tableId, fields: { nom: 'X' } })], meta: { page: 1, per_page: 50, total: 1, total_pages: 1 }, }; } async get(tableId: number, rowId: number): Promise { if (rowId === 9999) throw errors.notFound('Row', rowId); return new Row({ id: rowId, tableId, fields: { nom: 'X' } }); } async create(tableId: number, fields: Record): Promise { return new Row({ id: 1000, tableId, fields }); } async update(tableId: number, rowId: number, fields: Record): Promise { return new Row({ id: rowId, tableId, fields }); } async delete(_tableId: number, _rowId: number): Promise {} } const READ_TOKEN = 'brg_read'; const WRITE_TOKEN = 'brg_write'; function installContainer(redis: FakeRedis, opts: { globalMax: number; mutationMax: number }) { const repos: RepoSet = { tables: {} as RepoSet['tables'], fields: {} as RepoSet['fields'], views: {} as RepoSet['views'], rows: new FakeRowsRepo() as unknown as RepoSet['rows'], }; 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, 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:tables'] }], [ WRITE_TOKEN, { token: WRITE_TOKEN, name: 'writer', scopes: ['read:tables', 'write:tables'] }, ], ]), oidc: null, groupsScopesMap: {}, logger, }); } 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:tables'] }], [ WRITE_TOKEN, { token: WRITE_TOKEN, name: 'writer', scopes: ['read:tables', 'write:tables'] }, ], ]), oidc: null, groupsScopesMap: {}, 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('/tables', tablesRoutes); app.route('/api/v1', v1); return app; } afterEach(() => setContainer(null)); describe('Rate limit + cache invalidation 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/tables/5/rows : 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/tables/5/rows', { 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/tables/5/rows', { headers }); const r2 = await app.request('/api/v1/tables/5/rows', { headers }); const r3 = await app.request('/api/v1/tables/5/rows', { headers }); expect(r1.status).toBe(200); expect(r2.status).toBe(200); expect(r3.status).toBe(429); }); it('POST row : applique mutation rate limit + invalide le cache de la table', 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/tables/5/rows', { method: 'POST', headers: { Authorization: `Bearer ${WRITE_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ nom: 'X', heures: 40 }), }); expect(r.status).toBe(201); // 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 generique : juste la table touchee + sa row. expect(redis.invalidations).toContain('bridge:tables:5:list:*'); expect(redis.invalidations).toContain('bridge:tables:5:views:*'); expect(redis.invalidations.some((p) => p.startsWith('bridge:tables:5:row:'))).toBe(true); // Pas de cascade cross-table. expect(redis.invalidations.every((p) => p.startsWith('bridge:tables:5:'))).toBe(true); }); 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({ nom: 'X' }); const r1 = await app.request('/api/v1/tables/5/rows', { method: 'POST', headers, body }); const r2 = await app.request('/api/v1/tables/5/rows', { method: 'POST', headers, body }); expect(r1.status).toBe(201); expect(r2.status).toBe(429); }); });