Skip to content

Commit 7241497

Browse files
committed
Perform re-authentication for empty unauthorized responses
1 parent ec12aae commit 7241497

File tree

2 files changed

+17
-15
lines changed

2 files changed

+17
-15
lines changed

b2sdk/_internal/session.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def _wrap_token(self, raw_api_method, token_type, *args, **kwargs):
459459
callback = self._token_callbacks[token_type]
460460
partial_callback = partial(callback, raw_api_method, *args, **kwargs)
461461

462-
return self._reauthorization_loop(partial_callback)
462+
return self._execute_with_auth_retry(partial_callback)
463463

464464
def _api_token_callback(self, raw_api_method, *args, **kwargs):
465465
api_url = self.account_info.get_api_url()
@@ -470,20 +470,21 @@ def _api_token_only_callback(self, raw_api_method, *args, **kwargs):
470470
account_auth_token = self.account_info.get_account_auth_token()
471471
return raw_api_method(account_auth_token, *args, **kwargs)
472472

473-
def _reauthorization_loop(self, callback):
474-
auth_failure_encountered = False
475-
while 1:
476-
try:
477-
return callback()
478-
except InvalidAuthToken:
479-
if not auth_failure_encountered:
480-
auth_failure_encountered = True
481-
reauthorization_success = self.authorize_automatically()
482-
if reauthorization_success:
483-
continue
484-
raise
485-
except Unauthorized as e:
486-
raise self._add_app_key_info_to_unauthorized(e)
473+
def _execute_with_auth_retry(self, callback, first_attempt: bool = True):
474+
try:
475+
return callback()
476+
except InvalidAuthToken:
477+
if first_attempt and self.authorize_automatically():
478+
return self._execute_with_auth_retry(callback, first_attempt=False)
479+
raise
480+
except Unauthorized as exc:
481+
# When performing HEAD requests, the api can return an empty response
482+
# with a 401 status code, which may or may not be related to expired
483+
# token, thus we also try to re-authorize if explicit `unauthorized`
484+
# code is missing
485+
if not exc.code and first_attempt and self.authorize_automatically():
486+
return self._execute_with_auth_retry(callback, first_attempt=False)
487+
raise self._add_app_key_info_to_unauthorized(exc)
487488

488489
def _add_app_key_info_to_unauthorized(self, unauthorized):
489490
"""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Perform re-authentication for empty 401 responses returned for `HEAD` requests.

0 commit comments

Comments
 (0)