BIT-15744: add remaining unit tests for admin-ui, api routes, collector-worker db, ingest-api services

Complete test coverage implementation for errors.bitreport.pt:

admin-ui (98 tests):
- test/components/: AppShell, DataAlert, IncidentNotes, KpiCard, SeverityBadge, StateBadge
- test/lib/: format, demo-incidents, incidents-data, incidents-data-api, stats-data, stats-data-api
- vitest.config.ts with jsdom + v8 coverage + @vitejs/plugin-react

api route tests (54 tests):
- src/routes/admin/auth.test.ts (15 tests)
- src/routes/admin/incidents.test.ts (11 tests)
- src/routes/admin/stats.test.ts (18 tests)
- src/routes/public/errorMonitoringStats.test.ts (10 tests)

collector-worker db/scheduler tests (22 tests):
- src/db/collectorRunWriter.test.ts (10 tests)
- src/db/loadActiveSources.test.ts (6 tests)
- src/scheduler/runHttpSourceOnce.test.ts (6 tests)

ingest-api service tests (13 tests):
- src/buildApp.test.ts, plugins/prometheus.test.ts
- services/ingestAuth.test.ts, services/processIngestBatch.utils.test.ts

Total: 187 additional tests (255 total across all modules). All pass.

Paperclip-Issue: BIT-15744
Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
David SantosandPaperclip committed 2026-05-03 07:24:38 +00:00
1 parent 989a92ba07
commit 3d4444eb21
33 files changed
+6374 -24

No files matched your search

