Debian Codegraph @

ibm_cloud_sdk_core/token_managers/token_manager.py

raw
1 # coding: utf-8
2
3 # Copyright 2020, 2024 IBM All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 import time
19 from abc import ABC, abstractmethod
20 from threading import Lock
21
22 import requests
23
24 from ibm_cloud_sdk_core.logger import get_logger
25 from ..api_exception import ApiException
26
27 logger = get_logger()
28
29
30 # pylint: disable=too-many-instance-attributes
31 class TokenManager(ABC):
32 """An abstract class to contain functionality for parsing, storing, and requesting tokens.
33
34 get_token will retrieve a new token from the url in case the that there is no existing token,
35 or the previous token has expired. Child classes will implement request_token, which will do
36 the actual acquisition of a new token.
37
38 Args:
39 url: The url to request tokens from.
40
41 Keyword Args:
42 disable_ssl_verification: A flag that indicates whether verification of
43 the server's SSL certificate should be disabled or not. Defaults to False.
44
45 Attributes:
46 url (str): The url to request tokens from.
47 disable_ssl_verification (bool): A flag that indicates whether verification of
48 the server's SSL certificate should be disabled or not.
49 expire_time (int): The time in epoch seconds when the current stored token will expire.
50 refresh_time (int): The time in epoch seconds when the current stored token should be refreshed.
51 request_time (int): The time the last outstanding token request was issued
52 lock (Lock): Lock variable to serialize access to refresh/request times
53 http_config (dict): A dictionary containing values that control the timeout, proxies, and etc of HTTP requests.
54 access_token (str): The latest stored access token
55 user_agent (str): The User-Agent header value to be included in each outbound token request
56 """
57
58 def __init__(self, url: str, *, disable_ssl_verification: bool = False):
59 self.url = url
60 self.disable_ssl_verification = disable_ssl_verification
61 self.expire_time = 0
62 self.refresh_time = 0
63 self.request_time = 0
64 self.lock = Lock()
65 self.http_config = {}
66 self.access_token = None
67 self.user_agent = None
68
69 def get_token(self) -> str:
70 """Get a token to be used for authentication.
71
72 The source of the token is determined by the following logic:
73 1. a) If the current token is expired (or never fetched), make a request for one
74 b) If the current token should be refreshed, issue a refresh request
75 2. After any requests initiated above complete, return the stored token
76
77 Returns:
78 str: A valid access token
79 """
80 if self._is_token_expired():
81 logger.debug('Performing synchronous token fetch')
82 self.paced_request_token()
83
84 if self._token_needs_refresh():
85 logger.debug('Performing background asynchronous token fetch')
86 token_response = self.request_token()
87 self._save_token_info(token_response)
88 else:
89 logger.debug('Using cached access token')
90
91 return self.access_token
92
93 def set_disable_ssl_verification(self, status: bool = False) -> None:
94 """Sets the ssl verification to enabled or disabled.
95
96 Args:
97 status: the flag to be used for determining status.
98
99 Raises:
100 TypeError: The `status` is not a bool.
101 """
102 if isinstance(status, bool):
103 self.disable_ssl_verification = status
104 else:
105 raise TypeError('status must be a bool')
106
107 def _set_user_agent(self, user_agent: str = None) -> None:
108 self.user_agent = user_agent
109
110 def _get_user_agent(self) -> str:
111 return self.user_agent
112
113 def paced_request_token(self) -> None:
114 """
115 Paces requests to request_token.
116
117 This method pseudo-serializes requests for an access_token
118 when the current token is expired (or has never been fetched).
119 The first caller into this method records its `request_time` and
120 then issues the token request. Subsequent callers will check the
121 `request_time` to see if a request is active (has been issued within
122 the past 60 seconds), and if so will sleep for a short time interval
123 (currently 0.5 seconds) before checking again. The check for an active
124 request and update of `request_time` are serailized by the `lock`
125 variable so that only one caller can become the active requester
126 with a 60 second interval.
127
128 Threads that sleep waiting for the active request to complete will
129 eventually find a newly valid token and return, or 60 seconds will
130 elapse and a new thread will assume the role of the active request.
131 """
132 while self._is_token_expired():
133 current_time = self._get_current_time()
134
135 with self.lock:
136 request_active = self.request_time > (current_time - 60)
137 if not request_active:
138 self.request_time = current_time
139
140 if not request_active:
141 token_response = self.request_token()
142 self._save_token_info(token_response)
143 self.request_time = 0
144 return
145
146 # Sleep for 0.5 seconds before checking token again
147 time.sleep(0.5)
148
149 @abstractmethod # pragma: no cover
150 def request_token(self) -> None:
151 """Should be overridden by child classes."""
152 pass
153
154 @staticmethod
155 def _get_current_time() -> int:
156 return int(time.time())
157
158 def _is_token_expired(self) -> bool:
159 """
160 Check if currently stored token is expired.
161
162 Returns
163 -------
164 bool
165 True if token is expired; False otherwise
166 """
167 current_time = self._get_current_time()
168 return self.expire_time < current_time
169
170 def _token_needs_refresh(self) -> bool:
171 """
172 Check if currently stored token needs refresh.
173
174 Returns
175 -------
176 bool
177 True if token needs refresh; False otherwise
178 """
179 current_time = self._get_current_time()
180
181 with self.lock:
182 needs_refresh = self.refresh_time < current_time
183 if needs_refresh:
184 self.refresh_time = current_time + 60
185
186 return needs_refresh
187
188 @abstractmethod
189 def _save_token_info(self, token_response: dict) -> None: # pragma: no cover
190 """
191 Decode the access token and save the response from the service to the object's state
192
193 Refresh time is set to approximately 80% of the token's TTL to ensure that
194 the token refresh completes before the current token expires.
195
196 Parameters
197 ----------
198 token_response : dict
199 Response from token service
200 """
201 pass
202
203 def _request(self, method, url, *, headers=None, params=None, data=None, auth_tuple=None, **kwargs):
204 kwargs = dict({"timeout": 60}, **kwargs)
205 kwargs = dict(kwargs, **self.http_config)
206
207 if self.disable_ssl_verification:
208 kwargs['verify'] = False
209
210 response = requests.request(
211 method=method, url=url, headers=headers, params=params, data=data, auth=auth_tuple, **kwargs
212 )
213 if 200 <= response.status_code <= 299:
214 return response
215
216 raise ApiException(response.status_code, http_response=response)