Coverage for app / dependency / user / context.py: 99%

75 statements  

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

1import logging 

2from dataclasses import dataclass 

3from typing import Optional 

4from fastapi import Depends, Header, HTTPException, status 

5from sqlalchemy.orm import Session 

6from sqlalchemy.exc import NoResultFound 

7from app.dependency.base import get_db 

8from app.common.settings import get_settings 

9from app.common.internal_auth import verify_internal_token, InternalAuthError 

10from app.db.postgres.models import User 

11from app.common.exceptions import UserNotProvisionedException, UserDisabledException 

12from app.services import platform_roles 

13from app.services.platform_roles import PlatformRole 

14 

15logger = logging.getLogger(__name__) 

16 

17 

18@dataclass 

19class AuthIdentity: 

20 """Verified caller identity, independent of whether a DB user exists yet.""" 

21 

22 user_id: str 

23 email: Optional[str] = None 

24 name: Optional[str] = None 

25 #: The platform roles Auth0 assigned (app/services/platform_roles.py), or 

26 #: None when the identity says nothing about them — which is not "none". 

27 roles: Optional[tuple[str, ...]] = None 

28 

29 

30def _roles_claim(value: object) -> Optional[tuple[str, ...]]: 

31 """A ``roles`` claim as names; anything but a list of strings says 

32 nothing.""" 

33 if not isinstance(value, list) or not all(isinstance(r, str) for r in value): 

34 return None 

35 return tuple(value) 

36 

37 

38def _roles_header(value: Optional[str]) -> Optional[tuple[str, ...]]: 

39 """``X-User-Roles`` (comma-separated, set by svc-bff only): absent says 

40 nothing, empty says none.""" 

41 if value is None: 

42 return None 

43 return tuple(r.strip() for r in value.split(",") if r.strip()) 

44 

45 

46def resolve_identity( 

47 x_internal_token: Optional[str], 

48 x_user_id: Optional[str], 

49 x_user_email: Optional[str] = None, 

50 x_user_name: Optional[str] = None, 

51 x_user_roles: Optional[str] = None, 

52) -> AuthIdentity: 

53 """ 

54 Establish the trusted caller identity. 

55 

56 When internal auth is configured, identity (subject, email, name, platform 

57 roles) is taken from a verified, audience-bound token minted by svc-bff — 

58 the ``X-User-*`` headers are not trusted on their own. When it is not 

59 configured (legacy / migration), we fall back to the forwarded headers. 

60 """ 

61 settings = get_settings() 

62 

63 if settings.internal_auth_active: 

64 if not x_internal_token: 

65 raise HTTPException( 

66 status_code=status.HTTP_401_UNAUTHORIZED, 

67 detail="Missing internal authentication token", 

68 ) 

69 try: 

70 claims = verify_internal_token(x_internal_token) 

71 except InternalAuthError as exc: 

72 logger.warning("Internal token rejected: %s", exc) 

73 raise HTTPException( 

74 status_code=status.HTTP_401_UNAUTHORIZED, 

75 detail="Invalid internal authentication token", 

76 ) from exc 

77 return AuthIdentity( 

78 user_id=claims["sub"], 

79 email=claims.get("email") or None, 

80 name=claims.get("name") or None, 

81 roles=_roles_claim(claims.get("roles")), 

82 ) 

83 

84 # Legacy fallback: trust the forwarded identity headers. 

85 if x_user_id is None: 

86 raise HTTPException( 

87 status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized" 

88 ) 

89 return AuthIdentity( 

90 user_id=x_user_id, 

91 email=x_user_email, 

92 name=x_user_name, 

93 roles=_roles_header(x_user_roles), 

94 ) 

95 

96 

97def _resolve_user_id( 

98 x_internal_token: Optional[str], 

99 x_user_id: Optional[str], 

100) -> str: 

101 """Backwards-compatible helper returning just the verified subject.""" 

102 return resolve_identity(x_internal_token, x_user_id).user_id 

103 

104 

105def get_identity( 

106 x_user_id: Optional[str] = Header(None, alias="X-User-Id"), 

107 x_user_email: Optional[str] = Header(None, alias="X-User-Email"), 

108 x_user_name: Optional[str] = Header(None, alias="X-User-Name"), 

109 x_internal_token: Optional[str] = Header(None, alias="X-Internal-Token"), 

110 x_user_roles: Optional[str] = Header(None, alias="X-User-Roles"), 

111) -> AuthIdentity: 

112 """ 

113 FastAPI dependency exposing the verified identity without requiring the 

114 user to be provisioned in the DB. Use this for onboarding/existence-check 

115 endpoints (e.g. GET/POST /users/me); use get_current_user when a 

116 provisioned, active User row is required. 

117 """ 

118 return resolve_identity( 

119 x_internal_token, x_user_id, x_user_email, x_user_name, x_user_roles 

120 ) 

121 

122 

123def get_current_user( 

124 db: Session = Depends(get_db), 

125 x_user_id: Optional[str] = Header(None, alias="X-User-Id"), 

126 x_internal_token: Optional[str] = Header(None, alias="X-Internal-Token"), 

127 x_user_roles: Optional[str] = Header(None, alias="X-User-Roles"), 

128) -> User: 

129 # Called directly (tests, the scenario runner), an omitted header is its 

130 # ``Header`` default rather than None. 

131 identity = resolve_identity( 

132 x_internal_token, 

133 x_user_id, 

134 x_user_roles=x_user_roles if isinstance(x_user_roles, str) else None, 

135 ) 

136 

137 try: 

138 user = db.query(User).filter(User.auth0_id == identity.user_id).one() 

139 except NoResultFound as exc: 

140 raise UserNotProvisionedException from exc 

141 

142 if not user.is_active: 

143 raise UserDisabledException 

144 

145 sync_roles(db, user, identity.roles) 

146 return user 

147 

148 

149def sync_roles(db: Session, user: User, roles: Optional[tuple[str, ...]]) -> None: 

150 """Keep ``user``'s platform roles as Auth0 says they are 

151 (app/services/platform_roles.py), committing only a change. A failed 

152 write is logged and left for the next request: the request goes on with 

153 the row as it was.""" 

154 if not platform_roles.sync(user, roles): 

155 return 

156 try: 

157 db.commit() 

158 except Exception: # noqa: BLE001 - never fail a request over its roles 

159 db.rollback() 

160 logger.exception("Could not store the platform roles of user %s", user.id) 

161 

162 

163def require_superuser(current_user: User = Depends(get_current_user)) -> User: 

164 """The current user, or 403 unless they are a superuser. 

165 

166 For platform administration — routes that act on *every* user's records 

167 rather than on resources a caller owns, so no ownership check can scope 

168 them. 

169 """ 

170 if not current_user.is_superuser: 

171 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

172 return current_user 

173 

174 

175def require_role(role: PlatformRole): 

176 """A dependency: the current user, or 403 unless they hold ``role`` 

177 (a superuser holds every one). The 403 names the role, so someone who 

178 needs it knows what to ask for in Auth0.""" 

179 label = platform_roles.ROLES[role].label 

180 

181 def dependency(current_user: User = Depends(get_current_user)) -> User: 

182 if not platform_roles.holds(current_user, role): 

183 raise HTTPException( 

184 status_code=status.HTTP_403_FORBIDDEN, 

185 detail=f"This needs the {label} platform role.", 

186 ) 

187 return current_user 

188 

189 return dependency