Debian Codegraph @

src/globus_sdk/authorizers/client_credentials.py

raw
1 from __future__ import annotations
2
3 import logging
4 import typing as t
5
6 import globus_sdk
7 from globus_sdk.scopes import Scope, ScopeParser
8
9 from .renewing import RenewingAuthorizer
10
11 log = logging.getLogger(__name__)
12
13
14 class ClientCredentialsAuthorizer(
15 RenewingAuthorizer["globus_sdk.OAuthClientCredentialsResponse"]
16 ):
17 r"""
18 Implementation of a RenewingAuthorizer that renews confidential app client
19 Access Tokens using a ConfidentialAppAuthClient and a set of scopes to
20 fetch a new Access Token when the old one expires.
21
22 Example usage looks something like this:
23
24 >>> import globus_sdk
25 >>> confidential_client = globus_sdk.ConfidentialAppAuthClient(
26 client_id=..., client_secret=...)
27 >>> scopes = "..."
28 >>> cc_authorizer = globus_sdk.ClientCredentialsAuthorizer(
29 >>> confidential_client, scopes)
30 >>> # create a new client
31 >>> transfer_client = globus_sdk.TransferClient(authorizer=cc_authorizer)
32
33 any client that inherits from :class:`BaseClient <globus_sdk.BaseClient>`
34 should be able to use a ClientCredentialsAuthorizer to act as
35 the client itself.
36
37 :param confidential_client: client object with a valid id and client secret
38 :param scopes: A string of space-separated scope names being requested for the
39 access tokens that will be used for the Authorization header. These scopes must
40 all be for the same resource server, or else the token response will have
41 multiple access tokens.
42 :param access_token: Initial Access Token to use, only used if ``expires_at`` is
43 also set. Must be requested with the same set of scopes passed to this
44 authorizer.
45 :param expires_at: Expiration time for the starting ``access_token`` expressed as a
46 POSIX timestamp (i.e. seconds since the epoch)
47 :param on_refresh: A callback which is triggered any time this authorizer fetches a
48 new access_token. The ``on_refresh`` callable is invoked on the
49 :class:`globus_sdk.OAuthClientCredentialsResponse` object resulting from the
50 token being refreshed. It should take only one positional argument, the token
51 response object.
52 This is useful for implementing storage for Access Tokens, as the
53 ``on_refresh`` callback can be used to update the Access Tokens and
54 their expiration times.
55 """
56
57 def __init__(
58 self,
59 confidential_client: globus_sdk.ConfidentialAppAuthClient,
60 scopes: str | Scope | t.Iterable[str | Scope],
61 *,
62 access_token: str | None = None,
63 expires_at: int | None = None,
64 on_refresh: (
65 None | t.Callable[[globus_sdk.OAuthClientCredentialsResponse], t.Any]
66 ) = None,
67 ) -> None:
68 # values for _get_token_data
69 self.confidential_client = confidential_client
70 self.scopes = ScopeParser.serialize(scopes)
71
72 log.debug(
73 "Setting up ClientCredentialsAuthorizer with confidential_client="
74 f"[instance:{id(confidential_client)}] and scopes={self.scopes}"
75 )
76
77 super().__init__(access_token, expires_at, on_refresh)
78
79 def _get_token_response(self) -> globus_sdk.OAuthClientCredentialsResponse:
80 """
81 Make a request for new tokens, using a 'client_credentials' grant.
82 """
83 return self.confidential_client.oauth2_client_credentials_tokens(
84 requested_scopes=self.scopes
85 )
86
87 def _extract_token_data(
88 self, res: globus_sdk.OAuthClientCredentialsResponse
89 ) -> dict[str, t.Any]:
90 """
91 Get the tokens .by_resource_server,
92 Ensure that only one token was gotten, and return that token.
93 """
94 token_data = res.by_resource_server.values()
95 if len(token_data) != 1:
96 raise ValueError(
97 "Attempting get new access token for client credentials "
98 "authorizer didn't return exactly one token. Ensure scopes "
99 f"{self.scopes} are for only one resource server."
100 )
101
102 return next(iter(token_data))