Coverage for app / middleware / internal_auth.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Internal authentication middleware for svc-ai. 

3 

4svc-ai is not internet-facing and is called only by svc-core. Every request 

5(other than unauthenticated health/liveness probes) must carry a valid, 

6audience-bound internal JWT minted by svc-core. This prevents anyone with 

7network reach to svc-ai from executing arbitrary LLM/agent runs — which would 

8otherwise burn provider credits and expose a prompt-injection / tool-execution 

9surface. 

10 

11When ``INTERNAL_JWT_SECRET`` is unset the middleware is inert (legacy / 

12migration), and a warning is emitted once at import so the gap is visible. 

13""" 

14 

15import logging 

16 

17import jwt 

18from fastapi import Request 

19from fastapi.responses import JSONResponse 

20from starlette.middleware.base import BaseHTTPMiddleware 

21 

22from app.common.settings import get_settings 

23 

24logger = logging.getLogger(__name__) 

25 

26# Paths reachable without an internal token (probes + API docs). 

27_EXEMPT_PATHS = {"/health", "/docs", "/docs/oauth2-redirect", "/openapi.json", "/redoc"} 

28 

29 

30class InternalAuthMiddleware(BaseHTTPMiddleware): 

31 async def dispatch(self, request: Request, call_next): 

32 settings = get_settings() 

33 

34 if not settings.internal_auth_active: 

35 return await call_next(request) 

36 

37 if request.url.path in _EXEMPT_PATHS or request.method == "OPTIONS": 

38 return await call_next(request) 

39 

40 token = request.headers.get("X-Internal-Token") 

41 if not token: 

42 return JSONResponse( 

43 status_code=401, 

44 content={"detail": "Missing internal authentication token"}, 

45 ) 

46 

47 # Accept current + previous secret for zero-downtime rotation overlap. 

48 secrets = [ 

49 s 

50 for s in ( 

51 settings.INTERNAL_JWT_SECRET, 

52 settings.INTERNAL_JWT_SECRET_PREVIOUS, 

53 ) 

54 if s 

55 ] 

56 verified = False 

57 last_exc: Exception | None = None 

58 for secret in secrets: 

59 try: 

60 jwt.decode( 

61 token, 

62 secret, 

63 algorithms=["HS256"], 

64 audience=settings.INTERNAL_JWT_AUDIENCE, 

65 options={"require": ["exp", "iat", "sub", "aud", "iss"]}, 

66 ) 

67 verified = True 

68 break 

69 except jwt.PyJWTError as exc: 

70 last_exc = exc 

71 

72 if not verified: 

73 logger.warning( 

74 "Rejected svc-ai request: invalid internal token: %s", last_exc 

75 ) 

76 return JSONResponse( 

77 status_code=401, 

78 content={"detail": "Invalid internal authentication token"}, 

79 ) 

80 

81 return await call_next(request)