From f6c590cd8d5834f7e2a2d746ded934549e1fd5f8 Mon Sep 17 00:00:00 2001 From: Samuel Gulliksson Date: Sat, 11 Feb 2023 13:11:34 +0100 Subject: [PATCH] Don't throw exception for token error response. (#844) * Don't throw exception for token error response. --- src/oic/oauth2/__init__.py | 9 ++------- tests/test_oauth2.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/oic/oauth2/__init__.py b/src/oic/oauth2/__init__.py index 9af823cc..25959c4c 100644 --- a/src/oic/oauth2/__init__.py +++ b/src/oic/oauth2/__init__.py @@ -743,14 +743,9 @@ def parse_request_response( logger.error("(%d) %s" % (reqresp.status_code, sanitize(reqresp.text))) raise ParseError("ERROR: Something went wrong: %s" % reqresp.text) - if reqresp.status_code in SUCCESSFUL: - verified_body_type = verify_header(reqresp, body_type) - elif ( - reqresp.status_code in [400, 401] - and response - and issubclass(response, ErrorResponse) + if reqresp.status_code in SUCCESSFUL or ( + reqresp.status_code in [400, 401] and response ): - # This is okay if we are expecting an error response, do not log verified_body_type = verify_header(reqresp, body_type) else: # Any other error diff --git a/tests/test_oauth2.py b/tests/test_oauth2.py index 0c602f9d..4640f3e0 100644 --- a/tests/test_oauth2.py +++ b/tests/test_oauth2.py @@ -11,6 +11,7 @@ from oic.oauth2 import Grant from oic.oauth2 import Server from oic.oauth2 import Token +from oic.oauth2 import TokenErrorResponse from oic.oauth2.exception import GrantError from oic.oauth2.exception import MissingEndpoint from oic.oauth2.exception import ResponseError @@ -598,6 +599,27 @@ class CCMessageFactory(OauthMessageFactory): assert isinstance(resp, AccessTokenResponse) assert resp["access_token"] == "Token" + def test_do_access_token_request_handle_error_response(self): + class CCMessageFactory(OauthMessageFactory): + """We are doing client credentials.""" + + token_endpoint = MessageTuple(CCAccessTokenRequest, AccessTokenResponse) + + self.client.message_factory = CCMessageFactory + with responses.RequestsMock() as rsps: + rsps.add( + rsps.POST, + self.token_endpoint, + status=400, + json={"error": "invalid_request", "error_description": "test error"}, + ) + + resp = self.client.do_access_token_request() + assert rsps.calls[0].request.body == "grant_type=client_credentials" + + assert isinstance(resp, TokenErrorResponse) + assert resp["error"] == "invalid_request" + def test_do_access_token_request_extension_grant(self): class ExtensionMessageFactory(OauthMessageFactory): """We are doing Extension grant."""