Files
webmail/app/api/errors/__tests__/route.test.ts
T
Linus Rath cba1109444 feat: report browser and server errors to an error tracker the admin sets
Admins had logs and nothing else: client errors only reached the
browser console. An admin can now set a Sentry-protocol address (DSN)
for Bugsink, GlitchTip or Sentry under System > Monitoring, or with
`ERROR_REPORTING_DSN`, `ERROR_REPORTING_DSN_FILE`,
`ERROR_REPORTING_SAMPLE_RATE` and `ERROR_REPORTING_ENVIRONMENT`.
Bulwark Lite reads the same from `errorReporting` in policy.json.
Everything stays off while no address is set.

- browsers report errors from the error boundaries, window.onerror,
  unhandled rejections and failed JMAP requests (method and error type
  only), with route and JMAP method breadcrumbs and the chunks' debug IDs
- the server reports what Next hands to onRequestError and what routes
  log with logger.error
- every report is scrubbed first: quoted text, addresses, URLs, file
  names, tokens and the rest after the first line are removed, and the
  server scrubs what browsers post to /api/errors again
- reports are deduplicated and rate-limited per session and process
- errors are counted per day for "errors today" on the admin page
- startup messages and audit entries go through the logger, so
  `LOG_FORMAT=json` covers them
2026-11-01 02:50:19 +01:00

90 lines
3.2 KiB
TypeScript

// @vitest-environment node
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
const config: Record<string, unknown> = {};
vi.mock('@/lib/admin/config-manager', () => ({
configManager: {
ensureLoaded: async () => {},
get: (key: string, fallback: unknown) => (key in config ? config[key] : fallback),
},
}));
import { POST } from '../route';
import { flushErrors, readErrors, resetAggregateForTests, utcDay } from '@/lib/error-reporting/aggregate';
const DSN = 'https://6f0b9c79ed3a4315b76595bc2536ac40@bugsink.example.org/3';
const SUBJECT = 'Merger plans for Acme Q3';
let dir: string;
let ip = 0;
function post(body: unknown): NextRequest {
ip += 1;
return new NextRequest('http://localhost/api/errors', {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-forwarded-for': `203.0.113.${ip}` },
body: typeof body === 'string' ? body : JSON.stringify(body),
});
}
const report = {
name: 'TypeError',
message: `Cannot open "${SUBJECT}"`,
frames: [{ path: `https://mail.example.org/_next/static/chunks/1.js?subject=${encodeURIComponent(SUBJECT)}`, line: 2, column: 30, fn: 'Ab' }],
version: '1.20.0',
};
beforeEach(() => {
dir = mkdtempSync(path.join(tmpdir(), 'bulwark-errors-route-'));
process.env.TELEMETRY_DATA_DIR = dir;
for (const key of Object.keys(config)) delete config[key];
resetAggregateForTests();
});
afterEach(() => {
resetAggregateForTests();
delete process.env.TELEMETRY_DATA_DIR;
rmSync(dir, { recursive: true, force: true });
});
describe('POST /api/errors', () => {
it('keeps nothing while error collection is off', async () => {
const res = await POST(post(report));
expect(res.status).toBe(204);
await flushErrors();
expect(await readErrors()).toEqual({});
});
it('counts a report, scrubbed again, without its message', async () => {
config.errorReportingDsn = DSN;
expect((await POST(post(report))).status).toBe(204);
await flushErrors();
const stored = JSON.stringify(await readErrors());
expect(stored).not.toContain('Merger');
expect(stored).not.toContain('subject=');
const [entry] = Object.values((await readErrors())[utcDay()]);
expect(entry).toMatchObject({ name: 'TypeError', runtime: 'browser', version: '1.20.0', count: 1 });
expect(entry.frames).toEqual([{ path: '/_next/static/chunks/1.js', line: 2, column: 30, fn: 'Ab' }]);
});
it('ignores a name or code that is not an identifier or fixed code', async () => {
config.errorReportingDsn = DSN;
await POST(post({ ...report, name: SUBJECT, code: SUBJECT }));
await flushErrors();
const [entry] = Object.values((await readErrors())[utcDay()]);
expect(entry.name).toBe('Error');
expect(entry.code).toBeUndefined();
});
it('refuses bodies that are too large or not JSON objects', async () => {
config.errorReportingDsn = DSN;
expect((await POST(post('x'.repeat(17 * 1024)))).status).toBe(413);
expect((await POST(post('[1,2]'))).status).toBe(400);
expect((await POST(post('not json'))).status).toBe(400);
});
});