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
16 changes: 10 additions & 6 deletions sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,16 @@ features:
note: "flow_type of AuthClientOptions, passed as the auth argument of the supabase client, and of the auth client constructor."
symbols:
- AuthClientOptions
client.authentication_integration.session_url_detection: not_implemented
client.authentication_integration.session_url_detection:
status: implemented
note: "initialize_from_url(url) reads the query string and the fragment. It saves the session of an implicit grant redirect, exchanges the code of a PKCE redirect for the flow named by sb_flow_id, and raises AuthImplicitGrantRedirectError for error, error_code or error_description. initialize(url=...) does the same for a URL with implicit grant tokens, an error_description or the code of a pending PKCE flow, and recovers the stored session otherwise."
symbols:
- AsyncSupabaseAuthClient.initialize_from_url
- SyncSupabaseAuthClient.initialize_from_url
supporting_symbols:
- AsyncSupabaseAuthClient.initialize
- SyncSupabaseAuthClient.initialize
- AuthImplicitGrantRedirectError

client.session_management.custom_storage:
status: implemented
Expand Down Expand Up @@ -1579,12 +1588,8 @@ supporting_symbols:
- AsyncSupabaseAuthClient
- SyncSupabaseAuthClient
- SupabaseAuthHttpClient
- AsyncSupabaseAuthClient.initialize
- AsyncSupabaseAuthClient.initialize_from_storage
- AsyncSupabaseAuthClient.initialize_from_url
- SyncSupabaseAuthClient.initialize
- SyncSupabaseAuthClient.initialize_from_storage
- SyncSupabaseAuthClient.initialize_from_url
- AsyncSupabaseAuthMFAClient
- SyncSupabaseAuthMFAClient
- SupabaseAuthMFAHttpClient
Expand All @@ -1598,7 +1603,6 @@ supporting_symbols:
- WithCaptchaToken
- AuthError
- AuthApiError
- AuthImplicitGrantRedirectError
- AuthInvalidCredentialsError
- AuthInvalidJwtError
- AuthPKCECodeVerifierMissingError
Expand Down
162 changes: 118 additions & 44 deletions src/auth/src/supabase_auth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from yarl import URL

from ._pkce import (
_FLOW_ID_PARAMETER,
_append_flow_id,
_is_valid_flow_id,
_parse_code_verifier,
Expand Down Expand Up @@ -60,11 +61,12 @@
_bind_algorithm,
_handle_error_response,
_header_names_algorithm,
_is_implicit_grant_flow,
_is_implicit_grant_callback,
_is_locally_verifiable,
_jwk_by_kid,
_parse_url_params,
_parse_verify_otp_response,
_raise_for_redirect_error,
_redirect_to_as_query,
_validate_not_before,
_verify_otp_event,
Expand Down Expand Up @@ -533,24 +535,8 @@ def _reset_password_for_email(
@handle_http_io
def _get_session_from_url(
self,
url: str,
params: dict[str, str],
) -> HttpMethod[tuple[Session, str | None]]:
if not _is_implicit_grant_flow(url):
raise AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.")
params = _parse_url_params(url)
error_description = params.get("error_description")
if error_description:
error_code = params.get("error_code")
error = params.get("error")
if not error_code:
raise AuthImplicitGrantRedirectError("No error_code detected.")
if not error:
raise AuthImplicitGrantRedirectError("No error detected.")
raise AuthImplicitGrantRedirectError(
error_description,
code=error_code,
error=error,
)
provider_token = params.get("provider_token")
provider_refresh_token = params.get("provider_refresh_token")
access_token = params.get("access_token")
Expand Down Expand Up @@ -748,29 +734,73 @@ async def __aexit__(
# Initializations

async def initialize(self, *, url: str | None = None) -> None:
if url and _is_implicit_grant_flow(url):
await self.initialize_from_url(url)
"""
Signs in from `url`, as `initialize_from_url` does, when it carries
implicit grant tokens, an `error_description`, or a PKCE `code` whose
flow is pending. Recovers the stored session otherwise, and also
when the code exchange fails, before raising its error.
"""
parameters = _parse_url_params(url) if url else {}
if _is_implicit_grant_callback(parameters):
await self._initialize_from_parameters(parameters)
elif await self._is_pkce_callback(parameters):
try:
await self._initialize_from_parameters(parameters)
except Exception:
await self.initialize_from_storage()
Comment thread
spydon marked this conversation as resolved.
Resolved
raise
else:
await self.initialize_from_storage()

async def initialize_from_storage(self) -> None:
return await self.session_manager.recover_and_refresh()

async def initialize_from_url(self, url: str) -> None:
"""
Completes the sign-in that redirected to `url`, such as an OAuth,
magic link or password recovery callback. Parameters are read from
both the query string and the fragment.

- `error`, `error_code` or `error_description` raise
`AuthImplicitGrantRedirectError`.
- `access_token` and the other implicit grant tokens are saved as the
session.
- With the `pkce` flow type, `code` is exchanged for a session as
`exchange_code_for_session` does, for the flow named by the
`sb_flow_id` parameter when it is present.

A failed sign-in keeps the stored session. A URL with none of these
parameters is ignored.
"""
await self._initialize_from_parameters(_parse_url_params(url))

async def _is_pkce_callback(self, parameters: dict[str, str]) -> bool:
if self.flow_type != "pkce" or "code" not in parameters:
Comment thread
spydon marked this conversation as resolved.
Resolved
return False
try:
if _is_implicit_grant_flow(url):
session, redirect_type = await self._get_session_from_url(url)
await self.session_manager.save_session(session)
await self._pending_code_verifier(parameters.get(_FLOW_ID_PARAMETER))
except AuthPKCECodeVerifierMissingError:
return False
return True

async def _initialize_from_parameters(self, parameters: dict[str, str]) -> None:
_raise_for_redirect_error(parameters)
if "access_token" in parameters:
session, redirect_type = await self._get_session_from_url(parameters)
await self.session_manager.save_session(session)
Comment thread
spydon marked this conversation as resolved.
Resolved
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.SIGNED_IN, session)
)
if redirect_type == "recovery":
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.SIGNED_IN, session)
AuthStateChange(AuthChangeEvent.PASSWORD_RECOVERY, session)
)
if redirect_type == "recovery":
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.PASSWORD_RECOVERY, session)
)
except Exception as e:
await self.session_manager.remove_session()
raise e
return
code = parameters.get("code")
if code and self.flow_type == "pkce":
await self.exchange_code_for_session(
code, flow_id=parameters.get(_FLOW_ID_PARAMETER)
)

