Skip to content

Commit b074cad

Browse files
authored
fix: catch ValueError for json.loads() (#1842)
see internal bug 448976223 TODO: - [x] add test - [x] match the exception string so we don't catch unexpected cases
1 parent cb62f57 commit b074cad

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

google/auth/_helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ def _parse_request_body(body: Optional[bytes], content_type: str = "") -> Any:
489489
if not content_type or "application/json" in content_type:
490490
try:
491491
return json.loads(body_str)
492-
except (json.JSONDecodeError, TypeError):
492+
except (TypeError, ValueError):
493493
return body_str
494494
if "application/x-www-form-urlencoded" in content_type:
495495
parsed_query = urllib.parse.parse_qs(body_str)

tests/test__helpers.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,34 @@ def test_parse_request_body_other_type():
623623
assert _helpers._parse_request_body("string") is None
624624

625625

626+
def test_parse_request_body_json_type_error():
627+
body = b'{"key": "value"}'
628+
with mock.patch("json.loads", side_effect=TypeError):
629+
# json.loads should raise a TypeError, and the function should return the
630+
# original string
631+
assert _helpers._parse_request_body(body, "application/json") == body.decode(
632+
"utf-8"
633+
)
634+
635+
636+
def test_parse_request_body_json_value_error():
637+
body = b'{"key": "value"}'
638+
content_type = "application/json"
639+
with mock.patch("json.loads", side_effect=ValueError):
640+
# json.loads should raise a ValueError, and the function should return the
641+
# original string
642+
assert _helpers._parse_request_body(body, content_type) == body.decode("utf-8")
643+
644+
645+
def test_parse_request_body_json_decode_error():
646+
body = b'{"key": "value"}'
647+
content_type = "application/json"
648+
with mock.patch("json.loads", side_effect=json.JSONDecodeError("msg", "doc", 0)):
649+
# json.loads should raise a JSONDecodeError, and the function should return the
650+
# original string
651+
assert _helpers._parse_request_body(body, content_type) == body.decode("utf-8")
652+
653+
626654
def test_parse_response_json_valid():
627655
class MockResponse:
628656
def json(self):

0 commit comments

Comments
 (0)