Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform re-authentication for empty unauthorized responses #526

Merged
merged 2 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions b2sdk/_internal/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ def _wrap_token(self, raw_api_method, token_type, *args, **kwargs):
callback = self._token_callbacks[token_type]
partial_callback = partial(callback, raw_api_method, *args, **kwargs)

return self._reauthorization_loop(partial_callback)
return self._execute_with_auth_retry(partial_callback)

def _api_token_callback(self, raw_api_method, *args, **kwargs):
api_url = self.account_info.get_api_url()
Expand All @@ -470,20 +470,21 @@ def _api_token_only_callback(self, raw_api_method, *args, **kwargs):
account_auth_token = self.account_info.get_account_auth_token()
return raw_api_method(account_auth_token, *args, **kwargs)

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

def _add_app_key_info_to_unauthorized(self, unauthorized):
"""
Expand Down
1 change: 1 addition & 0 deletions changelog.d/+reauth_empty_unauthorized.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Perform re-authentication for empty 401 responses returned for `HEAD` requests.
Loading