feat(api): CRM parity mutations and recent-errors filters (BIT-726)
Add POST /api/error-monitoring/resolve, bulk-resolve, and purge-resolved with resolve key or admin JWT (errors:triage / errors:delete). Extend GET recent-errors with status, severity, project_slug, q, offset, and stable ordering. Document contracts in api/docs/ERROR_MONITORING_PUBLIC_API.md; add vitest for public auth helpers. Proxy new routes and widen admin-ui middleware for /api/error-monitoring/*. Paperclip-Issue: BIT-726 Paperclip-Run: 3fbf92be-736e-4b11-8e90-cf993d8cd5ca Paperclip-Agent: Pedro Alves (id d706f4e6-5d05-4cec-b6e8-f8fb1f203aae) Made-with: Cursor
This commit is contained in:
1 parent
e0af92eda1
commit
8b0044be82
10 files changed
+919
-49
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import {
|
||||
authorizeReadQuery,
|
||||
resolveMutationSecret,
|
||||
authorizeMutation,
|
||||
} from './errorMonitoringAuth.js';
|
||||
|
||||
function mockReply(): FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown } {
|
||||
let code: number | undefined;
|
||||
let body: unknown;
|
||||
const reply = {
|
||||
code(c: number) {
|
||||
code = c;
|
||||
return reply;
|
||||
},
|
||||
send(b: unknown) {
|
||||
body = b;
|
||||
return reply;
|
||||
},
|
||||
lastCode: () => code,
|
||||
lastBody: () => body,
|
||||
};
|
||||
return reply as FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown };
|
||||
}
|
||||
|
||||
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 };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...prev };
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', 'resolve-secret');
|
||||
});
|
||||
|
||||
it('allows matching api_key in body', async () => {
|
||||
const request = {
|
||||
query: {},
|
||||
cookies: {},
|
||||
headers: {},
|
||||
body: { api_key: 'resolve-secret' },
|
||||
jwtVerify: vi.fn(),
|
||||
} as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
const auth = await authorizeMutation(request, reply, { api_key: 'resolve-secret' }, 'errors:triage');
|
||||
expect(auth).toEqual({ via: 'api_key', session: null });
|
||||
});
|
||||
|
||||
it('returns 401 when key wrong and no session', async () => {
|
||||
const request = {
|
||||
query: {},
|
||||
cookies: {},
|
||||
headers: {},
|
||||
body: { api_key: 'bad' },
|
||||
jwtVerify: vi.fn(),
|
||||
} as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
const auth = await authorizeMutation(request, reply, { api_key: 'bad' }, 'errors:triage');
|
||||
expect(auth).toBeNull();
|
||||
expect(reply.lastCode()).toBe(401);
|
||||
});
|
||||
|
||||
it('resolveMutationSecret reads env', () => {
|
||||
expect(resolveMutationSecret()).toBe('resolve-secret');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* 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 session = await trySessionWithPermission(request, permission);
|
||||
if (session) {
|
||||
return { via: 'session', session };
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
async function trySessionWithPermission(
|
||||
request: FastifyRequest,
|
||||
permission: Permission,
|
||||
): Promise<{ email: string; userId: string } | null> {
|
||||
const token = request.cookies[ACCESS_COOKIE];
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const payload = await request.jwtVerify<JwtPayload>({ onlyCookie: false });
|
||||
if (!can(payload.role, permission)) {
|
||||
return null;
|
||||
}
|
||||
return { email: payload.email, userId: payload.sub };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
Reference in new issue
Block a user