Coverage for app/internal_auth.py: 100%

14 statements  

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

1""" 

2Internal service-to-service authentication — token minting. 

3 

4svc-bff is the only internet-adjacent caller of svc-core. Forwarding raw 

5identity headers (``X-User-Id`` etc.) means any party that can reach svc-core 

6on the internal network can impersonate any user. To close that gap, svc-bff 

7mints a short-lived, audience-bound JWT for every downstream request. svc-core 

8verifies the signature and derives identity from the token's ``sub`` claim. 

9 

10The token is symmetric (HS256) with a shared secret — the simplest key 

11management for a closed internal mesh. It is intentionally short-lived 

12(``INTERNAL_JWT_TTL``) so a leaked token has a small blast radius. 

13""" 

14 

15import time 

16from typing import Optional 

17 

18import jwt 

19 

20from app.config import settings 

21 

22 

23def mint_internal_token( 

24 *, 

25 sub: str, 

26 email: str = "", 

27 name: str = "", 

28 organisation_id: Optional[str] = None, 

29 roles: Optional[list[str]] = None, 

30) -> Optional[str]: 

31 """ 

32 Mint a signed internal JWT carrying the authenticated user's identity. 

33 

34 ``roles`` are the platform roles svc-auth read from the ID token 

35 (docs/system/security/auth-flow.md#platform-roles). They become the 

36 ``roles`` claim only when the session has them: an absent claim says 

37 nothing, and svc-core then leaves the user's roles alone, while an empty 

38 list says "none". 

39 

40 Returns None when internal auth is not configured (no secret), so callers 

41 can fall back to legacy header-only propagation during migration. 

42 """ 

43 if not settings.internal_auth_active: 

44 return None 

45 

46 now = int(time.time()) 

47 claims = { 

48 "iss": settings.INTERNAL_JWT_ISSUER, 

49 "aud": settings.INTERNAL_JWT_AUDIENCE, 

50 "sub": sub, 

51 "email": email, 

52 "name": name, 

53 "iat": now, 

54 "exp": now + settings.INTERNAL_JWT_TTL, 

55 } 

56 if organisation_id: 

57 claims["org"] = organisation_id 

58 if roles is not None: 

59 claims["roles"] = list(roles) 

60 

61 return jwt.encode(claims, settings.INTERNAL_JWT_SECRET, algorithm="HS256")