import { randomUUID } from "node:crypto"; import fastify from "fastify"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import swagger from "@fastify/swagger"; import swaggerUi from "@fastify/swagger-ui"; import type { Pool } from "mysql2/promise"; import type { IngestEnv } from "./config/env.js"; import { attachIngestAuth } from "./services/ingestAuth.js"; import { createIngestRateLimiter } from "./services/ingestRateLimit.js"; import { computeRequestBodyHash, processIngestBatch, type IngestEventInput, } from "./services/processIngestBatch.js"; import prometheusPlugin, { ingestEventsTotal, ingestBatchSize, } from "./plugins/prometheus.js"; import { ingestBatchBodyJsonSchema } from "./ingestJsonSchemas.js"; const _ingestResultStoredSchema = { type: "object", additionalProperties: false, required: ["incident_id", "occurrence_id", "fingerprint"], properties: { incident_id: { type: "string" }, occurrence_id: { type: "string" }, fingerprint: { type: "string" }, }, } as const; const _ingestResultSkippedSchema = { type: "object", additionalProperties: false, required: ["skipped", "rule_id", "reason", "noise_ruleset_version", "fingerprint_policy_version"], properties: { skipped: { type: "boolean", enum: [true] }, rule_id: { type: "string" }, reason: { type: "string" }, noise_ruleset_version: { type: "string" }, fingerprint_policy_version: { type: "integer" }, }, } as const; function _ingestEventsPostPath(url: string): boolean { const _path = url.split("?", 1)[0] ?? url; return _path === "/v1/ingest/events" || _path.endsWith("/v1/ingest/events"); } export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { const _ingestLimiter = createIngestRateLimiter(); const _app = fastify({ logger: true, requestIdHeader: "x-request-id", genReqId: () => randomUUID(), }); await _app.register(swagger, { openapi: { openapi: "3.1.0", info: { title: "BitReport error reporting — passive ingest API", description: "Authenticated per-project ingest for error events (BIT-154.3). Keys are hashed at rest; send the raw token via `Authorization: Bearer` or `X-Api-Key`.", version: "0.1.0", }, servers: [{ url: "/" }], tags: [{ name: "ingest", description: "Event ingestion" }], components: { securitySchemes: { bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "opaque token", }, apiKeyAuth: { type: "apiKey", in: "header", name: "X-Api-Key", }, }, }, }, }); await _app.register(swaggerUi, { routePrefix: "/v1/docs/ui", uiConfig: { docExpansion: "list", deepLinking: true }, }); await _app.register(prometheusPlugin); _app.get("/health", { schema: { description: "Liveness probe", tags: ["ingest"], response: { 200: { type: "object", properties: { status: { type: "string" } }, }, }, }, handler: async () => ({ status: "ok" }), }); await _app.register( async (ingestScope: FastifyInstance) => { ingestScope.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => { if (request.method !== "POST" || !_ingestEventsPostPath(request.url)) { return; } const _auth = request.headers.authorization; const _ak = request.headers["x-api-key"]; const _hasCred = (typeof _auth === "string" && _auth.trim() !== "") || (typeof _ak === "string" && _ak.trim() !== ""); if (_hasCred) { return; } const _r = _ingestLimiter.tryConsume( `anon_ip:${request.ip}`, input.env.INGEST_ANON_IP_MAX, input.env.INGEST_ANON_IP_WINDOW_MS, ); if (!_r.ok) { reply.header("retry-after", String(_r.retryAfterSec)); return reply.status(429).send({ error: "rate_limited", message: "Too many unauthenticated ingest attempts from this address.", }); } }); ingestScope.post("/events", { schema: { description: "Ingest one or more error events for the project bound to the API key.", tags: ["ingest"], security: [{ bearerAuth: [] }, { apiKeyAuth: [] }], body: ingestBatchBodyJsonSchema, response: { 200: { type: "object", properties: { fingerprint_policy_version: { type: "integer" }, noise_ruleset_version: { type: "string" }, noise_filtered_count: { type: "integer" }, results: { type: "array", items: { oneOf: [_ingestResultStoredSchema, _ingestResultSkippedSchema], }, }, }, required: [ "fingerprint_policy_version", "noise_ruleset_version", "noise_filtered_count", "results", ], }, 401: { type: "object", properties: { error: { type: "string" }, message: { type: "string" }, }, }, 429: { type: "object", properties: { error: { type: "string" }, message: { type: "string" }, }, }, 409: { type: "object", properties: { error: { type: "string" }, message: { type: "string" }, }, }, 500: { type: "object", properties: { error: { type: "string" }, message: { type: "string" }, }, }, }, }, preValidation: async (request: FastifyRequest, reply: FastifyReply) => { await attachIngestAuth(input.pool, request, reply); }, preHandler: async (request: FastifyRequest, reply: FastifyReply) => { const _a = request.ingestAuth; if (!_a) { return; } const _max = _a.rateLimitMax ?? input.env.INGEST_RATE_LIMIT_MAX; const _win = _a.rateLimitWindowMs ?? input.env.INGEST_RATE_LIMIT_WINDOW_MS; const _r = _ingestLimiter.tryConsume(`ingest_key:${_a.keyId}`, _max, _win); if (!_r.ok) { reply.header("retry-after", String(_r.retryAfterSec)); return reply.status(429).send({ error: "rate_limited", message: "Ingest rate limit exceeded for this API key; retry after the Retry-After interval.", }); } }, handler: async (request: FastifyRequest, reply: FastifyReply) => { if (!request.ingestAuth) { return; } const _body = request.body as { events: IngestEventInput[] }; const _idemHeader = request.headers["idempotency-key"]; const _idempotencyKey = typeof _idemHeader === "string" && _idemHeader.trim() !== "" ? _idemHeader.trim().slice(0, 128) : null; const _bodyHash = computeRequestBodyHash(_body); try { ingestBatchSize.observe(_body.events.length); const _out = await processIngestBatch({ pool: input.pool, ingestKeyId: request.ingestAuth.keyId, projectId: request.ingestAuth.projectId, events: _body.events, idempotencyKey: _idempotencyKey, bodyHash: _bodyHash, }); // Track event outcomes if (_out.body && typeof _out.body === 'object' && 'results' in _out.body) { const results = (_out.body as { results: Array<{ skipped?: boolean }> }).results; let stored = 0; let skipped = 0; for (const r of results) { if (r.skipped) skipped++; else stored++; } if (stored > 0) ingestEventsTotal.inc({ outcome: 'stored' }, stored); if (skipped > 0) ingestEventsTotal.inc({ outcome: 'skipped_noise' }, skipped); } return reply.status(_out.status).send(_out.body); } catch (_err) { const _msg = _err instanceof Error ? _err.message : "ingest_failed"; if (_msg === "unsupported_schema_version") { return reply.status(400).send({ error: "bad_request", message: "Unsupported schema_version (only 1 is accepted).", }); } if (_msg === "invalid_occurred_at") { return reply.status(400).send({ error: "bad_request", message: "occurred_at must be a valid ISO-8601 timestamp.", }); } ingestEventsTotal.inc({ outcome: 'error' }, _body.events.length); request.log.error(_err, "ingest_failed"); return reply.status(500).send({ error: "internal_error", message: input.env.NODE_ENV === "production" ? "Ingest failed; see server logs for request id." : _msg, }); } }, }); }, { prefix: "/v1/ingest" }, ); _app.addHook("onSend", async (_request: FastifyRequest, reply: FastifyReply) => { reply.header("X-Content-Type-Options", "nosniff"); }); _app.get("/v1/openapi.json", async (_request: FastifyRequest, reply: FastifyReply) => { return reply.send(_app.swagger()); }); return _app; }