caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

83 lines
2.8 KiB
Python

"""Fail-closed API-key authentication for the Prism public edge."""
from __future__ import annotations
import hashlib
import hmac
import os
from dataclasses import dataclass
from fastapi import HTTPException, Request
from .limits import RateLimiter
def key_fingerprint(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def configured_key_hashes() -> frozenset[str]:
raw = os.getenv("PRISM_API_KEY_SHA256S", "")
return frozenset(item.strip().lower() for item in raw.split(",") if item.strip())
@dataclass(frozen=True)
class Principal:
key_fingerprint: str
provider_key: str = ""
provider_api_key: str = ""
class ApiKeyAuthenticator:
def __init__(
self,
allowed_hashes: frozenset[str] | None = None,
rate_limiter: RateLimiter | None = None,
) -> None:
self._allowed_hashes = allowed_hashes
# Rate limiting is stateful across requests, so the limiter is built once
# (reading its ceiling from the environment) rather than per request.
self._rate_limiter = rate_limiter or RateLimiter.from_environment()
def authenticate(self, request: Request) -> Principal:
allowed = self._allowed_hashes
if allowed is None:
allowed = configured_key_hashes()
if not allowed:
raise HTTPException(
status_code=503, detail="Prism API keys are not configured"
)
authorization = request.headers.get("authorization", "")
bearer = (
authorization[7:].strip()
if authorization.lower().startswith("bearer ")
else ""
)
raw_key = bearer or request.headers.get("x-prism-key", "").strip()
fingerprint = key_fingerprint(raw_key) if raw_key else ""
if not fingerprint or not any(
hmac.compare_digest(fingerprint, expected) for expected in allowed
):
raise HTTPException(status_code=401, detail="Invalid Prism API key")
# Rate limit only authenticated fingerprints so an unknown key can never
# consume a valid key's budget, and a leaked key cannot flood the edge.
if not self._rate_limiter.allow(fingerprint):
raise HTTPException(
status_code=429, detail="Prism API key rate limit exceeded"
)
provider_key = request.headers.get("x-provider", "").strip()
provider_api_key = request.headers.get("x-provider-api-key", "").strip()
if bool(provider_key) != bool(provider_api_key):
raise HTTPException(
status_code=400,
detail="X-Provider and X-Provider-Api-Key must be supplied together",
)
return Principal(
key_fingerprint=fingerprint,
provider_key=provider_key,
provider_api_key=provider_api_key,
)