2929 requests = None
3030
3131
32- DEFAULT_METADATA_URL = 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token'
32+ DEFAULT_METADATA_URL = (
33+ "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token"
34+ )
3335
3436
3537def get_jwt (account_id , access_key_id , private_key , jwt_expiration_timeout ):
3638 now = time .time ()
3739 now_utc = datetime .utcfromtimestamp (now )
3840 exp_utc = datetime .utcfromtimestamp (now + jwt_expiration_timeout )
3941 return jwt .encode (
40- key = private_key , algorithm = "PS256" , headers = {"typ" : "JWT" , "alg" : "PS256" , "kid" : access_key_id },
42+ key = private_key ,
43+ algorithm = "PS256" ,
44+ headers = {"typ" : "JWT" , "alg" : "PS256" , "kid" : access_key_id },
4145 payload = {
4246 "iss" : account_id ,
43- "aud" : "https://iam.api.cloud.yandex.net/iam/v1/tokens" , "iat" : now_utc , "exp" : exp_utc
44- }
47+ "aud" : "https://iam.api.cloud.yandex.net/iam/v1/tokens" ,
48+ "iat" : now_utc ,
49+ "exp" : exp_utc ,
50+ },
4551 )
4652
4753
@@ -110,25 +116,39 @@ def _get_iam_token(self):
110116 def _log_refresh_start (self , current_time ):
111117 self .logger .debug ("Start refresh token from metadata" )
112118 if current_time > self ._refresh_in :
113- self .logger .info ("Cached token reached refresh_in deadline, current time %s, deadline %s" , current_time ,
114- self ._refresh_in )
119+ self .logger .info (
120+ "Cached token reached refresh_in deadline, current time %s, deadline %s" ,
121+ current_time ,
122+ self ._refresh_in ,
123+ )
115124
116125 if current_time > self ._expires_in and self ._expires_in > 0 :
117- self .logger .error ("Cached token reached expires_in deadline, current time %s, deadline %s" , current_time ,
118- self ._expires_in )
126+ self .logger .error (
127+ "Cached token reached expires_in deadline, current time %s, deadline %s" ,
128+ current_time ,
129+ self ._expires_in ,
130+ )
119131
120132 def _update_expiration_info (self , auth_metadata ):
121- self ._expires_in = time .time () + min (self ._hour , auth_metadata ['expires_in' ] / 2 )
122- self ._refresh_in = time .time () + min (self ._hour / 2 , auth_metadata ['expires_in' ] / 4 )
133+ self ._expires_in = time .time () + min (
134+ self ._hour , auth_metadata ["expires_in" ] / 2
135+ )
136+ self ._refresh_in = time .time () + min (
137+ self ._hour / 2 , auth_metadata ["expires_in" ] / 4
138+ )
123139
124140 def _refresh (self ):
125141 current_time = time .time ()
126142 self ._log_refresh_start (current_time )
127143 try :
128144 auth_metadata = self ._get_iam_token ()
129- self ._iam_token .update (auth_metadata [' access_token' ])
145+ self ._iam_token .update (auth_metadata [" access_token" ])
130146 self ._update_expiration_info (auth_metadata )
131- self .logger .info ("Token refresh successful. current_time %s, refresh_in %s" , current_time , self ._refresh_in )
147+ self .logger .info (
148+ "Token refresh successful. current_time %s, refresh_in %s" ,
149+ current_time ,
150+ self ._refresh_in ,
151+ )
132152
133153 except (KeyboardInterrupt , SystemExit ):
134154 return
@@ -143,41 +163,52 @@ def _refresh(self):
143163 def iam_token (self ):
144164 current_time = time .time ()
145165 if current_time > self ._refresh_in :
146- tracing .trace (self .tracer , {
147- "refresh" : True
148- })
166+ tracing .trace (self .tracer , {"refresh" : True })
149167 self ._tp .submit (self ._refresh )
150168 iam_token = self ._iam_token .consume (timeout = 3 )
151- tracing .trace (
152- self .tracer , {
153- "consumed" : True
154- }
155- )
169+ tracing .trace (self .tracer , {"consumed" : True })
156170 if iam_token is None :
157171 if self .last_error is None :
158- raise issues .ConnectionError ("%s: timeout occurred while waiting for token.\n %s" % self .__class__ .__name__ , self .extra_error_message )
159- raise issues .ConnectionError ("%s: %s.\n %s" % (self .__class__ .__name__ , self .last_error , self .extra_error_message ))
172+ raise issues .ConnectionError (
173+ "%s: timeout occurred while waiting for token.\n %s"
174+ % self .__class__ .__name__ ,
175+ self .extra_error_message ,
176+ )
177+ raise issues .ConnectionError (
178+ "%s: %s.\n %s"
179+ % (self .__class__ .__name__ , self .last_error , self .extra_error_message )
180+ )
160181 return iam_token
161182
162183 def auth_metadata (self ):
163- return [
164- (credentials .YDB_AUTH_TICKET_HEADER , self .iam_token )
165- ]
184+ return [(credentials .YDB_AUTH_TICKET_HEADER , self .iam_token )]
166185
167186
168187@six .add_metaclass (abc .ABCMeta )
169188class TokenServiceCredentials (IamTokenCredentials ):
170189 def __init__ (self , iam_endpoint = None , iam_channel_credentials = None , tracer = None ):
171190 super (TokenServiceCredentials , self ).__init__ (tracer )
172- self ._iam_endpoint = 'iam.api.cloud.yandex.net:443' if iam_endpoint is None else iam_endpoint
173- self ._iam_channel_credentials = {} if iam_channel_credentials is None else iam_channel_credentials
191+ self ._iam_endpoint = (
192+ "iam.api.cloud.yandex.net:443" if iam_endpoint is None else iam_endpoint
193+ )
194+ self ._iam_channel_credentials = (
195+ {} if iam_channel_credentials is None else iam_channel_credentials
196+ )
174197 self ._get_token_request_timeout = 10
175- if iam_token_service_pb2_grpc is None or jwt is None or iam_token_service_pb2 is None :
198+ if (
199+ iam_token_service_pb2_grpc is None
200+ or jwt is None
201+ or iam_token_service_pb2 is None
202+ ):
176203 raise RuntimeError (
177- "Install jwt & yandex python cloud library to use service account credentials provider" )
204+ "Install jwt & yandex python cloud library to use service account credentials provider"
205+ )
178206
179207 def _channel_factory (self ):
180- return grpc .secure_channel (self ._iam_endpoint , grpc .ssl_channel_credentials (** self ._iam_channel_credentials ))
208+ return grpc .secure_channel (
209+ self ._iam_endpoint ,
210+ grpc .ssl_channel_credentials (** self ._iam_channel_credentials ),
211+ )
181212
182213 @abc .abstractmethod
183214 def _get_token_request (self ):
@@ -186,20 +217,20 @@ def _get_token_request(self):
186217 @tracing .with_trace ()
187218 def _get_iam_token (self ):
188219 with self ._channel_factory () as channel :
189- tracing .trace (self .tracer , {
190- "iam_token.from_service" : True
191- })
220+ tracing .trace (self .tracer , {"iam_token.from_service" : True })
192221 stub = iam_token_service_pb2_grpc .IamTokenServiceStub (channel )
193- response = stub .Create (self ._get_token_request (), timeout = self ._get_token_request_timeout )
222+ response = stub .Create (
223+ self ._get_token_request (), timeout = self ._get_token_request_timeout
224+ )
194225 expires_in = max (0 , response .expires_at .seconds - int (time .time ()))
195- return {' access_token' : response .iam_token , ' expires_in' : expires_in }
226+ return {" access_token" : response .iam_token , " expires_in" : expires_in }
196227
197228
198229@six .add_metaclass (abc .ABCMeta )
199230class BaseJWTCredentials (object ):
200231 def __init__ (self , account_id , access_key_id , private_key ):
201232 self ._account_id = account_id
202- self ._jwt_expiration_timeout = 60. * 60
233+ self ._jwt_expiration_timeout = 60.0 * 60
203234 self ._token_expiration_timeout = 120
204235 self ._access_key_id = access_key_id
205236 self ._private_key = private_key
@@ -210,40 +241,59 @@ def set_token_expiration_timeout(self, value):
210241
211242 @classmethod
212243 def from_file (cls , key_file , iam_endpoint = None , iam_channel_credentials = None ):
213- with open (os .path .expanduser (key_file ), 'r' ) as r :
244+ with open (os .path .expanduser (key_file ), "r" ) as r :
214245 output = json .loads (r .read ())
215- account_id = output .get (' service_account_id' , None )
246+ account_id = output .get (" service_account_id" , None )
216247 if account_id is None :
217- account_id = output .get (' user_account_id' , None )
248+ account_id = output .get (" user_account_id" , None )
218249 return cls (
219250 account_id ,
220- output ['id' ],
221- output [' private_key' ],
251+ output ["id" ],
252+ output [" private_key" ],
222253 iam_endpoint = iam_endpoint ,
223- iam_channel_credentials = iam_channel_credentials
254+ iam_channel_credentials = iam_channel_credentials ,
224255 )
225256
226257
227258class JWTIamCredentials (TokenServiceCredentials , BaseJWTCredentials ):
228- def __init__ (self , account_id , access_key_id , private_key , iam_endpoint = None , iam_channel_credentials = None ):
259+ def __init__ (
260+ self ,
261+ account_id ,
262+ access_key_id ,
263+ private_key ,
264+ iam_endpoint = None ,
265+ iam_channel_credentials = None ,
266+ ):
229267 TokenServiceCredentials .__init__ (self , iam_endpoint , iam_channel_credentials )
230268 BaseJWTCredentials .__init__ (self , account_id , access_key_id , private_key )
231269
232270 def _get_token_request (self ):
233271 return iam_token_service_pb2 .CreateIamTokenRequest (
234272 jwt = get_jwt (
235- self ._account_id , self ._access_key_id , self ._private_key , self ._jwt_expiration_timeout
273+ self ._account_id ,
274+ self ._access_key_id ,
275+ self ._private_key ,
276+ self ._jwt_expiration_timeout ,
236277 )
237278 )
238279
239280
240281class YandexPassportOAuthIamCredentials (TokenServiceCredentials ):
241- def __init__ (self , yandex_passport_oauth_token , iam_endpoint = None , iam_channel_credentials = None ):
282+ def __init__ (
283+ self ,
284+ yandex_passport_oauth_token ,
285+ iam_endpoint = None ,
286+ iam_channel_credentials = None ,
287+ ):
242288 self ._yandex_passport_oauth_token = yandex_passport_oauth_token
243- super (YandexPassportOAuthIamCredentials , self ).__init__ (iam_endpoint , iam_channel_credentials )
289+ super (YandexPassportOAuthIamCredentials , self ).__init__ (
290+ iam_endpoint , iam_channel_credentials
291+ )
244292
245293 def _get_token_request (self ):
246- return iam_token_service_pb2 .CreateIamTokenRequest (yandex_passport_oauth_token = self ._yandex_passport_oauth_token )
294+ return iam_token_service_pb2 .CreateIamTokenRequest (
295+ yandex_passport_oauth_token = self ._yandex_passport_oauth_token
296+ )
247297
248298
249299class MetadataUrlCredentials (IamTokenCredentials ):
@@ -256,18 +306,36 @@ def __init__(self, metadata_url=None, tracer=None):
256306 super (MetadataUrlCredentials , self ).__init__ (tracer )
257307 if requests is None :
258308 raise RuntimeError (
259- "Install requests library to use metadata credentials provider" )
260- self ._metadata_url = DEFAULT_METADATA_URL if metadata_url is None else metadata_url
309+ "Install requests library to use metadata credentials provider"
310+ )
311+ self ._metadata_url = (
312+ DEFAULT_METADATA_URL if metadata_url is None else metadata_url
313+ )
261314 self ._tp .submit (self ._refresh )
262315 self .extra_error_message = "Check that metadata service configured properly and application deployed in VM or function at Yandex.Cloud."
263316
264317 @tracing .with_trace ()
265318 def _get_iam_token (self ):
266- response = requests .get (self ._metadata_url , headers = {'Metadata-Flavor' : 'Google' }, timeout = 3 )
319+ response = requests .get (
320+ self ._metadata_url , headers = {"Metadata-Flavor" : "Google" }, timeout = 3
321+ )
267322 response .raise_for_status ()
268323 return json .loads (response .text )
269324
270325
271326class ServiceAccountCredentials (JWTIamCredentials ):
272- def __init__ (self , service_account_id , access_key_id , private_key , iam_endpoint = None , iam_channel_credentials = None ):
273- super (ServiceAccountCredentials , self ).__init__ (service_account_id , access_key_id , private_key , iam_endpoint , iam_channel_credentials )
327+ def __init__ (
328+ self ,
329+ service_account_id ,
330+ access_key_id ,
331+ private_key ,
332+ iam_endpoint = None ,
333+ iam_channel_credentials = None ,
334+ ):
335+ super (ServiceAccountCredentials , self ).__init__ (
336+ service_account_id ,
337+ access_key_id ,
338+ private_key ,
339+ iam_endpoint ,
340+ iam_channel_credentials ,
341+ )
0 commit comments