Coverage for app / common / internal_auth.py: 94%

32 statements  

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

1""" 

2Internal service-to-service authentication for svc-core. 

3 

4Two responsibilities: 

5 

61. **Verify** tokens minted by svc-bff (audience ``svc-core``). The verified 

7 ``sub`` claim is the trusted user identity — svc-core no longer relies on the 

8 raw ``X-User-Id`` header alone. 

92. **Mint** tokens for outbound calls to svc-ai (audience ``svc-ai``) so svc-ai 

10 can authenticate svc-core in turn. 

11 

12Tokens are HS256 with a shared secret. Verification is strict: signature, 

13audience, issuer presence, and expiry are all checked. 

14""" 

15 

16import time 

17from typing import Optional 

18 

19import jwt 

20 

21from app.common.settings import get_settings 

22 

23 

24class InternalAuthError(Exception): 

25 """Raised when an internal token is missing, malformed, or invalid.""" 

26 

27 

28def verify_internal_token(token: str) -> dict: 

29 """ 

30 Verify an inbound internal JWT and return its claims. 

31 

32 Raises InternalAuthError on any validation failure. 

33 """ 

34 settings = get_settings() 

35 # Accept the current secret and, during a rotation overlap, the previous one 

36 # (tokens are short-lived, so verifying against both gives zero-downtime 

37 # rotation). Minting always uses the current secret. 

38 secrets = [ 

39 s 

40 for s in ( 

41 settings.INTERNAL_JWT_SECRET, 

42 settings.INTERNAL_JWT_SECRET_PREVIOUS, 

43 ) 

44 if s 

45 ] 

46 if not secrets: 

47 raise InternalAuthError("Internal auth secret not configured") 

48 

49 claims = None 

50 last_exc: Optional[Exception] = None 

51 for secret in secrets: 

52 try: 

53 claims = jwt.decode( 

54 token, 

55 secret, 

56 algorithms=["HS256"], 

57 audience=settings.INTERNAL_JWT_VERIFY_AUDIENCE, 

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

59 ) 

60 break 

61 except jwt.PyJWTError as exc: 

62 last_exc = exc 

63 

64 if claims is None: 

65 raise InternalAuthError(f"Invalid internal token: {last_exc}") from last_exc 

66 

67 if not claims.get("sub"): 

68 raise InternalAuthError("Internal token missing subject") 

69 

70 return claims 

71 

72 

73def mint_internal_token( 

74 *, 

75 sub: str, 

76 email: str = "", 

77 name: str = "", 

78 organisation_id: Optional[str] = None, 

79) -> Optional[str]: 

80 """ 

81 Mint a signed token for an outbound call to svc-ai. 

82 

83 Returns None when internal auth is not configured, so callers can fall back 

84 to unauthenticated calls during migration. 

85 """ 

86 settings = get_settings() 

87 if not settings.INTERNAL_JWT_SECRET: 

88 return None 

89 

90 now = int(time.time()) 

91 claims = { 

92 "iss": settings.INTERNAL_JWT_ISSUER, 

93 "aud": settings.INTERNAL_JWT_AI_AUDIENCE, 

94 "sub": sub, 

95 "email": email, 

96 "name": name, 

97 "iat": now, 

98 "exp": now + settings.INTERNAL_JWT_TTL, 

99 } 

100 if organisation_id: 

101 claims["org"] = organisation_id 

102 

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