Skip to content

feat: add support for anonymous sessions - #156

Open
rmad17 wants to merge 7 commits into
mainfrom
feat/anonymous-sessions
Open

feat: add support for anonymous sessions#156
rmad17 wants to merge 7 commits into
mainfrom
feat/anonymous-sessions

Conversation

@rmad17

@rmad17 rmad17 commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Changes

Added

  • Adds ServerClient.anonymous for pre-login anonymous sessions: create_session,
    get_token, introspect, and logout. Gives a visitor a persistent anon@<uuid>
    identity plus a short-lived access token before they authenticate, with up to 1 KB of metadata attached at
    creation. Framework-agnostic RWA core — mounts no routes and sets no cookies.
    identifier, isolated from the authenticated _a0_session store. AnonymousSession never
    exposes the raw session token to the caller.
  • Adds a token renewal ladder on get_token: fresh cached access token is returned;
    expired access token is re-minted with the session token; an expired or invalid session
    token silently creates a brand-new session, once, surfaced via
    AnonymousSession.is_new. Metadata is lost and sub changes on that silent re-mint — this
    never raises, since an anonymous pre-login session carries no authorization.
  • Injects the anonymous session_token into start_interactive_login() automatically when
    a session is active, sourced only from the SDK's own encrypted store and bound into
    TransactionData under the existing state binding.
  • Adds typed anonymous option/response models (AnonymousSession,
    AnonymousTokenResponse, AnonymousSessionContext, AnonymousSessionIntrospection) and a
    typed error hierarchy under AnonymousApiError, including five config subclasses
    (AnonymousFeatureNotEnabledError, AnonymousClientNotEnabledError,
    AnonymousClientNotSupportedError, AnonymousResourceServerError, AnonymousScopeError)
  • Enforces metadata safeguards client-side before any network call: rejects dangerous keys
    (__proto__, constructor, prototype) and enforces a 1 KB (UTF-8 JSON) size cap.

Testing

As part of manual testing following flows have been completed:

Happy Path

  1. CreatePOST /anonymous/session mints an anon@<uuid> identity; returns session_token (opaque JWE, ANONYMOUS_SESSION_ prefix) + access_token (RS256 JWS, audience-bound).
  2. Get tokenGET /anonymous/session walks the renewal ladder: cached → re-mint via session_token → silent new session.
  3. Login injectionGET /anonymous/login-url confirms session_token is auto-injected into /authorize (session_token_injected: true), no call-site change.
  4. LogoutPOST /anonymous/logout best-effort calls /anonymous/logout, then always clears local store; post-logout GET returns AnonymousTokenError (fail-closed). Issued access tokens self-expire (not
    revoked).

Negative / Fail-Closed

# Scenario Expected result Status
N1 invalid audience anonymous_resource_server_error
N2 ungranted scope anonymous_scope_error
N3 non-string metadata value invalid_metadata (local, pre-network)
N4 dangerous key __proto__ invalid_metadata
N5 metadata >1KB metadata_too_large
N6 no session AnonymousTokenError
  • This change adds unit test coverage
  • This change adds integration test coverage
  • This change has been tested on the latest version of the platform/language or why not

Checklist

try:
async with self._get_http_client() as client:
await client.post(f"{base_url}/anonymous/logout", json=body)
except httpx.HTTPError:
@rmad17
rmad17 marked this pull request as ready for review August 14, 2026 06:11
@rmad17
rmad17 requested a review from a team as a code owner August 14, 2026 06:11

@yogeshchoudhary147 yogeshchoudhary147 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against both the implementation and the SDK requirements doc. Inline comments below cover spec deviations, confirmed bugs, and test gaps. Two earlier findings have been retracted: the _normalize_url str.replace concern (false positive for real-world domain inputs) and the claim that httpx.HTTPError catches 4xx/5xx responses (it does not — those are only raised via raise_for_status(), which logout() never calls).

# Anonymous Session Error Classes
# =============================================================================

class AnonymousApiError(Auth0Error):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spec deviation — error class names diverge from the requirements doc.

The SDK requirements doc specifies:

class AnonymousSessionError(Auth0Error): ...
class AnonymousSessionCreateError(AnonymousSessionError): ...
class AnonymousSessionTokenExpiredError(AnonymousSessionError): ...

This implementation ships AnonymousApiError, AnonymousCreateError, AnonymousTokenError, etc.

If the JS SDKs use the spec names, Python's public error surface will be inconsistent across SDKs. Any shared developer-facing error-handling documentation will show different class names per platform. If the rename is intentional, the spec should be updated to reflect it.

super().__init__(code, message, cause)


