Adding WWW-Authenticate info.

Sometimes when mistral requests are failing with "401 Unauthorized"
against keycloak, the reason are not mentioned in the logs.

In case keycloack return 401 it must provide the www-Authenticate
response header with the reason:
https://www.w3.org/Protocols/HTTP/1.0/spec.html#WWW-Authenticate

This code take care of it by adding the WWW-Authenticate value to
mistral api-log.

Change-Id: I7ae221aaeb2233184bd4818490e72ff662dca5cb
Closes-Bug: #1737500
This commit is contained in:
Idan Narotzki 2018-04-09 08:37:55 +00:00 committed by Renat Akhmerov
parent 54fe5b0109
commit 1ece440ac5
3 changed files with 23 additions and 5 deletions

View File

@ -48,8 +48,9 @@ class KeycloakAuthHandler(auth.AuthHandler):
try:
decoded = jwt.decode(access_token, algorithms=['RS256'],
verify=False)
except Exception:
msg = _("Token can't be decoded because of wrong format.")
except Exception as e:
msg = _("Token can't be decoded because of wrong format %s")\
% str(e)
LOG.error(msg)
raise exc.UnauthorizedException(message=msg)
@ -90,6 +91,15 @@ class KeycloakAuthHandler(auth.AuthHandler):
LOG.error(msg)
raise exc.MistralException(message=msg)
if resp.status_code == 401:
LOG.warning("HTTP response from OIDC provider:"
" [%s] with WWW-Authenticate: [%s]",
pprint.pformat(resp.text),
resp.headers.get("WWW-Authenticate"))
else:
LOG.debug("HTTP response from OIDC provider: %s",
pprint.pformat(resp.text))
resp.raise_for_status()
LOG.debug(

View File

@ -241,7 +241,7 @@ class AuthHook(hooks.PecanHook):
pecan.abort(
status_code=401,
detail=msg,
headers={'Server-Error-Message': msg}
headers={'Server-Error-Message': msg, "WWW-Authenticate": msg}
)

View File

@ -82,6 +82,8 @@ USER_CLAIMS = {
"picture": "http://example.com/janedoe/me.jpg"
}
WWW_AUTHENTICATE_HEADER = {'WWW-Authenticate': 'unauthorized reason is ...'}
class TestKeyCloakOIDCAuth(base.BaseTest):
@ -166,7 +168,8 @@ class TestKeyCloakOIDCAuth(base.BaseTest):
req_mock.get(
USER_INFO_ENDPOINT,
status_code=401,
reason='Access token is invalid'
reason='Access token is invalid',
headers=WWW_AUTHENTICATE_HEADER
)
req = self._build_request(token)
@ -179,6 +182,11 @@ class TestKeyCloakOIDCAuth(base.BaseTest):
"401 Client Error: Access token is invalid for url",
str(e)
)
self.assertEqual(
'unauthorized reason is ...',
e.response.headers.get('WWW-Authenticate')
)
else:
raise Exception("Test is broken")
@ -273,7 +281,7 @@ class TestKeyCloakOIDCAuthScenarios(base.DbTestCase):
self.assertEqual('401 Unauthorized', resp.status)
self.assertIn('Failed to validate access token', resp.text)
self.assertIn(
"Token can't be decoded because of wrong format.",
"Token can't be decoded because of wrong format",
resp.text
)