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