Coverage for src/pyrf_api/deps.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-06 21:54 +0000

1"""API dependencies: auth, etc.""" 

2 

3import os 

4 

5from fastapi import Depends, HTTPException 

6from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 

7 

8_SECURITY = HTTPBearer(auto_error=False) 

9 

10 

11def _auth_disabled() -> bool: 

12 """Check if bearer auth is disabled (for local dev / browser testing).""" 

13 val = os.environ.get("PYRF_API_AUTH_DISABLED", "").strip().lower() 

14 return val == "true" 

15 

16 

17def verify_bearer_token( 

18 credentials: HTTPAuthorizationCredentials | None = Depends(_SECURITY), # noqa: B008 

19) -> None: 

20 """Verify Bearer token against PYRF_API_TOKEN. No-op if PYRF_API_AUTH_DISABLED=true.""" 

21 if _auth_disabled(): 

22 return 

23 

24 expected = os.environ.get("PYRF_API_TOKEN", "").strip() 

25 if not expected: 

26 raise HTTPException( 

27 status_code=500, 

28 detail="Server misconfiguration: PYRF_API_TOKEN not set", 

29 ) 

30 

31 if credentials is None: 

32 raise HTTPException(status_code=401, detail="Missing Authorization header") 

33 

34 if credentials.scheme.lower() != "bearer": 

35 raise HTTPException(status_code=401, detail="Expected Bearer scheme") 

36 

37 if credentials.credentials != expected: 

38 raise HTTPException(status_code=401, detail="Unauthorized")