Debian Codegraph @

src/globus_sdk/authorizers/renewing.py

raw
1 from __future__ import annotations
2
3 import abc
4 import logging
5 import time
6 import typing as t
7
8 from globus_sdk import exc
9 from globus_sdk._internal.utils import sha256_string
10
11 from .base import GlobusAuthorizer
12
13 if t.TYPE_CHECKING:
14 from globus_sdk.services.auth import OAuthTokenResponse
15
16 log = logging.getLogger(__name__)
17 # Provides a buffer for token expiration time to account for
18 # possible delays or clock skew.
19 EXPIRES_ADJUST_SECONDS = 60
20
21 # the type of the response which is produced by the authorizer, received by it, and
22 # passed to the `on_refresh` callback
23 ResponseT = t.TypeVar("ResponseT", bound="OAuthTokenResponse")
24
25
26 class RenewingAuthorizer(GlobusAuthorizer, t.Generic[ResponseT], metaclass=abc.ABCMeta):
27 r"""
28 A ``RenewingAuthorizer`` is an abstract superclass to any authorizer
29 that needs to get new Access Tokens in order to form Authorization headers.
30
31 It may be passed an initial Access Token, but if so must also be passed
32 an expires_at value for that token.
33
34 It provides methods that handle the logic for checking and adjusting
35 expiration time, callbacks on renewal, and 401 handling.
36
37 To make an authorizer that implements this class implement
38 the _get_token_response and _extract_token_data methods for that
39 authorization type,
40
41 :param access_token: Initial Access Token to use, only used if ``expires_at`` is
42 also set
43 :param expires_at: Expiration time for the starting ``access_token`` expressed as a
44 POSIX timestamp (i.e. seconds since the epoch)
45 :param on_refresh: A callback which is triggered any time this authorizer fetches a
46 new access_token. The ``on_refresh`` callable is invoked on the response
47 object resulting from the token being refreshed. It should take only one
48 argument, the token response object.
49 This is useful for implementing storage for Access Tokens, as the
50 ``on_refresh`` callback can be used to update the Access Tokens and
51 their expiration times.
52 """
53
54 def __init__(
55 self,
56 access_token: str | None = None,
57 expires_at: int | None = None,
58 on_refresh: None | t.Callable[[ResponseT], t.Any] = None,
59 ) -> None:
60 self._access_token: str | None = None
61 self._access_token_hash: str | None = None
62
63 log.debug(
64 "Setting up a RenewingAuthorizer. It will use an "
65 "auth type of Bearer and can handle 401s."
66 )
67
68 if (access_token is not None and expires_at is None) or (
69 access_token is None and expires_at is not None
70 ):
71 raise exc.GlobusSDKUsageError(
72 "A RenewingAuthorizer cannot be initialized with one of "
73 "access_token and expires_at. Either provide both or neither."
74 )
75
76 self.access_token = access_token
77 self.expires_at = expires_at
78 self.on_refresh = on_refresh
79
80 if self.access_token is not None:
81 log.debug(
82 "RenewingAuthorizer will start by using access_token "
83 f'with hash "{self._access_token_hash}"'
84 )
85 # if data were unspecified, fetch a new access token
86 else:
87 log.debug(
88 "Creating RenewingAuthorizer without Access "
89 "Token. Fetching initial token now."
90 )
91 self._get_new_access_token()
92
93 @property
94 def access_token(self) -> str | None:
95 return self._access_token
96
97 @access_token.setter
98 def access_token(self, value: str | None) -> None:
99 self._access_token = value
100 if value:
101 self._access_token_hash = sha256_string(value)
102
103 @abc.abstractmethod
104 def _get_token_response(self) -> ResponseT:
105 """
106 Using whatever method the specific authorizer implementing this class
107 does, get a new token response.
108 """
109
110 @abc.abstractmethod
111 def _extract_token_data(self, res: ResponseT) -> dict[str, t.Any]:
112 """
113 Given a token response object, get the first element of
114 token_response.by_resource_server
115 This method is expected to enforce that by_resource_server is only
116 returning one access token, and return a ValueError otherwise.
117 """
118
119 def _get_new_access_token(self) -> None:
120 """
121 Given token data from _get_token_response and _extract_token_data,
122 set the access token and expiration time, calculate the new token
123 hash, and call on_refresh
124 """
125 # get the first (and only) token
126 res = self._get_token_response()
127 token_data = self._extract_token_data(res)
128
129 self.expires_at = token_data["expires_at_seconds"]
130 self.access_token = token_data["access_token"]
131
132 log.debug(
133 "RenewingAuthorizer.access_token updated to "
134 f'token with hash "{self._access_token_hash}"'
135 )
136
137 if callable(self.on_refresh):
138 log.debug("will call on_refresh callback")
139 self.on_refresh(res)
140 log.debug("on_refresh callback finished")
141
142 def ensure_valid_token(self) -> None:
143 """
144 Check that the authorizer has a valid token. Checks that the token is set and
145 that the expiration time is in the future.
146
147 This is called implicitly by ``get_authorization_header``, but you can
148 call it explicitly if you want to ensure that a token gets refreshed.
149 This can be useful in order to get at a new, valid token via the
150 ``on_refresh`` handler.
151 """
152 log.debug("RenewingAuthorizer checking expiration time")
153 if self.access_token is None:
154 log.debug("RenewingAuthorizer has no token")
155 else:
156 if (
157 self.expires_at is not None
158 and time.time() <= self.expires_at - EXPIRES_ADJUST_SECONDS
159 ):
160 log.debug("RenewingAuthorizer determined time has not yet expired")
161 return
162 else:
163 log.debug("RenewingAuthorizer has a token, but it is expired")
164
165 log.debug("RenewingAuthorizer fetching new Access Token")
166 self._get_new_access_token()
167
168 def get_authorization_header(self) -> str:
169 """
170 Check to see if a new token is needed and return "Bearer <access_token>"
171 """
172 self.ensure_valid_token()
173 log.debug(f'bearer token has hash "{self._access_token_hash}"')
174 return f"Bearer {self.access_token}"
175
176 def handle_missing_authorization(self) -> bool:
177 """
178 The renewing authorizer can respond to a service 401 by immediately
179 invalidating its current Access Token. When this happens, the next call
180 to ``set_authorization_header()`` will result in a new Access Token
181 being fetched.
182 """
183 log.debug(
184 "RenewingAuthorizer seeing 401. Invalidating "
185 "token and preparing for refresh."
186 )
187 # None for expires_at invalidates any current token
188 self.expires_at = None
189 # respond True, as in "we took some action, the 401 *may* be resolved"
190 return True