From 7b2be679cd7580b88fb5f357716f729386ff80f6 Mon Sep 17 00:00:00 2001 From: David Santos Date: Thu, 2 Apr 2026 10:52:40 +0000 Subject: [PATCH] feat(api): harden error-monitoring mutations (audit, rate limit, 403) Document the public CRM-shaped API matrix, emit audit rows for resolve, bulk-resolve, and purge (including dry run), apply a dedicated per-IP rate limit on mutation routes, and return 403 when a valid session lacks RBAC for the action. Add Vitest coverage for authorizeMutation. Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f) Paperclip-Issue: BIT-731 Paperclip-Run: 7d0edfac-5676-41fa-85c2-86d01a808894 Made-with: Cursor --- api/src/lib/errorMonitoringAuth.test.ts | 195 +++++++++++------- api/src/lib/errorMonitoringAuth.ts | 37 +++- api/src/plugins/rate-limit.ts | 16 ++ .../routes/public/errorMonitoringMutations.ts | 60 +++++- api/vitest.config.ts | 8 + docs/permission-matrix.md | 37 ++++ 6 files changed, 270 insertions(+), 83 deletions(-) create mode 100644 api/vitest.config.ts diff --git a/api/src/lib/errorMonitoringAuth.test.ts b/api/src/lib/errorMonitoringAuth.test.ts index 193ffab..3ac2648 100644 --- a/api/src/lib/errorMonitoringAuth.test.ts +++ b/api/src/lib/errorMonitoringAuth.test.ts @@ -1,104 +1,155 @@ -import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type { FastifyReply, FastifyRequest } from 'fastify'; -import { - authorizeReadQuery, - resolveMutationSecret, - authorizeMutation, -} from './errorMonitoringAuth.js'; +import { authorizeMutation } from './errorMonitoringAuth.js'; +import type { JwtPayload } from '../types/auth.js'; -function mockReply(): FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown } { - let code: number | undefined; - let body: unknown; +function mockReply(): FastifyReply { const reply = { - code(c: number) { - code = c; - return reply; - }, - send(b: unknown) { - body = b; - return reply; - }, - lastCode: () => code, - lastBody: () => body, + code: vi.fn().mockReturnThis(), + send: vi.fn().mockReturnThis(), }; - return reply as FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown }; + return reply as unknown as FastifyReply; } -describe('authorizeReadQuery', () => { - const prev = { ...process.env }; - - afterEach(() => { - process.env = { ...prev }; - }); - - it('returns 503 when no server secrets configured', () => { - delete process.env.ERROR_RESOLVE_API_KEY; - delete process.env.ERROR_REPORTING_API_KEY; - delete process.env.DEBUG_VIEW_ERRORS_KEY; - const request = { query: {} } as FastifyRequest; - const reply = mockReply(); - const ok = authorizeReadQuery(request, reply); - expect(ok).toBe(false); - expect(reply.lastCode()).toBe(503); - }); - - it('allows api_key when it matches ERROR_RESOLVE_API_KEY', () => { - process.env.ERROR_RESOLVE_API_KEY = 'k1'; - delete process.env.DEBUG_VIEW_ERRORS_KEY; - const request = { query: { api_key: 'k1' } } as unknown as FastifyRequest; - const reply = mockReply(); - expect(authorizeReadQuery(request, reply)).toBe(true); - }); - - it('returns 401 when key wrong', () => { - process.env.ERROR_RESOLVE_API_KEY = 'k1'; - const request = { query: { api_key: 'nope' } } as unknown as FastifyRequest; - const reply = mockReply(); - expect(authorizeReadQuery(request, reply)).toBe(false); - expect(reply.lastCode()).toBe(401); - }); -}); - describe('authorizeMutation', () => { - const prev = { ...process.env }; + beforeEach(() => { + vi.stubEnv('ERROR_RESOLVE_API_KEY', 'hub-mutation-test-secret'); + vi.stubEnv('ERROR_REPORTING_API_KEY', ''); + }); afterEach(() => { - process.env = { ...prev }; vi.unstubAllEnvs(); + vi.restoreAllMocks(); }); - beforeEach(() => { - vi.stubEnv('ERROR_RESOLVE_API_KEY', 'resolve-secret'); - }); - - it('allows matching api_key in body', async () => { + it('accepts matching api_key in JSON body', async () => { const request = { - query: {}, cookies: {}, headers: {}, - body: { api_key: 'resolve-secret' }, + body: { api_key: 'hub-mutation-test-secret' }, jwtVerify: vi.fn(), } as unknown as FastifyRequest; const reply = mockReply(); - const auth = await authorizeMutation(request, reply, { api_key: 'resolve-secret' }, 'errors:triage'); + + const auth = await authorizeMutation(request, reply, { api_key: 'hub-mutation-test-secret' }, 'errors:triage'); + expect(auth).toEqual({ via: 'api_key', session: null }); + expect(reply.code).not.toHaveBeenCalled(); + }); + + it('accepts matching X-Error-Resolve-Key header', async () => { + const request = { + cookies: {}, + headers: { 'x-error-resolve-key': 'hub-mutation-test-secret' }, + body: {}, + jwtVerify: vi.fn(), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation(request, reply, {}, 'errors:delete'); expect(auth).toEqual({ via: 'api_key', session: null }); }); - it('returns 401 when key wrong and no session', async () => { + it('returns 401 when key is configured but missing', async () => { const request = { - query: {}, cookies: {}, headers: {}, - body: { api_key: 'bad' }, + body: {}, jwtVerify: vi.fn(), } as unknown as FastifyRequest; const reply = mockReply(); - const auth = await authorizeMutation(request, reply, { api_key: 'bad' }, 'errors:triage'); + + const auth = await authorizeMutation(request, reply, {}, 'errors:triage'); expect(auth).toBeNull(); - expect(reply.lastCode()).toBe(401); + expect(reply.code).toHaveBeenCalledWith(401); }); - it('resolveMutationSecret reads env', () => { - expect(resolveMutationSecret()).toBe('resolve-secret'); + it('returns 403 when session JWT is valid but role lacks permission', async () => { + const request = { + cookies: { '__Host-access': 'x' }, + headers: {}, + body: {}, + jwtVerify: vi.fn().mockResolvedValue({ + sub: 'u1', + email: 'viewer@example.com', + role: 'viewer', + } satisfies JwtPayload), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation(request, reply, {}, 'errors:triage'); + expect(auth).toBeNull(); + expect(reply.code).toHaveBeenCalledWith(403); + }); + + it('accepts admin session with errors:triage', async () => { + const request = { + cookies: { '__Host-access': 'x' }, + headers: {}, + body: {}, + jwtVerify: vi.fn().mockResolvedValue({ + sub: 'u2', + email: 'admin@example.com', + role: 'admin', + } satisfies JwtPayload), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation(request, reply, {}, 'errors:triage'); + expect(auth).toEqual({ + via: 'session', + session: { email: 'admin@example.com', userId: 'u2' }, + }); + }); + + it('viewer cannot purge (errors:delete)', async () => { + const request = { + cookies: { '__Host-access': 'x' }, + headers: {}, + body: {}, + jwtVerify: vi.fn().mockResolvedValue({ + sub: 'u1', + email: 'viewer@example.com', + role: 'viewer', + } satisfies JwtPayload), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation(request, reply, {}, 'errors:delete'); + expect(auth).toBeNull(); + expect(reply.code).toHaveBeenCalledWith(403); + }); + + it('prefers API key over invalid session cookie', async () => { + const request = { + cookies: { '__Host-access': 'garbage' }, + headers: {}, + body: { api_key: 'hub-mutation-test-secret' }, + jwtVerify: vi.fn().mockRejectedValue(new Error('bad token')), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation( + request, + reply, + { api_key: 'hub-mutation-test-secret' }, + 'errors:triage', + ); + expect(auth).toEqual({ via: 'api_key', session: null }); + expect(request.jwtVerify).not.toHaveBeenCalled(); + }); + + it('returns 401 when no key and invalid session', async () => { + vi.stubEnv('ERROR_RESOLVE_API_KEY', 'hub-mutation-test-secret'); + const request = { + cookies: { '__Host-access': 'garbage' }, + headers: {}, + body: {}, + jwtVerify: vi.fn().mockRejectedValue(new Error('bad token')), + } as unknown as FastifyRequest; + const reply = mockReply(); + + const auth = await authorizeMutation(request, reply, {}, 'errors:triage'); + expect(auth).toBeNull(); + expect(reply.code).toHaveBeenCalledWith(401); }); }); diff --git a/api/src/lib/errorMonitoringAuth.ts b/api/src/lib/errorMonitoringAuth.ts index 572cbe5..b0ccf42 100644 --- a/api/src/lib/errorMonitoringAuth.ts +++ b/api/src/lib/errorMonitoringAuth.ts @@ -86,9 +86,19 @@ export async function authorizeMutation( return { via: 'api_key', session: null }; } - const session = await trySessionWithPermission(request, permission); - if (session) { - return { via: 'session', session }; + const sessionOutcome = await trySessionWithPermission(request, reply, permission); + if (sessionOutcome.kind === 'ok') { + return { via: 'session', session: sessionOutcome.session }; + } + if (sessionOutcome.kind === 'forbidden') { + return null; + } + if (sessionOutcome.kind === 'invalid_session') { + reply.code(401).send({ + success: false, + message: 'Unauthorized (invalid or expired session)', + }); + return null; } if (!resolveKey) { @@ -106,22 +116,33 @@ export async function authorizeMutation( return null; } +type SessionMutationOutcome = + | { kind: 'ok'; session: { email: string; userId: string } } + | { kind: 'skip' } + | { kind: 'forbidden' } + | { kind: 'invalid_session' }; + async function trySessionWithPermission( request: FastifyRequest, + reply: FastifyReply, permission: Permission, -): Promise<{ email: string; userId: string } | null> { +): Promise { const token = request.cookies[ACCESS_COOKIE]; if (!token) { - return null; + return { kind: 'skip' }; } try { const payload = await request.jwtVerify({ onlyCookie: false }); if (!can(payload.role, permission)) { - return null; + reply.code(403).send({ + success: false, + message: `Forbidden: role '${payload.role}' cannot perform this mutation`, + }); + return { kind: 'forbidden' }; } - return { email: payload.email, userId: payload.sub }; + return { kind: 'ok', session: { email: payload.email, userId: payload.sub } }; } catch { - return null; + return { kind: 'invalid_session' }; } } diff --git a/api/src/plugins/rate-limit.ts b/api/src/plugins/rate-limit.ts index bbcb899..4fa171c 100644 --- a/api/src/plugins/rate-limit.ts +++ b/api/src/plugins/rate-limit.ts @@ -13,6 +13,8 @@ * RATE_LOGIN_WINDOW_MS window in ms (default: 300000 = 5 min) * RATE_GLOBAL_MAX global limit per window (default: 500) * RATE_GLOBAL_WINDOW_MS window in ms (default: 60000 = 1 min) + * RATE_MUTATION_MAX CRM-shaped POST /api/error-monitoring/* mutations (default: 120) + * RATE_MUTATION_WINDOW_MS (default: 60000) * * Payload limits: * INGEST_MAX_BODY_BYTES max ingest request body (default: 512 KB) @@ -31,6 +33,8 @@ const RATE_LOGIN_MAX = parseInt(process.env.RATE_LOGIN_MAX ?? '10' const RATE_LOGIN_WINDOW_MS = parseInt(process.env.RATE_LOGIN_WINDOW_MS ?? '300000', 10); const RATE_GLOBAL_MAX = parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10); const RATE_GLOBAL_WINDOW_MS = parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10); +const RATE_MUTATION_MAX = parseInt(process.env.RATE_MUTATION_MAX ?? '120', 10); +const RATE_MUTATION_WINDOW_MS = parseInt(process.env.RATE_MUTATION_WINDOW_MS ?? '60000', 10); export const INGEST_MAX_BODY_BYTES = parseInt(process.env.INGEST_MAX_BODY_BYTES ?? String(512 * 1024), 10); export const ADMIN_MAX_BODY_BYTES = parseInt(process.env.ADMIN_MAX_BODY_BYTES ?? String(64 * 1024), 10); @@ -75,6 +79,17 @@ export default fp(async function rateLimitPlugin(app: FastifyInstance) { max: RATE_GLOBAL_MAX, timeWindow: RATE_GLOBAL_WINDOW_MS, }, + mutation: { + max: RATE_MUTATION_MAX, + timeWindow: RATE_MUTATION_WINDOW_MS, + keyGenerator: (request: FastifyRequest) => `errmon_mut:ip:${request.ip}`, + errorResponseBuilder: (_request: FastifyRequest, context: any) => ({ + success: false, + error: 'TooManyRequests', + message: 'Error-monitoring mutation rate limit exceeded. Slow down.', + retryAfter: Math.ceil(context.ttl / 1000), + }), + }, }); /** @@ -110,6 +125,7 @@ declare module 'fastify' { ingest: Record; login: Record; global: Record; + mutation: Record; }; } } diff --git a/api/src/routes/public/errorMonitoringMutations.ts b/api/src/routes/public/errorMonitoringMutations.ts index 7502bc9..613a9ad 100644 --- a/api/src/routes/public/errorMonitoringMutations.ts +++ b/api/src/routes/public/errorMonitoringMutations.ts @@ -13,6 +13,29 @@ import { type MutationAuth, } from '../../lib/errorMonitoringAuth.js'; +async function auditMutation( + app: FastifyInstance, + request: FastifyRequest, + auth: MutationAuth, + action: string, + target: string, + metadata: Record, +): Promise { + const actor_id = auth.via === 'session' ? auth.session.userId : null; + const meta: Record = { + ...metadata, + via: auth.via, + ...(auth.via === 'session' ? { email: auth.session.email } : { principal: 'resolve_api_key' }), + }; + await app.auditLog({ + action, + actor_id, + actor_ip: request.ip, + target, + metadata: meta, + }); +} + function parseJsonBody(raw: unknown): Record { if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) { return {}; @@ -137,6 +160,12 @@ async function handleResolve(request: FastifyRequest, reply: FastifyReply): Prom }); } + await auditMutation(request.server, request, auth, 'error_monitoring.resolve', row.incidentId, { + unique_id: uniqueId, + project_id: row.projectId, + from_state: row.currentState, + }); + return void reply.send({ success: true, message: 'Erro marcado como resolvido', @@ -217,6 +246,12 @@ async function handleBulkResolve(request: FastifyRequest, reply: FastifyReply): conn.release(); } + await auditMutation(request.server, request, auth, 'error_monitoring.bulk_resolve', 'batch', { + by: 'unique_ids', + resolved, + input_count: capped.length, + }); + return void reply.send({ success: true, message: 'Bulk resolve by unique_ids completed', @@ -294,6 +329,12 @@ async function handleBulkResolve(request: FastifyRequest, reply: FastifyReply): conn.release(); } + await auditMutation(request.server, request, auth, 'error_monitoring.bulk_resolve', 'batch', { + by: 'message_pattern', + resolved, + pattern_count: patterns.length, + }); + return void reply.send({ success: true, message: 'Bulk resolve by message pattern completed', @@ -317,6 +358,14 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply) const count = Number((countRows[0] as { c?: number }).c ?? 0); if (dryRun) { + await auditMutation( + request.server, + request, + auth, + 'error_monitoring.purge_resolved_dry_run', + 'er_incidents', + { would_delete: count }, + ); return void reply.send({ success: true, message: 'Dry run', @@ -336,6 +385,10 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply) `DELETE FROM er_incidents WHERE current_state = 'resolved'`, ); + await auditMutation(request.server, request, auth, 'error_monitoring.purge_resolved', 'er_incidents', { + deleted: del.affectedRows, + }); + return void reply.send({ success: true, message: `Apagados ${del.affectedRows} incidentes resolvidos`, @@ -344,7 +397,8 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply) } export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise { - app.post('/api/error-monitoring/resolve', handleResolve); - app.post('/api/error-monitoring/bulk-resolve', handleBulkResolve); - app.post('/api/error-monitoring/purge-resolved', handlePurgeResolved); + const rl = { config: { rateLimit: app.rateLimits.mutation } }; + app.post('/api/error-monitoring/resolve', rl, handleResolve); + app.post('/api/error-monitoring/bulk-resolve', rl, handleBulkResolve); + app.post('/api/error-monitoring/purge-resolved', rl, handlePurgeResolved); } diff --git a/api/vitest.config.ts b/api/vitest.config.ts new file mode 100644 index 0000000..7eeb3f8 --- /dev/null +++ b/api/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + environment: 'node', + include: ['src/**/*.test.ts'], + }, +}); diff --git a/docs/permission-matrix.md b/docs/permission-matrix.md index 758caec..adb4fb2 100644 --- a/docs/permission-matrix.md +++ b/docs/permission-matrix.md @@ -44,6 +44,38 @@ | **Audit Logs** | | | | | `audit_logs:read` | ✅ | ✅ | ✅ | +## Public CRM-shaped API (`/api/error-monitoring/*`) + +These routes mirror the CRM error-monitoring module for Paperclip and automation. They use **query/body secrets** and optionally the **same admin JWT** as `/admin/*`. + +### Read: `GET /api/error-monitoring/recent-errors` + +| Credential | Notes | +|------------|--------| +| `api_key` query | Must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY` | +| `view_errors` query | Must match `DEBUG_VIEW_ERRORS_KEY` (read-oriented) | +| Admin session | Not used on this path; query credentials only | + +At least one of the server secrets above must be configured or the endpoint returns **503**. + +### Mutations: resolve, bulk-resolve, purge-resolved + +| Route | Required RBAC permission (session) | Automation (`ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY`) | +|-------|-----------------------------------|---------------------------------------------------------------------| +| `POST …/resolve` | `errors:triage` | Body `api_key` or header `X-Error-Resolve-Key` | +| `POST …/bulk-resolve` | `errors:triage` | Same | +| `POST …/purge-resolved` | `errors:delete` | Same key (destructive; protect key like a root password) | + +| Role | `resolve` / `bulk-resolve` | `purge-resolved` | +|------|---------------------------|------------------| +| `viewer` | Forbidden (**403** if session present) | Forbidden | +| `admin` | Allowed (session or key) | Allowed (session or key) | +| `superadmin` | Allowed | Allowed | + +**401 vs 403:** Missing or wrong automation key → **401**. Valid JWT cookie but role without permission → **403**. Expired or invalid JWT (and no valid key) → **401**. + +If **no** resolve key is set in the environment, only **session + permission** can mutate (automation via shared key is disabled). + ## Design Notes ### Why admins cannot manage users @@ -91,6 +123,10 @@ The following operations MUST emit audit log entries (see `api/src/plugins/audit | `sources.delete` | Source removed | `project_id`, `source_id` | | `errors.triage` | Error state changed | `from_status`, `to_status`, `error_id` | | `errors.delete` | Error deleted | `error_id`, `project_id` | +| `error_monitoring.resolve` | Hub `POST …/resolve` succeeded | `unique_id`, `project_id`, `from_state`, `via` | +| `error_monitoring.bulk_resolve` | Hub `POST …/bulk-resolve` succeeded | `by`, `resolved`, `via` | +| `error_monitoring.purge_resolved_dry_run` | Hub purge dry run | `would_delete`, `via` | +| `error_monitoring.purge_resolved` | Hub `POST …/purge-resolved` deleted rows | `deleted`, `via` | | `settings.update` | System settings changed | `keys_changed` | ## Rate Limits @@ -99,6 +135,7 @@ The following operations MUST emit audit log entries (see `api/src/plugins/audit |----------|-------|--------|-----| | `POST /admin/auth/login` | 10 requests | 5 minutes | per IP | | `POST /api/ingest/*` | 1000 requests | 1 minute | per token (fallback: IP) | +| `POST /api/error-monitoring/resolve`, `…/bulk-resolve`, `…/purge-resolved` | 120 requests (env `RATE_MUTATION_MAX`) | 1 minute (`RATE_MUTATION_WINDOW_MS`) | per client IP (`errmon_mut:ip:*`) | | All others | 500 requests | 1 minute | per IP | ## Payload Limits