Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/auth/src/supabase_auth/_async/gotrue_base_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
4 changes: 2 additions & 2 deletions src/auth/src/supabase_auth/_sync/gotrue_base_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
6 changes: 4 additions & 2 deletions src/auth/src/supabase_auth/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
71 changes: 71 additions & 0 deletions src/auth/tests/_async/test_gotrue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
69 changes: 69 additions & 0 deletions src/auth/tests/_sync/test_gotrue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading