Perps-Terminal / backend /security.py
Naufal Arhab
feat(sniper): implement dual-horizon (15m-1D) sniper engine, forward outcome evaluator, auto-breakeven SL, and UI surfacing
740fcec
Raw History Blame Contribute Delete
3.57 kB
"""
API Authentication & Fail-Closed Security Utilities
===================================================
Enforces constant-time Bearer token validation using PERPS_API_TOKEN for
all sensitive operational routes (/api/execution/*, /api/pairs*, /api/journal*).
Design:
- Fail closed (HTTP 503) if PERPS_API_TOKEN is unset or blank.
- Reject missing/malformed/invalid Bearer tokens with HTTP 401.
- Never log or expose secret tokens in error responses.
"""
import hmac
import os
from fastapi import HTTPException, Request
import config
# Optional runtime override attribute for isolated unit testing.
PERPS_API_TOKEN: str | None = None
CRON_SECRET: str | None = None
def get_configured_api_token() -> str:
"""Resolve the active PERPS_API_TOKEN without failing open."""
if PERPS_API_TOKEN is not None:
return PERPS_API_TOKEN.strip()
cfg_val = getattr(config, "PERPS_API_TOKEN", None)
if cfg_val is not None:
return str(cfg_val).strip()
return os.getenv("PERPS_API_TOKEN", "").strip()
def get_configured_cron_secret() -> str:
"""Resolve optional Vercel/scheduler CRON_SECRET."""
if CRON_SECRET is not None:
return CRON_SECRET.strip()
cfg_val = getattr(config, "CRON_SECRET", None)
if cfg_val is not None:
return str(cfg_val).strip()
return os.getenv("CRON_SECRET", "").strip()
def is_auth_configured() -> bool:
"""Return True when PERPS_API_TOKEN is non-empty."""
return bool(get_configured_api_token())
def _extract_bearer_token(request: Request) -> str:
auth_header = (request.headers.get("Authorization") or "").strip()
if not auth_header:
return ""
parts = auth_header.split(None, 1)
if len(parts) != 2 or parts[0].lower() != "bearer":
return ""
return parts[1].strip()
def _matches_any_token(provided: str, valid_tokens: list[str]) -> bool:
if not provided:
return False
provided_bytes = provided.encode("utf-8")
matched = False
for expected in valid_tokens:
if expected and hmac.compare_digest(provided_bytes, expected.encode("utf-8")):
matched = True
return matched
async def require_api_token(request: Request) -> None:
"""FastAPI dependency enforcing fail-closed Bearer token authentication."""
expected = get_configured_api_token()
if not expected:
raise HTTPException(
status_code=503,
detail="Server API token (PERPS_API_TOKEN) is not configured. Protected routes fail closed.",
)
provided = _extract_bearer_token(request)
if not _matches_any_token(provided, [expected]):
raise HTTPException(
status_code=401,
detail="Unauthorized: invalid or missing Bearer token.",
headers={"WWW-Authenticate": "Bearer"},
)
async def require_cron_or_api_token(request: Request) -> None:
"""Accept either CRON_SECRET or PERPS_API_TOKEN for scheduled cron triggers (fail closed)."""
valid_tokens = [tok for tok in (get_configured_cron_secret(), get_configured_api_token()) if tok]
if not valid_tokens:
raise HTTPException(
status_code=503,
detail="Neither CRON_SECRET nor PERPS_API_TOKEN is configured. Cron endpoint fails closed.",
)
provided = _extract_bearer_token(request)
if not _matches_any_token(provided, valid_tokens):
raise HTTPException(
status_code=401,
detail="Unauthorized: invalid or missing cron Bearer token.",
headers={"WWW-Authenticate": "Bearer"},
)