class AnonymousLogoutError(AnonymousApiError):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AnonymousLogoutError is dead code — it can never be raised.

_map_anonymous_error() maps operation == "logout" to this class, but logout() never calls _map_anonymous_error(). The except httpx.HTTPError in logout() catches only transport-level failures; non-2xx HTTP responses are silently ignored because the response object is never inspected at all. The only exception logout() can raise to a caller is ConfigurationError from _require_store().

Either:

  • logout() should check the response status, call _map_anonymous_error(), and re-raise on non-2xx (while still clearing local state), or
  • AnonymousLogoutError and the logout branch in _map_anonymous_error() should be removed.


def __init__(
self,
domain,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

domain parameter is untyped.

Every sibling client (MfaClient, MyAccountClient) types this as Union[str, Callable]. This is the only one that leaves it bare. Inconsistency will surface under type checkers and makes the parameter contract invisible to IDE users.

raise AnonymousCreateError(
f"metadata key '{key}' is not allowed", code="invalid_metadata"
)
if not isinstance(value, str):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metadata value restriction is narrower than the spec and should be confirmed against the actual API.

The requirements doc defines metadata as Record<string, unknown> (any JSON value). This implementation rejects non-string values client-side. If the Auth0 API actually accepts non-string values, this check incorrectly blocks valid callers. If the API only accepts strings in practice, the spec is wrong and needs updating.

Consequently, AnonymousSessionContext.metadata is typed Optional[dict[str, Any]] (any value), while creation only permits dict[str, str]. The type annotation does not express the constraint, so the model's round-trip deserialization of a stored context containing an integer value would silently succeed at the Pydantic level.


now = int(time.time())
new_context = AnonymousSessionContext(
session_token=token_response.session_token or context.session_token,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or idiom silently swallows empty strings for Optional[str] fields.

session_token=token_response.session_token or context.session_token,
sub=token_response.sub or context.sub,
session_id=token_response.session_id or context.session_id,

"" or context.X falls back to the stale context value, so if the API ever returns an empty string for any of these, the old value is silently persisted. Prefer explicit None-checks:

session_token=token_response.session_token if token_response.session_token is not None else context.session_token,

This is consistent with how session_expires_in is handled two lines below.

"Failed to parse anonymous introspection response"
) from e

async def logout(self, store_options: Optional[dict[str, Any]] = None) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logout() never raises AnonymousLogoutError — see the comment on error/__init__.py:392.

Additionally, there is no test covering the branch at line ~693 where _decrypt_context raises _AnonymousSessionExpired (sets context = None and skips the server call). That path clears local state correctly but is untested.

access_token: str
token_type: str = "Bearer"
expires_in: int
session_token: Optional[str] = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session_token is Optional here but effectively required on the create path.

_create_session_at() validates the response with this model and then immediately does:

if not token_response.session_token:
    raise AnonymousCreateError("Anonymous token response missing required fields")

The Optional typing exists to accommodate the re-mint path (where the server may not return a new session token). Consider a separate narrow model for the create response, or at minimum a Pydantic validator that enforces presence, so the constraint is expressed in the type rather than in a manual post-validation check.

domain=origin_domain,
redirect_uri=auth_params.get("redirect_uri"),
organization=resolved_org,
session_token=anonymous_session_token,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: should complete_interactive_login() promote session_token from TransactionData into StateStore?

The auth0-server-js section of the requirements doc says:

completeInteractiveLogin() — on callback, read the session token back from TransactionStore and promote it into StateStore as part of the authenticated session.

The Python section does not mention this step. The session token is saved into TransactionData here but nothing reads it back during the callback. If auth0-fastapi (GA) will need to reconstruct the anonymous session after login, this plumbing would need to exist in auth0-server-python first. Please confirm the omission is intentional for EA scope.

# =============================================================================


class _OneSlotStore:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_OneSlotStore is duplicated — identical class exists as OneSlotStore in test_anonymous_client.py:41.

The explanatory comment about why AsyncMock is insufficient (identifier-as-salt, not location key) exists in both files. Moving it to conftest.py as a shared fixture would eliminate the duplication and keep the explanation in one place.

SECRET = "test-secret-long-enough-for-encryption"


class OneSlotStore:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two test coverage gaps in introspect():

  1. No test for what happens when the stored context is corrupted (invalid JWE) — introspect() should raise AnonymousIntrospectError, but this branch is untested. Compare to the equivalent test in TestGetToken.test_corrupted_stored_token_triggers_silent_new_session.
  2. The TestLogout class has no test for the context = None branch (corrupted/missing context skips the server call but still clears local state).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants