Files
errors.bitreport.pt/api/src/lib/errorMonitoringAuth.ts
T
David Santos 7b2be679cd 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
2026-04-02 10:52:40 +00:00

157 lines
4.8 KiB
TypeScript

/**
* Shared auth for CRM-shaped public error-monitoring routes on the hub.
* Read: api_key / view_errors query params.
* Mutations: ERROR_RESOLVE_API_KEY (or ERROR_REPORTING_API_KEY) via body or
* X-Error-Resolve-Key, or admin session (JWT cookie) with RBAC permission.
*/
import type { FastifyReply, FastifyRequest } from 'fastify';
import { safeEqual } from '../plugins/auth.js';
import { can, type JwtPayload, type Permission } from '../types/auth.js';
const ACCESS_COOKIE = '__Host-access';
export function resolveReadSecrets(): { apiKey: string; viewKey: string } {
const apiKey =
(process.env.ERROR_RESOLVE_API_KEY ?? process.env.ERROR_REPORTING_API_KEY ?? '').trim();
const viewKey = (process.env.DEBUG_VIEW_ERRORS_KEY ?? '').trim();
return { apiKey, viewKey };
}
export function resolveMutationSecret(): string {
const k = (process.env.ERROR_RESOLVE_API_KEY ?? process.env.ERROR_REPORTING_API_KEY ?? '').trim();
return k;
}
export function authorizeReadQuery(request: FastifyRequest, reply: FastifyReply): boolean {
const { apiKey, viewKey } = resolveReadSecrets();
if (!apiKey && !viewKey) {
reply.code(503).send({
success: false,
message:
'Recent-errors API is not configured (set ERROR_RESOLVE_API_KEY and/or DEBUG_VIEW_ERRORS_KEY).',
});
return false;
}
const q = request.query as { api_key?: string; view_errors?: string };
const providedApi = typeof q.api_key === 'string' ? q.api_key : '';
const providedView = typeof q.view_errors === 'string' ? q.view_errors : '';
if (apiKey && providedApi && safeEqual(providedApi, apiKey)) {
return true;
}
if (viewKey && providedView && safeEqual(providedView, viewKey)) {
return true;
}
reply.code(401).send({
success: false,
message: 'Unauthorized',
});
return false;
}
function sentResolveKeyFromRequest(
request: FastifyRequest,
body: Record<string, unknown>,
): string {
const fromBody = body.api_key;
const header = request.headers['x-error-resolve-key'];
const h = Array.isArray(header) ? header[0] : header;
const fromHeader = typeof h === 'string' ? h : '';
const b = typeof fromBody === 'string' ? fromBody : '';
return (b || fromHeader).trim();
}
/**
* CRM parity: if a resolve key is configured, caller must send a matching key
* OR present a valid admin session with `permission`. If no resolve key is set,
* only session + permission is accepted (token-only automation disabled).
*/
export type MutationAuth =
| { via: 'api_key'; session: null }
| { via: 'session'; session: { email: string; userId: string } };
export async function authorizeMutation(
request: FastifyRequest,
reply: FastifyReply,
body: Record<string, unknown>,
permission: Permission,
): Promise<MutationAuth | null> {
const resolveKey = resolveMutationSecret();
const sent = sentResolveKeyFromRequest(request, body);
if (resolveKey && sent && safeEqual(sent, resolveKey)) {
return { via: 'api_key', session: null };
}
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) {
reply.code(401).send({
success: false,
message: 'Unauthorized (session or ERROR_RESOLVE_API_KEY required)',
});
return null;
}
reply.code(401).send({
success: false,
message: 'Unauthorized',
});
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<SessionMutationOutcome> {
const token = request.cookies[ACCESS_COOKIE];
if (!token) {
return { kind: 'skip' };
}
try {
const payload = await request.jwtVerify<JwtPayload>({ onlyCookie: false });
if (!can(payload.role, permission)) {
reply.code(403).send({
success: false,
message: `Forbidden: role '${payload.role}' cannot perform this mutation`,
});
return { kind: 'forbidden' };
}
return { kind: 'ok', session: { email: payload.email, userId: payload.sub } };
} catch {
return { kind: 'invalid_session' };
}
}
export function changedByRef(auth: MutationAuth): { type: 'api_key' | 'user'; ref: string } {
if (auth.via === 'api_key') {
return { type: 'api_key', ref: 'resolve_api' };
}
const email = auth.session.email || 'unknown';
const ref = email.length > 128 ? email.slice(0, 125) + '...' : email;
return { type: 'user', ref };
}