diff --git a/slack_sdk/web/base_client.py b/slack_sdk/web/base_client.py index 7be28dacf..7d2ecee00 100644 --- a/slack_sdk/web/base_client.py +++ b/slack_sdk/web/base_client.py @@ -218,9 +218,23 @@ def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, An return { "status_code": int(response["status"]), "headers": dict(response["headers"]), - "data": response["parsed_body"] if "parsed_body" in response else json.loads(response["body"]), + "data": self._parse_response_body(response), } + def _parse_response_body(self, response: Dict[str, Any]) -> Optional[Union[dict, bytes]]: + """Returns the body parsed to a dict, or an error payload when it is not JSON.""" + body = response.get("body", None) + if "parsed_body" in response: + return response["parsed_body"] + if body is None or isinstance(body, bytes): + return body + try: + return json.loads(body) + except json.decoder.JSONDecodeError: + message = _build_unexpected_body_error_message(body) + self._logger.error(f"Failed to decode Slack API response: {message}") + return {"ok": False, "error": message} + def _urllib_api_call( self, *, @@ -304,17 +318,7 @@ def convert_params(values: dict) -> dict: url = f"{url}&{q}" if "?" in url else f"{url}?{q}" response = self._perform_urllib_http_request(url=url, args=request_args) # type: ignore[arg-type] - response_body = response.get("body", None) - response_body_data: Optional[Union[dict, bytes]] = response_body - if "parsed_body" in response: - response_body_data = response["parsed_body"] - elif response_body is not None and not isinstance(response_body, bytes): - try: - response_body_data = json.loads(response["body"]) - except json.decoder.JSONDecodeError: - message = _build_unexpected_body_error_message(response.get("body", "")) - self._logger.error(f"Failed to decode Slack API response: {message}") - response_body_data = {"ok": False, "error": message} + response_body_data = self._parse_response_body(response) all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {} if query_params: @@ -415,8 +419,13 @@ def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, An body_string = resp["body"] if isinstance(resp["body"], str) else None body_bytes = body_string.encode("utf-8") if body_string is not None else resp["body"] if body_string is not None and body_string.startswith("{"): - parsed_body = json.loads(body_string) - resp["parsed_body"] = parsed_body + try: + parsed_body = json.loads(body_string) + resp["parsed_body"] = parsed_body + except json.decoder.JSONDecodeError: + # Truncated or otherwise malformed body. Leave parsed_body unset so + # the caller builds its usual non-JSON error instead of raising here. + parsed_body = {} else: parsed_body = {} retry_response = RetryHttpResponse( diff --git a/tests/slack_sdk/web/test_web_client.py b/tests/slack_sdk/web/test_web_client.py index c1dd7a3ae..e6e8bf873 100644 --- a/tests/slack_sdk/web/test_web_client.py +++ b/tests/slack_sdk/web/test_web_client.py @@ -290,3 +290,26 @@ def test_non_json_response_body_raises_api_error(self): with self.assertRaises(err.SlackApiError) as raised: self.client.api_test() self.assertTrue(raised.exception.response["error"].startswith("Received a response in a non-JSON format")) + + def test_non_json_response_body_starting_with_brace_raises_api_error(self): + # The retry-handler branch parses any 200 body that starts with "{", so a + # truncated body must not escape from it as a JSONDecodeError. + response = {"status": 200, "headers": {}, "body": '{"ok": tru'} + with patch.object(self.client, "_perform_urllib_http_request_internal", return_value=response): + with self.assertRaises(err.SlackApiError) as raised: + self.client.api_test() + self.assertTrue(raised.exception.response["error"].startswith("Received a response in a non-JSON format")) + + def test_non_json_response_body_during_pagination_raises_api_error(self): + pages = [ + { + "status": 200, + "headers": {}, + "body": json.dumps({"ok": True, "channels": [], "response_metadata": {"next_cursor": "next"}}), + }, + {"status": 200, "headers": {}, "body": '{"ok": tru'}, + ] + with patch.object(self.client, "_perform_urllib_http_request_internal", side_effect=pages): + with self.assertRaises(err.SlackApiError) as raised: + list(self.client.conversations_list(limit=1)) + self.assertTrue(raised.exception.response["error"].startswith("Received a response in a non-JSON format"))