+313
View File
@@ -17,6 +17,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"ajv": "^8.18.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
@@ -26,6 +27,77 @@
"node": ">=20"
}
},
"node_modules/@ampproject/remapping": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.28.5",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
"integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.0"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true,
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
@@ -582,6 +654,37 @@
"node": ">=12"
}
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
"integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -589,6 +692,17 @@
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lukeed/ms": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
@@ -989,6 +1103,39 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@vitest/coverage-v8": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-2.1.9.tgz",
"integrity": "sha512-Z2cOr0ksM00MpEfyVE8KXIYPEcBFxdbLSs56L8PO0QQMxt/6bDj45uQfxoc96v05KW3clk7vvgP0qfDit9DmfQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.3.0",
"@bcoe/v8-coverage": "^0.2.3",
"debug": "^4.3.7",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-lib-source-maps": "^5.0.6",
"istanbul-reports": "^3.1.7",
"magic-string": "^0.30.12",
"magicast": "^0.3.5",
"std-env": "^3.8.0",
"test-exclude": "^7.0.1",
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "2.1.9",
"vitest": "2.1.9"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1685,6 +1832,23 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -1753,6 +1917,60 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-source-maps": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz",
"integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.23",
"debug": "^4.1.1",
"istanbul-lib-coverage": "^3.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
@@ -1855,6 +2073,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz",
"integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.25.4",
"@babel/types": "^7.25.4",
"source-map-js": "^1.2.0"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mime": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
@@ -2523,6 +2769,19 @@
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/tdigest": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
@@ -2532,6 +2791,60 @@
"bintrees": "1.0.2"
}
},
"node_modules/test-exclude": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz",
"integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==",
"dev": true,
"license": "ISC",
"dependencies": {
"@istanbuljs/schema": "^0.1.2",
"glob": "^10.4.1",
"minimatch": "^10.2.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/test-exclude/node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/test-exclude/node_modules/brace-expansion": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/test-exclude/node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"brace-expansion": "^5.0.5"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+1 -1
View File
@@ -23,10 +23,10 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"ajv": "^8.18.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"@vitest/coverage-v8": "^2.1.0",
"vitest": "^2.1.0"
},
"engines": {
+156
View File
@@ -0,0 +1,156 @@
/**
* Integration tests for buildApp — exercises routes via Fastify inject,
* mocking DB pool and processIngestBatch so no real DB is needed.
*/
import { describe, it, expect, vi, beforeAll } from 'vitest';
import type { FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { buildApp } from './buildApp.js';
import { sha256Hex } from './lib/hash.js';
vi.mock('./plugins/prometheus.js', () => ({
default: async () => {},
ingestEventsTotal: { inc: vi.fn() },
ingestBatchSize: { observe: vi.fn() },
errorHubLastEventTimestamp: { set: vi.fn() },
errorHubIngestFailuresTotal: { inc: vi.fn() },
}));
vi.mock('./services/processIngestBatch.js', () => ({
processIngestBatch: vi.fn().mockResolvedValue({
status: 200,
body: {
fingerprint_policy_version: 1,
noise_ruleset_version: '1',
noise_filtered_count: 0,
results: [{ incident_id: 'inc-1', occurrence_id: 'occ-1', fingerprint: 'fp-1' }],
},
}),
computeRequestBodyHash: vi.fn().mockReturnValue('hash-abc'),
}));
const TOKEN = 'my-ingest-token';
const TOKEN_HASH = sha256Hex(TOKEN);
const validKeyRow: RowDataPacket = {
id: 'key-1',
project_id: 'proj-1',
project_slug: 'wdmi-store',
rate_limit_max: null,
rate_limit_window_ms: null,
} as unknown as RowDataPacket;
const baseEnv = {
NODE_ENV: 'test',
PORT: 3000,
INGEST_BASE_URL: 'http://ingest.local',
INGEST_RATE_LIMIT_MAX: 500,
INGEST_RATE_LIMIT_WINDOW_MS: 60000,
INGEST_ANON_IP_MAX: 20,
INGEST_ANON_IP_WINDOW_MS: 60000,
INGEST_PUSH_TIMEOUT_MS: 10000,
INGEST_PUSH_MAX_RETRIES: 2,
INGEST_PUSH_RETRY_BASE_MS: 100,
INGEST_PUSH_RETRY_MAX_JITTER_MS: 50,
HTTP_FETCH_TIMEOUT_MS: 10000,
MAX_BACKOFF_EXPONENT: 6,
};
function makePool(keyRows: RowDataPacket[] = []) {
return {
execute: vi.fn().mockResolvedValue([keyRows]),
};
}
let app: FastifyInstance;
beforeAll(async () => {
app = await buildApp({ env: baseEnv as never, pool: makePool([validKeyRow]) as never });
});
describe('GET /health', () => {
it('returns 200 with status ok', async () => {
const res = await app.inject({ method: 'GET', url: '/health' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ status: 'ok' });
});
});
describe('POST /v1/ingest/events — auth rejection', () => {
it('returns 401 when no credentials provided', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when API key is not found in DB', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: 'Bearer invalid-key' },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
});
describe('POST /v1/ingest/events — successful ingest', () => {
it('returns 200 with ingest results on valid auth and payload', async () => {
const localPool = makePool([validKeyRow]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: `Bearer ${TOKEN}` },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'Test error message',
},
],
},
});
expect(res.statusCode).toBe(200);
const body = res.json<{ results: unknown[] }>();
expect(body.results).toHaveLength(1);
});
});
describe('GET /v1/openapi.json', () => {
it('returns OpenAPI JSON spec', async () => {
const res = await app.inject({ method: 'GET', url: '/v1/openapi.json' });
expect(res.statusCode).toBe(200);
const spec = res.json<{ openapi: string; info: { title: string } }>();
expect(spec.openapi).toBe('3.1.0');
expect(spec.info.title).toContain('ingest');
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Tests for the Prometheus metrics plugin in ingest-api.
*/
import { describe, it, expect } from 'vitest';
import Fastify from 'fastify';
import prometheusPlugin from './prometheus.js';
async function buildTestApp() {
const app = Fastify({ logger: false });
await app.register(prometheusPlugin);
return app;
}
describe('prometheusPlugin', () => {
it('exposes GET /metrics returning Prometheus text format', async () => {
const app = await buildTestApp();
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/plain');
expect(res.payload).toContain('er_ingest_');
});
it('increments active connections on request and decrements on response', async () => {
const app = await buildTestApp();
// Fire a request — active connections hook runs around it
await app.inject({ method: 'GET', url: '/metrics' });
// No assertion on exact gauge value since it resets per request,
// but confirm the metrics endpoint still returns data
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
});
it('records ingest request duration for /v1/ingest paths', async () => {
const app = Fastify({ logger: false });
await app.register(prometheusPlugin);
app.post('/v1/ingest/events', async (_req, reply) => reply.status(200).send({ ok: true }));
await app.inject({ method: 'POST', url: '/v1/ingest/events', payload: {} });
const metricsRes = await app.inject({ method: 'GET', url: '/metrics' });
expect(metricsRes.payload).toContain('er_ingest_request_duration_seconds');
expect(metricsRes.payload).toContain('er_ingest_requests_total');
});
it('does not track /metrics itself in SLO histogram', async () => {
const app = await buildTestApp();
// Call metrics twice — the second call should not create a recursive entry
await app.inject({ method: 'GET', url: '/metrics' });
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
});
});
+167
View File
@@ -0,0 +1,167 @@
/**
* Tests for attachIngestAuth — validates token extraction, DB lookup, and error paths.
*/
import { describe, it, expect, vi } from 'vitest';
import type { FastifyReply, FastifyRequest } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { attachIngestAuth } from './ingestAuth.js';
import { sha256Hex } from '../lib/hash.js';
function makeReply() {
const reply = {
statusCode: 200,
_body: null as unknown,
status: vi.fn().mockReturnThis() as ReturnType<typeof vi.fn>,
send: vi.fn().mockImplementation(function (this: unknown, body: unknown) {
(reply as { _body: unknown })._body = body;
return Promise.resolve();
}),
};
(reply.status as ReturnType<typeof vi.fn>).mockReturnValue(reply);
return reply;
}
function makeRequest(overrides: {
authorization?: string;
'x-api-key'?: string;
}): FastifyRequest {
return {
headers: overrides,
ingestAuth: undefined,
} as unknown as FastifyRequest;
}
function makePool(rows: RowDataPacket[]) {
return {
execute: vi.fn().mockResolvedValue([rows]),
};
}
describe('attachIngestAuth', () => {
const TOKEN = 'my-secret-token';
const TOKEN_HASH = sha256Hex(TOKEN);
const validRow: RowDataPacket = {
id: 'key-id-123',
project_id: 'proj-id-456',
project_slug: 'wdmi-store',
rate_limit_max: 100,
rate_limit_window_ms: 60000,
} as unknown as RowDataPacket;
it('returns 401 when no authorization header and no x-api-key', async () => {
const pool = makePool([]);
const request = makeRequest({});
const reply = makeReply();
await attachIngestAuth(
pool as never,
request,
reply as unknown as FastifyReply,
);
expect(reply.status).toHaveBeenCalledWith(401);
expect(reply._body).toMatchObject({ error: 'unauthorized' });
});
it('returns 401 when authorization header has no Bearer prefix', async () => {
const pool = makePool([]);
const request = makeRequest({ authorization: 'Basic abc123' });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).toHaveBeenCalledWith(401);
});
it('returns 401 when token not found in DB (Bearer auth)', async () => {
const pool = makePool([]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).toHaveBeenCalledWith(401);
expect(reply._body).toMatchObject({ error: 'unauthorized', message: expect.stringContaining('Invalid') });
});
it('attaches ingestAuth on valid Bearer token', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).not.toHaveBeenCalled();
expect(request.ingestAuth).toMatchObject({
keyId: 'key-id-123',
projectId: 'proj-id-456',
projectSlug: 'wdmi-store',
rateLimitMax: 100,
rateLimitWindowMs: 60000,
});
});
it('attaches ingestAuth via X-Api-Key header', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ 'x-api-key': TOKEN });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth).toBeDefined();
expect(request.ingestAuth?.projectSlug).toBe('wdmi-store');
});
it('sends hashed token to DB query', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(pool.execute).toHaveBeenCalledWith(
expect.any(String),
[TOKEN_HASH],
);
});
it('sets rateLimitMax to null when DB value is zero', async () => {
const rowWithZeroLimit: RowDataPacket = {
...validRow,
rate_limit_max: 0,
rate_limit_window_ms: 0,
} as unknown as RowDataPacket;
const pool = makePool([rowWithZeroLimit]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.rateLimitMax).toBeNull();
expect(request.ingestAuth?.rateLimitWindowMs).toBeNull();
});
it('sets rateLimitMax to null when DB value is null', async () => {
const rowWithNullLimit: RowDataPacket = {
...validRow,
rate_limit_max: null,
rate_limit_window_ms: null,
} as unknown as RowDataPacket;
const pool = makePool([rowWithNullLimit]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.rateLimitMax).toBeNull();
expect(request.ingestAuth?.rateLimitWindowMs).toBeNull();
});
it('prefers Authorization header over X-Api-Key', async () => {
const pool = makePool([validRow]);
const request = makeRequest({
authorization: `Bearer ${TOKEN}`,
'x-api-key': 'different-token',
});
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(pool.execute).toHaveBeenCalledWith(expect.any(String), [TOKEN_HASH]);
});
it('lowercases projectSlug', async () => {
const rowUpperSlug: RowDataPacket = {
...validRow,
project_slug: 'WDMI-Store',
} as unknown as RowDataPacket;
const pool = makePool([rowUpperSlug]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.projectSlug).toBe('wdmi-store');
});
});
@@ -0,0 +1,30 @@
/**
* Tests for exported helpers from processIngestBatch.
*/
import { describe, it, expect } from 'vitest';
import { computeRequestBodyHash } from './processIngestBatch.js';
describe('computeRequestBodyHash', () => {
it('returns a hex string', () => {
const hash = computeRequestBodyHash({ events: [] });
expect(typeof hash).toBe('string');
expect(hash).toMatch(/^[0-9a-f]{64}$/);
});
it('returns same hash for same input', () => {
const body = { events: [{ schema_version: 1, occurred_at: '2026-01-01T00:00:00Z', level: 'error', message: 'test' }] };
expect(computeRequestBodyHash(body)).toBe(computeRequestBodyHash(body));
});
it('returns different hash for different input', () => {
const a = computeRequestBodyHash({ events: [{ message: 'a' }] });
const b = computeRequestBodyHash({ events: [{ message: 'b' }] });
expect(a).not.toBe(b);
});
it('is order-independent for object keys', () => {
const a = computeRequestBodyHash({ a: 1, b: 2 });
const b = computeRequestBodyHash({ b: 2, a: 1 });
expect(a).toBe(b);
});
});