Skip to content

Commit

Permalink
Try to raise most specific exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruwann committed Mar 18, 2022
1 parent 18b9f49 commit 836cf68
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions connexion/security/security_handler_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,18 +366,18 @@ def verify_security(cls, auth_funcs, function):
@functools.wraps(function)
def wrapper(request):
token_info = cls.no_value
problem = None
errors = []
for func in auth_funcs:
try:
token_info = func(request)
if token_info is not cls.no_value:
break
except (OAuthProblem, OAuthResponseProblem, OAuthScopeProblem) as err:
problem = err
except Exception as err:
errors += err

if token_info is cls.no_value:
if problem is not None:
raise problem
if errors != []:
cls._raise_most_specific(errors)
else:
logger.info("... No auth provided. Aborting with 401.")
raise OAuthProblem(description='No authorization token provided')
Expand All @@ -389,6 +389,37 @@ def wrapper(request):

return wrapper

@staticmethod
def _raise_most_specific(exceptions: t.List[Exception]) -> None:
"""Raises the most specific error from a list of exceptions by status code.
The status codes are expected to be either in the `code`
or in the `status` attribute of the exceptions.
The order is as follows:
- 403: valid credentials but not enough privileges
- 401: no or invalid credentials
- for other status codes, the smallest one is selected
:param errors: List of exceptions.
:type errors: t.List[Exception]
"""
if not exceptions:
return
# We only use status code attributes from exceptions
# We use 600 as default because 599 is highest valid status code
status_to_exc = {
getattr(exc, 'code', getattr(exc, 'status', 600)): exc
for exc in exceptions
}
if 403 in status_to_exc:
raise status_to_exc[403]
elif 401 in status_to_exc:
raise status_to_exc[401]
else:
lowest_status_code = min(status_to_exc)
raise status_to_exc[lowest_status_code]

@abc.abstractmethod
def get_token_info_remote(self, token_info_url):
"""
Expand Down

0 comments on commit 836cf68

Please sign in to comment.