From 4073413024af30c223563a7920d6877dc72d2271 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Fri, 27 Nov 2026 08:48:55 -0800 Subject: [PATCH 1/3] feat: add follow_redirects option to the configuration Lets callers stop the SDK from following HTTP redirects from the FGA server, so a 3xx is raised as an ApiException instead of the request and its credentials going to another location. Applies to the sync and async clients, including token requests. Defaults to True, so nothing changes unless it's set. Fixes #338 Signed-off-by: Srinivas Chippagiri --- README.md | 12 ++++ openfga_sdk/client/configuration.py | 2 + openfga_sdk/configuration.py | 7 +++ openfga_sdk/rest.py | 4 ++ openfga_sdk/sync/rest.py | 4 ++ test/follow_redirects_test.py | 97 +++++++++++++++++++++++++++++ 6 files changed, 126 insertions(+) create mode 100644 test/follow_redirects_test.py diff --git a/README.md b/README.md index 90a65e86..db352daf 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ This is an autogenerated python SDK for OpenFGA. It provides a wrapper around th - [Write Assertions](#write-assertions) - [Calling Other Endpoints](#calling-other-endpoints) - [Retries](#retries) + - [Redirects](#redirects) - [API Endpoints](#api-endpoints) - [Models](#models) - [OpenTelemetry](#opentelemetry) @@ -1413,6 +1414,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 (and its credentials) being sent to the new location. 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/client/configuration.py b/openfga_sdk/client/configuration.py index 9eae4e8c..c6da4a91 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 bc015d76..625b80d6 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 diff --git a/openfga_sdk/rest.py b/openfga_sdk/rest.py index 54090ae9..7d193b12 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/rest.py b/openfga_sdk/sync/rest.py index db4391db..4fc9d83f 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/test/follow_redirects_test.py b/test/follow_redirects_test.py new file mode 100644 index 00000000..7f7ac9bb --- /dev/null +++ b/test/follow_redirects_test.py @@ -0,0 +1,97 @@ +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() From 638fe84d618845ee44643d28390be8e385a5ed00 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 1 Dec 2026 02:36:26 -0800 Subject: [PATCH 2/3] fix: handle non-JSON redirect bodies and test OAuth redirects Signed-off-by: Srinivas Chippagiri --- openfga_sdk/api_client.py | 8 ++- openfga_sdk/sync/api_client.py | 8 ++- openfga_sdk/telemetry/attributes.py | 2 +- test/follow_redirects_test.py | 108 ++++++++++++++++++++++++++++ 4 files changed, 119 insertions(+), 7 deletions(-) diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index 8afbd0c1..4385b440 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=bytes(e.body or b"").decode("utf-8", errors="replace"), 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/sync/api_client.py b/openfga_sdk/sync/api_client.py index 61b6108d..d68ef4e1 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=bytes(e.body or b"").decode("utf-8", errors="replace"), 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/telemetry/attributes.py b/openfga_sdk/telemetry/attributes.py index 02451c1f..829da381 100644 --- a/openfga_sdk/telemetry/attributes.py +++ b/openfga_sdk/telemetry/attributes.py @@ -296,7 +296,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 index 7f7ac9bb..b164f1ea 100644 --- a/test/follow_redirects_test.py +++ b/test/follow_redirects_test.py @@ -95,3 +95,111 @@ async def test_async_raises_on_redirect_when_disabled(redirect_server): 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 From 3c04168ba8244d7d9a3cb470da175667de10876d Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 1 Dec 2026 09:52:05 -0800 Subject: [PATCH 3/3] test: cover redirect decode, validate follow_redirects type, clarify README Signed-off-by: Srinivas Chippagiri --- README.md | 2 +- openfga_sdk/configuration.py | 5 +++ test/follow_redirects_test.py | 65 +++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index db352daf..364cba4a 100644 --- a/README.md +++ b/README.md @@ -1416,7 +1416,7 @@ 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 (and its credentials) being sent to the new location. It applies to token requests too. +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( diff --git a/openfga_sdk/configuration.py b/openfga_sdk/configuration.py index 625b80d6..a807167c 100644 --- a/openfga_sdk/configuration.py +++ b/openfga_sdk/configuration.py @@ -665,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/test/follow_redirects_test.py b/test/follow_redirects_test.py index b164f1ea..a12b1d53 100644 --- a/test/follow_redirects_test.py +++ b/test/follow_redirects_test.py @@ -203,3 +203,68 @@ def test_telemetry_tolerates_non_mapping_error_body(): 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()