Skip to content

Commit 7593e79

Browse files
committed
feat: Recognize invalid authentication
* SSLError means the key/certificate pair is invalid. * 401 Unauthorized from gateway means the username/password is invalid.
1 parent 6b1ebcb commit 7593e79

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

insights/client/connection.py

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,16 +77,32 @@ def _api_request_failed(exception, message='The Insights API could not be reache
7777
logger.error(message)
7878

7979

80-
def _is_dns_error(exception):
81-
while isinstance(exception, Exception):
82-
if isinstance(exception, socket.gaierror):
83-
return True
80+
def _is_basic_auth_error(result):
81+
if result.status_code != 401 or result.headers["Content-Type"] != "application/json":
82+
return False
8483

85-
exception = exception.__context__
84+
try:
85+
body = result.json()
86+
except requests.exceptions.JSONDecodeError:
87+
return False
88+
89+
if not isinstance(body, dict) or "errors" not in body or not isinstance(body["errors"], list):
90+
return False
91+
92+
for error in body["errors"]:
93+
if "status" in error and error["status"] == 401 and "meta" in error and isinstance(error["meta"], dict) and "response_by" in error["meta"] and error["meta"]["response_by"] == "gateway":
94+
return True
8695

8796
return False
8897

8998

99+
def _exception_root_cause(exception):
100+
while True:
101+
if not exception.__context__:
102+
return exception
103+
exception = exception.__context__
104+
105+
90106
def _fallback_ip(hostname):
91107
if hostname.endswith("redhat.com"):
92108
if hostname.endswith("stage.redhat.com"):
@@ -554,8 +570,21 @@ def test_connection(self, rc=0):
554570
logger.error(" Additional information may be in %s" % self.config.logging_file)
555571
logger.error("")
556572

557-
if _is_dns_error(result):
558-
self._test_connection(url)
573+
if isinstance(result, REQUEST_FAILED_EXCEPTIONS):
574+
root_cause = _exception_root_cause(result)
575+
if isinstance(result, requests.exceptions.SSLError):
576+
logger.error(" Invalid key or certificate.")
577+
elif isinstance(result, requests.exceptions.ConnectionError) and isinstance(root_cause, socket.gaierror):
578+
self._test_connection(url)
579+
else:
580+
logger.error(" Unknown error %s.", result)
581+
elif isinstance(result, requests.Response):
582+
if _is_basic_auth_error(result):
583+
logger.error(" Invalid username or password.")
584+
else:
585+
logger.error(" Unknown response.")
586+
else:
587+
logger.error(" Unknown result %s.", result)
559588

560589
return 1
561590

0 commit comments

Comments
 (0)