diff --git a/README.md b/README.md index 512bb3b..ec9a7cd 100644 --- a/README.md +++ b/README.md @@ -1441,6 +1441,17 @@ async def main(): ``` +### Redirects + +By default the SDK follows HTTP redirects returned by the server, as aiohttp and urllib3 do. If your FGA server is not expected to redirect, you can turn this off with `follow_redirects=False`, so a 3xx response is raised as an `ApiException` with the status code instead of the request being sent to the new location. aiohttp and urllib3 already drop the `Authorization` header on cross-host redirects, but a 307/308 from the token endpoint would still forward the client secret, and any custom headers go along too. It applies to token requests too. + +```python +config = ClientConfiguration( + api_url=environ.get("FGA_API_URL"), + follow_redirects=False, +) +``` + ### Error Handling The SDK provides comprehensive error handling with detailed error information and convenient helper methods. diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index 8afbd0c..fd89c1b 100644 --- a/openfga_sdk/api_client.py +++ b/openfga_sdk/api_client.py @@ -294,7 +294,7 @@ async def __call_api( ) except (RateLimitExceededError, ServiceException) as e: _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), + response=e, credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, @@ -317,7 +317,8 @@ async def __call_api( await asyncio.sleep(wait_time_in_sec) continue - e.body = e.body.decode("utf-8") + if isinstance(e.body, (bytes, bytearray)): + e.body = bytes(e.body).decode("utf-8", errors="replace") response_type = response_types_map.get(e.status, None) if response_type is not None: e.parsed_exception = self.__deserialize( @@ -359,7 +360,8 @@ async def __call_api( continue except ApiException as e: - e.body = e.body.decode("utf-8") + if isinstance(e.body, (bytes, bytearray)): + e.body = bytes(e.body).decode("utf-8", errors="replace") response_type = response_types_map.get(e.status, None) if response_type is not None: e.parsed_exception = self.__deserialize( diff --git a/openfga_sdk/client/configuration.py b/openfga_sdk/client/configuration.py index 9eae4e8..c6da4a9 100644 --- a/openfga_sdk/client/configuration.py +++ b/openfga_sdk/client/configuration.py @@ -42,6 +42,7 @@ def __init__( | None ) = None, headers: dict[str, str] | None = None, + follow_redirects: bool = True, ): super().__init__( api_scheme, @@ -54,6 +55,7 @@ def __init__( timeout_millisec=timeout_millisec, telemetry=telemetry, headers=headers, + follow_redirects=follow_redirects, ) self._authorization_model_id = authorization_model_id diff --git a/openfga_sdk/configuration.py b/openfga_sdk/configuration.py index bc015d7..a807167 100644 --- a/openfga_sdk/configuration.py +++ b/openfga_sdk/configuration.py @@ -164,6 +164,8 @@ class Configuration: in PEM format :param api_url: str - the URL of the FGA server :param timeout_millisec: int | None - the default timeout in milliseconds for requests + :param follow_redirects: bool - whether to follow HTTP redirects from the server. + Defaults to True. When False, a 3xx response is raised as an ApiException. """ _default = None @@ -202,6 +204,7 @@ def __init__( ) = None, timeout_millisec: int | None = None, headers: dict[str, str] | None = None, + follow_redirects: bool = True, ): """Constructor""" self._url = api_url @@ -216,6 +219,10 @@ def __init__( self._retry_params = RetryParams() self._timeout_millisec = timeout_millisec or 5000 * 60 + self.follow_redirects = follow_redirects + """Follow HTTP redirects returned by the server. When False, a 3xx + response is raised as an ApiException instead of being followed. + """ """Default Base url """ self.server_index = 0 @@ -658,6 +665,11 @@ def is_valid(self): f"timeout_millisec not within reasonable range (0,60000), {self._timeout_millisec}" ) + if not isinstance(self.follow_redirects, bool): + raise FgaValidationException( + f"follow_redirects must be a bool, got {type(self.follow_redirects).__name__}" + ) + if self._headers is not None: for key, value in self._headers.items(): if not isinstance(key, str): diff --git a/openfga_sdk/rest.py b/openfga_sdk/rest.py index 54090ae..7d193b1 100644 --- a/openfga_sdk/rest.py +++ b/openfga_sdk/rest.py @@ -164,6 +164,9 @@ def __init__( self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers self._timeout_millisec = configuration.timeout_millisec + self._follow_redirects = ( + getattr(configuration, "follow_redirects", True) is not False + ) self.pool_manager = aiohttp.ClientSession(connector=connector, trust_env=True) # aiohttp 3.10+ resends GET, HEAD, PUT and DELETE once by itself when a # kept-alive connection drops. Turn that off, as aiohttp.test_utils does, @@ -223,6 +226,7 @@ async def build_request( "url": url, "timeout": timeout, "headers": headers, + "allow_redirects": self._follow_redirects, } if self.proxy: diff --git a/openfga_sdk/sync/api_client.py b/openfga_sdk/sync/api_client.py index 61b6108..9821a4f 100644 --- a/openfga_sdk/sync/api_client.py +++ b/openfga_sdk/sync/api_client.py @@ -292,7 +292,7 @@ def __call_api( ) except (RateLimitExceededError, ServiceException) as e: _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), + response=e, credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, @@ -314,7 +314,8 @@ def __call_api( time.sleep(wait_time_in_sec) continue - e.body = e.body.decode("utf-8") + if isinstance(e.body, (bytes, bytearray)): + e.body = bytes(e.body).decode("utf-8", errors="replace") response_type = response_types_map.get(e.status, None) if response_type is not None: e.parsed_exception = self.__deserialize( @@ -351,7 +352,8 @@ def __call_api( time.sleep(min(random_time(retry, min_wait_in_ms), max_wait_in_sec)) continue except ApiException as e: - e.body = e.body.decode("utf-8") + if isinstance(e.body, (bytes, bytearray)): + e.body = bytes(e.body).decode("utf-8", errors="replace") response_type = response_types_map.get(e.status, None) if response_type is not None: e.parsed_exception = self.__deserialize( diff --git a/openfga_sdk/sync/rest.py b/openfga_sdk/sync/rest.py index db4391d..4fc9d83 100644 --- a/openfga_sdk/sync/rest.py +++ b/openfga_sdk/sync/rest.py @@ -200,6 +200,9 @@ def __init__( maxsize = 4 self._timeout_millisec = configuration.timeout_millisec + self._follow_redirects = ( + getattr(configuration, "follow_redirects", True) is not False + ) if hasattr(configuration, "proxy") and configuration.proxy is not None: self.pool_manager: urllib3.ProxyManager | urllib3.PoolManager = ( @@ -287,6 +290,7 @@ def build_request( "timeout": timeout, "headers": headers, "preload_content": _preload_content, + "redirect": self._follow_redirects, } if query_params: diff --git a/openfga_sdk/telemetry/attributes.py b/openfga_sdk/telemetry/attributes.py index edb06b0..2f3ebd6 100644 --- a/openfga_sdk/telemetry/attributes.py +++ b/openfga_sdk/telemetry/attributes.py @@ -300,7 +300,7 @@ def fromResponse( response.status ) - if response.body is not None: + if isinstance(response.body, dict): response_model_id = response.body.get( "openfga-authorization-model-id" ) or response.body.get("openfga_authorization_model_id") diff --git a/test/follow_redirects_test.py b/test/follow_redirects_test.py new file mode 100644 index 0000000..4cd7636 --- /dev/null +++ b/test/follow_redirects_test.py @@ -0,0 +1,329 @@ +import threading + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from openfga_sdk import rest +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.configuration import Configuration +from openfga_sdk.exceptions import ApiException +from openfga_sdk.sync import rest as sync_rest + + +class _RedirectHandler(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/target": + body = b'{"ok":true}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + self.send_response(302) + self.send_header("Location", "/target") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + +@pytest.fixture +def redirect_server(): + server = ThreadingHTTPServer(("127.0.0.1", 0), _RedirectHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + server.server_close() + + +def _config(follow_redirects=None): + if follow_redirects is None: + return Configuration(api_url="http://127.0.0.1") + return Configuration(api_url="http://127.0.0.1", follow_redirects=follow_redirects) + + +def test_follow_redirects_defaults_to_true(): + assert Configuration().follow_redirects is True + assert ClientConfiguration().follow_redirects is True + + +def test_client_configuration_passes_follow_redirects(): + assert ClientConfiguration(follow_redirects=False).follow_redirects is False + + +def test_sync_follows_redirects_by_default(redirect_server): + client = sync_rest.RESTClientObject(_config()) + try: + resp = client.request("GET", f"{redirect_server}/start") + assert resp.status == 200 + assert resp.data == b'{"ok":true}' + finally: + client.close() + + +def test_sync_raises_on_redirect_when_disabled(redirect_server): + client = sync_rest.RESTClientObject(_config(follow_redirects=False)) + try: + with pytest.raises(ApiException) as err: + client.request("GET", f"{redirect_server}/start") + assert err.value.status == 302 + finally: + client.close() + + +@pytest.mark.asyncio +async def test_async_follows_redirects_by_default(redirect_server): + client = rest.RESTClientObject(_config()) + try: + resp = await client.request("GET", f"{redirect_server}/start") + assert resp.status == 200 + assert resp.data == b'{"ok":true}' + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_async_raises_on_redirect_when_disabled(redirect_server): + client = rest.RESTClientObject(_config(follow_redirects=False)) + try: + with pytest.raises(ApiException) as err: + await client.request("GET", f"{redirect_server}/start") + assert err.value.status == 302 + finally: + await client.close() + + +class _Sink: + """Records every request that reaches the redirect target.""" + + def __init__(self): + self.requests = [] + + +def _make_token_server(status, sink): + class Target(BaseHTTPRequestHandler): + def _record(self): + length = int(self.headers.get("Content-Length") or 0) + sink.requests.append((self.path, self.rfile.read(length))) + self.send_response(200) + self.send_header("Content-Length", "0") + self.end_headers() + + do_GET = do_POST = _record + + def log_message(self, *args): + pass + + target = ThreadingHTTPServer(("127.0.0.1", 0), Target) + target_url = f"http://127.0.0.1:{target.server_address[1]}/stolen" + + class Issuer(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + self.rfile.read(length) + self.send_response(status) + self.send_header("Location", target_url) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + issuer = ThreadingHTTPServer(("127.0.0.1", 0), Issuer) + for server in (target, issuer): + threading.Thread(target=server.serve_forever, daemon=True).start() + return issuer, target + + +def _oauth_config(issuer, config_cls=ClientConfiguration): + from openfga_sdk.credentials import CredentialConfiguration, Credentials + + url = f"http://127.0.0.1:{issuer.server_address[1]}" + return config_cls( + api_url=url, + follow_redirects=False, + credentials=Credentials( + method="client_credentials", + configuration=CredentialConfiguration( + client_id="id", + client_secret="topsecret", + api_issuer=url, + api_audience="aud", + ), + ), + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [307, 308]) +async def test_async_oauth_token_redirect_not_followed(status): + from openfga_sdk.client import OpenFgaClient + + sink = _Sink() + issuer, target = _make_token_server(status, sink) + client = OpenFgaClient(_oauth_config(issuer)) + try: + with pytest.raises(ApiException) as err: + await client.list_stores() + assert err.value.status == status + assert sink.requests == [] + finally: + await client.close() + issuer.shutdown() + target.shutdown() + + +@pytest.mark.parametrize("status", [307, 308]) +def test_sync_oauth_token_redirect_not_followed(status): + from openfga_sdk.sync import OpenFgaClient + + sink = _Sink() + issuer, target = _make_token_server(status, sink) + client = OpenFgaClient(_oauth_config(issuer)) + try: + with pytest.raises(ApiException) as err: + client.list_stores() + assert err.value.status == status + assert sink.requests == [] + finally: + client.close() + issuer.shutdown() + target.shutdown() + + +def test_telemetry_tolerates_non_mapping_error_body(): + from openfga_sdk.telemetry.attributes import TelemetryAttributes + + for body in ("", "moved", None): + exc = ApiException(status=302, reason="Found") + exc.body = body + attrs = TelemetryAttributes.fromResponse(response=exc) + assert attrs[TelemetryAttributes.http_response_status_code] == 302 + + +def _make_binary_redirect_server(): + class Handler(BaseHTTPRequestHandler): + def _respond(self): + body = b"\xff\xfe\x80 moved" + self.send_response(302) + self.send_header("Location", "/elsewhere") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = _respond + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +@pytest.mark.asyncio +async def test_async_api_call_redirect_with_binary_body_raises_api_exception(): + from openfga_sdk.client import OpenFgaClient + + server = _make_binary_redirect_server() + url = f"http://127.0.0.1:{server.server_address[1]}" + client = OpenFgaClient(ClientConfiguration(api_url=url, follow_redirects=False)) + try: + with pytest.raises(ApiException) as err: + await client.list_stores() + assert err.value.status == 302 + finally: + await client.close() + server.shutdown() + + +def test_sync_api_call_redirect_with_binary_body_raises_api_exception(): + from openfga_sdk.sync import OpenFgaClient + + server = _make_binary_redirect_server() + url = f"http://127.0.0.1:{server.server_address[1]}" + client = OpenFgaClient(ClientConfiguration(api_url=url, follow_redirects=False)) + try: + with pytest.raises(ApiException) as err: + client.list_stores() + assert err.value.status == 302 + finally: + client.close() + server.shutdown() + + +@pytest.mark.parametrize("value", [0, 1, None, "false", "true"]) +def test_follow_redirects_must_be_a_bool(value): + from openfga_sdk.exceptions import FgaValidationException + + config = Configuration(api_url="http://127.0.0.1", follow_redirects=value) + with pytest.raises(FgaValidationException): + config.is_valid() + + +@pytest.mark.parametrize("value", [True, False]) +def test_follow_redirects_accepts_a_bool(value): + Configuration(api_url="http://127.0.0.1", follow_redirects=value).is_valid() + + +def _make_binary_status_server(status): + class Handler(BaseHTTPRequestHandler): + def _respond(self): + body = b"\xff\xfe\x80 oops" + self.send_response(status) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = _respond + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [429, 503]) +async def test_async_api_call_error_with_binary_body_raises_service_exception(status): + from openfga_sdk.client import OpenFgaClient + from openfga_sdk.configuration import RetryParams + from openfga_sdk.exceptions import RateLimitExceededError, ServiceException + + server = _make_binary_status_server(status) + url = f"http://127.0.0.1:{server.server_address[1]}" + client = OpenFgaClient( + ClientConfiguration(api_url=url, retry_params=RetryParams(max_retry=0)) + ) + try: + with pytest.raises((RateLimitExceededError, ServiceException)) as err: + await client.list_stores() + assert err.value.status == status + finally: + await client.close() + server.shutdown() + + +@pytest.mark.parametrize("status", [429, 503]) +def test_sync_api_call_error_with_binary_body_raises_service_exception(status): + from openfga_sdk.client.configuration import ClientConfiguration as CC + from openfga_sdk.configuration import RetryParams + from openfga_sdk.exceptions import RateLimitExceededError, ServiceException + from openfga_sdk.sync import OpenFgaClient + + server = _make_binary_status_server(status) + url = f"http://127.0.0.1:{server.server_address[1]}" + client = OpenFgaClient(CC(api_url=url, retry_params=RetryParams(max_retry=0))) + try: + with pytest.raises((RateLimitExceededError, ServiceException)) as err: + client.list_stores() + assert err.value.status == status + finally: + client.close() + server.shutdown()