Coverage for fastid / integrations / base / oauth.py: 64%

118 statements  

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

1from collections.abc import AsyncIterator, Sequence 

2from types import TracebackType 

3from typing import ( 

4 Any, 

5 ClassVar, 

6 Self, 

7) 

8from urllib.parse import urlencode 

9 

10import httpx 

11 

12from fastid.auth.schemas import DiscoveryDocument, OAuth2Callback, OpenID, ProviderMeta, TokenResponse 

13from fastid.integrations.constants import MAX_SUCCESS_CODE, MIN_SUCCESS_CODE 

14from fastid.integrations.exceptions import ( 

15 AuthorizationError, 

16 ClientError, 

17 DiscoveryError, 

18 RedirectURIError, 

19 StateError, 

20 TokenError, 

21 UserinfoError, 

22) 

23from fastid.integrations.schemas import LoginResponse, UserinfoResponse 

24from fastid.integrations.utils import generate_pkce_challenge, generate_pkce_verifier, generate_random_state 

25 

26 

27class OAuth2Client: 

28 default_meta: ClassVar[ProviderMeta] 

29 default_use_pkce: ClassVar[bool] = False 

30 pkce_challenge_method: ClassVar[str] = "S256" 

31 use_client_secret: ClassVar[bool] = True 

32 

33 def __init__( # noqa: PLR0913 

34 self, 

35 client_id: str, 

36 client_secret: str, 

37 redirect_uri: str | None = None, 

38 scope: Sequence[str] | None = None, 

39 meta: ProviderMeta | None = None, 

40 use_pkce: bool | None = None, 

41 ) -> None: 

42 self.meta = meta or self.default_meta 

43 self.client_id = client_id 

44 self.client_secret = client_secret 

45 self.redirect_uri = redirect_uri 

46 self.use_state = self.meta.use_state 

47 self.use_pkce = self.default_use_pkce if use_pkce is None else use_pkce 

48 self.discovery_url = self.meta.discovery_url 

49 self._discovery = None 

50 

51 scope = scope or self.meta.scope 

52 assert scope is not None 

53 self.scope = scope 

54 

55 if self.meta.discovery is not None: 

56 self._discovery = self.meta.discovery 

57 

58 if self.meta.server_url is not None: 

59 self.discovery_url = f"{self.meta.server_url}/.well-known/openid-configuration" 

60 

61 self._token: TokenResponse | None = None 

62 self._client: httpx.AsyncClient | None = None 

63 

64 @property 

65 def discovery(self) -> DiscoveryDocument: 

66 if self._discovery is None: 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true

67 msg = "Discovery document is not available. Please discover first." 

68 raise DiscoveryError(msg) 

69 return self._discovery 

70 

71 @property 

72 def token(self) -> TokenResponse: 

73 if not self._token: 

74 msg = "Token is not available. Please authorize first." 

75 raise TokenError(msg) 

76 return self._token 

77 

78 @property 

79 def client(self) -> httpx.AsyncClient: 

80 if not self._client: 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true

81 msg = "Client is not available. Please enter the context." 

82 raise ClientError(msg) 

83 return self._client 

84 

85 async def convert_token(self, response: dict[str, Any]) -> TokenResponse: 

86 return TokenResponse.model_validate(response) 

87 

88 async def convert_userinfo(self, response: dict[str, Any]) -> OpenID: # noqa: ARG002 

89 return OpenID() 

90 

91 async def discover(self) -> DiscoveryDocument: 

92 assert self.discovery_url is not None 

93 response = await self.client.get(self.discovery_url) 

94 return DiscoveryDocument.model_validate(response.json()) 

95 

96 async def login_url( 

97 self, 

98 *, 

99 redirect_uri: str | None = None, 

100 state: str | None = None, 

101 params: dict[str, Any] | None = None, 

102 ) -> str: 

103 params = params or {} 

104 if self.use_state or self.use_pkce: 104 ↛ 107line 104 didn't jump to line 107 because the condition on line 104 was always true

105 state = state or generate_random_state() 

106 params |= {"state": state} 

107 if self.use_pkce: 

108 assert state is not None 

109 params |= { 

110 "code_challenge": generate_pkce_challenge(generate_pkce_verifier(state, self.client_secret)), 

111 "code_challenge_method": self.pkce_challenge_method, 

112 } 

