From f8587edae91f58de30f4ef439531f090ebe6f769 Mon Sep 17 00:00:00 2001 From: Henry Su Date: Thu, 22 Oct 2026 18:42:41 -0500 Subject: [PATCH 1/2] test(auth): expect network failures to raise AuthRetryableError --- src/auth/tests/_async/test_gotrue.py | 71 ++++++++++++++++++++++++++++ src/auth/tests/_sync/test_gotrue.py | 69 +++++++++++++++++++++++++++ 2 files changed, 140 insertions(+) diff --git a/src/auth/tests/_async/test_gotrue.py b/src/auth/tests/_async/test_gotrue.py index 8efba21e3..200afd73c 100644 --- a/src/auth/tests/_async/test_gotrue.py +++ b/src/auth/tests/_async/test_gotrue.py @@ -797,3 +797,74 @@ def handler(request: Request) -> Response: assert Session.model_validate_json(stored).access_token == "new-access-token" assert client._refresh_token_timer is not None client._refresh_token_timer.cancel() + + +async def test_network_error_raises_auth_retryable_error() -> None: + # A transport failure (no HTTP response) must surface as a retryable auth + # error, not as a raw httpx exception. + from httpx import AsyncClient, ConnectError, MockTransport, Request, Response + from supabase_auth import AsyncGoTrueClient + from supabase_auth.errors import AuthRetryableError + + def handler(request: Request) -> Response: + raise ConnectError("boom", request=request) + + client = AsyncGoTrueClient( + url="http://auth.test", + http_client=AsyncClient(transport=MockTransport(handler)), + ) + + with pytest.raises(AuthRetryableError) as exc_info: + await client.sign_in_with_password( + {"email": "user@example.com", "password": "password"} + ) + assert exc_info.value.status == 0 + + +async def test_initialize_from_storage_keeps_session_on_network_error() -> None: + # A network failure while refreshing an expired stored session must keep + # the session and schedule a retry instead of signing the user out. + from httpx import AsyncClient, ConnectError, MockTransport, Request, Response + from supabase_auth import AsyncGoTrueClient + from supabase_auth.types import Session, User + + user = { + "id": str(uuid4()), + "aud": "authenticated", + "app_metadata": {}, + "user_metadata": {}, + "created_at": "2024-01-01T00:00:00Z", + } + + def handler(request: Request) -> Response: + assert request.url.path == "/token" + raise ConnectError("boom", request=request) + + client = AsyncGoTrueClient( + url="http://auth.test", + http_client=AsyncClient(transport=MockTransport(handler)), + ) + expired_session = Session( + access_token="expired-access-token", + refresh_token="old-refresh-token", + token_type="bearer", + expires_in=3600, + expires_at=round(time.time()) - 60, + user=User.model_validate(user), + ) + await client._storage.set_item( + client._storage_key, expired_session.model_dump_json() + ) + + try: + await client.initialize_from_storage() + + stored = await client._storage.get_item(client._storage_key) + assert stored is not None + assert ( + Session.model_validate_json(stored).access_token == "expired-access-token" + ) + assert client._refresh_token_timer is not None + finally: + if client._refresh_token_timer: + client._refresh_token_timer.cancel() diff --git a/src/auth/tests/_sync/test_gotrue.py b/src/auth/tests/_sync/test_gotrue.py index 54127a32e..9ca5d9c5d 100644 --- a/src/auth/tests/_sync/test_gotrue.py +++ b/src/auth/tests/_sync/test_gotrue.py @@ -793,3 +793,72 @@ def handler(request: Request) -> Response: assert Session.model_validate_json(stored).access_token == "new-access-token" assert client._refresh_token_timer is not None client._refresh_token_timer.cancel() + + +def test_network_error_raises_auth_retryable_error() -> None: + # A transport failure (no HTTP response) must surface as a retryable auth + # error, not as a raw httpx exception. + from httpx import Client, ConnectError, MockTransport, Request, Response + from supabase_auth import SyncGoTrueClient + from supabase_auth.errors import AuthRetryableError + + def handler(request: Request) -> Response: + raise ConnectError("boom", request=request) + + client = SyncGoTrueClient( + url="http://auth.test", + http_client=Client(transport=MockTransport(handler)), + ) + + with pytest.raises(AuthRetryableError) as exc_info: + client.sign_in_with_password( + {"email": "user@example.com", "password": "password"} + ) + assert exc_info.value.status == 0 + + +def test_initialize_from_storage_keeps_session_on_network_error() -> None: + # A network failure while refreshing an expired stored session must keep + # the session and schedule a retry instead of signing the user out. + from httpx import Client, ConnectError, MockTransport, Request, Response + from supabase_auth import SyncGoTrueClient + from supabase_auth.types import Session, User + + user = { + "id": str(uuid4()), + "aud": "authenticated", + "app_metadata": {}, + "user_metadata": {}, + "created_at": "2024-01-01T00:00:00Z", + } + + def handler(request: Request) -> Response: + assert request.url.path == "/token" + raise ConnectError("boom", request=request) + + client = SyncGoTrueClient( + url="http://auth.test", + http_client=Client(transport=MockTransport(handler)), + ) + expired_session = Session( + access_token="expired-access-token", + refresh_token="old-refresh-token", + token_type="bearer", + expires_in=3600, + expires_at=round(time.time()) - 60, + user=User.model_validate(user), + ) + client._storage.set_item(client._storage_key, expired_session.model_dump_json()) + + try: + client.initialize_from_storage() + + stored = client._storage.get_item(client._storage_key) + assert stored is not None + assert ( + Session.model_validate_json(stored).access_token == "expired-access-token" + ) + assert client._refresh_token_timer is not None + finally: + if client._refresh_token_timer: + client._refresh_token_timer.cancel() From 687f216a3cc57fd19cc6e28070cb3ce0dcc1fc4a Mon Sep 17 00:00:00 2001 From: Henry Su Date: Thu, 22 Oct 2026 18:43:37 -0500 Subject: [PATCH 2/2] fix(auth): map httpx transport errors to AuthRetryableError _request only converted HTTPStatusError and RuntimeError, so network failures such as httpx.ConnectError and ReadTimeout escaped as raw httpx exceptions. Callers catching AuthError missed them, and session recovery and auto refresh, which only retry AuthRetryableError, removed the stored session on a transient network failure. Catch httpx.RequestError as well; handle_exception already maps any non-HTTPStatusError to AuthRetryableError with status 0, matching auth-js. The narrowing came from 5c07a73 (fix(auth): mypy auth), which replaced `except Exception` with the current tuple. --- src/auth/src/supabase_auth/_async/gotrue_base_api.py | 4 ++-- src/auth/src/supabase_auth/_sync/gotrue_base_api.py | 4 ++-- src/auth/src/supabase_auth/helpers.py | 6 ++++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/auth/src/supabase_auth/_async/gotrue_base_api.py b/src/auth/src/supabase_auth/_async/gotrue_base_api.py index c442e69d8..26427ff28 100644 --- a/src/auth/src/supabase_auth/_async/gotrue_base_api.py +++ b/src/auth/src/supabase_auth/_async/gotrue_base_api.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Optional -from httpx import AsyncClient, HTTPStatusError, QueryParams, Response +from httpx import AsyncClient, HTTPStatusError, QueryParams, RequestError, Response from pydantic import BaseModel from typing_extensions import Literal, Self @@ -72,5 +72,5 @@ async def _request( response.raise_for_status() return response - except (HTTPStatusError, RuntimeError) as e: + except (HTTPStatusError, RequestError, RuntimeError) as e: raise handle_exception(e) # noqa diff --git a/src/auth/src/supabase_auth/_sync/gotrue_base_api.py b/src/auth/src/supabase_auth/_sync/gotrue_base_api.py index ac48b7100..ee4257a79 100644 --- a/src/auth/src/supabase_auth/_sync/gotrue_base_api.py +++ b/src/auth/src/supabase_auth/_sync/gotrue_base_api.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Optional -from httpx import Client, HTTPStatusError, QueryParams, Response +from httpx import Client, HTTPStatusError, QueryParams, RequestError, Response from pydantic import BaseModel from typing_extensions import Literal, Self @@ -72,5 +72,5 @@ def _request( response.raise_for_status() return response - except (HTTPStatusError, RuntimeError) as e: + except (HTTPStatusError, RequestError, RuntimeError) as e: raise handle_exception(e) # noqa diff --git a/src/auth/src/supabase_auth/helpers.py b/src/auth/src/supabase_auth/helpers.py index ab110a534..a07d4ac5d 100644 --- a/src/auth/src/supabase_auth/helpers.py +++ b/src/auth/src/supabase_auth/helpers.py @@ -12,7 +12,7 @@ from typing import Any, Dict, Optional, Type, TypedDict, TypeVar, Union from urllib.parse import urlparse -from httpx import HTTPStatusError, Response +from httpx import HTTPStatusError, RequestError, Response from pydantic import BaseModel, TypeAdapter, ValidationError from .constants import ( @@ -132,7 +132,9 @@ def filter(prop) -> bool: return next((error[prop] for prop in props if filter(prop)), str(error)) -def handle_exception(error: HTTPStatusError | RuntimeError) -> AuthError: +def handle_exception( + error: HTTPStatusError | RequestError | RuntimeError, +) -> AuthError: if not isinstance(error, HTTPStatusError): return AuthRetryableError(get_error_message(error), 0) try: