|
| 1 | +import { createHash } from "node:crypto"; |
| 2 | + |
| 3 | +import { redactOtlpBody, upsertResourceAttribute, type OtlpTraceBody } from "~/lib/otelRedact"; |
| 4 | +import { allow, type RateLimitTier } from "~/lib/otelRateLimit"; |
| 5 | +import { tokenHash, verifyJiraToken } from "~/lib/otelVerifier"; |
| 6 | + |
| 7 | +export const runtime = "nodejs"; |
| 8 | + |
| 9 | +const SERVICE_NAME = "marcode"; |
| 10 | + |
| 11 | +function readBearerToken(request: Request): string | undefined { |
| 12 | + const header = request.headers.get("authorization") ?? request.headers.get("Authorization"); |
| 13 | + if (!header) return undefined; |
| 14 | + const match = /^Bearer\s+(.+)$/i.exec(header.trim()); |
| 15 | + return match?.[1]?.trim() || undefined; |
| 16 | +} |
| 17 | + |
| 18 | +function readClientIp(request: Request): string { |
| 19 | + const forwardedFor = request.headers.get("x-forwarded-for"); |
| 20 | + if (forwardedFor) { |
| 21 | + const first = forwardedFor.split(",")[0]?.trim(); |
| 22 | + if (first) return first; |
| 23 | + } |
| 24 | + return request.headers.get("x-real-ip") ?? "unknown"; |
| 25 | +} |
| 26 | + |
| 27 | +function parseExtraHeaders(input: string | undefined): Record<string, string> { |
| 28 | + if (!input) return {}; |
| 29 | + const out: Record<string, string> = {}; |
| 30 | + for (const part of input.split(",")) { |
| 31 | + const [name, ...rest] = part.split("="); |
| 32 | + if (!name) continue; |
| 33 | + const value = rest.join("=").trim(); |
| 34 | + if (!value) continue; |
| 35 | + out[name.trim()] = value; |
| 36 | + } |
| 37 | + return out; |
| 38 | +} |
| 39 | + |
| 40 | +function isOtlpTraceBody(value: unknown): value is OtlpTraceBody { |
| 41 | + return ( |
| 42 | + typeof value === "object" && |
| 43 | + value !== null && |
| 44 | + "resourceSpans" in value && |
| 45 | + Array.isArray((value as { resourceSpans: unknown }).resourceSpans) |
| 46 | + ); |
| 47 | +} |
| 48 | + |
| 49 | +export async function POST(request: Request): Promise<Response> { |
| 50 | + const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; |
| 51 | + if (!endpoint) { |
| 52 | + return Response.json({ error: "OTEL ingest not configured" }, { status: 503 }); |
| 53 | + } |
| 54 | + |
| 55 | + const ip = readClientIp(request); |
| 56 | + const ipHash = createHash("sha256").update(ip).digest("hex").slice(0, 16); |
| 57 | + const token = readBearerToken(request); |
| 58 | + const limitKey = `${ip}:${token ? tokenHash(token) : "anon"}`; |
| 59 | + |
| 60 | + const verification = token ? await verifyJiraToken(token) : { valid: false, isGenesis: false }; |
| 61 | + const isGenesis = verification.isGenesis; |
| 62 | + const tier: RateLimitTier = verification.valid ? "authed" : "anonymous"; |
| 63 | + |
| 64 | + if (!isGenesis) { |
| 65 | + const result = allow(limitKey, tier); |
| 66 | + if (!result.allowed) { |
| 67 | + return new Response(JSON.stringify({ error: "Rate limit exceeded" }), { |
| 68 | + status: 429, |
| 69 | + headers: { |
| 70 | + "Content-Type": "application/json", |
| 71 | + "Retry-After": Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1000)).toString(), |
| 72 | + }, |
| 73 | + }); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + let body: unknown; |
| 78 | + try { |
| 79 | + body = await request.json(); |
| 80 | + } catch { |
| 81 | + return Response.json({ error: "Invalid JSON body" }, { status: 400 }); |
| 82 | + } |
| 83 | + if (!isOtlpTraceBody(body)) { |
| 84 | + return Response.json({ error: "Body must be OTLP/JSON with resourceSpans" }, { status: 400 }); |
| 85 | + } |
| 86 | + |
| 87 | + upsertResourceAttribute(body, "service.name", { stringValue: SERVICE_NAME }); |
| 88 | + upsertResourceAttribute(body, "user.is_genesis", { boolValue: isGenesis }); |
| 89 | + upsertResourceAttribute(body, "ingest.client_ip_hash", { stringValue: ipHash }); |
| 90 | + redactOtlpBody(body); |
| 91 | + |
| 92 | + const extraHeaders = parseExtraHeaders(process.env.OTEL_EXPORTER_OTLP_TRACES_HEADERS); |
| 93 | + let upstream: Response; |
| 94 | + try { |
| 95 | + upstream = await fetch(endpoint, { |
| 96 | + method: "POST", |
| 97 | + headers: { "Content-Type": "application/json", ...extraHeaders }, |
| 98 | + body: JSON.stringify(body), |
| 99 | + }); |
| 100 | + } catch (cause) { |
| 101 | + return Response.json({ error: "Trace export failed", detail: String(cause) }, { status: 502 }); |
| 102 | + } |
| 103 | + if (!upstream.ok) { |
| 104 | + const text = await upstream.text().catch(() => ""); |
| 105 | + return new Response(JSON.stringify({ error: "Tempo rejected the trace", detail: text }), { |
| 106 | + status: 502, |
| 107 | + headers: { "Content-Type": "application/json" }, |
| 108 | + }); |
| 109 | + } |
| 110 | + return new Response(null, { status: 204 }); |
| 111 | +} |
0 commit comments