blackducksoftware / hub-rest-api-python

HUB REST API Python bindings
Apache License 2.0
89 stars 105 forks source link

Add robust error handling to authentication #139

Closed skiyooka closed 3 years ago

skiyooka commented 3 years ago

Inspect the HTTP response status code and print out more meaningful error messages but more importantly include the requests.response object when raising an exception so that the caller can better diagnose the root cause.

Previously upon authentication failure, the traceback was very cryptic raising a KeyError 'Set-cookie' for failed username/password authentication and KeyError 'bearerToken' for failed access token authentication.

skiyooka commented 3 years ago

I determined that the fix for https://github.com/blackducksoftware/sage/issues/3 is best placed here in HubInstance rather than in Sage.

Tested on 2020.10 and 2020.12.

Example cryptic tracebacks during failed authentication that this pull request addresses:

Traceback (most recent call last):
  File "version_activity.py", line 416, in <module>
    hub = authenticate_hub(args)
  File "version_activity.py", line 383, in authenticate_hub
    hub = HubInstance(args.urlbase, args.username, args.password, write_config_flag=create_config, insecure=accept_self_signed)
  File "/usr/local/lib/python3.8/site-packages/blackduck/HubRestApi.py", line 117, in __init__
    self.token, self.csrf_token, self.cookie = self.get_auth_token()
  File "/usr/local/lib/python3.8/site-packages/blackduck/HubRestApi.py", line 164, in get_auth_token
    cookie = response.headers['Set-Cookie']
  File "/usr/local/lib/python3.8/site-packages/requests/structures.py", line 54, in __getitem__
    return self._store[key.lower()][1]
KeyError: 'set-cookie'
Traceback (most recent call last):
  File "version_activity.py", line 416, in <module>
    hub = authenticate_hub(args)
  File "version_activity.py", line 387, in authenticate_hub
    hub = HubInstance(args.urlbase, api_token=token, write_config_flag=create_config, insecure=accept_self_signed)
  File "/usr/local/lib/python3.8/site-packages/blackduck/HubRestApi.py", line 117, in __init__
    self.token, self.csrf_token, self.cookie = self.get_auth_token()
  File "/usr/local/lib/python3.8/site-packages/blackduck/HubRestApi.py", line 151, in get_auth_token
    bearer_token = json.loads(response.content.decode('utf-8'))['bearerToken']
KeyError: 'bearerToken'
skiyooka commented 3 years ago

As this is now incorporated into the new Client, Sage will be refactored to use it. Closing this PR.