/** * `src/auth/internal-token.ts` -- verification for the ONE machine-to-machine * credential 0pt already uses for engine (Python) -> edge (Next.js) calls: * the `X-Internal-Token` header, checked against the `INTERNAL_TOKEN` env var * (the same shared secret `lib/engine.ts` and `lib/health-checks.ts` already * send on the opposite-direction edge -> engine calls). * * P014 FIX: `services/api/workers/quality_bridge.py` has always called * `POST /api/0pt/quality/bridge-run` with `X-Internal-Token`, never an * `Authorization: Bearer` header. But this route sits under * `/api/0pt/:path*`, which `middleware.ts` guards unconditionally with real * Zitadel Bearer verification -- and nothing anywhere checked * `X-Internal-Token` as an alternative credential. The result: in any * environment with the default `AUTH_ENFORCE` posture (enforced), the * Python engine's ONLY call into this bridge was rejected with 401 by * middleware before the route handler ever ran. `OPT_QUALITY_BRIDGE_ENABLED=true` * therefore could never actually succeed against a real deployment -- * quality_bridge.py's fail-open design (see its own docstring) silently * absorbed the 401 as `status: "unavailable"`, so nothing outwardly broke, * but the whole point of building the bridge (an advisory second opinion * from the TS QualityService) was unreachable. Neither test suite caught * this: the TS test (tests/p0/quality-bridge.test.ts) calls the route's * POST function directly, bypassing middleware.ts entirely; the Python test * (services/api/tests/test_quality_bridge.py) mocks the HTTP layer and never * exercises the edge's real auth gate. * * This module verifies `X-Internal-Token` in constant time. middleware.ts * accepts it ONLY for the one route the engine actually calls * (`/api/0pt/quality/bridge-run`) -- not a blanket bypass for the rest of * `/api/0pt/*`. Fails closed: an unset/empty `INTERNAL_TOKEN` env var never * authenticates, even against an empty or missing header (no accidental * "unset equals unset, so let it through"). * * Uses only Web APIs (`TextEncoder`), not `node:crypto` -- Next.js * middleware runs on the Edge runtime, which does not expose Node's * `crypto.timingSafeEqual`. */ /** Minimal header accessor -- Web `Headers` and `NextRequest.headers` satisfy this. */ export interface HeaderLookup { get(name: string): string | null | undefined; } export const INTERNAL_TOKEN_HEADER = "x-internal-token"; /** Constant-time-ish byte comparison (Edge-runtime safe: no node:crypto). */ function timingSafeEqualStr(a: string, b: string): boolean { const enc = new TextEncoder(); const aBytes = enc.encode(a); const bBytes = enc.encode(b); const len = Math.max(aBytes.length, bBytes.length); let diff = aBytes.length ^ bBytes.length; for (let i = 0; i < len; i++) { diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0); } return diff === 0; } /** * True only when `X-Internal-Token` is present AND matches a non-empty * configured `INTERNAL_TOKEN`. Fails closed on every other combination * (missing header, missing/empty env var, mismatch). */ export function verifyInternalServiceToken( headers: HeaderLookup, // @types/node 22's ProcessEnv has only an index signature, so a direct // default is not assignable to the narrow named-property shape. This is a // type-only view of the same object; runtime behaviour is unchanged. env: { INTERNAL_TOKEN?: string } = process.env as { INTERNAL_TOKEN?: string }, ): boolean { const expected = env.INTERNAL_TOKEN?.trim(); if (!expected) return false; const provided = headers.get(INTERNAL_TOKEN_HEADER); if (!provided) return false; return timingSafeEqualStr(provided, expected); }