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
This commit is contained in:
1 parent
8b0044be82
commit
7b2be679cd
6 files changed
+270
-83
No files matched your search
@@ -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: '[email protected]',
|
||||
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: '[email protected]',
|
||||
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: '[email protected]', userId: 'u2' },
|
||||
});
|
||||
});
|
||||
|
||||
it('viewer cannot purge (errors:delete)', async () => {
|
||||
const request = {
|
||||
cookies: { '__Host-access': 'x' },
|
||||
headers: {},
|
||||
body: {},
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
sub: 'u1',
|
||||
email: '[email protected]',
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<SessionMutationOutcome> {
|
||||
const token = request.cookies[ACCESS_COOKIE];
|
||||
if (!token) {
|
||||
return null;
|
||||
return { kind: 'skip' };
|
||||
}
|
||||
try {
|
||||
const payload = await request.jwtVerify<JwtPayload>({ 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' };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
login: Record<string, unknown>;
|
||||
global: Record<string, unknown>;
|
||||
mutation: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown>,
|
||||
): Promise<void> {
|
||||
const actor_id = auth.via === 'session' ? auth.session.userId : null;
|
||||
const meta: Record<string, unknown> = {
|
||||
...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<string, unknown> {
|
||||
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<void> {
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user