From 9287ccebd525daf12dc07408d94fac37dfbcfcdc Mon Sep 17 00:00:00 2001 From: Man Alin Date: Tue, 1 Dec 2026 11:18:54 +0000 Subject: [PATCH] fix: reject incorrectly typed response values Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- openfga_sdk/api_client.py | 58 +++++++++++++++++++++---------- openfga_sdk/sync/api_client.py | 58 +++++++++++++++++++++---------- test/deserialization_test.py | 48 +++++++++++++++++++++++++ test/sync/deserialization_test.py | 46 ++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 36 deletions(-) create mode 100644 test/deserialization_test.py create mode 100644 test/sync/deserialization_test.py diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index 8afbd0c..46488bf 100644 --- a/openfga_sdk/api_client.py +++ b/openfga_sdk/api_client.py @@ -550,10 +550,18 @@ def __deserialize(self, data, klass): if type(klass) is str: if klass.startswith("list["): + if not isinstance(data, list): + raise FgaValidationException( + f"Invalid response type for `{klass}`: expected a list, got {type(data).__name__}" + ) sub_kls = re.match(r"list\[(.*)\]", klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith("dict["): + if not isinstance(data, dict): + raise FgaValidationException( + f"Invalid response type for `{klass}`: expected a dict, got {type(data).__name__}" + ) sub_kls = re.match(r"dict\[([^,]*), (.*)\]", klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -858,19 +866,24 @@ def _apply_auth_params(self, headers, queries, auth_setting): raise ApiValueError("Authentication token must be in `query` or `header`") def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data + """Deserialize a JSON primitive without coercing it to another type.""" + valid = False + if klass is bool: + valid = type(data) is bool + elif klass is int: + valid = type(data) is int + elif klass is float: + valid = type(data) is int or type(data) is float + elif klass is str: + valid = type(data) is str + elif klass is bytes: + valid = type(data) is bytes or type(data) is str + + if not valid: + raise FgaValidationException( + f"Invalid response type: expected `{klass.__name__}`, got `{type(data).__name__}`" + ) + return klass(data) if klass is not bytes or type(data) is bytes else data def __deserialize_object(self, value): """Return an original value. @@ -885,6 +898,10 @@ def __deserialize_date(self, string): :param string: str. :return: date. """ + if not isinstance(string, str): + raise FgaValidationException( + f"Invalid response type: expected `str`, got `{type(string).__name__}`" + ) try: return parse(string).date() except ImportError: @@ -902,6 +919,10 @@ def __deserialize_datetime(self, string): :param string: str. :return: datetime. """ + if not isinstance(string, str): + raise FgaValidationException( + f"Invalid response type: expected `str`, got `{type(string).__name__}`" + ) try: return parse(string) except ImportError: @@ -929,12 +950,13 @@ def __deserialize_model(self, data, klass): if not klass.openapi_types and has_discriminator is False: return data + if not isinstance(data, dict): + raise FgaValidationException( + f"Invalid response type for `{klass.__name__}`: expected a dict, got {type(data).__name__}" + ) + kwargs = {} - if ( - data is not None - and klass.openapi_types is not None - and isinstance(data, list | dict) - ): + if data is not None and klass.openapi_types is not None: for attr, attr_type in klass.openapi_types.items(): if klass.attribute_map[attr] in data: value = data[klass.attribute_map[attr]] diff --git a/openfga_sdk/sync/api_client.py b/openfga_sdk/sync/api_client.py index 61b6108..51fa041 100644 --- a/openfga_sdk/sync/api_client.py +++ b/openfga_sdk/sync/api_client.py @@ -543,10 +543,18 @@ def __deserialize(self, data, klass): if type(klass) is str: if klass.startswith("list["): + if not isinstance(data, list): + raise FgaValidationException( + f"Invalid response type for `{klass}`: expected a list, got {type(data).__name__}" + ) sub_kls = re.match(r"list\[(.*)\]", klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith("dict["): + if not isinstance(data, dict): + raise FgaValidationException( + f"Invalid response type for `{klass}`: expected a dict, got {type(data).__name__}" + ) sub_kls = re.match(r"dict\[([^,]*), (.*)\]", klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -851,19 +859,24 @@ def _apply_auth_params(self, headers, queries, auth_setting): raise ApiValueError("Authentication token must be in `query` or `header`") def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data + """Deserialize a JSON primitive without coercing it to another type.""" + valid = False + if klass is bool: + valid = type(data) is bool + elif klass is int: + valid = type(data) is int + elif klass is float: + valid = type(data) is int or type(data) is float + elif klass is str: + valid = type(data) is str + elif klass is bytes: + valid = type(data) is bytes or type(data) is str + + if not valid: + raise FgaValidationException( + f"Invalid response type: expected `{klass.__name__}`, got `{type(data).__name__}`" + ) + return klass(data) if klass is not bytes or type(data) is bytes else data def __deserialize_object(self, value): """Return an original value. @@ -878,6 +891,10 @@ def __deserialize_date(self, string): :param string: str. :return: date. """ + if not isinstance(string, str): + raise FgaValidationException( + f"Invalid response type: expected `str`, got `{type(string).__name__}`" + ) try: return parse(string).date() except ImportError: @@ -895,6 +912,10 @@ def __deserialize_datetime(self, string): :param string: str. :return: datetime. """ + if not isinstance(string, str): + raise FgaValidationException( + f"Invalid response type: expected `str`, got `{type(string).__name__}`" + ) try: return parse(string) except ImportError: @@ -922,12 +943,13 @@ def __deserialize_model(self, data, klass): if not klass.openapi_types and has_discriminator is False: return data + if not isinstance(data, dict): + raise FgaValidationException( + f"Invalid response type for `{klass.__name__}`: expected a dict, got {type(data).__name__}" + ) + kwargs = {} - if ( - data is not None - and klass.openapi_types is not None - and isinstance(data, list | dict) - ): + if data is not None and klass.openapi_types is not None: for attr, attr_type in klass.openapi_types.items(): if klass.attribute_map[attr] in data: value = data[klass.attribute_map[attr]] diff --git a/test/deserialization_test.py b/test/deserialization_test.py new file mode 100644 index 0000000..091af76 --- /dev/null +++ b/test/deserialization_test.py @@ -0,0 +1,48 @@ +from unittest.mock import MagicMock + +import pytest + +from openfga_sdk.api_client import ApiClient +from openfga_sdk.configuration import Configuration +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.rest import RESTResponse + + +def rest_response(data: bytes) -> RESTResponse: + response = MagicMock() + response.status = 200 + response.reason = "OK" + return RESTResponse(response=response, data=data) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "body,response_type", + [ + pytest.param(b'{"allowed": "false"}', "CheckResponse", id="bool-as-string"), + pytest.param(b'{"allowed": 1}', "CheckResponse", id="bool-as-number"), + pytest.param(b"not json", "CheckResponse", id="non-json-object"), + pytest.param( + b'{"objects": "doc:1"}', "ListObjectsResponse", id="list-as-string" + ), + pytest.param(b'{"objects": [1]}', "ListObjectsResponse", id="string-as-number"), + ], +) +async def test_async_response_wrong_types_raise_validation_error(body, response_type): + async with ApiClient(Configuration(api_url="http://example.com")) as client: + with pytest.raises(FgaValidationException): + client.deserialize(rest_response(body), response_type) + + +@pytest.mark.asyncio +async def test_async_response_correct_types_still_deserialize(): + async with ApiClient(Configuration(api_url="http://example.com")) as client: + check = client.deserialize( + rest_response(b'{"allowed": false}'), "CheckResponse" + ) + objects = client.deserialize( + rest_response(b'{"objects": ["doc:1"]}'), "ListObjectsResponse" + ) + + assert check.allowed is False + assert objects.objects == ["doc:1"] diff --git a/test/sync/deserialization_test.py b/test/sync/deserialization_test.py new file mode 100644 index 0000000..9eadb7d --- /dev/null +++ b/test/sync/deserialization_test.py @@ -0,0 +1,46 @@ +from unittest.mock import MagicMock + +import pytest + +from openfga_sdk.configuration import Configuration +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.sync.api_client import ApiClient +from openfga_sdk.sync.rest import RESTResponse + + +def rest_response(data: bytes) -> RESTResponse: + response = MagicMock() + response.status = 200 + response.reason = "OK" + return RESTResponse(response=response, data=data) + + +@pytest.mark.parametrize( + "body,response_type", + [ + pytest.param(b'{"allowed": "false"}', "CheckResponse", id="bool-as-string"), + pytest.param(b'{"allowed": 1}', "CheckResponse", id="bool-as-number"), + pytest.param(b"not json", "CheckResponse", id="non-json-object"), + pytest.param( + b'{"objects": "doc:1"}', "ListObjectsResponse", id="list-as-string" + ), + pytest.param(b'{"objects": [1]}', "ListObjectsResponse", id="string-as-number"), + ], +) +def test_sync_response_wrong_types_raise_validation_error(body, response_type): + with ApiClient(Configuration(api_url="http://example.com")) as client: + with pytest.raises(FgaValidationException): + client.deserialize(rest_response(body), response_type) + + +def test_sync_response_correct_types_still_deserialize(): + with ApiClient(Configuration(api_url="http://example.com")) as client: + check = client.deserialize( + rest_response(b'{"allowed": false}'), "CheckResponse" + ) + objects = client.deserialize( + rest_response(b'{"objects": ["doc:1"]}'), "ListObjectsResponse" + ) + + assert check.allowed is False + assert objects.objects == ["doc:1"]