Files
0pt/src/auth/internal-token.ts
T
siax-bot 680fa7ee6b
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / Component conformance (blocking) (pull_request) Successful in 13s
CI (SIAX Cloud) / security (pull_request) Successful in 25s
masterplan-lock / check (pull_request) Successful in 8s
security / scan (pull_request) Failing after 51s
CI (SIAX Cloud) / integration (pull_request) Successful in 3m33s
CI (SIAX Cloud) / quality (pull_request) Successful in 4m30s
fix(ci): repair baseline typecheck and pnpm supply-chain config
- pnpm-workspace.yaml: blockExoticSubdeps, minimumReleaseAge=10080,
  trustPolicy=no-downgrade (Semgrep p/ci blocking rules)
- src/auth/{internal-service-tenant,internal-token}.ts: type-only view of
  process.env for narrow named-property defaults (@types/node 22 ProcessEnv)
- tests: typed mutable env view for NODE_ENV save/restore (readonly in
  @types/node 22). No auth check weakened, no runtime behaviour changed.

Verification: pnpm run typecheck EXIT 0 (was 8 errors); vitest 30/30 PASS.
2026-11-17 21:17:32 +01:00

77 lines
3.6 KiB
TypeScript

/**
* `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);
}