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]>
168 lines
5.9 KiB
TypeScript
168 lines
5.9 KiB
TypeScript
/**
|
|
* 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');
|
|
});
|
|
});
|