import type { Pool } from "mysql2/promise"; import type { RowDataPacket } from "mysql2"; import type { FastifyReply, FastifyRequest } from "fastify"; import { sha256Hex } from "../lib/hash.js"; export type IngestAuthContext = { keyId: string; projectId: string; /** Lowercase `er_projects.slug` — Prometheus `project_slug` label (BIT-4903). */ projectSlug: string; rateLimitMax: number | null; rateLimitWindowMs: number | null; }; function _extractBearerToken(header: string | undefined): string | null { if (typeof header !== "string" || header.trim() === "") { return null; } const _m = /^Bearer\s+(\S+)$/i.exec(header.trim()); if (_m) { return _m[1] ?? null; } return null; } export async function attachIngestAuth( pool: Pool, request: FastifyRequest, reply: FastifyReply, ): Promise { const _fromAuth = _extractBearerToken(request.headers.authorization); const _fromHeader = typeof request.headers["x-api-key"] === "string" ? request.headers["x-api-key"].trim() : ""; const _token = _fromAuth ?? (_fromHeader !== "" ? _fromHeader : null); if (_token === null) { await reply.status(401).send({ error: "unauthorized", message: "Missing ingest credentials (Authorization: Bearer or X-Api-Key).", }); return; } const _hash = sha256Hex(_token); const [rows] = await pool.execute( `SELECT CAST(k.id AS CHAR) AS id, CAST(k.project_id AS CHAR) AS project_id, LOWER(p.slug) AS project_slug, k.rate_limit_max, k.rate_limit_window_ms FROM er_ingest_keys k INNER JOIN er_projects p ON p.id = k.project_id WHERE k.token_hash = ? AND k.status = 'active' AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at > NOW(6))`, [_hash], ); if (rows.length === 0) { await reply.status(401).send({ error: "unauthorized", message: "Invalid or inactive ingest key.", }); return; } const _row = rows[0] as { id: string; project_id: string; project_slug: string; rate_limit_max: unknown; rate_limit_window_ms: unknown; }; if (!_row) { await reply.status(401).send({ error: "unauthorized", message: "Invalid or inactive ingest key.", }); return; } const _rlMaxNum = _row.rate_limit_max != null ? Number(_row.rate_limit_max) : NaN; const _rlWinNum = _row.rate_limit_window_ms != null ? Number(_row.rate_limit_window_ms) : NaN; request.ingestAuth = { keyId: _row.id, projectId: _row.project_id, projectSlug: String(_row.project_slug ?? "").trim().toLowerCase(), rateLimitMax: Number.isFinite(_rlMaxNum) && _rlMaxNum > 0 ? _rlMaxNum : null, rateLimitWindowMs: Number.isFinite(_rlWinNum) && _rlWinNum > 0 ? _rlWinNum : null, }; }