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
@@ -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' };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user