Debian Codegraph @

src/globus_sdk/services/auth/response/oauth.py

raw
1 from __future__ import annotations
2
3 import json
4 import logging
5 import textwrap
6 import time
7 import typing as t
8
9 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
10
11 from globus_sdk import exc
12 from globus_sdk.response import GlobusHTTPResponse
13
14 from .._common import SupportsJWKMethods
15 from ..id_token_decoder import IDTokenDecoder
16
17 log = logging.getLogger(__name__)
18
19
20 def _convert_token_info_dict(
21 source_dict: GlobusHTTPResponse,
22 ) -> dict[str, t.Any]:
23 """
24 Extract a set of fields into a new dict for indexing by resource server.
25 Allow for these fields to be `None` when absent:
26 - "refresh_token"
27 - "token_type"
28 """
29 expires_in = source_dict.get("expires_in", 0)
30
31 return {
32 "scope": source_dict["scope"],
33 "access_token": source_dict["access_token"],
34 "refresh_token": source_dict.get("refresh_token"),
35 "token_type": source_dict.get("token_type"),
36 "expires_at_seconds": int(time.time() + expires_in),
37 "resource_server": source_dict["resource_server"],
38 }
39
40
41 class _ByScopesGetter:
42 """
43 A fancy dict-like object for looking up token data by scope name.
44 Allows usage like
45
46 >>> tokens = OAuthTokenResponse(...)
47 >>> tok = tokens.by_scopes['openid profile']['access_token']
48 """
49
50 def __init__(self, scope_map: dict[str, t.Any]) -> None:
51 self.scope_map = scope_map
52
53 def __str__(self) -> str:
54 return json.dumps(self.scope_map)
55
56 def __iter__(self) -> t.Iterator[str]:
57 """iteration gets you every individual scope"""
58 return iter(self.scope_map.keys())
59
60 def __getitem__(self, scopename: str) -> dict[str, str | int]:
61 if not isinstance(scopename, str):
62 raise KeyError(f'by_scopes cannot contain non-string value "{scopename}"')
63
64 # split on spaces
65 scopes = scopename.split()
66 # collect every matching token in a set to dedup
67 # but collect actual results (dicts) in a list
68 rs_names = set()
69 toks = []
70 for scope in scopes:
71 try:
72 rs_names.add(self.scope_map[scope]["resource_server"])
73 toks.append(self.scope_map[scope])
74 except KeyError as err:
75 raise KeyError(
76 (
77 'Scope specifier "{}" contains scope "{}" '
78 "which was not found"
79 ).format(scopename, scope)
80 ) from err
81 # if there isn't exactly 1 token, it's an error
82 if len(rs_names) != 1:
83 raise KeyError(
84 'Scope specifier "{}" did not match exactly one token!'.format(
85 scopename
86 )
87 )
88 # pop the only element in the set
89 return t.cast(t.Dict[str, t.Union[str, int]], toks.pop())
90
91 def __contains__(self, item: str) -> bool:
92 """
93 contains is driven by checking against getitem
94 that way, the definitions are always "in sync" if we update them in
95 the future
96 """
97 try:
98 self.__getitem__(item)
99 return True
100 except KeyError:
101 pass
102
103 return False
104
105
106 class OAuthTokenResponse(GlobusHTTPResponse):
107 """
108 Class for responses from the OAuth2 code for tokens exchange used in
109 3-legged OAuth flows.
110 """
111
112 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
113 super().__init__(*args, **kwargs)
114 self._init_rs_dict()
115 self._init_scopes_getter()
116
117 def _init_scopes_getter(self) -> None:
118 scope_map = {}
119 for _rs, tok_data in self._by_resource_server.items():
120 for s in tok_data["scope"].split():
121 scope_map[s] = tok_data
122 self._by_scopes = _ByScopesGetter(scope_map)
123
124 def _init_rs_dict(self) -> None:
125 # call the helper at the top level
126 self._by_resource_server = {
127 self["resource_server"]: _convert_token_info_dict(self)
128 }
129 # call the helper on everything in 'other_tokens'
130 self._by_resource_server.update(
131 {
132 unprocessed_item["resource_server"]: _convert_token_info_dict(
133 unprocessed_item
134 )
135 for unprocessed_item in self["other_tokens"]
136 }
137 )
138
139 @property
140 def by_resource_server(self) -> dict[str, dict[str, t.Any]]:
141 """
142 Representation of the token response in a ``dict`` indexed by resource
143 server.
144
145 Although ``OAuthTokenResponse.data`` is still available and
146 valid, this representation is typically more desirable for applications
147 doing inspection of access tokens and refresh tokens.
148 """
149 return self._by_resource_server
150
151 @property
152 def by_scopes(self) -> _ByScopesGetter:
153 """
154 Representation of the token response in a dict-like object indexed by
155 scope name (or even space delimited scope names, so long as they match
156 the same token).
157
158 If you request scopes `scope1 scope2 scope3`, where `scope1` and
159 `scope2` are for the same service (and therefore map to the same
160 token), but `scope3` is for a different service, the following forms of
161 access are valid:
162
163 >>> tokens = ...
164 >>> # single scope
165 >>> token_data = tokens.by_scopes['scope1']
166 >>> token_data = tokens.by_scopes['scope2']
167 >>> token_data = tokens.by_scopes['scope3']
168 >>> # matching scopes
169 >>> token_data = tokens.by_scopes['scope1 scope2']
170 >>> token_data = tokens.by_scopes['scope2 scope1']
171 """
172 return self._by_scopes
173
174 def decode_id_token(
175 self,
176 openid_configuration: None | GlobusHTTPResponse | dict[str, t.Any] = None,
177 jwk: RSAPublicKey | None = None,
178 jwt_params: dict[str, t.Any] | None = None,
179 ) -> dict[str, t.Any]:
180 """
181 Parse the included ID Token (OIDC) as a dict and return it.
182
183 If you provide the `jwk`, you must also provide `openid_configuration`.
184
185 :param openid_configuration: The OIDC config as a GlobusHTTPResponse or dict.
186 When not provided, it will be fetched automatically.
187 :param jwk: The JWK as a cryptography public key object. When not provided, it
188 will be fetched and parsed automatically.
189 :param jwt_params: An optional dict of parameters to pass to the jwt decode
190 step. If ``"leeway"`` is included, it will be passed as the ``leeway``
191 parameter, and all other values are passed as ``options``.
192 """
193 id_token = self["id_token"]
194 log.debug('Decoding ID Token "%s"', id_token)
195 if not isinstance(self.client, SupportsJWKMethods):
196 raise exc.GlobusSDKUsageError(
197 "decode_id_token() requires a client which supports JWK methods. "
198 "This error suggests that an improper client type is attached to "
199 "the token response."
200 )
201 else:
202 auth_client: SupportsJWKMethods = self.client
203
204 decoder = IDTokenDecoder(auth_client)
205
206 if openid_configuration:
207 decoder.store_openid_configuration(openid_configuration)
208 else:
209 if jwk:
210 raise exc.GlobusSDKUsageError(
211 "passing jwk without openid configuration is not allowed"
212 )
213 if jwk:
214 decoder.store_jwk(jwk)
215
216 jwt_params = jwt_params or {}
217 if "leeway" in jwt_params:
218 jwt_params = jwt_params.copy()
219 decoder.jwt_leeway = jwt_params.pop("leeway")
220
221 decoder.jwt_options = jwt_params
222
223 return decoder.decode(id_token)
224
225 def __str__(self) -> str:
226 by_rs = json.dumps(self.by_resource_server, indent=2, separators=(",", ": "))
227 id_token_to_print = t.cast(t.Optional[str], self.get("id_token"))
228 if id_token_to_print is not None:
229 id_token_to_print = id_token_to_print[:10] + "... (truncated)"
230 return (
231 f"{self.__class__.__name__}:\n"
232 + f" id_token: {id_token_to_print}\n"
233 + " by_resource_server:\n"
234 + textwrap.indent(by_rs, " ")
235 )
236
237
238 class OAuthAuthorizationCodeResponse(OAuthTokenResponse):
239 """
240 Class for responses from the OAuth2 'authorization_code' grant.
241
242 This class of response is returned by methods which get new tokens via a
243 code-exchange, as in 3-legged OAuth or PKCE.
244
245 For example,
246 :meth:`globus_sdk.ConfidentialAppAuthClient.oauth2_exchange_code_for_tokens`
247 will return an ``OAuthAuthorizationCodeResponse``.
248 """
249
250
251 class OAuthClientCredentialsResponse(OAuthTokenResponse):
252 """
253 Class for responses from the OAuth2 'client_credentials' grant.
254
255 This class of response is returned by methods which get new tokens by means of
256 client credentials, namely
257 :meth:`globus_sdk.ConfidentialAppAuthClient.oauth2_client_credentials_tokens`.
258 """
259
260
261 class OAuthRefreshTokenResponse(OAuthTokenResponse):
262 """
263 Class for responses from the OAuth2 'refresh_token' grant.
264
265 This class of response is returned by methods which get new tokens from an
266 existing Refresh Token, e.g.,
267 :meth:`globus_sdk.NativeAppAuthClient.oauth2_refresh_token`.
268 """
269
270
271 class OAuthDependentTokenResponse(OAuthTokenResponse):
272 """
273 Class for responses from the OAuth2
274 'urn:globus:auth:grant_type:dependent_token' grant.
275
276 This is an extension grant type defined by Globus.
277
278 :meth:`oauth2_get_dependent_tokens \
279 <globus_sdk.ConfidentialAppAuthClient.oauth2_get_dependent_tokens>`
280 provides this response, and includes some documentation on its proper usage.
281 """
282
283 def _init_rs_dict(self) -> None:
284 # call the helper on everything in the response array
285 self._by_resource_server = {
286 unprocessed_item["resource_server"]: _convert_token_info_dict(
287 unprocessed_item
288 )
289 for unprocessed_item in self.data
290 }
291
292 def decode_id_token(
293 self,
294 openid_configuration: None | (GlobusHTTPResponse | dict[str, t.Any]) = None,
295 jwk: RSAPublicKey | None = None,
296 jwt_params: dict[str, t.Any] | None = None,
297 ) -> dict[str, t.Any]:
298 # just in case
299 raise NotImplementedError(
300 "OAuthDependentTokenResponse.decode_id_token() is not and cannot "
301 "be implemented. Dependent Tokens data does not include an "
302 "id_token"
303 )