Some checks are pending
CI / Lint bridge (Biome) (push) Waiting to run
CI / Type-check bridge (push) Blocked by required conditions
CI / Tests unit bridge (push) Blocked by required conditions
CI / Tests integration bridge (push) Blocked by required conditions
CI / Security scan (push) Waiting to run
CI / Docker build + healthcheck (push) Blocked by required conditions
Pivot strategique : DocAdenice = produit Notion-like generique. Le bridge
est livre vide a un user qui cree ses tables Baserow comme il veut. Code
sans aucune ontologie metier.
Suppressions :
- 9 entites domain metier (Personne, Formation, Bloc, Module, Attribution,
Client, Projet, Tache, Intervention) + types.ts (Role, statuts)
- baserow-repo.ts (mega-fichier 554 LOC avec 9 repos heritant BaseRepo)
- 6 routes metier (personnes, formations, projets, modules, interventions,
attributions) + tests associes
- Lookup PersonneRepo.findByEmail dans middleware auth
- Mapping DEFAULT_ROLE_SCOPES dans middleware/scopes.ts
- Cascade rollup metier dans webhooks/baserow-handler.ts
Ajouts :
- Domain generique : Table, Row, Field, View + schemas zod refondus
- 4 repos generiques : tables / rows / fields / views
- Route unique routes/tables.ts avec 9 endpoints REST CRUD generiques
- Claim JWT acadenice_permissions[] lu directement dans le middleware auth
(alimente par RBAC dynamique cote DocAdenice en R2)
- examples/acadenice-formation-hub/ : README + seed-baserow.md schema
9 tables + example-roles.md (Formateur, Developpeur, Direction, Support,
Admin avec permissions generiques)
Refactors :
- BaserowClient etendu : listTables, getTable, listFields, listViews,
getGridViewRows
- middleware/auth.ts : extractPermissions(payload), AuthenticatedUser
remplace roles[] par permissions[]
- middleware/scopes.ts : computeOidcScopes(groups, permissions, map)
- webhooks/baserow-handler.ts : invalidation generique
bridge:tables:<tableId>:* sans cascade cross-table
- lib/cache.ts : invalidateEntity -> invalidateTable(redis, tableId, rowId?)
- container.ts : drop tableIds, RepoSet={tables, rows, fields, views}
- 501 NOT_IMPLEMENTED si DB token sur endpoints /tables qui exigent JWT
Tests : 250/250 verts (depuis 319). Coverage : domain 98.9%, adapters 89%,
auth 97.08%, rate-limit 100%, cache 100%, webhooks 100%.
Quality gates verts : typecheck, lint biome, vitest, coverage thresholds.
Refs: R1 dans le pivot strategique DocAdenice Notion-like generique.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
265 lines
9.6 KiB
TypeScript
265 lines
9.6 KiB
TypeScript
/**
|
|
* 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<string, number>();
|
|
public eventIds = new Set<string>();
|
|
|
|
async invalidatePattern(pattern: string): Promise<number> {
|
|
this.invalidations.push(pattern);
|
|
return 1;
|
|
}
|
|
|
|
async checkRateLimit(key: string, max: number, _window: number): Promise<boolean> {
|
|
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<boolean> {
|
|
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<Row> {
|
|
if (rowId === 9999) throw errors.notFound('Row', rowId);
|
|
return new Row({ id: rowId, tableId, fields: { nom: 'X' } });
|
|
}
|
|
async create(tableId: number, fields: Record<string, unknown>): Promise<Row> {
|
|
return new Row({ id: 1000, tableId, fields });
|
|
}
|
|
async update(tableId: number, rowId: number, fields: Record<string, unknown>): Promise<Row> {
|
|
return new Row({ id: rowId, tableId, fields });
|
|
}
|
|
async delete(_tableId: number, _rowId: number): Promise<void> {}
|
|
}
|
|
|
|
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);
|
|
});
|
|
});
|