async def _save_session_and_notify(
self,
Expand Down Expand Up @@ -1366,29 +1396,73 @@ def __exit__(
# Initializations

def initialize(self, *, url: str | None = None) -> None:
if url and _is_implicit_grant_flow(url):
self.initialize_from_url(url)
"""
Signs in from `url`, as `initialize_from_url` does, when it carries
implicit grant tokens, an `error_description`, or a PKCE `code` whose
flow is pending. Recovers the stored session otherwise, and also
when the code exchange fails, before raising its error.
"""
parameters = _parse_url_params(url) if url else {}
if _is_implicit_grant_callback(parameters):
self._initialize_from_parameters(parameters)
elif self._is_pkce_callback(parameters):
try:
self._initialize_from_parameters(parameters)
except Exception:
self.initialize_from_storage()
raise
else:
self.initialize_from_storage()

def initialize_from_storage(self) -> None:
return self.session_manager.recover_and_refresh()

def initialize_from_url(self, url: str) -> None:
"""
Completes the sign-in that redirected to `url`, such as an OAuth,
magic link or password recovery callback. Parameters are read from
both the query string and the fragment.

- `error`, `error_code` or `error_description` raise
`AuthImplicitGrantRedirectError`.
- `access_token` and the other implicit grant tokens are saved as the
session.
- With the `pkce` flow type, `code` is exchanged for a session as
`exchange_code_for_session` does, for the flow named by the
`sb_flow_id` parameter when it is present.

A failed sign-in keeps the stored session. A URL with none of these
parameters is ignored.
"""
self._initialize_from_parameters(_parse_url_params(url))

def _is_pkce_callback(self, parameters: dict[str, str]) -> bool:
if self.flow_type != "pkce" or "code" not in parameters:
return False
try:
if _is_implicit_grant_flow(url):
session, redirect_type = self._get_session_from_url(url)
self.session_manager.save_session(session)
self._pending_code_verifier(parameters.get(_FLOW_ID_PARAMETER))
except AuthPKCECodeVerifierMissingError:
return False
return True

def _initialize_from_parameters(self, parameters: dict[str, str]) -> None:
_raise_for_redirect_error(parameters)
if "access_token" in parameters:
session, redirect_type = self._get_session_from_url(parameters)
self.session_manager.save_session(session)
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.SIGNED_IN, session)
)
if redirect_type == "recovery":
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.SIGNED_IN, session)
AuthStateChange(AuthChangeEvent.PASSWORD_RECOVERY, session)
)
if redirect_type == "recovery":
self.session_manager.notify_all_subscribers(
AuthStateChange(AuthChangeEvent.PASSWORD_RECOVERY, session)
)
except Exception as e:
self.session_manager.remove_session()
raise e
return
code = parameters.get("code")
if code and self.flow_type == "pkce":
self.exchange_code_for_session(
code, flow_id=parameters.get(_FLOW_ID_PARAMETER)
)

def _save_session_and_notify(
self,
Expand Down
15 changes: 12 additions & 3 deletions src/auth/src/supabase_auth/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from .errors import (
AuthApiError,
AuthError,
AuthImplicitGrantRedirectError,
AuthInvalidJwtError,
AuthRetryableError,
AuthUnknownError,
Expand Down Expand Up @@ -393,9 +394,17 @@ def _parse_url_params(url: str) -> dict[str, str]:
return params


def _is_implicit_grant_flow(url: str) -> bool:
params = _parse_url_params(url)
return "access_token" in params or "error_description" in params
def _is_implicit_grant_callback(parameters: dict[str, str]) -> bool:
return "access_token" in parameters or "error_description" in parameters


def _raise_for_redirect_error(parameters: dict[str, str]) -> None:
error = parameters.get("error")
code = parameters.get("error_code")
description = parameters.get("error_description")
message = description or error or code
if message:
raise AuthImplicitGrantRedirectError(message, error=error, code=code)


_JWKS_REFETCH_MIN_WAIT = 1.0
Expand Down
Loading
Loading