Coverage for fastid / auth / grants.py: 89%

128 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-10-18 16:37 +0000

1from abc import abstractmethod 

2from typing import Any 

3 

4from fastid.apps.exceptions import ( 

5 InvalidAuthorizationCodeError, 

6 InvalidClientCredentialsError, 

7) 

8from fastid.apps.models import App 

9from fastid.apps.repositories import AppClientIDSpecification 

10from fastid.apps.schemas import AppDTO 

11from fastid.auth.config import auth_settings 

12from fastid.auth.exceptions import ( 

13 EmailNotFoundError, 

14 InvalidTokenError, 

15 NoPermissionError, 

16 NotSupportedResponseTypeError, 

17) 

18from fastid.auth.models import User 

19from fastid.auth.repositories import EmailUserSpecification 

20from fastid.auth.schemas import ( 

21 AuthorizationResponse, 

22 OAuth2AuthorizationCodeRequest, 

23 OAuth2Callback, 

24 OAuth2ClientCredentialsRequest, 

25 OAuth2ConsentRequest, 

26 OAuth2PasswordRequest, 

27 OAuth2RefreshTokenRequest, 

28 PayloadResponse, 

29 SubscriberType, 

30 TokenResponse, 

31 UserDTO, 

32) 

33from fastid.auth.server import ServerURLDep 

34from fastid.cache.dependencies import CacheDep 

35from fastid.cache.exceptions import KeyNotFoundError 

36from fastid.core.base import UseCase 

37from fastid.database.dependencies import UOWDep 

38from fastid.database.exceptions import NoResultFoundError 

39from fastid.database.utils import UUIDv7, uuid 

40from fastid.security.crypto import generate_otp 

41from fastid.security.exceptions import JWTError 

42from fastid.security.jwt import jwt_backend 

43from fastid.security.schemas import JWTPayload 

44 

45 

46class Grant(UseCase): 

47 def __init__(self, uow: UOWDep, cache: CacheDep, server_url: ServerURLDep) -> None: 

48 self.uow = uow 

49 self.cache = cache 

50 self.server_url = server_url 

51 self.token_backend = jwt_backend 

52 

53 @abstractmethod 

54 async def authorize(self, form: Any) -> AuthorizationResponse: ... 

55 

56 async def validate_client(self, client_id: str) -> App: 

57 cache_key = f"apps:{client_id}" 

58 try: 

59 cached = await self.cache.get(cache_key) 

60 except KeyNotFoundError: 

61 try: 

62 app = await self.uow.apps.find(AppClientIDSpecification(client_id)) 

63 except NoResultFoundError as e: 

64 raise InvalidClientCredentialsError from e 

65 app_dict = app.dump() 

66 await self.cache.set( 

67 cache_key, 

68 app_dict, 

69 expire=auth_settings.app_expires_in_seconds, 

70 ) 

71 else: 

72 app = App(**cached) 

73 return app 

74 

75 async def authenticate_client(self, client_id: str, client_secret: str) -> App: 

76 app = await self.validate_client(client_id) 

77 app.verify_secret(client_secret) 

78 return app 

79 

80 def grant(self, user: User, scope: str) -> AuthorizationResponse: 

81 tokens = self._issue_tokens(user, scope) 

82 return self._get_auth_response(scope, tokens, user) 

83 

84 def _issue_tokens(self, user: User, scope: str) -> dict[str, dict[str, Any]]: 

85 self._check_scope(user, scope) 

86 tokens = { 

87 token_type: {"is_issued": False, "token": None, "payload": None} 

88 for token_type in ["access", "refresh", "id"] 

89 } 

90 self._issue_at(user, scope, tokens) 

91 if "offline_access" in scope: 

92 self._issue_rt(user, scope, tokens) 

93 if "openid" in scope: 

94 self._issue_it(user, tokens) 

95 return tokens 

96 

97 def _get_auth_response(self, scope: str, tokens: dict[str, Any], user: User) -> AuthorizationResponse: 

98 user_dto = UserDTO.model_validate(user) 

99 payload = self._get_payload_response(tokens) 

100 token = self._get_token_response(scope, tokens) 

101 return AuthorizationResponse(user=user_dto, payload=payload, token=token) 

102 

103 @staticmethod 

104 def _check_scope(user: User, scope: str) -> None: 

105 if "admin" in scope and not user.is_superuser: 

106 raise NoPermissionError 

107 

108 @staticmethod 

109 def _get_payload_response(tokens: dict[str, Any]) -> PayloadResponse: 

110 return PayloadResponse( 

111 access_token=tokens["access"]["payload"], 

112 id_token=tokens["id"]["payload"], 

113 refresh_token=tokens["refresh"]["payload"], 

114 ) 

115 

116 def _get_token_response(self, scope: str, tokens: dict[str, Any]) -> TokenResponse: 

117 token_id = str(uuid()) 

118 expires_in = self.token_backend.get_lifetime("access") 

119 return TokenResponse( 

120 token_id=token_id, 

121 expires_in=expires_in, 

122 scope=scope, 

123 access_token=tokens["access"]["token"], 

124 id_token=tokens["id"]["token"], 

125 refresh_token=tokens["refresh"]["token"], 

126 ) 

127 

128 def _issue_at(self, user: User, scope: str, tokens: dict[str, dict[str, Any]]) -> None: 

129 schema = JWTPayload(sub=str(user.id), scope=scope) 

