File size: 3,571 Bytes
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""
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"},
        )