113 redirect_uri = redirect_uri or self.redirect_uri 

114 if redirect_uri is None: 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true

115 msg = "redirect_uri must be provided, either at construction or request time" 

116 raise RedirectURIError(msg) 

117 request_params = { 

118 "response_type": "code", 

119 "client_id": self.client_id, 

120 "scope": " ".join(self.scope), 

121 "redirect_uri": redirect_uri, 

122 **params, 

123 } 

124 return f"{self.discovery.authorization_endpoint}?{urlencode(request_params)}" 

125 

126 async def login( 

127 self, 

128 callback: OAuth2Callback, 

129 *, 

130 body: dict[str, Any] | None = None, 

131 headers: dict[str, str] | None = None, 

132 ) -> LoginResponse: 

133 request = self._prepare_token_request(callback, body=body, headers=headers) 

134 auth = httpx.BasicAuth(self.client_id, self.client_secret) if self.use_client_secret else None 

135 response = await self.client.send( 

136 request, 

137 auth=auth, 

138 ) 

139 content = response.json() 

140 if response.status_code < MIN_SUCCESS_CODE or response.status_code > MAX_SUCCESS_CODE: 

141 msg = "Authorization failed: %s" 

142 raise AuthorizationError(msg, content) 

143 token = await self.convert_token(content) 

144 self._token = token 

145 return LoginResponse(token=token, token_raw=content) 

146 

147 async def userinfo(self) -> UserinfoResponse: 

148 assert self.discovery.userinfo_endpoint is not None 

149 headers = { 

150 "Authorization": f"{self.token.token_type} {self.token.access_token}", 

151 } 

152 response = await self.client.get(self.discovery.userinfo_endpoint, headers=headers) 

153 content = response.json() 

154 if response.status_code < MIN_SUCCESS_CODE or response.status_code > MAX_SUCCESS_CODE: 

155 msg = "Getting userinfo failed: %s" 

156 raise UserinfoError(msg, content) 

157 userinfo = await self.convert_userinfo(content) 

158 return UserinfoResponse(userinfo=userinfo, userinfo_raw=content) 

159 

160 async def callback(self, callback: OAuth2Callback) -> UserinfoResponse: 

161 await self.login(callback) 

162 return await self.userinfo() 

163 

164 def _prepare_token_request( 

165 self, 

166 callback: OAuth2Callback, 

167 *, 

168 body: dict[str, Any] | None = None, 

169 headers: dict[str, str] | None = None, 

170 ) -> httpx.Request: 

171 assert self.discovery.token_endpoint is not None 

172 body = body or {} 

173 headers = headers or {} 

174 headers |= {"Content-Type": "application/x-www-form-urlencoded"} 

175 if self.use_state: 175 ↛ 180line 175 didn't jump to line 180 because the condition on line 175 was always true

176 if not callback.state: 176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true

177 msg = "State was not found in the callback" 

178 raise StateError(msg) 

179 body |= {"state": callback.state} 

180 if self.use_pkce: 

181 if not callback.state: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true

182 msg = "PKCE code verifier was not found in the callback state" 

183 raise StateError(msg) 

184 body |= {"code_verifier": generate_pkce_verifier(callback.state, self.client_secret)} 

185 body = { 

186 "grant_type": "authorization_code", 

187 "code": callback.code, 

188 "redirect_uri": callback.redirect_uri or self.redirect_uri, 

189 "client_id": self.client_id, 

190 **body, 

191 } 

192 if self.use_client_secret: 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true

193 body["client_secret"] = self.client_secret 

194 return httpx.Request( 

195 "post", 

196 self.discovery.token_endpoint, 

197 data=body, 

198 headers=headers, 

199 ) 

200 

201 async def __aenter__(self) -> Self: 

202 self._client = httpx.AsyncClient() 

203 await self._client.__aenter__() 

204 if self._discovery is None: 

205 self._discovery = await self.discover() 

206 return self 

207 

208 async def __aexit__( 

209 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None 

210 ) -> None: 

211 self._token = None 

212 await self.client.__aexit__(exc_type, exc_value, traceback) 

213 

214 async def __call__(self) -> AsyncIterator[Self]: 

215 async with self: 

216 yield self