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: 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()