130 token, payload = self.token_backend.create("access", schema, issuer=self.server_url) 

131 tokens["access"]["is_issued"] = True 

132 tokens["access"]["token"] = token 

133 tokens["access"]["payload"] = payload 

134 

135 def _issue_rt(self, user: User, scope: str, tokens: dict[str, dict[str, Any]]) -> None: 

136 schema = JWTPayload(sub=str(user.id), scope=scope) 

137 token, payload = self.token_backend.create("refresh", schema, issuer=self.server_url) 

138 tokens["refresh"]["is_issued"] = True 

139 tokens["refresh"]["token"] = token 

140 tokens["refresh"]["payload"] = payload 

141 

142 def _issue_it(self, user: User, tokens: dict[str, dict[str, Any]]) -> None: 

143 schema = JWTPayload( 

144 sub=str(user.id), 

145 name=user.display_name, 

146 given_name=user.first_name, 

147 family_name=user.last_name, 

148 email=user.email, 

149 email_verified=user.is_verified, 

150 ) 

151 token, payload = self.token_backend.create("id", schema, issuer=self.server_url) 

152 tokens["id"]["is_issued"] = True 

153 tokens["id"]["token"] = token 

154 tokens["id"]["payload"] = payload 

155 

156 

157class PasswordGrant(Grant): 

158 async def authorize(self, form: OAuth2PasswordRequest) -> AuthorizationResponse: 

159 user = await self._find_by_email(form.username) 

160 await user.verify_password(form.password) 

161 return self.grant(user, form.scope) 

162 

163 async def _find_by_email(self, email: str) -> User: 

164 try: 

165 return await self.uow.users.find(EmailUserSpecification(email)) 

166 except NoResultFoundError as e: 

167 raise EmailNotFoundError from e 

168 

169 

170class AuthorizationCodeGrant(Grant): 

171 async def validate_consent(self, consent: OAuth2ConsentRequest) -> OAuth2ConsentRequest: 

172 if consent.response_type != "code": 

173 raise NotSupportedResponseTypeError 

174 assert consent.client_id is not None 

175 assert consent.redirect_uri is not None 

176 app = await self.validate_client(consent.client_id) 

177 app.verify_redirect_uri(consent.redirect_uri) 

178 return consent 

179 

180 async def approve_consent(self, consent: OAuth2ConsentRequest, user: User) -> str: 

181 code = generate_otp() 

182 await self.cache.set( 

183 f"ac:{consent.client_id}:{code}", 

184 f"{user.id}:{consent.scope}", 

185 expire=auth_settings.authorization_code_expires_in, 

186 ) 

187 callback = OAuth2Callback(code=code, state=consent.state, redirect_uri=consent.redirect_uri) 

188 return callback.get_url() 

189 

190 async def authorize(self, form: OAuth2AuthorizationCodeRequest) -> AuthorizationResponse: 

191 await self.authenticate_client(form.client_id, form.client_secret) 

192 try: 

193 data = await self.cache.pop(f"ac:{form.client_id}:{form.code}") 

194 except KeyNotFoundError as e: 

195 raise InvalidAuthorizationCodeError from e 

196 user_id, scope = data.split(":") 

197 user = await self.uow.users.get(UUIDv7(user_id)) 

198 return self.grant(user, scope) 

199 

200 

201class RefreshTokenGrant(Grant): 

202 async def authorize( 

203 self, 

204 form: OAuth2RefreshTokenRequest, 

205 ) -> AuthorizationResponse: 

206 await self.authenticate_client(form.client_id, form.client_secret) 

207 try: 

208 content = self.token_backend.validate("refresh", form.refresh_token, issuer=self.server_url) 

209 except JWTError as e: 

210 raise InvalidTokenError from e 

211 assert content.scope is not None 

212 user = await self.uow.users.get(UUIDv7(content.sub)) 

213 return self.grant(user, content.scope) 

214 

215 

216class ClientCredentialsGrant(Grant): 

217 async def authorize(self, form: OAuth2ClientCredentialsRequest) -> AuthorizationResponse: 

218 app = await self.authenticate_client(form.client_id, form.client_secret) 

219 self._check_app_scope(app, form.scope) 

220 tokens = await self._issue_app_tokens(app, form.scope) 

221 return self._get_app_auth_response(form.scope, tokens, app) 

222 

223 @staticmethod 

224 def _check_app_scope(app: App, scope: str) -> None: 

225 pass 

226 

227 async def _issue_app_tokens(self, app: App, scope: str) -> dict[str, dict[str, Any]]: 

228 tokens: dict[str, Any] = { 

229 token_type: {"is_issued": False, "token": None, "payload": None} 

230 for token_type in ["access", "refresh", "id"] 

231 } 

232 schema = JWTPayload(sub=str(app.id), scope=scope) 

233 token, payload = await self.token_backend.create_async("access", schema, issuer=self.server_url) 

234 tokens["access"]["is_issued"] = True 

235 tokens["access"]["token"] = token 

236 tokens["access"]["payload"] = payload 

237 return tokens 

238 

239 def _get_app_auth_response(self, scope: str, tokens: dict[str, Any], app: App) -> AuthorizationResponse: 

240 app_dto = AppDTO.model_validate(app) 

241 payload = self._get_payload_response(tokens) 

242 token = self._get_token_response(scope, tokens) 

243 return AuthorizationResponse(app=app_dto, payload=payload, token=token, sub_type=SubscriberType.app)