Debian Codegraph @

src/globus_sdk/globus_app/app.py

raw
1 from __future__ import annotations
2
3 import abc
4 import contextlib
5 import copy
6 import logging
7 import sys
8 import types
9 import typing as t
10 import uuid
11 from json import JSONDecodeError
12
13 from requests import Response
14
15 from globus_sdk import (
16 AuthClient,
17 AuthLoginClient,
18 GlobusSDKUsageError,
19 IDTokenDecoder,
20 )
21 from globus_sdk._internal.type_definitions import Closable
22 from globus_sdk.authorizers import GlobusAuthorizer
23 from globus_sdk.gare import GARE, GlobusAuthorizationParameters, to_gare
24 from globus_sdk.scopes import AuthScopes, Scope, ScopeParser
25 from globus_sdk.token_storage import (
26 ScopeRequirementsValidator,
27 TokenStorage,
28 TokenValidationError,
29 ValidatingTokenStorage,
30 )
31 from globus_sdk.transport import (
32 RetryCheck,
33 RetryCheckFlags,
34 RetryCheckResult,
35 RetryContext,
36 set_retry_check_flags,
37 )
38
39 from .authorizer_factory import AuthorizerFactory
40 from .config import DEFAULT_CONFIG, KNOWN_TOKEN_STORAGES, GlobusAppConfig
41 from .protocols import TokenStorageProvider
42
43 if sys.version_info >= (3, 11):
44 from typing import Self
45 else:
46 from typing_extensions import Self
47
48 log = logging.getLogger(__name__)
49
50
51 class GlobusApp(metaclass=abc.ABCMeta):
52 """
53 The abstract base class for managing authentication across services.
54
55 A single ``GlobusApp`` may be bound to many service clients, providing each them
56 with dynamically updated authorization tokens. The app is responsible for ensuring
57 these tokens are up-to-date and validly scoped; including initiating login flows to
58 acquire new tokens when necessary.
59
60 See :class:`UserApp` to oversee interactions with a human.
61
62 See :class:`ClientApp` to oversee interactions with a service account.
63
64 .. warning::
65
66 GlobusApp is **not** thread safe.
67
68 :ivar ValidatingTokenStorage token_storage: The interface used by the app to store,
69 retrieve, and validate Globus Auth-issued tokens.
70 :ivar dict[str, list[Scope]] scope_requirements: A copy of the app's aggregate scope
71 requirements. Modifying the returned dict will not affect the app's internal
72 store. To add scope requirements, instead use the :meth:`add_scope_requirements`
73 method.
74 """
75
76 _login_client: AuthLoginClient
77 # a bool is used to track whether or not the AuthorizerFactory is ready for use
78 # this allows code during init call into otherwise unsafe codepaths in the app,
79 # namely those which manipulate scope requirements
80 _authorizer_factory: AuthorizerFactory[GlobusAuthorizer]
81 _token_storage: TokenStorage
82 token_storage: ValidatingTokenStorage
83
84 def __init__(
85 self,
86 app_name: str = "Unnamed Globus App",
87 *,
88 login_client: AuthLoginClient | None = None,
89 client_id: uuid.UUID | str | None = None,
90 client_secret: str | None = None,
91 scope_requirements: (
92 t.Mapping[str, str | Scope | t.Iterable[str | Scope]] | None
93 ) = None,
94 config: GlobusAppConfig = DEFAULT_CONFIG,
95 ) -> None:
96 self.app_name = app_name
97 self.config = config
98 self._token_validation_error_handling_enabled = True
99 self._resources_to_close: list[Closable] = []
100
101 self.client_id, self._login_client = self._resolve_client_info(
102 app_name=self.app_name,
103 config=self.config,
104 client_id=client_id,
105 client_secret=client_secret,
106 login_client=login_client,
107 )
108 self._scope_requirements = self._resolve_scope_requirements(scope_requirements)
109
110 # create the inner token storage object, and pick up on whether or not this
111 # call handled creation or got a value from the outside
112 self._token_storage, token_storage_created_here = self._resolve_token_storage(
113 app_name=self.app_name,
114 client_id=self.client_id,
115 config=self.config,
116 )
117
118 # create a consent client for token validation
119 # this client won't be ready for immediate use, but will have the app attached
120 # at the end of init
121 consent_client = AuthClient(environment=config.environment)
122 self._resources_to_close.append(consent_client)
123
124 # create the requisite token storage for the app, with validation based on
125 # the provided parameters
126 # if the token storage was created by the app, the validating wrapper is added
127 # to the resources to close when closed
128 self.token_storage = self._initialize_validating_token_storage(
129 token_storage=self._token_storage,
130 consent_client=consent_client,
131 scope_requirements=self._scope_requirements,
132 )
133 if token_storage_created_here:
134 self._resources_to_close.append(self.token_storage)
135
136 # setup an ID Token Decoder based on config; build one if it was not provided
137 self._id_token_decoder = self._initialize_id_token_decoder(
138 app_name=self.app_name, config=self.config, login_client=self._login_client
139 )
140
141 # initialize our authorizer factory
142 self._initialize_authorizer_factory()
143 self._authorizer_factory_initialized = True
144
145 # finally, attach the app to the internal consent client
146 # this needs to wait until the very end of the app initialization process so
147 # that the authorizer factory is all ready to accept the client
148 # registering its scope requirements
149 #
150 # additionally, this will ensure that openid scope requirement is always
151 # registered (it's required for token identity validation).
152 consent_client.attach_globus_app(self, app_scopes=[AuthScopes.openid])
153
154 def _resolve_scope_requirements(
155 self,
156 scope_requirements: (
157 t.Mapping[str, str | Scope | t.Iterable[str | Scope]] | None
158 ),
159 ) -> dict[str, list[Scope]]:
160 if scope_requirements is None:
161 return {}
162
163 return {
164 resource_server: list(self._iter_scopes(scopes))
165 for resource_server, scopes in scope_requirements.items()
166 }
167
168 def _resolve_client_info(
169 self,
170 app_name: str,
171 config: GlobusAppConfig,
172 login_client: AuthLoginClient | None,
173 client_id: uuid.UUID | str | None,
174 client_secret: str | None,
175 ) -> tuple[uuid.UUID | str, AuthLoginClient]:
176 """
177 Extracts a client_id and login_client from GlobusApp initialization parameters,
178 validating that the parameters were provided correctly.
179
180 Depending on which parameters were provided, this method will either:
181 1. Create a new login client from the supplied credentials.
182 * The actual initialization is performed by the subclass using the
183 abstract method: _initialize_login_client``.
184 2. Extract the client_id from a supplied login_client.
185
186 If a new client is created here, it is also added to the set of resources to
187 close when this app is closed.
188
189 :returns: tuple of client_id and login_client
190 :raises: GlobusSDKUsageError if a single client ID or login client could not be
191 definitively resolved.
192 """
193 if login_client and client_id:
194 msg = "Mutually exclusive parameters: client_id and login_client."
195 raise GlobusSDKUsageError(msg)
196
197 if login_client:
198 # User provided an explicit login client, extract the client_id.
199 if login_client.client_id is None:
200 msg = "A GlobusApp login_client must have a discoverable client_id."
201 raise GlobusSDKUsageError(msg)
202 if login_client.environment != config.environment:
203 raise GlobusSDKUsageError(
204 "[Environment Mismatch] The login_client's environment "
205 f"({login_client.environment}) does not match the GlobusApp's "
206 f"configured environment ({config.environment})."
207 )
208
209 return login_client.client_id, login_client
210
211 elif client_id:
212 # User provided an explicit client_id, construct a login client
213 login_client = self._initialize_login_client(
214 app_name, config, client_id, client_secret
215 )
216 self._resources_to_close.append(login_client)
217 return client_id, login_client
218
219 else:
220 raise GlobusSDKUsageError(
221 "Could not set up a globus login client. One of client_id or "
222 "login_client is required."
223 )
224
225 @abc.abstractmethod
226 def _initialize_login_client(
227 self,
228 app_name: str,
229 config: GlobusAppConfig,
230 client_id: uuid.UUID | str,
231 client_secret: str | None,
232 ) -> AuthLoginClient:
233 """
234 Initializes and returns an AuthLoginClient to be used in authorization requests.
235 """
236
237 def _initialize_validating_token_storage(
238 self,
239 token_storage: TokenStorage,
240 consent_client: AuthClient,
241 scope_requirements: t.Mapping[str, t.Sequence[Scope]],
242 ) -> ValidatingTokenStorage:
243 """
244 Initializes the validating token storage for the app.
245 """
246 validating_token_storage = ValidatingTokenStorage(token_storage)
247
248 # construct ValidatingTokenStorage around the TokenStorage and
249 # our initial scope requirements
250 scope_validator = ScopeRequirementsValidator(scope_requirements, consent_client)
251
252 # use validators to enforce invariants about scopes
253 validating_token_storage.validators.append(scope_validator)
254
255 return validating_token_storage
256
257 def _resolve_token_storage(
258 self, app_name: str, client_id: uuid.UUID | str, config: GlobusAppConfig
259 ) -> tuple[TokenStorage, bool]:
260 """
261 Resolve the raw token storage to be used by the app, and whether or not it was
262 created explicitly here.
263
264 The storage may be:
265 1. A TokenStorage instance provided by the user, which we use directly.
266 2. A TokenStorageProvider, which we use to get a TokenStorage.
267 3. A string value, which we map onto supported TokenStorage types.
268
269 And in the case of (1), the bool is false. In the case of (2) and (3) it is
270 true.
271
272 :returns: TokenStorage instance to be used by the app, and whether or not this
273 function created the storage.
274 :raises: GlobusSDKUsageError if the provided token_storage value is unsupported.
275 """
276 token_storage = config.token_storage
277 # TODO - make namespace configurable
278 namespace = "DEFAULT"
279 if isinstance(token_storage, TokenStorage):
280 return (token_storage, False)
281
282 elif isinstance(token_storage, TokenStorageProvider):
283 return (
284 token_storage.for_globus_app(
285 app_name=app_name,
286 config=config,
287 client_id=client_id,
288 namespace=namespace,
289 ),
290 True,
291 )
292
293 elif token_storage in KNOWN_TOKEN_STORAGES:
294 provider = KNOWN_TOKEN_STORAGES[token_storage]
295 return (
296 provider.for_globus_app(
297 app_name=app_name,
298 config=config,
299 client_id=client_id,
300 namespace=namespace,
301 ),
302 True,
303 )
304
305 raise GlobusSDKUsageError(
306 f"Unsupported token_storage value: {token_storage}. Must be a "
307 f"TokenStorage, TokenStorageProvider, or a supported string value."
308 )
309
310 def _initialize_id_token_decoder(
311 self, *, app_name: str, config: GlobusAppConfig, login_client: AuthLoginClient
312 ) -> IDTokenDecoder:
313 """
314 Create an IDTokenDecoder or use the one provided via config, and set it on
315 the token storage adapters.
316
317 It is only set on inner storage if the decoder was not already set, so a
318 non-null value won't be overwritten.
319
320 This must run near the end of app initialization, when the `_token_storage`
321 (inner) and `token_storage` (validating storage, outer) storages have both
322 been initialized.
323 """
324 if isinstance(self.config.id_token_decoder, IDTokenDecoder):
325 id_token_decoder: IDTokenDecoder = self.config.id_token_decoder
326 else:
327 id_token_decoder = self.config.id_token_decoder.for_globus_app(
328 app_name=app_name,
329 config=config,
330 login_client=login_client,
331 )
332 if self._token_storage.id_token_decoder is None:
333 self._token_storage.id_token_decoder = id_token_decoder
334 self.token_storage.id_token_decoder = id_token_decoder
335
336 return id_token_decoder
337
338 @abc.abstractmethod
339 def _initialize_authorizer_factory(self) -> None:
340 """
341 Initializes self._authorizer_factory to be used for generating authorizers to
342 authorize requests.
343 """
344
345 def login(
346 self,
347 *,
348 auth_params: GlobusAuthorizationParameters | None = None,
349 force: bool = False,
350 ) -> None:
351 """
352 Log a user or client into the app, if needed, storing the resulting tokens.
353
354 A login flow will be performed if any of the following are true:
355 * The kwarg ``auth_params`` is provided.
356 * The kwarg ``force`` is set to True.
357 * The method ``self.login_required()`` evaluates to True.
358
359 :param auth_params: An optional set of authorization parameters to establish
360 requirements and controls for the login flow.
361 :param force: If True, perform a login flow even if one does not appear to
362 be necessary.
363 """
364 if auth_params or force or self.login_required():
365 self._run_login_flow(auth_params)
366
367 def login_required(self) -> bool:
368 """
369 Determine if a login flow will be required to interact with resource servers
370 under the current scope requirements.
371
372 This will return false if any of the following are true:
373 * Access tokens have never been issued.
374 * Access tokens have been issued but have insufficient scopes.
375 * Access tokens have expired and wouldn't be resolved with refresh tokens.
376
377 :returns: True if a login flow appears to be required, False otherwise.
378 """
379 for resource_server in self._scope_requirements.keys():
380 try:
381 with self._disabled_token_validation_error_handler():
382 self.get_authorizer(resource_server)
383 except TokenValidationError:
384 return True
385 return False
386
387 def logout(self) -> None:
388 """
389 Log the current user or client out of the app.
390
391 This will remove and revoke all tokens stored for the current app user.
392 """
393 # Revoke all tokens, removing them from the underlying token storage
394 inner_token_storage = self.token_storage.token_storage
395 for resource_server in self._scope_requirements.keys():
396 token_data = inner_token_storage.get_token_data(resource_server)
397 if token_data:
398 self._login_client.oauth2_revoke_token(token_data.access_token)
399 if token_data.refresh_token:
400 self._login_client.oauth2_revoke_token(token_data.refresh_token)
401 inner_token_storage.remove_token_data(resource_server)
402
403 # Invalidate any cached authorizers
404 self._authorizer_factory.clear_cache()
405
406 def close(self) -> None:
407 """
408 Close all resources currently held by the app.
409 This does not trigger a logout.
410 """
411 for resource in self._resources_to_close:
412 log.debug(
413 f"closing resource of type {type(resource).__name__} "
414 f"for {type(self).__name__}(app_name={self.app_name!r})"
415 )
416 resource.close()
417
418 # apps can act as context managers, and such usage calls close()
419 def __enter__(self) -> Self:
420 return self
421
422 def __exit__(
423 self,
424 exc_type: type[BaseException] | None,
425 exc_val: BaseException | None,
426 exc_tb: types.TracebackType | None,
427 ) -> None:
428 self.close()
429
430 @abc.abstractmethod
431 def _run_login_flow(
432 self, auth_params: GlobusAuthorizationParameters | None = None
433 ) -> None:
434 """
435 Run an authorization flow to get new tokens which are stored and available
436 for the next authorizer gotten by get_authorizer.
437
438 :param auth_params: An optional set of authorization parameters to establish
439 requirements and controls for the login flow.
440 """
441
442 def _auth_params_with_required_scopes(
443 self,
444 auth_params: GlobusAuthorizationParameters | None = None,
445 ) -> GlobusAuthorizationParameters:
446 """
447 Either make a new GlobusAuthorizationParameters with this app's required scopes
448 or combine this app's required scopes with given auth_params.
449 """
450 required_scopes = []
451 for scope_list in self._scope_requirements.values():
452 required_scopes.extend(scope_list)
453
454 if not auth_params:
455 auth_params = GlobusAuthorizationParameters()
456 parsed_required_scopes = []
457 for s in auth_params.required_scopes or []:
458 parsed_required_scopes.extend(ScopeParser.parse(s))
459
460 # merge scopes for deduplication to minimize url request length
461 # this is useful even if there weren't any auth_param scope requirements
462 # as the app's scope_requirements can have duplicates
463 combined_scopes = ScopeParser.merge_scopes(
464 required_scopes, parsed_required_scopes
465 )
466 auth_params.required_scopes = [str(s) for s in combined_scopes]
467
468 return auth_params
469
470 @contextlib.contextmanager
471 def _disabled_token_validation_error_handler(self) -> t.Iterator[None]:
472 """
473 Context manager to disable token validation error handling (as a default)
474 for the duration of the context.
475 """
476 # Record the starting value so we can reset it after the context ends.
477 initial_val = self._token_validation_error_handling_enabled
478
479 self._token_validation_error_handling_enabled = False
480 try:
481 yield
482 finally:
483 self._token_validation_error_handling_enabled = initial_val
484
485 def add_scope_requirements(
486 self, scope_requirements: t.Mapping[str, str | Scope | t.Iterable[str | Scope]]
487 ) -> None:
488 """
489 Add given scope requirements to the app's scope requirements. Any duplicate
490 requirements will be deduplicated with existing requirements.
491
492 :param scope_requirements: a dict of Scopes indexed by resource server
493 that will be added to this app's scope requirements
494 """
495 for resource_server, scopes in scope_requirements.items():
496 curr = self._scope_requirements.setdefault(resource_server, [])
497 curr.extend(self._iter_scopes(scopes))
498
499 self._authorizer_factory.clear_cache(*scope_requirements.keys())
500
501 def get_authorizer(self, resource_server: str) -> GlobusAuthorizer:
502 """
503 Get a ``GlobusAuthorizer`` for a resource server.
504
505 This method will be called by service clients while making HTTP requests.
506
507 :param resource_server: The resource server for which the requested Authorizer
508 should provide authorization headers.
509 """
510 error_handling_enabled = self._token_validation_error_handling_enabled
511
512 try:
513 # Disable token validation error handling for nested calls.
514 # This will ultimately ensure that the error handler is only called once
515 # by the root `get_authorizer` invocation.
516 with self._disabled_token_validation_error_handler():
517 return self._authorizer_factory.get_authorizer(resource_server)
518 except TokenValidationError as e:
519 if error_handling_enabled and self.config.token_validation_error_handler:
520 # Dispatch to the configured error handler if one is set then retry.
521 self.config.token_validation_error_handler(self, e)
522 return self._authorizer_factory.get_authorizer(resource_server)
523 raise e
524
525 def get_client_retry_checks(self) -> t.Sequence[RetryCheck]:
526 if not self.config.auto_redrive_gares:
527 return []
528 else:
529 return [_RedriveGlobusAppGARE(self)]
530
531 @property
532 def scope_requirements(self) -> dict[str, list[Scope]]:
533 """
534 Access a copy of app's aggregate scope requirements.
535
536 Modifying the returned dict will not affect the app's scope requirements.
537 To add scope requirements, use ``GlobusApp.add_scope_requirements()``.
538
539 .. note::
540
541 Users may observe that Globus Auth (``'auth.globus.org'``) is always
542 present, and always maps to the ``openid`` scope, even when the user has
543 not added this scope. This mapping is expected, as the ``openid`` scope is
544 needed internally for the functionality provided by ``GlobusApp``.
545 """
546 # Scopes are mutable objects so we return a deepcopy
547 return copy.deepcopy(self._scope_requirements)
548
549 def _iter_scopes(
550 self, scopes: str | Scope | t.Iterable[str | Scope]
551 ) -> t.Iterator[Scope]:
552 """Normalize scopes in various formats to an iterator of Scope objects."""
553 if isinstance(scopes, str):
554 yield from ScopeParser.parse(scopes)
555 elif isinstance(scopes, Scope):
556 yield scopes
557 else:
558 for item in scopes:
559 if isinstance(item, str):
560 yield from ScopeParser.parse(item)
561 else:
562 yield item
563
564
565 @set_retry_check_flags(RetryCheckFlags.RUN_ONCE)
566 class _RedriveGlobusAppGARE:
567 """
568 A client.transport RetryCheck specific to GlobusApps.
569
570 Upon receiving a GARE-parsable 403 response, this check will initiate a login,
571 refresh the authorizer, and dispatch a retry.
572 """
573
574 def __init__(self, app: GlobusApp) -> None:
575 self.app = app
576
577 def __call__(self, ctx: RetryContext) -> RetryCheckResult:
578 if (resource_server := ctx.caller_info.resource_server) is None:
579 return RetryCheckResult.no_decision
580
581 elif (gare := self._load_response_gare(ctx.response)) is None:
582 return RetryCheckResult.no_decision
583
584 log.debug("Intercepted re-drivable GARE; initiating app login.")
585 self.app.login(auth_params=gare.authorization_parameters)
586 updated_authorizer = self.app.get_authorizer(resource_server)
587 log.debug("Acquired updated authorizer after GARE login; retrying.")
588
589 ctx.caller_info.authorizer = updated_authorizer
590 return RetryCheckResult.do_retry
591
592 @staticmethod
593 def _load_response_gare(response: Response | None) -> GARE | None:
594 """Return a parsed GARE from a 403 response or None if not possible."""
595 if response is None or response.status_code != 403:
596 return None
597 try:
598 decoded_body = response.json()
599 except JSONDecodeError:
600 return None
601 else:
602 return to_gare(decoded_body)