diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5388da7c..14766bbe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,8 @@ concurrency: jobs: unittest: - runs-on: ubuntu-latest + # Pinned: ubuntu-latest is now 26.04, which has no Python 3.9 build + runs-on: ubuntu-24.04 strategy: matrix: diff --git a/CHANGELOG.md b/CHANGELOG.md index 43e6aae4..6dabb992 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Step-up authentication (RFC 9470)**: `LoginOptions.ACR_VALUES` and `LoginOptions.MAX_AGE` on + `login()` and `register()`; `step_up()`, `get_authentication_context()`, + `has_authentication_context()` and `is_step_up_supported()` on `OAuth`, `AsyncOAuth` and + `SmartOAuth`; `UnmetAuthenticationRequirementsError` and `LoginRequiredError`, raised by + `handle_redirect()` and by the Flask and FastAPI `/callback` routes after `state` is validated. + Opt-in: existing login URLs are unchanged. See "Step-up authentication" in the README. + +### Changed +- **Auth**: The tokens from an authorization callback now replace the session's access, ID and + refresh tokens. Previously a refresh or ID token from an earlier sign-in was kept when the new + response had none. +- **Auth**: The authorization callback now checks the ID token before storing the tokens: its + audience must include the client ID, its issuer must be the configured Kinde host, it must + not be expired, and its nonce must be the one sent with the login. Otherwise + `handle_redirect()` raises `KindeLoginException`. The nonce is consumed by the callback, so + a login can't be completed twice. +- **Auth**: `acr_values` and `max_age` inside `auth_params` are no longer sent when unset + (`None` or empty). An invalid `max_age`, or an `acr_values` that is not a string or a list + of strings, raises `ValueError`. +- **Auth**: Top-level `acr_values` and `max_age` keys in the login options were silently + ignored and are now sent, after validation. `max_age` must be an `int`, so for example + `login({"max_age": "300"})` now raises `ValueError`. + ### Fixed +- **Auth**: `TokenManager.get_access_token()` no longer deadlocks when it refreshes an expired + access token. +- **Auth**: Flask and FastAPI sessions use the same storage key in every worker process. Each + process generated its own, so a session stored by one worker could not be read by another, + and no session survived a restart. +- **Auth**: Tokens are now saved in the session with a revision, and each worker process + follows the newest one. A worker that had cached a session picks up tokens stored by + another worker (a step-up, or a later sign-in), refreshed tokens are saved back to the + session, and an older copy of the session written back by an overlapping request is + ignored and repaired. +- **Flask**: The `/callback` route keeps the post-login redirect location when it rejects a + callback, instead of dropping it before the callback is validated. - **CI**: Hardened `renovate.json` so Renovate can no longer re-propose bumping the Python `<3.12` `django` pin in `requirements.txt` to Django 6.x (Django 6.0+ requires Python 3.12+). Django is a test-only dependency for this SDK (no runtime usage), and the diff --git a/README.md b/README.md index cc680c50..1cc6581c 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,111 @@ if __name__ == "__main__": main() ``` +## Step-up authentication + +Ask Kinde for a stronger or more recent authentication before a sensitive action, for example "MFA in the last 5 minutes before changing payout details". Kinde collects only what is missing (the second factor, or a passkey), and the user keeps their session. This is [RFC 9470](https://www.rfc-editor.org/rfc/rfc9470) on the normal Kinde login flow. There is nothing to register in Kinde, and nothing changes for existing logins. + +| What | How | +|---|---| +| Ask for a context at login | `LoginOptions.ACR_VALUES` (`"mfa"` or `"phr"`) and `LoginOptions.MAX_AGE` (seconds) on `login()` and `register()` | +| Start a step-up | `await oauth.step_up(acr="mfa", max_age=300)` returns the URL to redirect to | +| Read how the user signed in | `oauth.get_authentication_context()` returns `{"acr": ..., "amr": [...], "auth_time": ...}` | +| Check a requirement | `oauth.has_authentication_context(acr="mfa", max_age=300)` | +| Check the environment | `oauth.is_step_up_supported()` | +| Callback errors | `UnmetAuthenticationRequirementsError`, `LoginRequiredError` | + +`mfa` means a second factor. `phr` means phishing-resistant (a passkey with user verification) and also meets an `mfa` requirement. Kinde leaves `acr` out for a single-factor sign-in, so `acr` is `None` then. + +### Require MFA in the last 5 minutes + +#### FastAPI + +```python +from fastapi.responses import PlainTextResponse, RedirectResponse +from kinde_sdk.core.exceptions import UnmetAuthenticationRequirementsError + +@app.get("/payouts") +async def payouts(): + if not kinde_oauth.is_authenticated(): + return RedirectResponse("/login") + if not kinde_oauth.has_authentication_context(acr="mfa", max_age=300): + # The built-in /callback route brings the user back to this page + return RedirectResponse(await kinde_oauth.step_up(acr="mfa", max_age=300)) + return {"message": "Payout details"} + +@app.exception_handler(UnmetAuthenticationRequirementsError) +async def step_up_not_possible(request, error): + # The user can't meet the requirement. This is final: don't send them back to Kinde. + return PlainTextResponse("Add an authenticator app to your account to continue.", status_code=403) +``` + +#### Flask + +```python +import asyncio +from flask import redirect +from kinde_sdk.core.exceptions import UnmetAuthenticationRequirementsError + +@app.route("/payouts") +def payouts(): + if not kinde_oauth.is_authenticated(): + return redirect("/login") + if not kinde_oauth.has_authentication_context(acr="mfa", max_age=300): + # The built-in /callback route brings the user back to this page + return redirect(asyncio.run(kinde_oauth.step_up(acr="mfa", max_age=300))) + return {"message": "Payout details"} + +@app.errorhandler(UnmetAuthenticationRequirementsError) +def step_up_not_possible(error): + # The user can't meet the requirement. This is final: don't send them back to Kinde. + return "Add an authenticator app to your account to continue.", 403 +``` + +`step_up()` is a coroutine, like `login()`. In an `async def` Flask view (which needs `flask[async]`), `await` it instead of using `asyncio.run()`. + +### When the user can't step up + +If the user has no enrolled MFA factor or no passkey, Kinde returns `error=unmet_authentication_requirements` to your callback instead of tokens. The SDK validates `state` and raises `UnmetAuthenticationRequirementsError`. The built-in `/callback` routes let it reach your app, so handle it with `@app.exception_handler(...)` (FastAPI) or `@app.errorhandler(...)` (Flask), as above. Without a handler of your own, the user sees a plain-text 403 page. + +- It is a final answer. Retrying gives the same error, and sending the user to login would sign them in without the step-up. Tell them why instead, for example "add a passkey to continue". +- The error has `error_description`, `state`, and the `acr_values` and `max_age` that were asked for, so you can say what is missing. +- A user who was signed in stays signed in, with the tokens they already had. +- `LoginRequiredError` is the same kind of error for `login_required`, which Kinde returns when a `prompt=none` request needs a screen. Both extend `KindeCallbackError`. + +If you handle the callback yourself, pass the error through and catch it: + +```python +try: + await oauth.handle_redirect(code, user_id, state, error=error, error_description=error_description) +except UnmetAuthenticationRequirementsError as e: + show_error(e.error_description) +``` + +### Good to know + +- **After a step-up, the callback replaces the access, ID and refresh tokens.** Refreshing never upgrades a session: a refreshed token keeps the `acr`, `amr` and `auth_time` it had. When `has_authentication_context()` is false, the only way forward is `step_up()`. +- **`step_up()` is interactive.** It raises `ValueError` for `prompt=none` (also inside `auth_params`), for an invalid `acr` or `max_age`, and when neither is given. `max_age` must be a non-negative `int`. `0` is valid and forces a fresh verification. +- **Don't check `max_age=0`.** `has_authentication_context(max_age=0)` is only true in the same second as the sign-in, so the user would be sent back to Kinde every time. Use a short window such as 60 seconds. +- **Call `step_up()` when you redirect, not to render a link.** Each call stores a new `state`, replacing any login in progress. +- **Scope and refresh tokens.** Like `login()`, `step_up()` asks for `openid profile email` unless `login_options` sets a scope, so pass the scope your login uses. The callback replaces every stored token and Kinde only returns a refresh token for the `offline` scope, so `step_up()` adds `offline` itself when the session has a refresh token. Otherwise the user would be signed out when the access token expires. +- **Where the user lands.** With FastAPI and Flask, the user comes back to the page that called `step_up()` when that request was a GET. For any other method nothing is remembered, so the user lands on `/`: pass `post_login_redirect_url="/somewhere"` to choose the page, which you should do for a form POST (the POST is not replayed). Without a framework integration, your own callback decides. +- **Environments without step-up.** If the discovery document has no `acr_values_supported`, Kinde ignores `acr_values` and `max_age`. `step_up()` then raises `KindeConfigurationException` and sends nothing, instead of pretending it worked. `get_authentication_context()` reports `auth_time` as `None` there, because the claim may be the token's issue time, so `has_authentication_context(max_age=...)` is always false. Check `is_step_up_supported()` first and deny the action, or force a fresh sign-in with `login({"prompt": "login"})`, which only proves the user signed in again. +- **If discovery can't be fetched.** While the discovery document is unavailable, `is_step_up_supported()` returns `False` and `step_up()` raises `KindeRetrieveException`. That one is temporary: `step_up()` retries the fetch, at most once every 5 seconds. The retry never blocks an event loop: `step_up()` awaits it on a worker thread, and a check made from async code starts it in the background without waiting. Until it has finished, `is_step_up_supported()` answers `False` and `auth_time` is not trusted, so `has_authentication_context(max_age=...)` is false. A check on `acr` alone is not affected. +- **More than one worker process.** Tokens are saved in the session with a revision, and every worker follows the newest one: a step-up handled by one worker is picked up by the others, and refreshed tokens are saved. This needs a session store that every worker shares (for Flask, the same `SECRET_KEY` and session backend). +- **Overlapping requests.** Session backends save a request's whole session when it ends, so a request that began before a step-up can write the old tokens back. A worker that has the newer tokens ignores that and repairs the session on its next request. The same goes for a token refresh that was started before a step-up, or before a later sign-in, and finished after it: its tokens rank below the newer authorization, so a worker that has the newer one keeps it and repairs the session in the same way. A worker that has never seen the session (another process, or after a restart) trusts what it reads, so in that window it can still see the old tokens and ask for the step-up again. +- **`auth_time` comes from the ID token.** `amr` is informational. `has_authentication_context()` decides on `acr` and `auth_time` only. An `auth_time` more than a minute in the future is invalid and meets no `max_age`. The ID token is only trusted when its `sub` matches the access token's. +- **The callback checks the ID token.** Before the tokens are stored, the ID token's audience, issuer, expiry and nonce are checked against this client and this login. A token that fails raises `KindeLoginException` and nothing is stored. +- **What `mfa` asserts.** `acr: "mfa"` means two factors were accepted under your MFA policy. It does not assert that they are independent: a social sign-in followed by a one-time code to the same mailbox proves one channel twice. `phr` is the stronger value, because a phishing site can't use a passkey. For payments and regulated workloads, assess factor independence, enrolment and recovery against your own configuration rather than relying on `acr` alone. +- **APIs.** `kinde_sdk.has_authentication_context(claims, acr="mfa", max_age=300)` is the same check as a pure function, for the claims of an access token you have verified yourself. A `require_authentication_context` dependency/decorator that answers with the RFC 9470 `401` challenge is planned as a follow-up. + +### Differences from the cross-SDK recommendations + +- **No `returnTo` in `state` for standalone use.** Returning the user is done through the FastAPI and Flask post-login redirect. Without a framework integration the SDK doesn't own the callback, so your callback chooses the destination. +- **Only a GET returns the user automatically.** `step_up()` from a POST (or any other method) doesn't send the user back to the page that made it. Pass `post_login_redirect_url=` for those. +- **No `prompt=login` fallback.** On an environment without step-up, `step_up(max_age=...)` raises like `step_up(acr=...)` does, and the app decides what to do. A fallback sign-in could never satisfy `has_authentication_context(max_age=...)` there, so a guarded page would redirect in a loop. +- **`auth_params` is a raw passthrough.** `LoginOptions.ACR_VALUES` accepts only `mfa` and `phr`, and `LoginOptions.MAX_AGE` only an `int`. Inside `auth_params`, `acr_values` is sent as given and `max_age` may also be a string of digits, as before. In both places an unset value is never sent and an invalid `max_age` raises `ValueError`. +- **No clock tolerance by default.** `oauth.has_authentication_context()` compares `auth_time` with the server clock exactly. The pure function takes `leeway=` if you need one. + ## Advanced Usage: Direct Storage Management This section covers direct interaction with the `StorageManager` for custom storage solutions. diff --git a/kinde_fastapi/framework/fastapi_framework.py b/kinde_fastapi/framework/fastapi_framework.py index 04fb09d0..3744d738 100644 --- a/kinde_fastapi/framework/fastapi_framework.py +++ b/kinde_fastapi/framework/fastapi_framework.py @@ -1,7 +1,12 @@ from typing import Optional from fastapi import FastAPI, Request -from fastapi.responses import RedirectResponse, HTMLResponse +from fastapi.responses import RedirectResponse, HTMLResponse, PlainTextResponse from kinde_sdk.core.framework.framework_interface import FrameworkInterface +from kinde_sdk.core.exceptions import ( + CALLBACK_ERRORS, + KindeCallbackError, + UnmetAuthenticationRequirementsError, +) from kinde_sdk.auth.oauth import OAuth from ..middleware.framework_middleware import FrameworkMiddleware import os @@ -62,6 +67,9 @@ def start(self) -> None: # Register Kinde routes self._register_kinde_routes() + + # Default page for errors the callback hands to the app + self._register_error_handlers() self._initialized = True @@ -113,6 +121,55 @@ def set_oauth(self, oauth: OAuth) -> None: """ self._oauth = oauth + def set_post_login_redirect_url(self, url: Optional[str] = None) -> None: + """ + Remember where the callback route sends the user after the next + sign-in or step-up. + + Args: + url: The URL to return to. If None, the current page is used when + the current request is a GET. For any other method nothing is + remembered (a POST is never replayed), and a location left by + an earlier, abandoned request is cleared. + """ + request = self.get_request() + if request is None: + return + if url is None: + if request.method != "GET": + request.session.pop('post_login_redirect_url', None) + return + url = str(request.url) + request.session['post_login_redirect_url'] = {'url': url} + + def _register_error_handlers(self) -> None: + """ + Register the default page for callback errors. + + The callback route raises UnmetAuthenticationRequirementsError and + LoginRequiredError. Handle them with ``@app.exception_handler(...)``. + This default only applies when the application has no handler of its own. + """ + if KindeCallbackError not in self.app.exception_handlers: + self.app.add_exception_handler(KindeCallbackError, self._default_callback_error_page) + + @staticmethod + async def _default_callback_error_page(request: Request, error: KindeCallbackError): + """Explain a callback error in plain words. The user stays signed in.""" + if isinstance(error, UnmetAuthenticationRequirementsError): + message = ( + "We couldn't complete the extra verification needed for this action. " + "Your account may not have a second sign-in method (such as an " + "authenticator app) or a passkey set up yet." + ) + status_code = 403 + else: + message = "You need to sign in again to continue." + status_code = 401 + if error.error_description: + message = f"{message}\n\nDetails: {error.error_description}" + return PlainTextResponse(message, status_code=status_code) + def _register_kinde_routes(self) -> None: """ Register all Kinde-specific routes with the FastAPI application. @@ -184,6 +241,29 @@ async def callback(request: Request, code: Optional[str] = None, state: Optional except Exception as ex: return HTMLResponse(f"Error parsing reauth state: {str(ex)}", status_code=400) + # A step-up the user cannot meet (or login_required after prompt=none) + # is a final answer. Hand it to the app: the core validates the state + # and raises the error. Never redirect to login or retry from here. + if error in CALLBACK_ERRORS: + assert self._oauth is not None + try: + await self._oauth.handle_redirect( + code, + request.session.get('user_id'), + state, + error=error, + error_description=request.query_params.get('error_description'), + ) + except KindeCallbackError: + # The state was valid, so this answers the pending request + # and its return location is finished with. A callback + # with a wrong state leaves it for the genuine one. + request.session.pop('post_login_redirect_url', None) + raise + except Exception as e: + return PlainTextResponse(f"Authentication failed: {str(e)}", status_code=400) + return PlainTextResponse("Authentication failed", status_code=400) + user_id = request.session.get('user_id') or str(uuid.uuid4()) try: diff --git a/kinde_flask/framework/flask_framework.py b/kinde_flask/framework/flask_framework.py index 2d69a15a..2a74f86f 100644 --- a/kinde_flask/framework/flask_framework.py +++ b/kinde_flask/framework/flask_framework.py @@ -1,7 +1,12 @@ from typing import Optional, TYPE_CHECKING -from flask import Flask, request, redirect, session +from flask import Flask, Response, request, redirect, session, has_request_context from flask_session import Session from kinde_sdk.core.framework.framework_interface import FrameworkInterface +from kinde_sdk.core.exceptions import ( + CALLBACK_ERRORS, + KindeCallbackError, + UnmetAuthenticationRequirementsError, +) from kinde_sdk.auth.oauth import OAuth from ..middleware.framework_middleware import FrameworkMiddleware import os @@ -94,6 +99,9 @@ def start(self) -> None: # Register Kinde routes self._register_kinde_routes() + + # Default page for errors the callback hands to the app + self._register_error_handlers() self._initialized = True @@ -145,6 +153,55 @@ def set_oauth(self, oauth: OAuth) -> None: """ self._oauth = oauth + def set_post_login_redirect_url(self, url: Optional[str] = None) -> None: + """ + Remember where the callback route sends the user after the next + sign-in or step-up. + + Args: + url: The URL to return to. If None, the current page is used when + the current request is a GET. For any other method nothing is + remembered (a POST is never replayed), and a location left by + an earlier, abandoned request is cleared. + """ + if not has_request_context(): + return + if url is None: + if request.method != "GET": + session.pop('post_login_redirect_url', None) + return + url = request.url + session['post_login_redirect_url'] = {'url': url} + + def _register_error_handlers(self) -> None: + """ + Register the default page for callback errors. + + The callback route raises UnmetAuthenticationRequirementsError and + LoginRequiredError. Handle them with ``@app.errorhandler(...)``. This + default only applies when the application has no handler of its own. + """ + handlers = self.app.error_handler_spec[None][None] + if KindeCallbackError not in handlers: + self.app.register_error_handler(KindeCallbackError, self._default_callback_error_page) + + @staticmethod + def _default_callback_error_page(error: KindeCallbackError): + """Explain a callback error in plain words. The user stays signed in.""" + if isinstance(error, UnmetAuthenticationRequirementsError): + message = ( + "We couldn't complete the extra verification needed for this action. " + "Your account may not have a second sign-in method (such as an " + "authenticator app) or a passkey set up yet." + ) + status = 403 + else: + message = "You need to sign in again to continue." + status = 401 + if error.error_description: + message = f"{message}\n\nDetails: {error.error_description}" + return Response(message, status=status, mimetype="text/plain") + @staticmethod def _run_async(coro): """ @@ -231,7 +288,31 @@ def callback(): except Exception as ex: return f"Error parsing reauth state: {str(ex)}", 400 - post_login_redirect = session.pop('post_login_redirect_url', None) + # A step-up the user cannot meet (or login_required after prompt=none) + # is a final answer. Hand it to the app: the core validates the state + # and raises the error. Never redirect to login or retry from here. + if error in CALLBACK_ERRORS: + try: + self._run_async(self._oauth.handle_redirect( + request.args.get('code'), + session.get('user_id'), + request.args.get('state'), + error=error, + error_description=request.args.get('error_description'), + )) + except KindeCallbackError: + # The state was valid, so this answers the pending request + # and its return location is finished with. A callback + # with a wrong state leaves it for the genuine one. + session.pop('post_login_redirect_url', None) + raise + except Exception as e: + return f"Authentication failed: {str(e)}", 400 + return "Authentication failed", 400 + + # Read the return location, and drop it only once the callback has + # been accepted: a callback with a wrong state must not discard it + post_login_redirect = session.get('post_login_redirect_url') if post_login_redirect: post_login_redirect = post_login_redirect.get('url', '/') else: @@ -254,6 +335,8 @@ def callback(): except Exception as e: return f"Authentication failed: {str(e)}", 400 + session.pop('post_login_redirect_url', None) + if not post_login_redirect.startswith('http'): # Use url_root to get just the scheme and host without the current path post_login_redirect = str(request.url_root).rstrip('/') + post_login_redirect diff --git a/kinde_sdk/__init__.py b/kinde_sdk/__init__.py index 1283d617..1d6c8a5b 100644 --- a/kinde_sdk/__init__.py +++ b/kinde_sdk/__init__.py @@ -19,6 +19,7 @@ from kinde_sdk.auth.user_session import UserSession from kinde_sdk.auth import permissions, claims, portals, feature_flags from kinde_sdk.auth.async_claims import async_claims +from kinde_sdk.auth.step_up import AcrValues, has_authentication_context from kinde_sdk.core.storage.storage_factory import StorageFactory from kinde_sdk.core.framework.framework_factory import FrameworkFactory from kinde_sdk.core.framework.framework_interface import FrameworkInterface @@ -37,6 +38,8 @@ "permissions", "claims", "async_claims", + "AcrValues", + "has_authentication_context", "portals", "feature_flags", "StorageFactory", diff --git a/kinde_sdk/auth/async_oauth.py b/kinde_sdk/auth/async_oauth.py index 539ba3fc..9a716144 100644 --- a/kinde_sdk/auth/async_oauth.py +++ b/kinde_sdk/auth/async_oauth.py @@ -4,7 +4,7 @@ """ import asyncio -from typing import Dict, Any, Optional +from typing import Dict, Any, List, Optional, Union from .base_oauth import BaseOAuth from .oauth import OAuth from kinde_sdk.core.helpers import get_user_details @@ -89,9 +89,51 @@ async def logout(self, user_id: Optional[str] = None, logout_options: Dict[str, """Generate logout URL asynchronously.""" return await self._sync_oauth.logout(user_id, logout_options) - async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = None) -> Dict[str, Any]: + async def handle_redirect( + self, + code: Optional[str], + user_id: Optional[str], + state: Optional[str] = None, + error: Optional[str] = None, + error_description: Optional[str] = None, + ) -> Dict[str, Any]: """Handle OAuth redirect asynchronously.""" + if error: + return await self._sync_oauth.handle_redirect( + code, user_id, state, error=error, error_description=error_description + ) return await self._sync_oauth.handle_redirect(code, user_id, state) + + async def step_up( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + login_options: Optional[Dict[str, Any]] = None, + post_login_redirect_url: Optional[str] = None, + ) -> str: + """Generate the URL for a step-up authentication request asynchronously.""" + return await self._sync_oauth.step_up( + acr=acr, + max_age=max_age, + login_options=login_options, + post_login_redirect_url=post_login_redirect_url, + ) + + def get_authentication_context(self) -> Dict[str, Any]: + """Get the acr, amr and auth_time of the current session (sync method).""" + return self._sync_oauth.get_authentication_context() + + def has_authentication_context( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + ) -> bool: + """Check whether the current session meets a required authentication context (sync method).""" + return self._sync_oauth.has_authentication_context(acr=acr, max_age=max_age) + + def is_step_up_supported(self) -> bool: + """Check whether the Kinde environment supports step-up authentication (sync method).""" + return self._sync_oauth.is_step_up_supported() # Delegate other properties and methods to the sync implementation def __getattr__(self, name): diff --git a/kinde_sdk/auth/base_oauth.py b/kinde_sdk/auth/base_oauth.py index e683154d..05a12f77 100644 --- a/kinde_sdk/auth/base_oauth.py +++ b/kinde_sdk/auth/base_oauth.py @@ -4,7 +4,7 @@ """ from abc import ABC, abstractmethod -from typing import Dict, Any, Optional +from typing import Dict, Any, List, Optional, Union class BaseOAuth(ABC): """ @@ -53,6 +53,42 @@ async def logout(self, user_id: Optional[str] = None, logout_options: Dict[str, pass @abstractmethod - async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = None) -> Dict[str, Any]: + async def handle_redirect( + self, + code: Optional[str], + user_id: Optional[str], + state: Optional[str] = None, + error: Optional[str] = None, + error_description: Optional[str] = None, + ) -> Dict[str, Any]: """Handle OAuth redirect.""" pass + + # Step-up authentication (RFC 9470). These are not abstract, so that + # existing subclasses keep working. + + async def step_up( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + login_options: Optional[Dict[str, Any]] = None, + post_login_redirect_url: Optional[str] = None, + ) -> str: + """Generate the URL for a step-up authentication request.""" + raise NotImplementedError + + def get_authentication_context(self) -> Dict[str, Any]: + """Get the acr, amr and auth_time of the current session.""" + raise NotImplementedError + + def has_authentication_context( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + ) -> bool: + """Check whether the current session meets a required authentication context.""" + raise NotImplementedError + + def is_step_up_supported(self) -> bool: + """Check whether the Kinde environment supports step-up authentication.""" + raise NotImplementedError diff --git a/kinde_sdk/auth/login_options.py b/kinde_sdk/auth/login_options.py index 3c87ec06..70f1b5ba 100644 --- a/kinde_sdk/auth/login_options.py +++ b/kinde_sdk/auth/login_options.py @@ -27,6 +27,10 @@ class LoginOptions: PLAN_INTEREST = "plan_interest" PRICING_TABLE_KEY = "pricing_table_key" + # Step-up authentication parameters (RFC 9470) + ACR_VALUES = "acr_values" # "mfa" or "phr", or a list of them + MAX_AGE = "max_age" # non-negative int, seconds since the last authentication + # Invitation parameters INVITATION_CODE = "invitation_code" IS_INVITATION = "is_invitation" diff --git a/kinde_sdk/auth/oauth.py b/kinde_sdk/auth/oauth.py index 0c2d19d1..67dc1754 100644 --- a/kinde_sdk/auth/oauth.py +++ b/kinde_sdk/auth/oauth.py @@ -1,8 +1,12 @@ +import asyncio +import hmac import os +import jwt import requests import logging +import threading import time -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional, Union from urllib.parse import urlencode from .user_session import UserSession @@ -18,7 +22,40 @@ KindeLoginException, KindeTokenException, KindeRetrieveException, + KindeCallbackError, + CALLBACK_ERRORS, ) +from .step_up import ( + authentication_context_from_claims, + discovery_supports_step_up, + has_authentication_context as _has_authentication_context, + normalize_acr_values, + normalize_max_age, + normalize_step_up_auth_param, + prompt_includes_none, + strongest_acr, +) + +# Seconds to wait before fetching the OpenID discovery document again after a +# failed fetch. Checks that run on every request wait longer than step_up(), +# which cannot go ahead without the document. +_DISCOVERY_RETRY_SECONDS = 60 +_STEP_UP_DISCOVERY_RETRY_SECONDS = 5 + +_DEFAULT_SCOPE = "openid profile email" + +# Clock tolerance, in seconds, when checking an ID token's expiry +_ID_TOKEN_LEEWAY_SECONDS = 60 + + +def _on_event_loop() -> bool: + """True when the caller is running on an asyncio event loop.""" + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + class OAuth: def __init__( @@ -61,6 +98,12 @@ def __init__( if not self.client_id: raise KindeConfigurationException("Client ID is required.") + # OpenID discovery document, cached by _fetch_openid_configuration() + self._openid_configuration = None + self._openid_configuration_tried_at = 0.0 + # Held while the document is fetched again after a failed fetch + self._openid_configuration_lock = threading.Lock() + # Initialize API endpoints self._set_api_endpoints() @@ -119,8 +162,15 @@ def _initialize_framework(self) -> None: # Create storage using the framework's storage factory self._storage = StorageFactory.create_storage({"type": self.framework}) - # Initialize storage manager with the framework-specific storage - self._storage_manager.initialize(config={"type": self.framework, "device_id": self._framework.get_name()}, storage=self._storage) + # Initialize storage manager with the framework-specific storage. The + # device id is part of every session key, so it must be the same in + # every worker process: a generated one would hide a session stored by + # one worker from all the others. + self._storage_manager.initialize( + config={"type": self.framework}, + device_id=self._framework.get_name(), + storage=self._storage, + ) def _initialize_null_framework(self, storage_config: Dict[str, Any]) -> None: """ @@ -225,6 +275,10 @@ def _fetch_openid_configuration(self): if response.status_code == 200: config = response.json() + + # Keep the document for is_step_up_supported() + if isinstance(config, dict): + self._openid_configuration = config # Update endpoints with the values from the configuration self.auth_url = config.get("authorization_endpoint", f"{self.host}/oauth2/auth") @@ -277,6 +331,9 @@ async def generate_auth_url( LoginOptions.REDIRECT_URL: "redirect_url", LoginOptions.HAS_SUCCESS_PAGE: "has_success_page", LoginOptions.WORKFLOW_DEPLOYMENT_ID: "workflow_deployment_id", + # Step-up authentication params + LoginOptions.ACR_VALUES: "acr_values", + LoginOptions.MAX_AGE: "max_age", # Registration params LoginOptions.PLAN_INTEREST: "plan_interest", LoginOptions.PRICING_TABLE_KEY: "pricing_table_key", @@ -292,7 +349,7 @@ async def generate_auth_url( "client_id": self.client_id, "response_type": login_options.get(LoginOptions.RESPONSE_TYPE, "code"), "redirect_uri": login_options.get(LoginOptions.REDIRECT_URI, self.redirect_uri), - "scope": login_options.get(LoginOptions.SCOPE, "openid profile email"), + "scope": login_options.get(LoginOptions.SCOPE, _DEFAULT_SCOPE), } # Add audience if specified in the instance or options @@ -314,6 +371,13 @@ async def generate_auth_url( # Only add is_invitation if it's truthy if login_options[option_key]: search_params[param_key] = "true" + elif option_key == LoginOptions.ACR_VALUES: + # "mfa" / "phr" or a list of them, sent space-separated + search_params[param_key] = normalize_acr_values(login_options[option_key]) + elif option_key == LoginOptions.MAX_AGE: + # Rejected unless a non-negative int: Kinde reads a malformed + # max_age as "re-authenticate", which would hide the bug + search_params[param_key] = str(normalize_max_age(login_options[option_key])) else: # Use string representation for query params search_params[param_key] = str(login_options[option_key]) @@ -326,6 +390,11 @@ async def generate_auth_url( # Add additional auth parameters if LoginOptions.AUTH_PARAMS in login_options and isinstance(login_options[LoginOptions.AUTH_PARAMS], dict): for key, value in login_options[LoginOptions.AUTH_PARAMS].items(): + if key in (LoginOptions.ACR_VALUES, LoginOptions.MAX_AGE): + # Never send an unset or malformed step-up parameter + value = normalize_step_up_auth_param(key, value) + if value is None: + continue # Convert all values to strings for URL parameters search_params[key] = str(value) if value is not None else "" @@ -391,6 +460,8 @@ async def login(self, login_options: Dict[str, Any] = None) -> str: - has_success_page: Whether to show success page - workflow_deployment_id: Workflow deployment ID - pricing_table_key: Optional string indicating the pricing table key + - acr_values: Required authentication context, "mfa" or "phr" (or a list) + - max_age: Maximum age of the last authentication, in seconds (non-negative int) - auth_params: Additional auth parameters Returns: @@ -430,6 +501,8 @@ async def register(self, login_options: Dict[str, Any] = None) -> str: - workflow_deployment_id: Workflow deployment ID - plan_interest: Optional string indicating the plan of interest - pricing_table_key: Optional string indicating the pricing table key + - acr_values: Required authentication context, "mfa" or "phr" (or a list) + - max_age: Maximum age of the last authentication, in seconds (non-negative int) - auth_params: Additional auth parameters Returns: @@ -451,6 +524,306 @@ async def register(self, login_options: Dict[str, Any] = None) -> str: ) return auth_url_data["url"] + async def step_up( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + login_options: Optional[Dict[str, Any]] = None, + post_login_redirect_url: Optional[str] = None, + ) -> str: + """ + Generate the URL for a step-up authentication request (RFC 9470). + + Ask Kinde for a stronger or more recent authentication before a + sensitive action. Kinde collects only what is missing, and the user + keeps their session. This is a normal interactive login with + ``acr_values`` and/or ``max_age``: redirect the user to the returned + URL. The current tokens stay in place until the callback replaces them. + + Args: + acr: Required context, ``"mfa"`` or ``"phr"`` (or a list of them). + max_age: Maximum age of the last authentication, in seconds. + ``0`` forces a fresh verification. + login_options: The usual login options (see ``login()``). + post_login_redirect_url: Where the framework's callback route sends + the user afterwards. Defaults to the current page for GET + requests. Ignored without a framework integration. + + The scope is the default (``openid profile email``) unless + ``login_options`` sets one, as for ``login()``: pass the scope your + login uses. ``offline`` is added when the session has a refresh + token, so the step-up doesn't leave it without one. + + Returns: + The authorization URL. + + Raises: + ValueError: If neither ``acr`` nor ``max_age`` is requested, a value + is invalid, or ``prompt=none`` is passed (including through + ``auth_params``). Kinde can't collect a factor without a screen. + KindeConfigurationException: If the environment doesn't advertise + step-up in its discovery document. Kinde would ignore + ``acr_values`` and ``max_age`` there, so nothing is sent. To + force a fresh sign-in on such an environment, use ``login()`` + with ``prompt=login``. + KindeRetrieveException: If the discovery document could not be + fetched, so support is unknown. This is temporary: the fetch + is retried, at most once every few seconds. + """ + options = dict(login_options) if login_options else {} + auth_params = options.get(LoginOptions.AUTH_PARAMS) + auth_params = dict(auth_params) if isinstance(auth_params, dict) else {} + + if acr is not None: + options[LoginOptions.ACR_VALUES] = acr + if max_age is not None: + options[LoginOptions.MAX_AGE] = max_age + + # Kinde cannot collect a factor without showing a screen + if prompt_includes_none(options.get(LoginOptions.PROMPT)) or prompt_includes_none(auth_params.get("prompt")): + raise ValueError("step_up() cannot be used with prompt=none: step-up authentication is interactive") + + # Work out what will be sent. auth_params override the typed options. + requested_acr = None + if options.get(LoginOptions.ACR_VALUES) is not None: + requested_acr = normalize_acr_values(options[LoginOptions.ACR_VALUES]) + passthrough_acr = normalize_step_up_auth_param("acr_values", auth_params.get("acr_values")) + if passthrough_acr is not None: + # Kinde silently ignores unrecognised values, which would skip the step-up + if strongest_acr(passthrough_acr) is None: + raise ValueError(f"Unsupported acr_values {passthrough_acr!r}. Expected 'mfa' or 'phr'") + requested_acr = passthrough_acr + + requested_max_age = None + if options.get(LoginOptions.MAX_AGE) is not None: + requested_max_age = normalize_max_age(options[LoginOptions.MAX_AGE]) + passthrough_max_age = normalize_step_up_auth_param("max_age", auth_params.get("max_age")) + if passthrough_max_age is not None: + requested_max_age = int(passthrough_max_age) + + if requested_acr is None and requested_max_age is None: + raise ValueError("step_up() requires acr, max_age, or both") + + # The callback replaces every stored token, and Kinde only returns a + # refresh token when "offline" is requested. Without it a session that + # could be refreshed before the step-up could not be afterwards, and + # the user would be signed out when the access token expires. + if self._session_has_refresh_token(): + if "scope" in auth_params: + auth_params["scope"] = self._scope_with_offline(auth_params["scope"]) + else: + options[LoginOptions.SCOPE] = self._scope_with_offline( + options.get(LoginOptions.SCOPE) or _DEFAULT_SCOPE + ) + + # Kinde ignores acr_values and max_age unless the environment advertises + # step-up. Sending them anyway would bring the user back unchanged, and + # a guard that asks again would redirect in a loop. + openid_configuration = await self._get_openid_configuration_async( + retry_after=_STEP_UP_DISCOVERY_RETRY_SECONDS + ) + if openid_configuration is None: + raise KindeRetrieveException( + "Could not fetch the OpenID configuration, so it is not known whether this " + "Kinde environment supports step-up authentication. Try again." + ) + if not discovery_supports_step_up(openid_configuration): + raise KindeConfigurationException( + "Step-up authentication is not supported on this Kinde environment: its discovery " + "document has no acr_values_supported, so acr_values and max_age would be ignored. " + "To force a fresh sign-in there, use login() with prompt=login." + ) + + if auth_params or LoginOptions.AUTH_PARAMS in options: + options[LoginOptions.AUTH_PARAMS] = auth_params + + # Same as login(): add support for re-authentication + options[LoginOptions.SUPPORT_RE_AUTH] = "true" + + auth_url_data = await self.generate_auth_url( + route_type=IssuerRouteTypes.LOGIN, + login_options=options + ) + + # Remember what was asked for, so a callback error can say what was not met + self._session_manager.storage_manager.setItems("user:step_up", { + "state": auth_url_data["state"], + "acr_values": requested_acr, + "max_age": requested_max_age, + }) + + # Bring the user back to where they were, through the framework's + # post-login redirect (a no-op without a framework integration) + remember_redirect = getattr(self._framework, "set_post_login_redirect_url", None) + if callable(remember_redirect): + remember_redirect(post_login_redirect_url) + + return auth_url_data["url"] + + def _session_has_refresh_token(self) -> bool: + """Whether the current user's session holds a refresh token.""" + user_id = self._framework.get_user_id() + if not user_id: + return False + token_manager = self._session_manager.get_token_manager(user_id) + return bool(token_manager and token_manager.tokens.get("refresh_token")) + + @staticmethod + def _scope_with_offline(scope: Any) -> str: + """``scope`` with ``offline`` added, unless it is already there.""" + scope = str(scope) + return scope if "offline" in scope.split() else f"{scope} offline".strip() + + def is_step_up_supported(self) -> bool: + """ + Check whether the Kinde environment supports step-up authentication. + + Reads ``acr_values_supported`` from the OpenID discovery document that + is fetched when the client is created. If that fetch failed, it is + retried here, at most once a minute. + + Returns: + bool: True if step-up is supported. False if it isn't, or while the + discovery document is unavailable (``step_up()`` tells the two + apart). Without support, Kinde ignores ``acr_values`` and ``max_age``. + """ + return discovery_supports_step_up(self._get_openid_configuration()) + + def _get_openid_configuration(self, retry_after: float = _DISCOVERY_RETRY_SECONDS) -> Optional[Dict[str, Any]]: + """ + Return the cached discovery document, or None if it is unavailable. + + A fetch that failed is not repeated until ``retry_after`` seconds have + passed since the last attempt, so that an unreachable host is not + waited on by every request. + + The retry is a blocking request. Called on an event loop it would + stall every request the loop is serving, so there it runs on a + background thread and this call returns None without waiting. + """ + config = self._openid_configuration + if config is not None: + return config + + if not _on_event_loop(): + return self._refresh_openid_configuration(retry_after) + + if self._openid_configuration_retry_due(retry_after) and not self._openid_configuration_lock.locked(): + threading.Thread( + target=self._refresh_openid_configuration, + args=(retry_after,), + name="kinde-openid-configuration", + daemon=True, + ).start() + return None + + async def _get_openid_configuration_async(self, retry_after: float) -> Optional[Dict[str, Any]]: + """ + ``_get_openid_configuration()`` for a coroutine: the retry runs on a + worker thread and is awaited, so the event loop keeps serving requests. + """ + config = self._openid_configuration + if config is not None: + return config + return await asyncio.to_thread(self._refresh_openid_configuration, retry_after) + + def _openid_configuration_retry_due(self, retry_after: float) -> bool: + return time.time() - self._openid_configuration_tried_at >= retry_after + + def _refresh_openid_configuration(self, retry_after: float) -> Optional[Dict[str, Any]]: + """ + Fetch the discovery document again, unless it has arrived meanwhile or + was tried in the last ``retry_after`` seconds. Blocks on the network. + + One fetch runs at a time. A caller that waited for another's fetch + uses its result instead of fetching again. + """ + with self._openid_configuration_lock: + config = self._openid_configuration + if config is not None: + return config + if not self._openid_configuration_retry_due(retry_after): + return None + + try: + response = requests.get(f"{self.host}/.well-known/openid-configuration", timeout=5) + if response.status_code == 200: + config = response.json() + if isinstance(config, dict): + self._openid_configuration = config + return config + except Exception as e: + self._logger.warning(f"Failed to fetch OpenID configuration: {str(e)}") + finally: + # Counted from the end of the attempt. A caller that waited for + # a slow failure must find the wait still running, and not + # fetch again straight away. + self._openid_configuration_tried_at = time.time() + return None + + def get_authentication_context(self) -> Dict[str, Any]: + """ + Get how the current user authenticated, from the session's tokens. + + Returns: + Dict[str, Any]: ``{"acr": ..., "amr": [...], "auth_time": ...}`` + - acr: ``"mfa"``, ``"phr"``, or None for a single-factor sign-in + - amr: the methods used (informational only), or ``[]`` + - auth_time: when the user last actively authenticated, in + seconds since the epoch, read from the ID token. None if + unknown, or if the environment doesn't support step-up + (the claim may then be the token's issue time). + + All three are empty when there is no signed-in user. + + Use this for UI decisions. On a server, make security decisions with + ``has_authentication_context()`` on every request that needs them. + """ + token_manager = None + user_id = self._framework.get_user_id() + if user_id: + token_manager = self._session_manager.get_token_manager(user_id) + if not token_manager: + return authentication_context_from_claims() + + return authentication_context_from_claims( + id_token_claims=token_manager.get_claims("id_token"), + access_token_claims=token_manager.get_claims("access_token"), + trust_auth_time=self.is_step_up_supported(), + ) + + def has_authentication_context( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + ) -> bool: + """ + Check whether the current user's authentication meets a requirement. + + Args: + acr: Required context, ``"mfa"`` or ``"phr"``. ``phr`` also meets ``mfa``. + max_age: Maximum age of the last authentication, in seconds. ``0`` + is almost never met; use a short window such as 60 instead. + + Returns: + bool: True if the user is signed in and meets the requirement. + When it returns False, call ``step_up()`` with the same arguments. + Refreshing tokens never changes the answer. + + Raises: + ValueError: If ``acr`` or ``max_age`` is not a valid requirement. + """ + # Validate first, so a mistyped requirement raises instead of returning False + if acr is not None: + normalize_acr_values(acr) + if max_age is not None: + normalize_max_age(max_age) + + if not self.is_authenticated(): + return False + + return _has_authentication_context(self.get_authentication_context(), acr=acr, max_age=max_age) + async def logout(self, user_id: Optional[str] = None, logout_options: Dict[str, Any] = None) -> str: """ Generate the logout URL and clear session if user_id provided. @@ -503,18 +876,42 @@ async def logout(self, user_id: Optional[str] = None, logout_options: Dict[str, query_string = urlencode(params) return f"{self.logout_url}?{query_string}" - async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = None) -> Dict[str, Any]: + async def handle_redirect( + self, + code: Optional[str], + user_id: Optional[str], + state: Optional[str] = None, + error: Optional[str] = None, + error_description: Optional[str] = None, + ) -> Dict[str, Any]: """ Handle the OAuth redirect and exchange the code for tokens. + + The tokens from the callback replace the session's access, ID and + refresh tokens, including when the user is already signed in (for + example after a step-up). Args: code: Authorization code from the redirect user_id: User identifier for token storage state: State parameter for verification + error: The ``error`` parameter from the redirect, if any + error_description: The ``error_description`` parameter from the redirect, if any Returns: Dict with user and token information + + Raises: + UnmetAuthenticationRequirementsError: The redirect carried + ``error=unmet_authentication_requirements``. This is final: + don't retry and don't redirect to login. + LoginRequiredError: The redirect carried ``error=login_required``. + KindeCallbackError: The redirect carried any other ``error``. + KindeLoginException: The state is missing or doesn't match. """ + if error: + self._raise_callback_error(error, error_description, state) + # Verify state if provided if state: stored_state = self._session_manager.storage_manager.get("user:state") @@ -523,6 +920,12 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = self._logger.error(f"State mismatch: received {state}, stored {stored_state}") raise KindeLoginException("Invalid state parameter") + # The nonce sent with this login. It is single-use: consumed here, so + # it can't be replayed even if the rest of the flow fails. + stored_nonce = self._session_manager.storage_manager.get("user:nonce") + expected_nonce = stored_nonce.get("value") if stored_nonce else None + self._session_manager.storage_manager.delete("user:nonce") + # Get code verifier for PKCE code_verifier = None stored_code_verifier = self._session_manager.storage_manager.get("user:code_verifier") @@ -538,6 +941,10 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = except Exception as e: self._logger.error(f"Token exchange failed: {str(e)}") raise KindeTokenException(f"Failed to exchange code for tokens: {str(e)}") from e + + # The ID token's acr and auth_time decide has_authentication_context(). + # Before it is stored, check it was issued to this client, for this login. + self._validate_id_token(token_data.get("id_token"), expected_nonce) # Store tokens user_info = { @@ -547,8 +954,10 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = "redirect_uri": self.redirect_uri, } - # Store session data - self._session_manager.set_user_data(user_id, user_info, token_data) + # Store session data. The new tokens replace all of the stored ones, so + # nothing issued before this authorization (such as a refresh token from + # before a step-up) is left behind. + self._session_manager.set_user_data(user_id, user_info, token_data, replace_tokens=True) # Get user details using the token token_manager = self._session_manager.get_token_manager(user_id) @@ -569,13 +978,98 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = if state: self._session_manager.storage_manager.delete("user:state") - # Clean up nonce - self._session_manager.storage_manager.delete("user:nonce") + # Clean up the pending step-up request, if any + self._session_manager.storage_manager.delete("user:step_up") return { "tokens": token_data, "user": user_details } + + def _validate_id_token(self, id_token: Optional[str], expected_nonce: Optional[str]) -> None: + """ + Check that an ID token from the callback belongs to this login. + + The signature isn't verified: the token comes straight from the token + endpoint over TLS. OpenID Connect still requires the audience, expiry + and issuer to be checked, and the nonce to match the one that was sent + with the authorization request. + + A response without an ID token has nothing to check. The + authentication context then comes from the access token alone. + + Raises: + KindeLoginException: If the token is malformed or expired, was + issued to another client or by another issuer, or doesn't + carry the nonce of this login. + """ + if not id_token: + return + + try: + claims = jwt.decode( + id_token, + options={ + "verify_signature": False, + "verify_aud": True, + "verify_exp": True, + "require": ["iss", "aud", "exp"], + }, + audience=self.client_id, + leeway=_ID_TOKEN_LEEWAY_SECONDS, + ) + except jwt.PyJWTError as e: + self._logger.error("Invalid ID token: %s", type(e).__name__) + raise KindeLoginException("Invalid ID token") from e + + if str(claims["iss"]).rstrip("/") != str(self.host).rstrip("/"): + self._logger.error("ID token issuer does not match the configured Kinde host") + raise KindeLoginException("Invalid ID token issuer") + + if not expected_nonce or not hmac.compare_digest( + str(claims.get("nonce", "")).encode("utf-8"), str(expected_nonce).encode("utf-8") + ): + self._logger.error("Nonce mismatch in ID token") + raise KindeLoginException("Invalid nonce in ID token") + + def _raise_callback_error(self, error: str, error_description: Optional[str], state: Optional[str]) -> None: + """ + Raise the exception for an OAuth error returned to the callback. + + The state is validated first, exactly once: the pending request is + cleared, so the same error redirect cannot be replayed. Stored tokens + are not touched, and nothing is retried. + """ + storage = self._session_manager.storage_manager + + stored_state = storage.get("user:state") + expected_state = stored_state.get("value") if stored_state else None + if ( + not state + or not expected_state + or not hmac.compare_digest(str(state).encode("utf-8"), str(expected_state).encode("utf-8")) + ): + self._logger.error("State mismatch on an error callback") + raise KindeLoginException("Invalid state parameter") + + # What the step-up request asked for, if this answers one + pending = storage.get("user:step_up") + if not isinstance(pending, dict) or pending.get("state") != state: + pending = {} + + # The authorization response has arrived: this request is finished + for key in ("user:state", "user:nonce", "user:code_verifier", "user:step_up"): + storage.delete(key) + + error_class = CALLBACK_ERRORS.get(error) + if error_class is not None: + raise error_class( + error_description, + state, + acr_values=pending.get("acr_values"), + max_age=pending.get("max_age"), + ) + raise KindeCallbackError(error_description, state, error=error) async def exchange_code_for_tokens(self, code: str, code_verifier: Optional[str] = None) -> Dict[str, Any]: """ diff --git a/kinde_sdk/auth/smart_oauth.py b/kinde_sdk/auth/smart_oauth.py index 820f0a0d..e6841790 100644 --- a/kinde_sdk/auth/smart_oauth.py +++ b/kinde_sdk/auth/smart_oauth.py @@ -5,7 +5,7 @@ import asyncio import warnings -from typing import Dict, Any, Optional +from typing import Dict, Any, List, Optional, Union from .base_oauth import BaseOAuth from .oauth import OAuth from .async_oauth import AsyncOAuth @@ -90,9 +90,57 @@ async def logout(self, user_id: Optional[str] = None, logout_options: Dict[str, """Generate logout URL.""" return await self._async_oauth.logout(user_id, logout_options) - async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = None) -> Dict[str, Any]: + async def handle_redirect( + self, + code: Optional[str], + user_id: Optional[str], + state: Optional[str] = None, + error: Optional[str] = None, + error_description: Optional[str] = None, + ) -> Dict[str, Any]: """Handle OAuth redirect.""" + if error: + return await self._async_oauth.handle_redirect( + code, user_id, state, error=error, error_description=error_description + ) return await self._async_oauth.handle_redirect(code, user_id, state) + + async def step_up( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + login_options: Optional[Dict[str, Any]] = None, + post_login_redirect_url: Optional[str] = None, + ) -> str: + """Generate the URL for a step-up authentication request.""" + return await self._async_oauth.step_up( + acr=acr, + max_age=max_age, + login_options=login_options, + post_login_redirect_url=post_login_redirect_url, + ) + + # The checks below go through the same client as step_up(). Each client + # keeps its own copy of the discovery document, so after a failed fetch + # one can know that step-up is supported before the other does. Split + # across the two, step_up() could send the user to Kinde while the check + # still answered "not met", and a guarded page would redirect in a loop. + + def get_authentication_context(self) -> Dict[str, Any]: + """Get the acr, amr and auth_time of the current session.""" + return self._async_oauth.get_authentication_context() + + def has_authentication_context( + self, + acr: Optional[Union[str, List[str]]] = None, + max_age: Optional[int] = None, + ) -> bool: + """Check whether the current session meets a required authentication context.""" + return self._async_oauth.has_authentication_context(acr=acr, max_age=max_age) + + def is_step_up_supported(self) -> bool: + """Check whether the Kinde environment supports step-up authentication.""" + return self._async_oauth.is_step_up_supported() # Delegate other properties and methods to the sync implementation def __getattr__(self, name): diff --git a/kinde_sdk/auth/step_up.py b/kinde_sdk/auth/step_up.py new file mode 100644 index 00000000..e8f25897 --- /dev/null +++ b/kinde_sdk/auth/step_up.py @@ -0,0 +1,311 @@ +""" +Step-up authentication (RFC 9470): the protocol logic shared by the OAuth clients. + +Everything here is pure (no I/O, no framework access), so it can be reused by +framework integrations and by server-side checks on verified token claims. + +Kinde's behaviour that this module encodes: + +- ``acr_values`` is ``mfa`` or ``phr`` (phishing-resistant). ``phr`` also meets ``mfa``. +- Kinde omits the ``acr`` claim for a single-factor sign-in, so an absent + ``acr`` means "neither ``mfa`` nor ``phr``". +- ``max_age`` is a non-negative whole number of seconds. ``0`` is valid. Kinde + treats any other malformed value as "re-authenticate", which would hide a + bug, so invalid values are rejected here before anything is sent. +""" + +import re +import time +from enum import Enum +from typing import Any, Dict, List, Mapping, Optional, Union + + +class AcrValues: + """Authentication contexts that Kinde recognises in ``acr_values``.""" + + MFA = "mfa" # A second factor + PHR = "phr" # Phishing-resistant (a passkey with user verification); also meets MFA + + +AcrInput = Union[str, List[str], tuple] + +# phr meets an mfa requirement; an absent acr ranks 0 +_ACR_RANK = {AcrValues.MFA: 1, AcrValues.PHR: 2} + +# Values from other providers that Kinde reads as mfa. Only relevant for values +# passed through auth_params; the SDK's own options send mfa or phr only. +_ACR_ALIASES = { + "http://schemas.openid.net/pape/policies/2007/06/multi-factor": AcrValues.MFA, + "urn:okta:loa:2fa:any": AcrValues.MFA, +} + +_DIGITS = re.compile(r"[0-9]+") + +# How far ahead of this machine's clock an auth_time may be and still count as +# "just now". Kinde's clock and the server's are never exactly in step. +_CLOCK_SKEW_SECONDS = 60 + + +def _split_acr_values(acr_values: Any) -> List[str]: + """Split a string or a list/tuple of strings into individual acr values.""" + if isinstance(acr_values, str): + return acr_values.split() + if isinstance(acr_values, (list, tuple)): + parts: List[str] = [] + for value in acr_values: + if not isinstance(value, str): + raise ValueError("acr_values must be a string or a list of strings") + parts.extend(value.split()) + return parts + raise ValueError("acr_values must be a string or a list of strings") + + +def normalize_acr_values(acr_values: AcrInput) -> str: + """ + Validate ``acr_values`` and return the space-separated string to send. + + Args: + acr_values: ``"mfa"``, ``"phr"``, a space-separated string, or a list of them. + + Returns: + The lower-cased, de-duplicated, space-separated value (e.g. ``"mfa phr"``). + + Raises: + ValueError: If the value is empty, not a string or list of strings, or + contains anything other than ``mfa`` or ``phr``. Kinde silently + ignores values it doesn't recognise, which would skip the step-up. + """ + parts = _split_acr_values(acr_values) + if not parts: + raise ValueError("acr_values must not be empty. Expected 'mfa' or 'phr'") + + normalized: List[str] = [] + for part in parts: + value = part.lower() + if value not in _ACR_RANK: + raise ValueError(f"Unsupported acr value {part!r}. Expected 'mfa' or 'phr'") + if value not in normalized: + normalized.append(value) + return " ".join(normalized) + + +def normalize_max_age(max_age: int) -> int: + """ + Validate ``max_age`` (seconds since the user last authenticated). + + Raises: + ValueError: If the value is not a non-negative ``int``. ``bool`` and + ``float`` are rejected, including ``True`` and ``300.0``. + """ + if isinstance(max_age, bool) or not isinstance(max_age, int): + raise ValueError( + f"max_age must be a non-negative whole number of seconds (int), got {max_age!r}" + ) + if max_age < 0: + raise ValueError(f"max_age must not be negative, got {max_age!r}") + return max_age + + +def normalize_step_up_auth_param(key: str, value: Any) -> Optional[str]: + """ + Normalize an ``acr_values`` or ``max_age`` entry passed through ``auth_params``. + + ``auth_params`` is a raw passthrough, so this is more lenient than the typed + login options: ``max_age`` may be a string of digits, and ``acr_values`` is + not restricted to ``mfa`` / ``phr``. An unset value is never sent. + + Returns: + The string to send, or ``None`` when the value is unset (``None`` or + empty) and the parameter must be omitted. + + Raises: + ValueError: If ``max_age`` is not a non-negative whole number (this + includes the strings ``"undefined"``, ``"null"`` and ``"NaN"``), or + ``acr_values`` is not a string or list of strings. + """ + if value is None: + return None + + if key == "max_age": + if isinstance(value, str): + text = value.strip() + if not text: + return None + if not _DIGITS.fullmatch(text): + raise ValueError( + f"max_age must be a non-negative whole number of seconds, got {value!r}" + ) + return str(int(text)) + return str(normalize_max_age(value)) + + if key == "acr_values": + parts = _split_acr_values(value) + return " ".join(parts) if parts else None + + raise ValueError(f"{key!r} is not a step-up parameter") + + +def strongest_acr(acr_values: Optional[AcrInput]) -> Optional[str]: + """ + Return the strongest context Kinde would apply for ``acr_values``. + + Kinde applies the highest recognised value and ignores the rest, so this + returns ``"phr"``, ``"mfa"``, or ``None`` when nothing is recognised. + """ + if acr_values is None: + return None + + best: Optional[str] = None + for part in _split_acr_values(acr_values): + value = part.lower() + value = _ACR_ALIASES.get(value, value) + if value in _ACR_RANK and (best is None or _ACR_RANK[value] > _ACR_RANK[best]): + best = value + return best + + +def prompt_includes_none(prompt: Any) -> bool: + """Whether a ``prompt`` value (string, enum or list) contains ``none``.""" + if prompt is None: + return False + if isinstance(prompt, Enum): + prompt = prompt.value + if isinstance(prompt, (list, tuple)): + return any(prompt_includes_none(value) for value in prompt) + return "none" in str(prompt).lower().split() + + +def discovery_supports_step_up(openid_configuration: Any) -> bool: + """ + Whether a discovery document advertises step-up (``acr_values_supported``). + + When it doesn't, Kinde ignores ``acr_values`` and ``max_age``, tokens carry + no ``acr`` or ``amr``, and ``auth_time`` may be the token's issue time. + """ + if not isinstance(openid_configuration, Mapping): + return False + supported = openid_configuration.get("acr_values_supported") + return isinstance(supported, (list, tuple)) and len(supported) > 0 + + +def _claim_acr(claims: Mapping) -> Optional[str]: + acr = claims.get("acr") + return acr if isinstance(acr, str) and acr else None + + +def _claim_amr(claims: Mapping) -> Optional[List[str]]: + amr = claims.get("amr") + if isinstance(amr, (list, tuple)): + return [value for value in amr if isinstance(value, str)] + return None + + +def _claim_auth_time(claims: Mapping) -> Optional[int]: + auth_time = claims.get("auth_time") + if isinstance(auth_time, bool) or not isinstance(auth_time, (int, float)): + return None + return int(auth_time) + + +def authentication_context_from_claims( + id_token_claims: Optional[Mapping] = None, + access_token_claims: Optional[Mapping] = None, + trust_auth_time: bool = True, +) -> Dict[str, Any]: + """ + Build the authentication context from decoded token claims. + + ``auth_time`` is read from the ID token, because Kinde always sets it there + and only sets it on the access token when it can establish it. The access + token is the fallback for each claim. + + Args: + id_token_claims: Claims of the session's ID token, if there is one. + access_token_claims: Claims of the session's access token. + trust_auth_time: Pass ``False`` when the environment doesn't advertise + step-up. ``auth_time`` may then be the token's issue time, so it is + reported as ``None`` instead. + + Returns: + ``{"acr": "mfa" | "phr" | None, "amr": [...], "auth_time": int | None}``. + ``acr`` is ``None`` for a single-factor sign-in. + """ + id_claims = id_token_claims if isinstance(id_token_claims, Mapping) else {} + access_claims = ( + access_token_claims if isinstance(access_token_claims, Mapping) else {} + ) + + # Tokens of two different users never describe one authentication. An ID + # token is only trusted when it names the same user as the access token, + # so one without a "sub" is not trusted either. + id_sub = id_claims.get("sub") + access_sub = access_claims.get("sub") + if id_claims and (not id_sub or id_sub != access_sub): + return {"acr": None, "amr": [], "auth_time": None} + + acr = _claim_acr(id_claims) or _claim_acr(access_claims) + + amr = _claim_amr(id_claims) + if amr is None: + amr = _claim_amr(access_claims) or [] + + auth_time = None + if trust_auth_time: + auth_time = _claim_auth_time(id_claims) + if auth_time is None: + auth_time = _claim_auth_time(access_claims) + + return {"acr": acr, "amr": amr, "auth_time": auth_time} + + +def has_authentication_context( + context: Mapping, + acr: Optional[AcrInput] = None, + max_age: Optional[int] = None, + now: Optional[float] = None, + leeway: int = 0, +) -> bool: + """ + Check whether an authentication context meets a requirement. + + This is the single implementation of the check. ``OAuth.has_authentication_context`` + uses it for the current session, and it works equally on the claims of a + token you have verified yourself (it only reads ``acr`` and ``auth_time``). + ``amr`` is never used to decide: Kinde has already folded it into ``acr``. + + Args: + context: A mapping with ``acr`` and ``auth_time``, such as the result of + ``get_authentication_context()`` or verified token claims. + acr: Required context, ``"mfa"`` or ``"phr"`` (``phr`` also meets ``mfa``). + max_age: Maximum age of the last authentication, in seconds. + now: Current time in seconds since the epoch. Defaults to ``time.time()``. + leeway: Clock tolerance, in seconds, added to ``max_age``. + + Returns: + ``True`` if the requirement is met. An absent ``acr`` meets no ``acr`` + requirement, and a missing ``auth_time`` meets no ``max_age`` requirement. + Nor does an ``auth_time`` in the future, beyond a minute of clock skew. + + Raises: + ValueError: If ``acr`` or ``max_age`` is not a valid requirement. + """ + if acr is not None: + required = strongest_acr(normalize_acr_values(acr)) + actual = _claim_acr(context) + if _ACR_RANK.get(actual.lower() if actual else "", 0) < _ACR_RANK[required]: + return False + + if max_age is not None: + max_age = normalize_max_age(max_age) + auth_time = _claim_auth_time(context) + if auth_time is None: + return False + if now is None: + now = time.time() + age = now - auth_time + # A future auth_time is invalid, not "very recent". A few seconds + # ahead is only the two clocks disagreeing, right after a sign-in. + if age < -max(leeway, _CLOCK_SKEW_SECONDS) or age > max_age + leeway: + return False + + return True diff --git a/kinde_sdk/auth/token_manager.py b/kinde_sdk/auth/token_manager.py index 3411fc39..cadf7ec9 100644 --- a/kinde_sdk/auth/token_manager.py +++ b/kinde_sdk/auth/token_manager.py @@ -33,9 +33,16 @@ def __init__(self, user_id, client_id, client_secret, token_url): self.client_secret = client_secret self.token_url = token_url self.tokens = {} # Store tokens (access/refresh) - self.lock = threading.Lock() # Add a lock for thread safety + # Re-entrant: get_access_token() holds the lock while it refreshes, + # and the refresh stores the new tokens through set_tokens() + self.lock = threading.RLock() self.redirect_uri = None # Initialize the redirect_uri attribute self.force_api = False # Initialize force_api setting + # Called after a refresh or a code exchange stores new tokens, so the + # session that owns this token manager can persist them + self.on_tokens_changed = None + # Revision of these tokens in the stored session, kept by UserSession + self.revision = None self.initialized = True def set_force_api(self, force_api: bool): @@ -46,9 +53,21 @@ def get_force_api(self) -> bool: """Get the force_api setting for this token manager.""" return self.force_api - def set_tokens(self, token_data: Dict[str, Any]): - """ Store tokens with expiration. """ + def set_tokens(self, token_data: Dict[str, Any], replace: bool = False): + """ + Store tokens with expiration. + + Args: + token_data: The token endpoint response. + replace: If True, drop every stored token first. Use this for the + tokens of a new authorization (a login or a step-up), so that + an older refresh or ID token is never kept alongside them. + The default merges, which is right for a token refresh. + """ with self.lock: + if replace: + self.tokens.clear() + # Update existing tokens instead of creating new dict self.tokens.update({ "access_token": token_data.get("access_token"), @@ -117,7 +136,30 @@ async def exchange_code_for_token(self, code: str, code_verifier: Optional[str] token_data = response.json() self.set_tokens(token_data) + self._notify_tokens_changed() return self.tokens["access_token"] + + def _notify_tokens_changed(self, refreshed: bool = False): + """ + Let the owning session persist tokens that changed outside a callback. + + Args: + refreshed: True when the new tokens come from refreshing the + previous ones, False when they come from a new authorization. + """ + callback = getattr(self, "on_tokens_changed", None) + if callback is None: + return + try: + callback(refreshed) + except Exception as e: + # Not raised: the new tokens are valid and are kept in memory, and + # failing here would sign the user out of a working session. The + # session saves them again the next time it is read (see + # UserSession._sync_with_storage). + logging.warning( + "Failed to save updated tokens to the session, will retry: %s", type(e).__name__ + ) def get_access_token(self): """ Get a valid access token. Refresh if expired. """ @@ -138,25 +180,32 @@ def get_access_token(self): def refresh_access_token(self): """ Use the refresh token to get a new access token. """ - if "refresh_token" not in self.tokens: - raise ValueError("No refresh token available") + # The lock is held from reading the refresh token until the result is + # saved, so nothing else in this process changes the tokens in between + with self.lock: + if "refresh_token" not in self.tokens: + raise ValueError("No refresh token available") - data = { - "grant_type": "refresh_token", - "refresh_token": self.tokens["refresh_token"], - "client_id": self.client_id, - } - - # Add client secret if available - if self.client_secret: - data["client_secret"] = self.client_secret - - response = requests.post(self.token_url, data=data) - response.raise_for_status() - token_data = response.json() - - self.set_tokens(token_data) - return self.tokens["access_token"] + data = { + "grant_type": "refresh_token", + "refresh_token": self.tokens["refresh_token"], + "client_id": self.client_id, + } + + # Add client secret if available + if self.client_secret: + data["client_secret"] = self.client_secret + + response = requests.post(self.token_url, data=data) + response.raise_for_status() + token_data = response.json() + + self.set_tokens(token_data) + # Persist the refreshed tokens: another process serving this session + # must not keep refreshing from the token that was just used. The + # session may instead replace them with newer stored tokens. + self._notify_tokens_changed(refreshed=True) + return self.tokens["access_token"] def get_id_token(self): """Get the ID token if available.""" diff --git a/kinde_sdk/auth/user_session.py b/kinde_sdk/auth/user_session.py index 19d9ca07..c4ea047c 100644 --- a/kinde_sdk/auth/user_session.py +++ b/kinde_sdk/auth/user_session.py @@ -1,17 +1,28 @@ from .token_manager import TokenManager +import logging import threading import time from typing import Dict, Any, Optional from kinde_sdk.core.storage.storage_manager import StorageManager +# Revision of a session that was stored before revisions existed +_NO_REVISION = (0, 0, 0.0) + + class UserSession: def __init__(self): self.user_sessions = {} # Store user-specific session data self.lock = threading.Lock() # Add a lock for thread safety self.storage_manager = StorageManager() # Use the provided storage backend - def set_user_data(self, user_id: str, user_info: Dict[str, Any], token_data: Dict[str, Any]): - """Store user session details and associate tokens.""" + def set_user_data(self, user_id: str, user_info: Dict[str, Any], token_data: Dict[str, Any], replace_tokens: bool = False): + """ + Store user session details and associate tokens. + + Args: + replace_tokens: If True, the stored access, ID and refresh tokens + are all replaced by ``token_data`` instead of merged with it. + """ with self.lock: # Acquire the lock if user_id not in self.user_sessions: # Create new token manager @@ -33,27 +44,165 @@ def set_user_data(self, user_id: str, user_info: Dict[str, Any], token_data: Dic else: # Update existing user info self.user_sessions[user_id]["user_info"] = user_info + + # Save again whenever the token manager refreshes its tokens + self._persist_token_changes(user_id) - # Set tokens in token manager - self.user_sessions[user_id]["token_manager"].set_tokens(token_data) - - # Save to persistent storage - self._save_to_storage(user_id) + # Set the tokens and save them as a new authorization. The token + # manager's lock is held across both, so its tokens and their + # revision always change together (see _sync_with_storage). + token_manager = self.user_sessions[user_id]["token_manager"] + with token_manager.lock: + if replace_tokens: + token_manager.set_tokens(token_data, replace=True) + else: + token_manager.set_tokens(token_data) + + self._commit_token_change(user_id, refreshed=False) def _save_to_storage(self, user_id: str): - """Save session data to storage.""" + """Save session data to storage, under the revision its tokens have now.""" session_data = self.user_sessions.get(user_id) if session_data: + token_manager = session_data["token_manager"] + # We need to serialize the session data # Token manager can't be directly serialized serialized_data = { "user_info": session_data["user_info"], - "tokens": session_data["token_manager"].tokens, + "tokens": token_manager.tokens, } + revision = self._as_revision(getattr(token_manager, "revision", None)) + if revision is not None: + serialized_data["revision"] = list(revision) # Store with user: prefix to make it user-specific but device-independent # if you want device-specific sessions, remove the "user:" prefix self.storage_manager.setItems(user_id, serialized_data) + def _persist_token_changes(self, user_id: str): + """Save the session whenever its token manager stores new tokens (e.g. a refresh).""" + token_manager = self.user_sessions[user_id]["token_manager"] + token_manager.on_tokens_changed = ( + lambda refreshed=False: self._commit_token_change(user_id, refreshed=refreshed) + ) + + def _commit_token_change(self, user_id: str, refreshed: bool): + """ + Give tokens that have just changed their revision, and save them. + + Args: + refreshed: True when the tokens were refreshed from the previous + ones. False when they come from a new authorization (a + sign-in or a step-up), which outranks everything before it. + + A refresh only continues the authorization it started from. If the + stored session moved past that point while the refresh was in flight + (another process handled a step-up, say), the refreshed tokens are + out of date: they are dropped and the stored ones adopted instead. + """ + session_data = self.user_sessions.get(user_id) + if not session_data: + return + token_manager = session_data["token_manager"] + + with token_manager.lock: + cached = self._as_revision(getattr(token_manager, "revision", None)) or _NO_REVISION + try: + stored_session = self._stored_session(user_id) + except Exception: + # Not known. The revision is still advanced, so that a save + # that fails below is repeated by _sync_with_storage(). + stored_session = None + stored = self._stored_revision(stored_session) + + if refreshed: + if stored > cached: + token_manager.tokens = dict(stored_session["tokens"]) + token_manager.revision = stored + return + token_manager.revision = (cached[0], cached[1] + 1, time.time()) + else: + token_manager.revision = (max(cached[0], stored[0]) + 1, 0, time.time()) + + self._save_to_storage(user_id) + + @staticmethod + def _as_revision(value: Any) -> Optional[tuple]: + """ + Read a revision: ``(authorization, refresh, saved_at)``, compared in + that order. + + ``authorization`` counts the sign-ins and step-ups that have replaced + the session's tokens, and ``refresh`` the refreshes since the last + one. Tokens refreshed from an earlier authorization therefore never + outrank a later authorization, however late the refresh finishes and + whichever process ran it. + + The counters order changes that followed one another, whatever the + clocks of the processes say. The time only settles a tie between two + processes that made the same change at the same moment. + """ + if not isinstance(value, (list, tuple)) or len(value) != 3: + return None + authorization, refresh, saved_at = value + for counter in (authorization, refresh): + if isinstance(counter, bool) or not isinstance(counter, int): + return None + if isinstance(saved_at, bool) or not isinstance(saved_at, (int, float)): + return None + return (authorization, refresh, float(saved_at)) + + def _stored_session(self, user_id: str) -> Optional[Dict[str, Any]]: + """The stored session for a user, if it holds tokens.""" + session_data = self.storage_manager.get(user_id) + if not isinstance(session_data, dict): + return None + tokens = session_data.get("tokens") + if not isinstance(tokens, dict) or "access_token" not in tokens: + return None + return session_data + + def _stored_revision(self, stored_session: Optional[Dict[str, Any]]) -> tuple: + if stored_session is None: + return _NO_REVISION + return self._as_revision(stored_session.get("revision")) or _NO_REVISION + + def _sync_with_storage(self, user_id: str, token_manager: TokenManager): + """ + Reconcile a session cached in this process with the stored session. + + Both can be out of date. Another process may have stored newer tokens + (a step-up, a refresh, a later sign-in). And the store may hold older + ones: session backends write a request's whole session back when it + ends, and a cookie session is whatever cookie the request carried, so + a request that began before the tokens changed puts the old ones back. + + The revision saved with the tokens decides. Newer stored tokens are + adopted. Older stored tokens are never adopted, and are overwritten + with the current ones. Tokens changed in memory without being saved + are left alone. + + The comparison and what follows from it happen under the token + manager's lock. A refresh holds that lock until its tokens are saved, + so a decision made here can't be applied over tokens that changed + after it was made. + """ + with token_manager.lock: + stored_session = self._stored_session(user_id) + if stored_session is None: + return + + stored_revision = self._stored_revision(stored_session) + cached_revision = self._as_revision(getattr(token_manager, "revision", None)) + if cached_revision is None: + # Nothing to compare with yet: keep the cached tokens + token_manager.revision = stored_revision + elif stored_revision > cached_revision: + token_manager.tokens = dict(stored_session["tokens"]) + token_manager.revision = stored_revision + elif stored_revision < cached_revision: + self._save_to_storage(user_id) + def reset(self): """Reset all session data - useful for testing""" with self.lock: @@ -95,14 +244,24 @@ def _load_from_storage(self, user_id: str) -> bool: if "redirect_uri" in user_info: token_manager.set_redirect_uri(user_info["redirect_uri"]) - # Set tokens - token_manager.tokens = tokens + # Set tokens. The token manager is shared by every session object in + # this process, so it may already hold newer tokens than this stored + # session, which can be an older copy (see _sync_with_storage). + stored_revision = self._stored_revision(session_data) + with token_manager.lock: + cached_revision = self._as_revision(getattr(token_manager, "revision", None)) + if cached_revision is None or not token_manager.tokens or stored_revision >= cached_revision: + token_manager.tokens = tokens + token_manager.revision = stored_revision # Store in memory self.user_sessions[user_id] = { "user_info": user_info, - "token_manager": token_manager + "token_manager": token_manager, } + + # Save again whenever the token manager refreshes its tokens + self._persist_token_changes(user_id) return True @@ -123,8 +282,25 @@ def get_token_manager(self, user_id: str) -> Optional[TokenManager]: if user_id not in self.user_sessions: if not self._load_from_storage(user_id): return None - - return self.user_sessions.get(user_id, {}).get("token_manager") + return self.user_sessions.get(user_id, {}).get("token_manager") + + token_manager = self.user_sessions[user_id].get("token_manager") + + # Another process may have replaced the session's tokens. Checked after + # releasing self.lock: this waits for a refresh in flight for this + # user, which must not hold up every other user's requests. + if token_manager is not None: + try: + self._sync_with_storage(user_id, token_manager) + except Exception as e: + # The session store can't be read or written just now. The + # cached tokens are still good: keep them, and compare again + # on the next call. + logging.warning( + "Could not compare the cached session with the stored one, will retry: %s", + type(e).__name__, + ) + return token_manager def is_authenticated(self, user_id: str) -> bool: diff --git a/kinde_sdk/core/exceptions.py b/kinde_sdk/core/exceptions.py index 7d562ea2..76ba67dc 100644 --- a/kinde_sdk/core/exceptions.py +++ b/kinde_sdk/core/exceptions.py @@ -10,6 +10,57 @@ class KindeLoginException(KindeException): """Raised when there is an error during the login process.""" pass +class KindeCallbackError(KindeLoginException): + """ + Raised when Kinde returns an OAuth error to the callback URL. + + Only raised after the ``state`` parameter has been validated. The user's + existing session and tokens are left untouched. + + Attributes: + error: The OAuth error code (e.g. ``"unmet_authentication_requirements"``). + error_description: The ``error_description`` from the callback, or ``""``. + state: The validated ``state`` from the callback. + acr_values: The ``acr_values`` of the step-up request this answers, if known. + max_age: The ``max_age`` of the step-up request this answers, if known. + """ + + error = None + + def __init__(self, error_description=None, state=None, error=None, acr_values=None, max_age=None): + if error is not None: + self.error = error + self.error_description = error_description or "" + self.state = state + self.acr_values = acr_values + self.max_age = max_age + super().__init__(self.error_description or self.error or "Authorization failed") + +class UnmetAuthenticationRequirementsError(KindeCallbackError): + """ + Raised when the user cannot meet the requested authentication context + (for example no enrolled MFA factor, or no passkey). + + This is a final answer: the same request gives the same error. Don't retry + and don't redirect to login. Tell the user why instead. + """ + + error = "unmet_authentication_requirements" + +class LoginRequiredError(KindeCallbackError): + """ + Raised when a ``prompt=none`` request cannot complete without an + interactive login. The app decides whether to start one. + """ + + error = "login_required" + +# Callback errors that are raised as their own exception type. +CALLBACK_ERRORS = { + UnmetAuthenticationRequirementsError.error: UnmetAuthenticationRequirementsError, + LoginRequiredError.error: LoginRequiredError, +} + class KindeTokenException(KindeException): """Raised when there is an error with token operations.""" pass diff --git a/kinde_sdk/core/framework/framework_interface.py b/kinde_sdk/core/framework/framework_interface.py index 16062622..84a5bbdb 100644 --- a/kinde_sdk/core/framework/framework_interface.py +++ b/kinde_sdk/core/framework/framework_interface.py @@ -74,6 +74,20 @@ def get_user_id(self) -> Optional[str]: """ pass + def set_post_login_redirect_url(self, url: Optional[str] = None) -> None: + """ + Remember where the callback route should send the user after the next + sign-in or step-up. + + Frameworks that register a callback route override this. The default + does nothing, for frameworks where the application owns the callback. + + Args: + url: The URL to return to. If None, the current page is used when + the current request is a GET. + """ + return None + @abstractmethod def can_auto_detect(self) -> bool: """ diff --git a/testv2/conftest.py b/testv2/conftest.py new file mode 100644 index 00000000..7e3d35c5 --- /dev/null +++ b/testv2/conftest.py @@ -0,0 +1,45 @@ +"""Fixtures shared by the test suite.""" + +from unittest.mock import AsyncMock + +import pytest +import requests + +from kinde_sdk.auth.oauth import OAuth +from kinde_sdk.auth.token_manager import TokenManager +from kinde_sdk.core.framework.null_framework import NullFramework +from testv2.step_up_helpers import FakeHttp + + +@pytest.fixture +def http(monkeypatch): + """ + Replace the network with a fake Kinde (discovery and the token endpoint). + + Opt-in: only tests that ask for ``http`` get it. Any other request fails + the test. + """ + fake = FakeHttp() + monkeypatch.setattr(requests, "get", fake.get) + monkeypatch.setattr(requests, "post", fake.post) + + # Kinde returns the nonce of an authorization request in the ID token it + # issues for that request's code. The fake does the same. + generate_auth_url = OAuth.generate_auth_url + + async def generate_auth_url_and_note_nonce(self, *args, **kwargs): + auth_url_data = await generate_auth_url(self, *args, **kwargs) + fake.nonce = auth_url_data["nonce"] + return auth_url_data + + monkeypatch.setattr(OAuth, "generate_auth_url", generate_auth_url_and_note_nonce) + monkeypatch.setattr( + "kinde_sdk.auth.oauth.helper_get_user_details", + AsyncMock(return_value={"id": "kp_user"}), + ) + # Creating a client gives the storage manager a fresh store + TokenManager.reset_instances() + NullFramework().clear_user_id() + yield fake + NullFramework().clear_user_id() + TokenManager.reset_instances() diff --git a/testv2/step_up_helpers.py b/testv2/step_up_helpers.py new file mode 100644 index 00000000..bdd400ab --- /dev/null +++ b/testv2/step_up_helpers.py @@ -0,0 +1,108 @@ +""" +Shared helpers for the step-up authentication tests. + +``FakeHttp`` stands in for ``requests``. The ``http`` fixture in +``testv2/conftest.py`` installs it, so the tests never touch the network. +""" + +import time +from unittest.mock import MagicMock +from urllib.parse import parse_qs, urlparse + +import jwt + +HOST = "https://test.kinde.com" +CLIENT_ID = "test_client_id" +JWT_KEY = "k" * 32 + +ENDPOINTS = { + "authorization_endpoint": f"{HOST}/oauth2/auth", + "token_endpoint": f"{HOST}/oauth2/token", + "end_session_endpoint": f"{HOST}/logout", + "userinfo_endpoint": f"{HOST}/oauth2/userinfo", +} +WITH_STEP_UP = {**ENDPOINTS, "acr_values_supported": ["mfa", "phr"]} +WITHOUT_STEP_UP = dict(ENDPOINTS) + + +class FakeHttp: + """Stands in for ``requests``: serves discovery and the token endpoint.""" + + def __init__(self): + self.discovery = WITH_STEP_UP + self.discovery_status = 200 + self.token_responses = [] + # The nonce of the authorization request in progress. Kinde ties it to + # the code it issues; the ``http`` fixture records it here. + self.nonce = None + self.get = MagicMock(side_effect=self._get) + self.post = MagicMock(side_effect=self._post) + + def _get(self, url, **kwargs): + assert ( + url == f"{HOST}/.well-known/openid-configuration" + ), f"unexpected GET {url}" + response = MagicMock() + response.status_code = self.discovery_status + response.json.return_value = self.discovery + return response + + def _post(self, url, data=None, **kwargs): + assert url == f"{HOST}/oauth2/token", f"unexpected POST {url}" + assert self.token_responses, "unexpected request to the token endpoint" + tokens = self.token_responses.pop(0) + if data.get("grant_type") == "authorization_code": + self._add_nonce(tokens) + response = MagicMock() + response.status_code = 200 + response.json.return_value = tokens + return response + + def _add_nonce(self, tokens): + """Put the login's nonce in the ID token, unless the test chose one.""" + if not self.nonce or "id_token" not in tokens: + return + claims = jwt.decode(tokens["id_token"], options={"verify_signature": False}) + if "nonce" not in claims: + tokens["id_token"] = jwt.encode( + {**claims, "nonce": self.nonce}, JWT_KEY, algorithm="HS256" + ) + + @property + def token_requests(self): + return [call.kwargs["data"] for call in self.post.call_args_list] + + +def make_jwt(**claims): + return jwt.encode({"sub": "kp_user", **claims}, JWT_KEY, algorithm="HS256") + + +def token_response( + label, access_claims=None, id_claims=None, refresh=True, id_token=True +): + """A token endpoint response. ``label`` makes each token distinguishable.""" + response = { + "access_token": make_jwt(jti=f"access-{label}", **(access_claims or {})), + "expires_in": 3600, + } + if id_token: + response["id_token"] = make_jwt( + **{ + "jti": f"id-{label}", + "iss": HOST, + "aud": [CLIENT_ID], + "exp": int(time.time()) + 3600, + **(id_claims or {}), + } + ) + if refresh: + response["refresh_token"] = f"refresh-{label}" + return response + + +def query(url): + """The query parameters of a URL, as a flat dict.""" + return { + key: values[0] + for key, values in parse_qs(urlparse(url).query, keep_blank_values=True).items() + } diff --git a/testv2/step_up_worker.py b/testv2/step_up_worker.py new file mode 100644 index 00000000..533e2a0f --- /dev/null +++ b/testv2/step_up_worker.py @@ -0,0 +1,178 @@ +""" +A Flask worker process for the multi-worker step-up tests. + +Each worker is a separate Python process with its own in-memory caches, like a +``gunicorn`` worker. The workers share one server-side session directory. The +network is faked inside the worker: the token endpoint behaves as Kinde does, +so a refresh keeps the ``acr`` of the grant its refresh token came from. + +Kinde returns the nonce of an authorization request in the ID token it issues +for that request's code. The login and its callback can land on different +workers, so here the code carries the nonce: ``~``. +""" + +import asyncio +import os +import time +import traceback + +HOST = "https://test.kinde.com" + + +def _fake_kinde(worker_name, token_requests): + from unittest.mock import MagicMock + + import jwt + + def tokens(label, mfa, refresh_token, nonce=None): + now = int(time.time()) + claims = {"sub": "kp_user", "auth_time": now if mfa else now - 3600} + if mfa: + claims.update(acr="mfa", amr=["pwd", "totp"]) + id_claims = { + **claims, + "jti": f"id-{label}", + "iss": HOST, + "aud": ["test_client_id"], + "exp": now + 3600, + } + if nonce: + id_claims["nonce"] = nonce + return { + "access_token": jwt.encode( + {**claims, "jti": f"access-{label}"}, "k" * 32, algorithm="HS256" + ), + "id_token": jwt.encode(id_claims, "k" * 32, algorithm="HS256"), + "refresh_token": refresh_token, + "expires_in": 3600, + } + + def get(url, **kwargs): + response = MagicMock() + response.status_code = 200 + response.json.return_value = { + "authorization_endpoint": f"{HOST}/oauth2/auth", + "token_endpoint": f"{HOST}/oauth2/token", + "end_session_endpoint": f"{HOST}/logout", + "userinfo_endpoint": f"{HOST}/oauth2/userinfo", + "acr_values_supported": ["mfa", "phr"], + } + return response + + def post(url, data=None, **kwargs): + code, _, nonce = (data.get("code") or "").partition("~") + token_requests.append( + { + "grant_type": data.get("grant_type"), + "code": code or None, + "refresh_token": data.get("refresh_token"), + } + ) + response = MagicMock() + response.status_code = 200 + if data["grant_type"] == "authorization_code": + response.json.return_value = tokens( + code, code.startswith("stepup"), f"refresh-from-{code}", nonce + ) + else: + # A refresh never upgrades: it keeps the context of its refresh token + refresh_token = data["refresh_token"] + response.json.return_value = tokens( + f"refreshed-by-{worker_name}", "stepup" in refresh_token, refresh_token + ) + return response + + return get, post + + +def run(worker_name, connection, session_dir): + """Serve requests sent over ``connection`` until ``None`` arrives.""" + os.environ["SECRET_KEY"] = "shared-secret" + os.environ["SESSION_FILE_DIR"] = session_dir + + import logging + from unittest.mock import AsyncMock + + logging.disable(logging.CRITICAL) + + import requests + + token_requests = [] + requests.get, requests.post = _fake_kinde(worker_name, token_requests) + + from flask import Flask, jsonify, redirect + + import kinde_sdk.auth.oauth as oauth_module + from kinde_sdk.auth.oauth import OAuth + + oauth_module.helper_get_user_details = AsyncMock(return_value={"id": "kp_user"}) + + app = Flask(__name__) + app.testing = True + oauth = OAuth( + client_id="test_client_id", + client_secret="test_client_secret", + redirect_uri="http://localhost/callback", + framework="flask", + app=app, + host=HOST, + ) + + def token_manager(): + user_id = oauth._framework.get_user_id() + return oauth._session_manager.get_token_manager(user_id) if user_id else None + + @app.route("/payouts") + def payouts(): + if not oauth.is_authenticated(): + return redirect("/login") + if not oauth.has_authentication_context(acr="mfa"): + return redirect(asyncio.run(oauth.step_up(acr="mfa"))) + return "payouts" + + @app.route("/whoami") + def whoami(): + authenticated = oauth.is_authenticated() + manager = token_manager() + return jsonify( + worker=worker_name, + authenticated=authenticated, + acr=oauth.get_authentication_context()["acr"], + access_token=( + manager.get_claims("access_token").get("jti") if manager else None + ), + refresh_token=manager.tokens.get("refresh_token") if manager else None, + ) + + @app.route("/expire") + def expire(): + token_manager().tokens["expires_at"] = time.time() - 1 + return "expired" + + client = app.test_client() + while True: + message = connection.recv() + if message is None: + break + path, cookie = message + try: + client.delete_cookie("session") + if cookie: + client.set_cookie("session", cookie) + sent = len(token_requests) + response = client.get(path) + for header in response.headers.getlist("Set-Cookie"): + if header.startswith("session="): + cookie = header.split(";")[0].split("=", 1)[1] + connection.send( + { + "status": response.status_code, + "location": response.headers.get("Location"), + "body": response.get_data(as_text=True), + "json": response.get_json(silent=True), + "cookie": cookie, + "token_requests": token_requests[sent:], + } + ) + except Exception: + connection.send({"error": traceback.format_exc()}) diff --git a/testv2/testv2_auth/test_step_up.py b/testv2/testv2_auth/test_step_up.py new file mode 100644 index 00000000..349ac994 --- /dev/null +++ b/testv2/testv2_auth/test_step_up.py @@ -0,0 +1,1374 @@ +""" +Step-up authentication (RFC 9470), phase 1: core behaviour. + +Every test runs against a real OAuth client with in-memory storage. The +network is replaced by the ``http`` fixture in ``testv2/conftest.py``, so +nothing leaves the machine. +""" + +import asyncio +import copy +import threading +import time +from unittest.mock import MagicMock + +import jwt +import pytest +import requests + +from kinde_sdk import AcrValues +from kinde_sdk.auth.async_oauth import AsyncOAuth +from kinde_sdk.auth.enums import PromptTypes +from kinde_sdk.auth.login_options import LoginOptions +from kinde_sdk.auth.oauth import OAuth +from kinde_sdk.auth.smart_oauth import SmartOAuth +from kinde_sdk.auth.step_up import ( + authentication_context_from_claims, + discovery_supports_step_up, + has_authentication_context, + normalize_acr_values, + normalize_max_age, + normalize_step_up_auth_param, + strongest_acr, +) +from kinde_sdk.core.exceptions import ( + KindeCallbackError, + KindeConfigurationException, + KindeLoginException, + KindeRetrieveException, + LoginRequiredError, + UnmetAuthenticationRequirementsError, +) +from kinde_sdk.core.framework.null_framework import NullFramework +from kinde_sdk.core.storage.storage_manager import StorageManager +from testv2.step_up_helpers import ( + CLIENT_ID, + HOST, + WITHOUT_STEP_UP, + query, + token_response, +) + +USER_ID = "session_1" + +# Login URLs produced by main before step-up was added (fixed state, nonce and challenge) +FIXED = { + "state": "fixed_state", + "nonce": "fixed_nonce", + "code_challenge": "fixed_challenge", +} +LOGIN_URL_BEFORE = ( + "https://test.kinde.com/oauth2/auth?client_id=test_client_id&response_type=code" + "&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=openid+profile+email" + "&supports_reauth=true&state=fixed_state&nonce=fixed_nonce" + "&code_challenge=fixed_challenge&code_challenge_method=S256" +) +REGISTER_URL_BEFORE = ( + "https://test.kinde.com/oauth2/auth?client_id=test_client_id&response_type=code" + "&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=openid+profile+email" + "&prompt=create&supports_reauth=true&state=fixed_state&nonce=fixed_nonce" + "&code_challenge=fixed_challenge&code_challenge_method=S256" +) +AUTH_PARAMS_URL_BEFORE = ( + "https://test.kinde.com/oauth2/auth?client_id=test_client_id&response_type=code" + "&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=openid+profile+email" + "&org_code=org_1&supports_reauth=true&custom=x&empty=&state=fixed_state&nonce=fixed_nonce" + "&code_challenge=fixed_challenge&code_challenge_method=S256" +) + + +def make_client(cls=OAuth): + return cls( + client_id="test_client_id", + client_secret="test_client_secret", + redirect_uri="http://localhost:8000/callback", + host=HOST, + ) + + +@pytest.fixture +def oauth(http): + return make_client() + + +async def complete_callback(client, http, url, response, user_id=USER_ID): + """Finish the authorization request behind ``url`` with a token response.""" + http.token_responses.append(response) + result = await client.handle_redirect("auth_code", user_id, query(url)["state"]) + NullFramework().set_user_id(user_id) + return result + + +async def sign_in(client, http, response=None, user_id=USER_ID): + response = response or token_response( + "login", id_claims={"auth_time": int(time.time()) - 3600} + ) + return await complete_callback( + client, http, await client.login(), response, user_id + ) + + +def stored_state(): + return StorageManager().get("user:state") + + +def jwt_encode(claims): + return jwt.encode(claims, "k" * 32, algorithm="HS256") + + +# --------------------------------------------------------------------------- +# Login options +# --------------------------------------------------------------------------- + + +class TestLoginOptions: + async def test_login_url_is_unchanged_without_the_new_options(self, oauth): + assert await oauth.login(dict(FIXED)) == LOGIN_URL_BEFORE + assert await oauth.register(dict(FIXED)) == REGISTER_URL_BEFORE + + async def test_existing_auth_params_passthrough_is_unchanged(self, oauth): + options = { + **FIXED, + "org_code": "org_1", + "auth_params": {"custom": "x", "empty": None}, + } + assert await oauth.login(options) == AUTH_PARAMS_URL_BEFORE + + @pytest.mark.parametrize("method", ["login", "register"]) + async def test_acr_values_is_sent(self, oauth, method): + url = await getattr(oauth, method)({LoginOptions.ACR_VALUES: "mfa"}) + assert query(url)["acr_values"] == "mfa" + assert "max_age" not in query(url) + + @pytest.mark.parametrize("method", ["login", "register"]) + async def test_acr_values_list_is_space_joined(self, oauth, method): + url = await getattr(oauth, method)({LoginOptions.ACR_VALUES: ["mfa", "phr"]}) + assert query(url)["acr_values"] == "mfa phr" + # urlencode writes the space as "+", as it already does for scope + assert "acr_values=mfa+phr" in url + + async def test_acr_values_accepts_the_constants_and_is_lower_cased(self, oauth): + url = await oauth.login({LoginOptions.ACR_VALUES: AcrValues.PHR}) + assert query(url)["acr_values"] == "phr" + url = await oauth.login({LoginOptions.ACR_VALUES: "MFA"}) + assert query(url)["acr_values"] == "mfa" + + @pytest.mark.parametrize("method", ["login", "register"]) + async def test_max_age_zero_is_sent(self, oauth, method): + url = await getattr(oauth, method)({LoginOptions.MAX_AGE: 0}) + assert query(url)["max_age"] == "0" + + async def test_max_age_is_sent_as_a_decimal_string(self, oauth): + url = await oauth.login({LoginOptions.MAX_AGE: 300}) + assert "max_age=300" in url + + @pytest.mark.parametrize( + "options", + [ + {}, + {LoginOptions.MAX_AGE: None}, + {LoginOptions.ACR_VALUES: None}, + {LoginOptions.AUTH_PARAMS: {"max_age": None}}, + {LoginOptions.AUTH_PARAMS: {"max_age": ""}}, + {LoginOptions.AUTH_PARAMS: {"max_age": " "}}, + {LoginOptions.AUTH_PARAMS: {"acr_values": None}}, + {LoginOptions.AUTH_PARAMS: {"acr_values": ""}}, + {LoginOptions.AUTH_PARAMS: {"acr_values": []}}, + ], + ) + @pytest.mark.parametrize("method", ["login", "register"]) + async def test_unset_values_are_never_sent(self, oauth, method, options): + url = await getattr(oauth, method)(dict(options)) + assert "max_age" not in query(url) + assert "acr_values" not in query(url) + assert "max_age" not in url and "acr_values" not in url + + @pytest.mark.parametrize( + "value", [-1, 1.5, 300.0, True, False, "300", "", "NaN", float("nan"), [300]] + ) + @pytest.mark.parametrize("method", ["login", "register"]) + async def test_invalid_max_age_is_rejected_before_the_url_is_built( + self, oauth, method, value + ): + with pytest.raises(ValueError, match="max_age"): + await getattr(oauth, method)({LoginOptions.MAX_AGE: value}) + assert stored_state() is None + + @pytest.mark.parametrize( + "value", ["undefined", "null", "NaN", "-1", "1.5", "five", -1, 1.5, True] + ) + async def test_invalid_max_age_in_auth_params_is_rejected(self, oauth, value): + with pytest.raises(ValueError, match="max_age"): + await oauth.login({LoginOptions.AUTH_PARAMS: {"max_age": value}}) + assert stored_state() is None + + @pytest.mark.parametrize( + "value, sent", [(0, "0"), (300, "300"), ("300", "300"), (" 60 ", "60")] + ) + async def test_valid_max_age_in_auth_params_is_sent(self, oauth, value, sent): + url = await oauth.login({LoginOptions.AUTH_PARAMS: {"max_age": value}}) + assert query(url)["max_age"] == sent + + async def test_acr_values_in_auth_params_is_passed_through(self, oauth): + url = await oauth.login( + {LoginOptions.AUTH_PARAMS: {"acr_values": ["mfa", "phr"]}} + ) + assert query(url)["acr_values"] == "mfa phr" + # A raw passthrough keeps accepting values Kinde reads as mfa + url = await oauth.login( + {LoginOptions.AUTH_PARAMS: {"acr_values": "urn:okta:loa:2fa:any"}} + ) + assert query(url)["acr_values"] == "urn:okta:loa:2fa:any" + + @pytest.mark.parametrize( + "value", ["", " ", [], "gold", ["mfa", "gold"], 1, ["mfa", 2], {"mfa"}] + ) + async def test_invalid_acr_values_is_rejected(self, oauth, value): + with pytest.raises(ValueError, match="acr"): + await oauth.login({LoginOptions.ACR_VALUES: value}) + assert stored_state() is None + + +class TestNormalizers: + def test_normalize_acr_values(self): + assert normalize_acr_values("mfa") == "mfa" + assert normalize_acr_values("phr mfa") == "phr mfa" + assert normalize_acr_values(("MFA", "mfa", "Phr")) == "mfa phr" + + def test_normalize_max_age(self): + assert normalize_max_age(0) == 0 + assert normalize_max_age(300) == 300 + + def test_normalize_step_up_auth_param_rejects_other_keys(self): + with pytest.raises(ValueError): + normalize_step_up_auth_param("prompt", "none") + + def test_strongest_acr(self): + assert strongest_acr(None) is None + assert strongest_acr("mfa") == "mfa" + assert strongest_acr("mfa phr") == "phr" + assert strongest_acr(["PHR", "mfa"]) == "phr" + assert strongest_acr("gold") is None + assert strongest_acr("urn:okta:loa:2fa:any") == "mfa" + assert strongest_acr("urn:okta:loa:2fa:any:ifpossible") is None + + +# --------------------------------------------------------------------------- +# step_up() +# --------------------------------------------------------------------------- + + +class TestStepUp: + async def test_step_up_is_an_interactive_login_with_the_extra_options(self, oauth): + url = await oauth.step_up(acr="mfa", max_age=300) + params = query(url) + + assert url.startswith(f"{HOST}/oauth2/auth?") + assert params["acr_values"] == "mfa" + assert params["max_age"] == "300" + assert "prompt" not in params + # The SDK's usual state, nonce and PKCE handling is reused + assert params["state"] == stored_state()["value"] + assert params["nonce"] == StorageManager().get("user:nonce")["value"] + assert params["code_challenge"] and params["code_challenge_method"] == "S256" + assert StorageManager().get("user:code_verifier")["value"] + assert params["supports_reauth"] == "true" + + async def test_step_up_with_acr_only_or_max_age_only(self, oauth): + params = query(await oauth.step_up(acr=AcrValues.PHR)) + assert params["acr_values"] == "phr" and "max_age" not in params + + params = query(await oauth.step_up(max_age=0)) + assert params["max_age"] == "0" and "acr_values" not in params + + async def test_step_up_keeps_the_usual_login_options(self, oauth): + url = await oauth.step_up( + acr="mfa", login_options={"org_code": "org_1", "lang": "fr"} + ) + params = query(url) + assert params["org_code"] == "org_1" and params["lang"] == "fr" + + async def test_step_up_reads_the_options_from_login_options_too(self, oauth): + options = {LoginOptions.ACR_VALUES: "mfa", LoginOptions.MAX_AGE: 60} + params = query(await oauth.step_up(login_options=options)) + assert params["acr_values"] == "mfa" and params["max_age"] == "60" + assert options == { + LoginOptions.ACR_VALUES: "mfa", + LoginOptions.MAX_AGE: 60, + } # not mutated + + params = query( + await oauth.step_up( + login_options={"auth_params": {"acr_values": "phr", "max_age": "0"}} + ) + ) + assert params["acr_values"] == "phr" and params["max_age"] == "0" + + @pytest.mark.parametrize( + "login_options", + [ + {LoginOptions.PROMPT: "none"}, + {LoginOptions.PROMPT: "NONE"}, + {LoginOptions.PROMPT: PromptTypes.NONE}, + {LoginOptions.PROMPT: "login none"}, + {LoginOptions.AUTH_PARAMS: {"prompt": "none"}}, + { + LoginOptions.PROMPT: "login", + LoginOptions.AUTH_PARAMS: {"prompt": "none"}, + }, + ], + ) + async def test_step_up_rejects_prompt_none(self, oauth, login_options): + with pytest.raises(ValueError, match="prompt=none"): + await oauth.step_up(acr="mfa", login_options=login_options) + assert stored_state() is None + + async def test_step_up_allows_other_prompts(self, oauth): + params = query( + await oauth.step_up(acr="mfa", login_options={LoginOptions.PROMPT: "login"}) + ) + assert params["prompt"] == "login" + + async def test_step_up_requires_something_to_step_up_to(self, oauth): + with pytest.raises(ValueError, match="requires acr, max_age"): + await oauth.step_up() + with pytest.raises(ValueError, match="requires acr, max_age"): + await oauth.step_up(login_options={"org_code": "org_1"}) + + @pytest.mark.parametrize( + "kwargs", + [ + {"acr": "gold"}, + {"acr": ""}, + {"max_age": -1}, + {"max_age": 1.5}, + {"max_age": True}, + {"acr": "mfa", "max_age": "300"}, + {"login_options": {"auth_params": {"acr_values": "gold"}}}, + {"acr": "mfa", "login_options": {"auth_params": {"max_age": "undefined"}}}, + ], + ) + async def test_step_up_rejects_invalid_requests(self, oauth, kwargs): + with pytest.raises(ValueError): + await oauth.step_up(**kwargs) + assert stored_state() is None + + async def test_step_up_keeps_the_current_tokens(self, oauth, http): + await sign_in(oauth, http) + before = dict(oauth.get_tokens(USER_ID)) + + await oauth.step_up(acr="mfa") + + after = oauth.get_tokens(USER_ID) + assert after["access_token"] == before["access_token"] + assert after["refresh_token"] == before["refresh_token"] + assert oauth.is_authenticated() + + async def test_step_up_asks_the_framework_to_bring_the_user_back(self, oauth): + oauth._framework = MagicMock() + + await oauth.step_up(acr="mfa") + oauth._framework.set_post_login_redirect_url.assert_called_once_with(None) + + oauth._framework.reset_mock() + await oauth.step_up(acr="mfa", post_login_redirect_url="/payouts") + oauth._framework.set_post_login_redirect_url.assert_called_once_with("/payouts") + + # A rejected request leaves the framework's redirect alone + oauth._framework.reset_mock() + with pytest.raises(ValueError): + await oauth.step_up(acr="mfa", login_options={LoginOptions.PROMPT: "none"}) + oauth._framework.set_post_login_redirect_url.assert_not_called() + + async def test_step_up_works_without_a_framework_integration(self, oauth): + # NullFramework inherits the no-op hook + assert NullFramework().set_post_login_redirect_url("/payouts") is None + assert await oauth.step_up(acr="mfa", post_login_redirect_url="/payouts") + + +class TestStepUpWithoutDiscoverySupport: + @pytest.fixture + def oauth(self, http): + http.discovery = WITHOUT_STEP_UP + return make_client() + + async def test_acr_raises_a_not_supported_error(self, oauth): + with pytest.raises(KindeConfigurationException, match="not supported"): + await oauth.step_up(acr="mfa") + with pytest.raises(KindeConfigurationException, match="not supported"): + await oauth.step_up(acr="mfa", max_age=300) + assert stored_state() is None + + async def test_max_age_raises_too(self, oauth): + # Kinde would ignore max_age, and auth_time is not reported here, so a + # fallback sign-in could never satisfy has_authentication_context() + with pytest.raises(KindeConfigurationException, match="not supported"): + await oauth.step_up(max_age=300) + with pytest.raises(KindeConfigurationException, match="prompt=login"): + await oauth.step_up(login_options={"auth_params": {"max_age": "300"}}) + assert stored_state() is None + + async def test_guard_on_max_age_cannot_loop(self, oauth, http): + await sign_in(oauth, http) + http.post.reset_mock() + + # The check an app would guard a page with is never met here... + assert oauth.has_authentication_context(max_age=300) is False + # ...and the step-up it would start raises every time, instead of redirecting + for _ in range(3): + with pytest.raises(KindeConfigurationException): + await oauth.step_up(max_age=300) + http.post.assert_not_called() + + async def test_login_options_are_still_sent_as_given(self, oauth): + # login() is a plain passthrough: only step_up() consults discovery + params = query( + await oauth.login({LoginOptions.ACR_VALUES: "mfa", LoginOptions.MAX_AGE: 0}) + ) + assert params["acr_values"] == "mfa" and params["max_age"] == "0" + + +# --------------------------------------------------------------------------- +# Callback errors +# --------------------------------------------------------------------------- + + +class TestCallbackErrors: + async def test_unmet_authentication_requirements_reaches_the_app(self, oauth, http): + await sign_in(oauth, http) + tokens_before = dict(oauth.get_tokens(USER_ID)) + state = query(await oauth.step_up(acr="phr", max_age=300))["state"] + http.post.reset_mock() + + with pytest.raises(UnmetAuthenticationRequirementsError) as raised: + await oauth.handle_redirect( + None, + USER_ID, + state, + error="unmet_authentication_requirements", + error_description="The requested authentication context could not be met", + ) + + error = raised.value + assert error.error == "unmet_authentication_requirements" + assert ( + error.error_description + == "The requested authentication context could not be met" + ) + assert error.state == state + assert str(error) == "The requested authentication context could not be met" + # What the step-up asked for, so the app can say what is missing + assert error.acr_values == "phr" + assert error.max_age == 300 + assert isinstance(error, KindeCallbackError) and isinstance( + error, KindeLoginException + ) + + # No retry, no token request, and the user is still signed in with the same tokens + http.post.assert_not_called() + assert oauth.is_authenticated() + assert ( + oauth.get_tokens(USER_ID)["access_token"] == tokens_before["access_token"] + ) + assert ( + oauth.get_tokens(USER_ID)["refresh_token"] == tokens_before["refresh_token"] + ) + + async def test_login_required_has_its_own_error(self, oauth): + state = query( + await oauth.login({LoginOptions.PROMPT: "none", LoginOptions.MAX_AGE: 300}) + )["state"] + + with pytest.raises(LoginRequiredError) as raised: + await oauth.handle_redirect(None, None, state, error="login_required") + + assert raised.value.error == "login_required" + assert raised.value.error_description == "" + assert raised.value.state == state + assert str(raised.value) == "login_required" + assert not isinstance(raised.value, UnmetAuthenticationRequirementsError) + + async def test_other_errors_are_reported_with_their_code(self, oauth): + state = query(await oauth.login())["state"] + + with pytest.raises(KindeCallbackError) as raised: + await oauth.handle_redirect( + None, None, state, error="access_denied", error_description="Denied" + ) + + assert type(raised.value) is KindeCallbackError + assert raised.value.error == "access_denied" + assert raised.value.error_description == "Denied" + + @pytest.mark.parametrize( + "error", ["unmet_authentication_requirements", "login_required"] + ) + @pytest.mark.parametrize("state", [None, "", "not-the-stored-state"]) + async def test_state_is_validated_before_the_error_is_reported( + self, oauth, error, state + ): + await oauth.step_up(acr="mfa") + + with pytest.raises(KindeLoginException, match="Invalid state") as raised: + await oauth.handle_redirect(None, None, state, error=error) + + assert not isinstance(raised.value, KindeCallbackError) + # The genuine request is still pending + assert stored_state() is not None + + async def test_error_without_a_pending_request_fails_state_validation(self, oauth): + with pytest.raises(KindeLoginException, match="Invalid state"): + await oauth.handle_redirect( + None, None, "anything", error="unmet_authentication_requirements" + ) + + async def test_error_callback_cannot_be_replayed(self, oauth, http): + state = query(await oauth.step_up(acr="mfa"))["state"] + with pytest.raises(UnmetAuthenticationRequirementsError): + await oauth.handle_redirect( + None, None, state, error="unmet_authentication_requirements" + ) + + # The request is finished: nothing is left to resume or retry + for key in ("user:state", "user:nonce", "user:code_verifier", "user:step_up"): + assert StorageManager().get(key) is None + with pytest.raises(KindeLoginException, match="Invalid state"): + await oauth.handle_redirect( + None, None, state, error="unmet_authentication_requirements" + ) + with pytest.raises(KindeLoginException, match="Invalid state"): + await oauth.handle_redirect("auth_code", USER_ID, state) + http.post.assert_not_called() + + async def test_error_takes_precedence_over_a_code(self, oauth, http): + state = query(await oauth.step_up(acr="mfa"))["state"] + with pytest.raises(UnmetAuthenticationRequirementsError): + await oauth.handle_redirect( + "auth_code", USER_ID, state, error="unmet_authentication_requirements" + ) + http.post.assert_not_called() + + async def test_request_details_are_not_taken_from_another_request(self, oauth): + await oauth.step_up(acr="phr") + # A later plain login replaces the pending request + state = query(await oauth.login())["state"] + + with pytest.raises(UnmetAuthenticationRequirementsError) as raised: + await oauth.handle_redirect( + None, None, state, error="unmet_authentication_requirements" + ) + + assert raised.value.acr_values is None and raised.value.max_age is None + + +# --------------------------------------------------------------------------- +# Session update +# --------------------------------------------------------------------------- + + +class TestSessionUpdate: + async def test_successful_step_up_replaces_all_three_tokens(self, oauth, http): + first = token_response("login", id_claims={"auth_time": 1000}) + await sign_in(oauth, http, first) + assert oauth.get_authentication_context()["acr"] is None + + second = token_response( + "step-up", + access_claims={"acr": "mfa"}, + id_claims={"acr": "mfa", "amr": ["pwd", "totp"], "auth_time": 2000}, + ) + # The user is already signed in: the callback is processed all the same + assert oauth.is_authenticated() + await complete_callback(oauth, http, await oauth.step_up(acr="mfa"), second) + + tokens = oauth.get_tokens(USER_ID) + assert tokens["access_token"] == second["access_token"] != first["access_token"] + assert tokens["id_token"] == second["id_token"] != first["id_token"] + assert tokens["refresh_token"] == "refresh-step-up" + assert oauth.get_authentication_context() == { + "acr": "mfa", + "amr": ["pwd", "totp"], + "auth_time": 2000, + } + assert StorageManager().get("user:step_up") is None + # The stored session matches what is in memory + assert ( + StorageManager().get(USER_ID)["tokens"]["refresh_token"] + == "refresh-step-up" + ) + + async def test_tokens_from_before_the_step_up_are_never_kept(self, oauth, http): + await sign_in( + oauth, http, token_response("login", id_claims={"auth_time": 1000}) + ) + + # The step-up response has no refresh token and no ID token + second = token_response( + "step-up", access_claims={"acr": "mfa"}, refresh=False, id_token=False + ) + await complete_callback(oauth, http, await oauth.step_up(acr="mfa"), second) + + token_manager = oauth._session_manager.get_token_manager(USER_ID) + assert "refresh_token" not in token_manager.tokens + assert "id_token" not in token_manager.tokens + assert token_manager.get_claims("id_token") == {} + assert token_manager.tokens["access_token"] == second["access_token"] + + async def test_refresh_after_step_up_uses_the_new_refresh_token(self, oauth, http): + await sign_in(oauth, http) + stepped_up = token_response( + "step-up", access_claims={"acr": "mfa"}, id_claims={"acr": "mfa"} + ) + await complete_callback(oauth, http, await oauth.step_up(acr="mfa"), stepped_up) + + token_manager = oauth._session_manager.get_token_manager(USER_ID) + token_manager.tokens["expires_at"] = time.time() - 1 + refreshed = token_response( + "refreshed", access_claims={"acr": "mfa"}, refresh=False, id_token=False + ) + http.token_responses.append(refreshed) + http.post.reset_mock() + + assert token_manager.get_access_token() == refreshed["access_token"] + + assert len(http.token_requests) == 1 + assert http.token_requests[0]["grant_type"] == "refresh_token" + assert http.token_requests[0]["refresh_token"] == "refresh-step-up" + # A refresh merges: the stepped-up ID token and refresh token stay + assert oauth.get_authentication_context()["acr"] == "mfa" + assert token_manager.tokens["refresh_token"] == "refresh-step-up" + + async def test_has_authentication_context_never_refreshes_to_satisfy_a_step_up( + self, oauth, http + ): + await sign_in(oauth, http) + http.post.reset_mock() + + assert oauth.has_authentication_context(acr="mfa") is False + + http.post.assert_not_called() + + +class TestStepUpKeepsTheRefreshToken: + """Kinde only returns a refresh token when the ``offline`` scope is requested.""" + + async def test_offline_is_requested_when_the_session_has_a_refresh_token( + self, oauth, http + ): + await sign_in(oauth, http) + assert oauth.get_tokens(USER_ID)["refresh_token"] == "refresh-login" + + url = await oauth.step_up(acr="mfa") + assert query(url)["scope"] == "openid profile email offline" + + await complete_callback( + oauth, http, url, token_response("step-up", id_claims={"acr": "mfa"}) + ) + assert oauth.get_tokens(USER_ID)["refresh_token"] == "refresh-step-up" + + async def test_scope_is_unchanged_without_a_refresh_token(self, oauth, http): + # Not signed in + assert query(await oauth.step_up(acr="mfa"))["scope"] == "openid profile email" + + await sign_in(oauth, http, token_response("login", refresh=False)) + assert query(await oauth.step_up(acr="mfa"))["scope"] == "openid profile email" + + @pytest.mark.parametrize( + "login_options, expected", + [ + ({"scope": "openid profile"}, "openid profile offline"), + ({"scope": "openid offline email"}, "openid offline email"), + ({"auth_params": {"scope": "openid"}}, "openid offline"), + ( + {"scope": "openid", "auth_params": {"scope": "openid offline"}}, + "openid offline", + ), + ], + ) + async def test_offline_is_added_once_to_the_scope_that_is_sent( + self, oauth, http, login_options, expected + ): + await sign_in(oauth, http) + passed = copy.deepcopy(login_options) + url = await oauth.step_up(acr="mfa", login_options=passed) + assert query(url)["scope"] == expected + # The caller's options are not modified + assert passed == login_options + + +class TestIdTokenValidation: + """The ID token's claims decide has_authentication_context(), so the callback checks it.""" + + @pytest.mark.parametrize( + "id_claims", + [ + {"nonce": "not-the-nonce-of-this-login"}, + {"aud": ["another_client"]}, + {"iss": "https://someone-else.kinde.com"}, + {"exp": int(time.time()) - 3600}, + ], + ids=["nonce", "audience", "issuer", "expired"], + ) + async def test_id_token_that_is_not_for_this_login_is_rejected( + self, oauth, http, id_claims + ): + await sign_in(oauth, http) + before = dict(oauth.get_tokens(USER_ID)) + + forged = token_response( + "forged", + id_claims={"acr": "mfa", "auth_time": int(time.time()), **id_claims}, + ) + with pytest.raises(KindeLoginException, match="ID token"): + await complete_callback(oauth, http, await oauth.step_up(acr="mfa"), forged) + + # Nothing was stored: the session is as it was, without the forged acr + assert oauth.get_tokens(USER_ID) == before + assert oauth.has_authentication_context(acr="mfa") is False + + @pytest.mark.parametrize("missing", ["nonce", "aud", "iss", "exp"]) + async def test_id_token_must_carry_each_checked_claim(self, oauth, http, missing): + url = await oauth.login() + claims = { + "sub": "kp_user", + "iss": HOST, + "aud": [CLIENT_ID], + "exp": int(time.time()) + 3600, + "nonce": query(url)["nonce"], + } + del claims[missing] + response = token_response("login") + response["id_token"] = jwt_encode(claims) + if missing == "nonce": + http.nonce = None # the fake Kinde leaves the nonce out too + + with pytest.raises(KindeLoginException, match="ID token"): + await complete_callback(oauth, http, url, response) + assert oauth.is_authenticated() is False + + async def test_audience_may_be_a_string_and_the_issuer_may_end_in_a_slash( + self, oauth, http + ): + response = token_response( + "login", id_claims={"aud": CLIENT_ID, "iss": f"{HOST}/"} + ) + await sign_in(oauth, http, response) + assert oauth.is_authenticated() is True + + async def test_nonce_is_single_use(self, oauth, http): + url = await oauth.login() + with pytest.raises(KindeLoginException, match="ID token"): + await complete_callback( + oauth, http, url, token_response("first", id_claims={"aud": ["x"]}) + ) + + # The same request can't be finished a second time, even with a good token + with pytest.raises(KindeLoginException, match="nonce"): + await complete_callback(oauth, http, url, token_response("second")) + assert StorageManager().get("user:nonce") is None + + async def test_response_without_an_id_token_is_still_accepted(self, oauth, http): + response = token_response( + "login", access_claims={"acr": "mfa"}, id_token=False + ) + await sign_in(oauth, http, response) + + assert oauth.is_authenticated() is True + assert oauth.get_authentication_context()["acr"] == "mfa" + + +# --------------------------------------------------------------------------- +# get_authentication_context() +# --------------------------------------------------------------------------- + + +class TestGetAuthenticationContext: + def test_without_a_signed_in_user(self, oauth): + assert oauth.get_authentication_context() == { + "acr": None, + "amr": [], + "auth_time": None, + } + + async def test_single_factor_sign_in_has_no_acr_or_amr(self, oauth, http): + await sign_in( + oauth, http, token_response("login", id_claims={"auth_time": 1716800000}) + ) + assert oauth.get_authentication_context() == { + "acr": None, + "amr": [], + "auth_time": 1716800000, + } + + async def test_reads_acr_amr_and_auth_time(self, oauth, http): + id_claims = {"acr": "mfa", "amr": ["pwd", "totp"], "auth_time": 1716800000} + await sign_in( + oauth, + http, + token_response("login", access_claims={"acr": "mfa"}, id_claims=id_claims), + ) + assert oauth.get_authentication_context() == { + "acr": "mfa", + "amr": ["pwd", "totp"], + "auth_time": 1716800000, + } + + async def test_auth_time_comes_from_the_id_token(self, oauth, http): + response = token_response( + "login", access_claims={"auth_time": 1111}, id_claims={"auth_time": 2222} + ) + await sign_in(oauth, http, response) + assert oauth.get_authentication_context()["auth_time"] == 2222 + + async def test_access_token_is_the_fallback_without_an_id_token(self, oauth, http): + response = token_response( + "login", + access_claims={"acr": "phr", "amr": ["passkey"], "auth_time": 1111}, + id_token=False, + ) + await sign_in(oauth, http, response) + assert oauth.get_authentication_context() == { + "acr": "phr", + "amr": ["passkey"], + "auth_time": 1111, + } + + async def test_auth_time_is_not_reported_without_discovery_support(self, http): + http.discovery = WITHOUT_STEP_UP + oauth = make_client() + await sign_in( + oauth, http, token_response("login", id_claims={"auth_time": 1716800000}) + ) + + assert oauth.get_authentication_context() == { + "acr": None, + "amr": [], + "auth_time": None, + } + assert oauth.has_authentication_context(max_age=10**12) is False + + def test_malformed_claims_are_ignored(self): + context = authentication_context_from_claims( + {"acr": ["mfa"], "amr": "pwd", "auth_time": "soon"}, + {"acr": 2, "amr": None, "auth_time": True}, + ) + assert context == {"acr": None, "amr": [], "auth_time": None} + assert authentication_context_from_claims(None, None) == { + "acr": None, + "amr": [], + "auth_time": None, + } + + def test_tokens_of_different_users_give_no_context(self): + context = authentication_context_from_claims( + {"sub": "kp_one", "acr": "mfa", "auth_time": 1}, + {"sub": "kp_two", "acr": "mfa"}, + ) + assert context == {"acr": None, "amr": [], "auth_time": None} + + @pytest.mark.parametrize( + "id_claims, access_claims", + [ + ({"acr": "mfa", "auth_time": 1}, {"sub": "kp_one", "acr": "mfa"}), # no sub + ({"sub": "", "acr": "mfa"}, {"sub": "kp_one"}), + ({"sub": "kp_one", "acr": "mfa"}, {"acr": "mfa"}), # nothing to match + ({"sub": "kp_one", "acr": "mfa"}, None), + ], + ) + def test_id_token_is_only_trusted_when_its_user_matches_the_access_token( + self, id_claims, access_claims + ): + context = authentication_context_from_claims(id_claims, access_claims) + assert context == {"acr": None, "amr": [], "auth_time": None} + + def test_access_token_is_used_when_there_is_no_id_token(self): + context = authentication_context_from_claims( + None, {"sub": "kp_one", "acr": "mfa", "auth_time": 5} + ) + assert context == {"acr": "mfa", "amr": [], "auth_time": 5} + + +# --------------------------------------------------------------------------- +# has_authentication_context() +# --------------------------------------------------------------------------- + +NOW = 1_716_800_000 + + +class TestHasAuthenticationContext: + @pytest.mark.parametrize( + "token_acr, required_acr, expected", + [ + (None, None, True), # absent / none -> meets + (None, "mfa", False), # absent / mfa -> doesn't meet + ("mfa", "mfa", True), + ("mfa", "phr", False), + ("phr", "mfa", True), + ("phr", "phr", True), + (None, "phr", False), + ("mfa", None, True), + ("gold", "mfa", False), # Kinde only returns mfa or phr + ("MFA", "mfa", True), + ("mfa", ["mfa", "phr"], False), # the highest requested context applies + ("phr", ["mfa", "phr"], True), + ], + ) + def test_acr_table(self, token_acr, required_acr, expected): + context = {"acr": token_acr, "amr": [], "auth_time": NOW} + assert ( + has_authentication_context(context, acr=required_acr, now=NOW) is expected + ) + + @pytest.mark.parametrize("token_acr", [None, "mfa", "phr"]) + def test_max_age_with_missing_auth_time_does_not_meet(self, token_acr): + context = {"acr": token_acr, "amr": [], "auth_time": None} + assert has_authentication_context(context, max_age=300, now=NOW) is False + assert ( + has_authentication_context({"acr": token_acr}, max_age=300, now=NOW) + is False + ) + assert ( + has_authentication_context(context, acr=token_acr, max_age=10**9, now=NOW) + is False + ) + + @pytest.mark.parametrize( + "age, max_age, leeway, expected", + [ + (0, 300, 0, True), + (300, 300, 0, True), # now - auth_time <= max_age + (301, 300, 0, False), + (600, 300, 0, False), + (0, 0, 0, True), + (1, 0, 0, False), + (305, 300, 10, True), # clock tolerance + (311, 300, 10, False), + ], + ) + def test_max_age(self, age, max_age, leeway, expected): + context = {"acr": "mfa", "amr": [], "auth_time": NOW - age} + assert ( + has_authentication_context(context, max_age=max_age, now=NOW, leeway=leeway) + is expected + ) + + @pytest.mark.parametrize( + "ahead, leeway, expected", + [ + (86400, 0, False), # a future auth_time is invalid, not "very recent" + (61, 0, False), + (60, 0, True), # the two clocks disagreeing, right after a sign-in + (2, 0, True), + (90, 120, True), # a larger tolerance, when the caller asks for one + (121, 120, False), + ], + ) + def test_auth_time_in_the_future(self, ahead, leeway, expected): + context = {"acr": "mfa", "amr": [], "auth_time": NOW + ahead} + for max_age in (0, 60, 10**9): + assert ( + has_authentication_context( + context, max_age=max_age, now=NOW, leeway=leeway + ) + is expected + ) + # Only max_age looks at auth_time + assert has_authentication_context(context, acr="mfa", now=NOW) is True + + def test_both_requirements_must_be_met(self): + recent_single_factor = {"acr": None, "auth_time": NOW} + old_mfa = {"acr": "mfa", "auth_time": NOW - 3600} + recent_mfa = {"acr": "mfa", "auth_time": NOW - 10} + assert ( + has_authentication_context( + recent_single_factor, acr="mfa", max_age=300, now=NOW + ) + is False + ) + assert ( + has_authentication_context(old_mfa, acr="mfa", max_age=300, now=NOW) + is False + ) + assert ( + has_authentication_context(recent_mfa, acr="mfa", max_age=300, now=NOW) + is True + ) + + def test_amr_is_never_used_to_decide(self): + context = { + "acr": None, + "amr": ["pwd", "totp", "passkey", "mfa"], + "auth_time": NOW, + } + assert has_authentication_context(context, acr="mfa", now=NOW) is False + assert ( + has_authentication_context({"acr": "mfa", "amr": []}, acr="mfa", now=NOW) + is True + ) + + def test_uses_the_clock_by_default(self): + assert ( + has_authentication_context({"auth_time": int(time.time())}, max_age=60) + is True + ) + assert ( + has_authentication_context( + {"auth_time": int(time.time()) - 120}, max_age=60 + ) + is False + ) + + def test_works_on_verified_token_claims(self): + claims = { + "sub": "kp_user", + "acr": "phr", + "amr": ["passkey"], + "auth_time": NOW - 5, + } + assert ( + has_authentication_context(claims, acr="mfa", max_age=60, now=NOW) is True + ) + + @pytest.mark.parametrize( + "kwargs", + [ + {"acr": "gold"}, + {"acr": ""}, + {"max_age": -1}, + {"max_age": 1.5}, + {"max_age": True}, + ], + ) + def test_invalid_requirement_raises(self, oauth, kwargs): + with pytest.raises(ValueError): + has_authentication_context( + {"acr": "phr", "auth_time": NOW}, now=NOW, **kwargs + ) + # Also on the client, and before looking at the session + with pytest.raises(ValueError): + oauth.has_authentication_context(**kwargs) + + async def test_client_checks_the_current_session(self, oauth, http): + assert oauth.has_authentication_context() is False # nobody is signed in + assert oauth.has_authentication_context(acr="mfa") is False + + await sign_in( + oauth, + http, + token_response("login", id_claims={"auth_time": int(time.time()) - 3600}), + ) + assert oauth.has_authentication_context() is True + assert oauth.has_authentication_context(acr="mfa") is False + assert oauth.has_authentication_context(max_age=300) is False + assert oauth.has_authentication_context(max_age=7200) is True + + now = int(time.time()) + stepped_up = token_response( + "step-up", + id_claims={"acr": "mfa", "amr": ["pwd", "totp"], "auth_time": now}, + ) + await complete_callback( + oauth, http, await oauth.step_up(acr="mfa", max_age=300), stepped_up + ) + assert oauth.has_authentication_context(acr="mfa", max_age=300) is True + assert oauth.has_authentication_context(acr="phr") is False + + async def test_client_requires_a_live_session(self, oauth, http): + response = token_response( + "login", + id_claims={"acr": "mfa", "auth_time": int(time.time())}, + refresh=False, + ) + await sign_in(oauth, http, response) + assert oauth.has_authentication_context(acr="mfa") is True + + # Expired, and nothing to refresh with + oauth._session_manager.get_token_manager(USER_ID).tokens["expires_at"] = ( + time.time() - 1 + ) + assert oauth.has_authentication_context(acr="mfa") is False + + +# --------------------------------------------------------------------------- +# is_step_up_supported() +# --------------------------------------------------------------------------- + + +class TestIsStepUpSupported: + def test_true_when_discovery_lists_acr_values_supported(self, oauth, http): + assert oauth.is_step_up_supported() is True + assert oauth.is_step_up_supported() is True + # Cached with the rest of discovery: fetched once, when the client was created + assert http.get.call_count == 1 + + def test_false_when_discovery_lacks_it(self, http): + http.discovery = WITHOUT_STEP_UP + oauth = make_client() + assert oauth.is_step_up_supported() is False + assert oauth.is_step_up_supported() is False + assert http.get.call_count == 1 + + @pytest.mark.parametrize("value", [None, [], "mfa", {}]) + def test_false_for_empty_or_malformed_values(self, value): + assert discovery_supports_step_up({"acr_values_supported": value}) is False + assert discovery_supports_step_up(None) is False + assert discovery_supports_step_up({"acr_values_supported": ["mfa"]}) is True + + def test_failed_discovery_is_retried_at_most_once_a_minute(self, http): + http.discovery_status = 503 + oauth = make_client() + assert oauth.auth_url == f"{HOST}/oauth2/auth" # existing fallback + assert http.get.call_count == 1 + + assert oauth.is_step_up_supported() is False + assert oauth.is_step_up_supported() is False + assert http.get.call_count == 2 # one retry, then rate limited + + http.discovery_status = 200 + assert oauth.is_step_up_supported() is False # still inside the minute + oauth._openid_configuration_tried_at = 0 + assert oauth.is_step_up_supported() is True + assert oauth.is_step_up_supported() is True + assert http.get.call_count == 3 + + def test_discovery_errors_mean_not_supported(self, http): + http.get.side_effect = requests.ConnectionError("offline") + oauth = make_client() + assert oauth.is_step_up_supported() is False + + +class TestStepUpWhileDiscoveryIsUnavailable: + @pytest.fixture + def oauth(self, http): + # The environment supports step-up, but discovery fails as the client starts + http.discovery_status = 503 + return make_client() + + @pytest.mark.parametrize("kwargs", [{"acr": "mfa"}, {"max_age": 300}]) + async def test_step_up_raises_a_retryable_error(self, oauth, kwargs): + with pytest.raises(KindeRetrieveException, match="Try again") as raised: + await oauth.step_up(**kwargs) + + # Not the "this environment doesn't support step-up" answer + assert not isinstance(raised.value, KindeConfigurationException) + assert stored_state() is None + + async def test_step_up_works_within_seconds_of_discovery_coming_back( + self, oauth, http + ): + # Uses up this minute's retry (off the event loop, so it is done before going on) + assert await asyncio.to_thread(oauth.is_step_up_supported) is False + oauth._openid_configuration_tried_at -= 5 + with pytest.raises(KindeRetrieveException): + await oauth.step_up(acr="mfa") + + http.discovery_status = 200 + oauth._openid_configuration_tried_at -= 5 # a few seconds later + + params = query(await oauth.step_up(acr="mfa")) + assert params["acr_values"] == "mfa" + assert oauth.is_step_up_supported() is True + + async def test_step_up_does_not_fetch_discovery_on_every_call(self, oauth, http): + fetched = http.get.call_count + for _ in range(3): + with pytest.raises(KindeRetrieveException): + await oauth.step_up(acr="mfa") + # One attempt, then the next few seconds of calls fail without waiting on the host + assert http.get.call_count == fetched + 1 + + oauth._openid_configuration_tried_at -= 5 + with pytest.raises(KindeRetrieveException): + await oauth.step_up(acr="mfa") + assert http.get.call_count == fetched + 2 + + async def test_invalid_requests_are_rejected_before_discovery_is_tried( + self, oauth, http + ): + fetched = http.get.call_count + with pytest.raises(ValueError): + await oauth.step_up(acr="mfa", login_options={LoginOptions.PROMPT: "none"}) + assert http.get.call_count == fetched + + +class TestDiscoveryRetryOnAnEventLoop: + """The retry is a blocking request, so it must not run on the event loop's thread.""" + + @pytest.fixture + def oauth(self, http): + http.discovery_status = 503 + client = make_client() + http.discovery_status = 200 + return client + + @pytest.fixture + def fetches(self, http): + """Records the thread of each discovery fetch, and holds it until released.""" + serve = http.get.side_effect + + class Fetches: + threads = [] + release = threading.Event() + + def get(url, **kwargs): + Fetches.threads.append(threading.get_ident()) + assert Fetches.release.wait(5), "the fetch was never released" + return serve(url, **kwargs) + + http.get.side_effect = get + yield Fetches + Fetches.release.set() + + async def test_step_up_awaits_the_fetch_on_another_thread(self, oauth, fetches): + fetches.release.set() + + assert query(await oauth.step_up(acr="mfa"))["acr_values"] == "mfa" + assert len(fetches.threads) == 1 + assert fetches.threads[0] != threading.get_ident() + + async def test_checks_return_without_waiting_and_retry_in_the_background( + self, oauth, fetches + ): + # The fetch is held, and neither check waits for it + assert oauth.is_step_up_supported() is False + assert oauth.has_authentication_context(max_age=300) is False + assert oauth.is_step_up_supported() is False + + fetches.release.set() + for _ in range(200): + if oauth._openid_configuration is not None: + break + await asyncio.sleep(0.01) + + assert oauth.is_step_up_supported() is True + # One fetch, started by the first check, and not on the event loop's thread + assert len(fetches.threads) == 1 + assert fetches.threads[0] != threading.get_ident() + + async def test_step_up_waits_for_a_fetch_that_a_check_started(self, oauth, fetches): + assert oauth.is_step_up_supported() is False # starts the fetch, which is held + asyncio.get_running_loop().call_later(0.05, fetches.release.set) + + # Not "try again": the fetch in flight is awaited, and it succeeds + assert query(await oauth.step_up(acr="mfa"))["acr_values"] == "mfa" + assert len(fetches.threads) == 1 + + def test_checks_outside_an_event_loop_fetch_inline(self, oauth, fetches): + fetches.release.set() + + assert oauth.is_step_up_supported() is True + assert fetches.threads == [threading.get_ident()] + + +# --------------------------------------------------------------------------- +# Async and smart clients +# --------------------------------------------------------------------------- + + +class TestAsyncAndSmartClients: + @pytest.mark.parametrize("cls", [AsyncOAuth, SmartOAuth]) + async def test_full_step_up_flow(self, http, cls): + client = make_client(cls) + assert client.is_step_up_supported() is True + assert client.get_authentication_context() == { + "acr": None, + "amr": [], + "auth_time": None, + } + + await sign_in(client, http) + assert client.has_authentication_context(acr="mfa") is False + + url = await client.step_up(acr="mfa", max_age=300, login_options={"lang": "fr"}) + params = query(url) + assert ( + params["acr_values"] == "mfa" + and params["max_age"] == "300" + and params["lang"] == "fr" + ) + + now = int(time.time()) + stepped_up = token_response( + "step-up", + id_claims={"acr": "mfa", "amr": ["pwd", "totp"], "auth_time": now}, + ) + await complete_callback(client, http, url, stepped_up) + + assert client.get_authentication_context() == { + "acr": "mfa", + "amr": ["pwd", "totp"], + "auth_time": now, + } + assert client.has_authentication_context(acr="mfa", max_age=300) is True + assert client.get_tokens(USER_ID)["refresh_token"] == "refresh-step-up" + + @pytest.mark.parametrize("cls", [AsyncOAuth, SmartOAuth]) + async def test_callback_errors(self, http, cls): + client = make_client(cls) + + state = query(await client.step_up(acr="phr"))["state"] + with pytest.raises(UnmetAuthenticationRequirementsError) as raised: + await client.handle_redirect( + None, + None, + state, + error="unmet_authentication_requirements", + error_description="Not met", + ) + assert ( + raised.value.error_description == "Not met" and raised.value.state == state + ) + + state = query(await client.login({LoginOptions.PROMPT: "none"}))["state"] + with pytest.raises(LoginRequiredError): + await client.handle_redirect(None, None, state, error="login_required") + http.post.assert_not_called() + + @pytest.mark.parametrize("cls", [AsyncOAuth, SmartOAuth]) + async def test_validation(self, http, cls): + client = make_client(cls) + with pytest.raises(ValueError, match="prompt=none"): + await client.step_up( + acr="mfa", login_options={LoginOptions.AUTH_PARAMS: {"prompt": "none"}} + ) + with pytest.raises(ValueError, match="max_age"): + await client.login({LoginOptions.MAX_AGE: -1}) + with pytest.raises(ValueError): + client.has_authentication_context(acr="gold") + + @pytest.mark.parametrize("cls", [AsyncOAuth, SmartOAuth]) + async def test_step_up_without_discovery_support(self, http, cls): + http.discovery = WITHOUT_STEP_UP + client = make_client(cls) + assert client.is_step_up_supported() is False + with pytest.raises(KindeConfigurationException, match="not supported"): + await client.step_up(acr="mfa") + with pytest.raises(KindeConfigurationException, match="not supported"): + await client.step_up(max_age=60) + + def test_smart_client_checks_see_what_step_up_learned_about_discovery(self, http): + http.discovery_status = 503 + client = make_client(SmartOAuth) + # A failed retry: checks won't fetch again for a minute + assert client.is_step_up_supported() is False + + # Discovery is back, and a few seconds later step_up() fetches it + http.discovery_status = 200 + client._async_oauth._sync_oauth._openid_configuration_tried_at -= 5 + assert query(asyncio.run(client.step_up(max_age=300)))["max_age"] == "300" + + # The checks must agree at once. Otherwise the user comes back from + # Kinde to a max_age check that still fails, and is sent there again. + assert client.is_step_up_supported() is True + + @pytest.mark.parametrize("cls", [AsyncOAuth, SmartOAuth]) + async def test_step_up_while_discovery_is_unavailable(self, http, cls): + http.discovery_status = 503 + client = make_client(cls) + with pytest.raises(KindeRetrieveException, match="Try again"): + await client.step_up(acr="mfa") + http.discovery_status = 200 + # A few seconds later (step_up() goes through the wrapped sync client) + core = getattr(client, "_async_oauth", client)._sync_oauth + core._openid_configuration_tried_at -= 5 + assert query(await client.step_up(acr="mfa"))["acr_values"] == "mfa" diff --git a/testv2/testv2_auth/test_token_manager.py b/testv2/testv2_auth/test_token_manager.py index 713b45d2..466f8cde 100644 --- a/testv2/testv2_auth/test_token_manager.py +++ b/testv2/testv2_auth/test_token_manager.py @@ -384,6 +384,73 @@ def test_get_access_token_expired_no_refresh(self): self.assertIn("Access token expired and no refresh token available", str(context.exception)) + def test_get_access_token_refreshes_without_deadlock(self): + """Test that an expired access token is refreshed through the real refresh path""" + # get_access_token() holds the lock while refresh_access_token() stores + # the new tokens through set_tokens(), which takes the same lock + self.token_manager.tokens = { + "access_token": "expired_token", + "refresh_token": "refresh_token", + "expires_at": time.time() - 100 # Expired + } + new_token = jwt.encode({"sub": "user123"}, "k" * 32, algorithm="HS256") + result = [] + + with patch('requests.post') as mock_post: + mock_post.return_value.json.return_value = {"access_token": new_token, "expires_in": 3600} + + thread = threading.Thread( + target=lambda: result.append(self.token_manager.get_access_token()), + daemon=True + ) + thread.start() + thread.join(timeout=5) + + self.assertFalse(thread.is_alive(), "get_access_token() deadlocked while refreshing") + self.assertEqual(result, [new_token]) + self.assertEqual(mock_post.call_args.kwargs["data"]["grant_type"], "refresh_token") + self.assertEqual(mock_post.call_args.kwargs["data"]["refresh_token"], "refresh_token") + # The refresh response had no refresh token, so the current one is kept + self.assertEqual(self.token_manager.tokens["refresh_token"], "refresh_token") + + def test_set_tokens_merges_by_default(self): + """Test that set_tokens keeps the refresh and ID tokens a response doesn't include""" + first_id_token = jwt.encode({"sub": "user123", "jti": "first"}, "k" * 32, algorithm="HS256") + self.token_manager.set_tokens({ + "access_token": jwt.encode({"sub": "user123"}, "k" * 32, algorithm="HS256"), + "refresh_token": "first_refresh_token", + "id_token": first_id_token, + "expires_in": 3600 + }) + + # A refresh response without a refresh token or an ID token + second_access_token = jwt.encode({"sub": "user123", "jti": "second"}, "k" * 32, algorithm="HS256") + self.token_manager.set_tokens({"access_token": second_access_token, "expires_in": 3600}) + + self.assertEqual(self.token_manager.tokens["access_token"], second_access_token) + self.assertEqual(self.token_manager.tokens["refresh_token"], "first_refresh_token") + self.assertEqual(self.token_manager.tokens["id_token"], first_id_token) + + def test_set_tokens_replace_drops_older_tokens(self): + """Test that set_tokens(replace=True) keeps nothing from an earlier authorization""" + self.token_manager.set_tokens({ + "access_token": jwt.encode({"sub": "user123"}, "k" * 32, algorithm="HS256"), + "refresh_token": "first_refresh_token", + "id_token": jwt.encode({"sub": "user123", "jti": "first"}, "k" * 32, algorithm="HS256"), + "expires_in": 3600 + }) + tokens = self.token_manager.tokens + + second_access_token = jwt.encode({"sub": "user123", "jti": "second"}, "k" * 32, algorithm="HS256") + self.token_manager.set_tokens({"access_token": second_access_token, "expires_in": 3600}, replace=True) + + self.assertEqual(self.token_manager.tokens["access_token"], second_access_token) + self.assertNotIn("refresh_token", self.token_manager.tokens) + self.assertNotIn("id_token", self.token_manager.tokens) + self.assertNotIn("id_token_claims", self.token_manager.tokens) + # Replaced in place: the session keeps a reference to this dict + self.assertIs(self.token_manager.tokens, tokens) + # Helper function to run async tests def asyncio_test(coro): """Run a coroutine in the event loop and return its result.""" diff --git a/testv2/testv2_auth/test_user_session.py b/testv2/testv2_auth/test_user_session.py index fc9dfb4a..8837b581 100644 --- a/testv2/testv2_auth/test_user_session.py +++ b/testv2/testv2_auth/test_user_session.py @@ -1,3 +1,4 @@ +import threading import unittest import pytest import time @@ -71,6 +72,36 @@ def mock_clear_device_data(): "expires_in": 3600 } + def test_set_user_data_replace_tokens(self): + """Test that replace_tokens drops the tokens of an earlier authorization""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + + # By default a response without a refresh or ID token is merged + self.user_session.set_user_data( + self.user_id, self.user_info, {"access_token": "second_access_token", "expires_in": 3600} + ) + tokens = self.user_session.get_token_manager(self.user_id).tokens + self.assertEqual(tokens["access_token"], "second_access_token") + self.assertEqual(tokens["refresh_token"], "test_refresh_token") + self.assertEqual(tokens["id_token"], "test_id_token") + + self.user_session.set_user_data( + self.user_id, + self.user_info, + {"access_token": "third_access_token", "expires_in": 3600}, + replace_tokens=True, + ) + + tokens = self.user_session.get_token_manager(self.user_id).tokens + self.assertEqual(tokens["access_token"], "third_access_token") + self.assertNotIn("refresh_token", tokens) + self.assertNotIn("id_token", tokens) + # The stored session matches + self.assertNotIn("refresh_token", self.storage_dict[self.user_id]["tokens"]) + def test_set_user_data(self): """Test setting user data""" # Set up JWT decode mock @@ -183,8 +214,352 @@ def test_get_token_manager(self): self.assertEqual(token_manager.user_id, self.user_id) self.assertEqual(token_manager.tokens["access_token"], "test_access_token") - # Since it's in memory, storage.get shouldn't be called - self.mock_storage_manager.get.assert_not_called() + # The stored session is checked for tokens replaced by another process. + # It is unchanged here, so the cached token manager is kept as it is. + self.mock_storage_manager.get.assert_called_once_with(self.user_id) + self.assertIs(self.user_session.get_token_manager(self.user_id), token_manager) + + def _stored_copy(self): + """The stored session as a serializing backend holds it: a copy, not the cached dict.""" + stored = dict(self.storage_dict[self.user_id]) + stored["tokens"] = dict(stored["tokens"]) + return stored + + def _store_tokens_from_another_process(self, token_data, saved_at=None): + """Replace the stored session's tokens, as a callback on another worker process would.""" + stored = self._stored_copy() + stored["tokens"] = dict(token_data) + stored["revision"] = [stored["revision"][0] + 1, 0, saved_at or time.time()] + self.storage_dict[self.user_id] = stored + + STEPPED_UP_TOKENS = { + "access_token": "stepped_up_access_token", + "refresh_token": "stepped_up_refresh_token", + "expires_at": time.time() + 3600, + "id_token_claims": {"sub": "user123", "acr": "mfa"}, + } + + def _sign_in(self): + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + # Stored sessions are serialized, so they don't share the cached dict + self.storage_dict[self.user_id] = self._stored_copy() + return self.user_session.get_token_manager(self.user_id) + + def _refresh(self, token_manager, during_request=None): + """Refresh an expired access token. ``during_request`` runs while the request to Kinde is in flight.""" + token_manager.tokens["expires_at"] = time.time() - 100 + + def post(url, data=None, **kwargs): + if during_request: + during_request() + response = MagicMock() + response.json.return_value = { + "access_token": "refreshed_access_token", + "refresh_token": "rotated_refresh_token", + "expires_in": 3600, + } + return response + + with patch('jwt.decode') as mock_decode, patch('requests.post', side_effect=post): + mock_decode.return_value = {"sub": "user123"} + return token_manager.get_access_token() + + def test_get_token_manager_picks_up_tokens_stored_by_another_process(self): + """Test that the stored session wins over a cached one when it changes""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + token_manager = self.user_session.get_token_manager(self.user_id) + + # Another worker handled a step-up callback for this session + self._store_tokens_from_another_process({ + "access_token": "stepped_up_access_token", + "id_token": "stepped_up_id_token", + "refresh_token": "stepped_up_refresh_token", + "expires_at": time.time() + 3600, + "id_token_claims": {"sub": "user123", "acr": "mfa"}, + }) + + self.assertIs(self.user_session.get_token_manager(self.user_id), token_manager) + self.assertEqual(token_manager.tokens["access_token"], "stepped_up_access_token") + self.assertEqual(token_manager.tokens["refresh_token"], "stepped_up_refresh_token") + self.assertEqual(token_manager.get_claims("id_token")["acr"], "mfa") + self.assertTrue(self.user_session.is_authenticated(self.user_id)) + + def test_get_token_manager_keeps_unsaved_changes_while_the_store_is_unchanged(self): + """Test that tokens changed in memory are not overwritten by an unchanged store""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + token_manager = self.user_session.get_token_manager(self.user_id) + + # Changed in memory only; the store still holds what was saved + self.storage_dict[self.user_id] = self._stored_copy() + token_manager.tokens = {"access_token": "changed_in_memory", "expires_at": time.time() + 3600} + + self.assertEqual( + self.user_session.get_token_manager(self.user_id).tokens["access_token"], "changed_in_memory" + ) + self.assertEqual(self.storage_dict[self.user_id]["tokens"]["access_token"], "test_access_token") + + def test_get_token_manager_never_adopts_an_older_stored_session(self): + """Test that an older copy of the session is not adopted, and is repaired""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + # What a request that is still in flight loaded when it began + older_copy = self._stored_copy() + + # Meanwhile a step-up callback replaces the session's tokens + self.user_session.set_user_data( + self.user_id, + self.user_info, + {"access_token": "stepped_up_access_token", "refresh_token": "stepped_up_refresh_token", "expires_in": 3600}, + replace_tokens=True, + ) + + # The in-flight request's session is what this process now reads as the store + self.storage_dict[self.user_id] = older_copy + + token_manager = self.user_session.get_token_manager(self.user_id) + self.assertEqual(token_manager.tokens["access_token"], "stepped_up_access_token") + self.assertEqual(token_manager.tokens["refresh_token"], "stepped_up_refresh_token") + # ...and the current tokens are written back over the older ones + stored = self.storage_dict[self.user_id] + self.assertEqual(stored["tokens"]["access_token"], "stepped_up_access_token") + self.assertEqual(stored["revision"][0], older_copy["revision"][0] + 1) + + def test_revisions_increase_across_processes(self): + """Test that a process with nothing cached saves a revision above the stored one""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + self.assertEqual(self.storage_dict[self.user_id]["revision"][0], 2) + self.storage_dict[self.user_id] = self._stored_copy() + + # Another process: its own caches, the same store + TokenManager._instances = {} + other_process = UserSession() + other_process.set_user_data( + self.user_id, self.user_info, {"access_token": "from_other_process", "expires_in": 3600}, + replace_tokens=True, + ) + + self.assertEqual(self.storage_dict[self.user_id]["revision"][0], 3) + self.assertEqual(self.storage_dict[self.user_id]["tokens"]["access_token"], "from_other_process") + + def test_load_from_storage_keeps_newer_tokens_already_in_this_process(self): + """Test that loading an older stored copy doesn't replace newer shared tokens""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + older_copy = self._stored_copy() + self.user_session.set_user_data( + self.user_id, self.user_info, {"access_token": "newer_access_token", "expires_in": 3600}, + replace_tokens=True, + ) + self.storage_dict[self.user_id] = older_copy + + # A second session object in the same process shares the token manager + other_session = UserSession() + token_manager = other_session.get_token_manager(self.user_id) + + self.assertEqual(token_manager.tokens["access_token"], "newer_access_token") + + def test_session_stored_without_a_revision_is_loaded(self): + """Test that a session saved before revisions existed still loads and updates""" + self.storage_dict[self.user_id] = { + "user_info": self.user_info, + "tokens": {"access_token": "legacy_access_token", "expires_at": time.time() + 3600}, + } + + token_manager = self.user_session.get_token_manager(self.user_id) + self.assertEqual(token_manager.tokens["access_token"], "legacy_access_token") + self.assertEqual(self.user_session.get_token_manager(self.user_id), token_manager) + + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + self.assertEqual(self.storage_dict[self.user_id]["revision"][0], 1) + + def test_refreshed_tokens_are_saved(self): + """Test that a token refresh is written back to the stored session""" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + self.user_session.set_user_data(self.user_id, self.user_info, self.token_data) + token_manager = self.user_session.get_token_manager(self.user_id) + # Stored sessions are serialized, so they don't share the cached dict + self.storage_dict[self.user_id] = self._stored_copy() + saved_revision = self.storage_dict[self.user_id]["revision"] + token_manager.tokens["expires_at"] = time.time() - 100 # Expired + + with patch('requests.post') as mock_post: + mock_post.return_value.json.return_value = { + "access_token": "refreshed_access_token", + "refresh_token": "rotated_refresh_token", + "expires_in": 3600, + } + self.assertTrue(self.user_session.is_authenticated(self.user_id)) + + self.assertEqual(mock_post.call_args.kwargs["data"]["refresh_token"], "test_refresh_token") + stored_tokens = self.storage_dict[self.user_id]["tokens"] + self.assertEqual(stored_tokens["access_token"], "refreshed_access_token") + self.assertEqual(stored_tokens["refresh_token"], "rotated_refresh_token") + # A refresh continues the same authorization + self.assertEqual(self.storage_dict[self.user_id]["revision"][0], saved_revision[0]) + self.assertEqual(self.storage_dict[self.user_id]["revision"][1], saved_revision[1] + 1) + # The session's own save is not mistaken for another process's + self.assertEqual( + self.user_session.get_token_manager(self.user_id).tokens["access_token"], "refreshed_access_token" + ) + + def test_refresh_that_finishes_after_a_step_up_elsewhere_is_dropped(self): + """Test that tokens refreshed from before a step-up don't replace the step-up""" + token_manager = self._sign_in() + + # Another worker stores a step-up while this one's refresh is in flight + access_token = self._refresh( + token_manager, + during_request=lambda: self._store_tokens_from_another_process(self.STEPPED_UP_TOKENS), + ) + + self.assertEqual(access_token, "stepped_up_access_token") + self.assertEqual(token_manager.tokens["refresh_token"], "stepped_up_refresh_token") + self.assertEqual(token_manager.get_claims("id_token")["acr"], "mfa") + stored = self.storage_dict[self.user_id] + self.assertEqual(stored["tokens"]["access_token"], "stepped_up_access_token") + self.assertEqual(stored["revision"][:2], [2, 0]) + + def test_refresh_from_an_earlier_authorization_never_outranks_a_later_one(self): + """Test that a late refresh loses to a step-up it could not see when it was saved""" + token_manager = self._sign_in() + signed_in = self._stored_copy() + + # The refresh is saved into this request's copy of the session, which + # was loaded before the step-up and doesn't show it + self._refresh(token_manager) + refreshed = self._stored_copy() + self.assertEqual(refreshed["tokens"]["access_token"], "refreshed_access_token") + + # The step-up was handled by another worker, before the refresh was saved + self.storage_dict[self.user_id] = signed_in + self._store_tokens_from_another_process( + self.STEPPED_UP_TOKENS, saved_at=refreshed["revision"][2] - 1 + ) + stepped_up = self._stored_copy() + + # This worker sees the step-up: it replaces the refreshed tokens + self.assertEqual( + self.user_session.get_token_manager(self.user_id).tokens["access_token"], "stepped_up_access_token" + ) + + # The worker that holds the step-up sees the late refresh: it keeps the + # step-up, and writes it back + self.storage_dict[self.user_id] = refreshed + token_manager = self.user_session.get_token_manager(self.user_id) + self.assertEqual(token_manager.tokens["access_token"], "stepped_up_access_token") + self.assertEqual(self.storage_dict[self.user_id]["tokens"]["access_token"], "stepped_up_access_token") + self.assertEqual(self.storage_dict[self.user_id]["revision"], stepped_up["revision"]) + + def test_refreshed_tokens_that_could_not_be_saved_are_saved_on_the_next_read(self): + """Test that a failed save keeps the refreshed tokens and is repeated""" + token_manager = self._sign_in() + + def failing_save(key, value): + raise OSError("session store is down") + + working_save = self.mock_storage_manager.setItems.side_effect + self.mock_storage_manager.setItems.side_effect = failing_save + with self.assertLogs(level="WARNING"): + access_token = self._refresh(token_manager) + + # The refresh still succeeds for this request + self.assertEqual(access_token, "refreshed_access_token") + self.assertEqual(self.storage_dict[self.user_id]["tokens"]["refresh_token"], "test_refresh_token") + + # The store is back: the next read of the session saves them + self.mock_storage_manager.setItems.side_effect = working_save + self.user_session.get_token_manager(self.user_id) + stored = self.storage_dict[self.user_id] + self.assertEqual(stored["tokens"]["access_token"], "refreshed_access_token") + self.assertEqual(stored["tokens"]["refresh_token"], "rotated_refresh_token") + + def test_cached_session_survives_a_session_store_that_cannot_be_read(self): + """Test that a failing store doesn't make an authentication check raise""" + token_manager = self._sign_in() + working_get = self.mock_storage_manager.get.side_effect + + def failing_get(key): + raise OSError("session store is down") + + self.mock_storage_manager.get.side_effect = failing_get + with self.assertLogs(level="WARNING"): + for _ in range(3): + self.assertIs(self.user_session.is_authenticated(self.user_id), True) + self.assertIs(self.user_session.get_token_manager(self.user_id), token_manager) + self.assertEqual(token_manager.tokens["access_token"], "test_access_token") + + # The store is back, with a step-up from another worker: it is picked up + self.mock_storage_manager.get.side_effect = working_get + self._store_tokens_from_another_process(self.STEPPED_UP_TOKENS) + self.assertIs(self.user_session.is_authenticated(self.user_id), True) + self.assertEqual(token_manager.tokens["access_token"], "stepped_up_access_token") + + def test_sync_that_waited_for_a_token_change_does_not_undo_it(self): + """Test that the stored session is compared after waiting for the token manager's lock""" + token_manager = self._sign_in() + self._store_tokens_from_another_process(self.STEPPED_UP_TOKENS) + + result = {} + reader = threading.Thread( + target=lambda: result.update(tokens=dict(self.user_session.get_token_manager(self.user_id).tokens)) + ) + + # A token change is in flight: it holds the lock until its tokens are saved + with token_manager.lock: + reader.start() + reader.join(0.2) # the reader is now waiting for the lock + self.assertTrue(reader.is_alive()) + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user123"} + token_manager.set_tokens({"access_token": "newest_access_token", "expires_in": 3600}, replace=True) + self.user_session._commit_token_change(self.user_id, refreshed=False) + reader.join(5) + + self.assertFalse(reader.is_alive()) + self.assertEqual(result["tokens"]["access_token"], "newest_access_token") + self.assertEqual(token_manager.tokens["access_token"], "newest_access_token") + self.assertEqual(self.storage_dict[self.user_id]["tokens"]["access_token"], "newest_access_token") + + def test_refresh_in_flight_for_one_user_does_not_hold_up_another(self): + """Test that waiting for one user's token manager doesn't block other users""" + token_manager = self._sign_in() + other_user = "other_user_id" + with patch('jwt.decode') as mock_decode: + mock_decode.return_value = {"sub": "user456"} + self.user_session.set_user_data(other_user, self.user_info, self.token_data) + + result = {} + same_user = threading.Thread(target=lambda: self.user_session.get_token_manager(self.user_id)) + another_user = threading.Thread( + target=lambda: result.update(token_manager=self.user_session.get_token_manager(other_user)) + ) + + with token_manager.lock: # a refresh in flight for the first user + same_user.start() + same_user.join(0.2) + self.assertTrue(same_user.is_alive()) + + another_user.start() + another_user.join(5) + self.assertFalse(another_user.is_alive()) + same_user.join(5) + + self.assertFalse(same_user.is_alive()) + self.assertEqual(result["token_manager"].user_id, other_user) def test_logout(self): """Test logout""" diff --git a/testv2/testv2_framework/test_step_up_fastapi.py b/testv2/testv2_framework/test_step_up_fastapi.py new file mode 100644 index 00000000..b6552692 --- /dev/null +++ b/testv2/testv2_framework/test_step_up_fastapi.py @@ -0,0 +1,523 @@ +""" +Step-up authentication through the FastAPI integration. + +A real FastAPI app, the real Kinde routes and the real OAuth client. Only the +network is faked (the ``http`` fixture in ``testv2/conftest.py``). +""" + +import time +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse +from starlette.middleware.sessions import SessionMiddleware +from starlette.testclient import TestClient + +from kinde_sdk.auth.oauth import OAuth +from kinde_sdk.core.exceptions import ( + KindeCallbackError, + KindeLoginException, + KindeTokenException, + LoginRequiredError, + UnmetAuthenticationRequirementsError, +) +from kinde_sdk.core.framework.framework_factory import FrameworkFactory +from testv2.step_up_helpers import ( + HOST, + query, + token_response, +) + +UNMET = "unmet_authentication_requirements" +UNMET_DESCRIPTION = "The requested authentication context could not be met" + + +def build_app(configure=None): + """A FastAPI app with Kinde wired in, and a route that requires recent MFA.""" + app = FastAPI() + app.add_middleware(SessionMiddleware, secret_key="test-secret") + if configure: + configure(app) + + oauth = OAuth( + client_id="test_client_id", + client_secret="test_client_secret", + redirect_uri="http://testserver/callback", + framework="fastapi", + app=app, + host=HOST, + ) + + async def payouts(): + if not oauth.is_authenticated(): + return RedirectResponse("/login") + if not oauth.has_authentication_context(acr="mfa", max_age=300): + return RedirectResponse( + await oauth.step_up(acr="mfa", max_age=300), status_code=303 + ) + return PlainTextResponse("payouts") + + app.add_api_route("/payouts", payouts, methods=["GET", "POST"]) + + @app.post("/transfer") + async def transfer(): + url = await oauth.step_up( + acr="phr", post_login_redirect_url="/transfer/confirm" + ) + return RedirectResponse(url, status_code=303) + + @app.get("/mfa-login") + async def mfa_login(): + return RedirectResponse( + await oauth.login({"acr_values": "mfa"}), status_code=303 + ) + + @app.get("/whoami") + async def whoami(): + return { + "authenticated": oauth.is_authenticated(), + "context": oauth.get_authentication_context(), + } + + return app, oauth + + +@pytest.fixture +def fastapi_env(http, monkeypatch): + # The framework is a process-wide singleton: start each test without one + monkeypatch.setattr(FrameworkFactory, "_framework_instance", None) + return http + + +@pytest.fixture +def site(fastapi_env): + app, oauth = build_app() + return SimpleNamespace( + app=app, + oauth=oauth, + client=TestClient(app, follow_redirects=False), + http=fastapi_env, + ) + + +def location(response): + return response.headers["location"] + + +def sign_in(site): + response = site.client.get("/login") + assert response.status_code == 307 + site.http.token_responses.append( + token_response("login", id_claims={"auth_time": int(time.time()) - 3600}) + ) + response = site.client.get( + "/callback", + params={"code": "login_code", "state": query(location(response))["state"]}, + ) + assert response.status_code == 307 + return response + + +def start_step_up(site, path="/payouts?tab=bank"): + response = site.client.get(path) + assert response.status_code == 303 + assert location(response).startswith(f"{HOST}/oauth2/auth?") + return query(location(response)) + + +def stepped_up_tokens(): + claims = {"acr": "mfa", "amr": ["pwd", "totp"], "auth_time": int(time.time())} + return token_response("step-up", access_claims={"acr": "mfa"}, id_claims=claims) + + +def assert_not_sent_anywhere(response): + """The response is not a redirect, to login or anywhere else.""" + assert response.status_code not in (301, 302, 303, 307, 308) + assert "location" not in response.headers + + +class TestFastAPIStepUp: + def test_login_callback_is_unchanged(self, site): + response = sign_in(site) + assert location(response).startswith("http://testserver/?state=") + assert site.client.get("/whoami").json()["authenticated"] is True + + def test_step_up_request_is_interactive_and_carries_the_requirement(self, site): + sign_in(site) + params = start_step_up(site) + assert params["acr_values"] == "mfa" + assert params["max_age"] == "300" + assert "prompt" not in params + + def test_user_lands_back_where_they_started(self, site): + sign_in(site) + params = start_step_up(site, "/payouts?tab=bank") + + site.http.token_responses.append(stepped_up_tokens()) + response = site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + assert response.status_code == 307 + # The existing callback appends the state to the post-login redirect + assert ( + location(response) + == f"http://testserver/payouts?tab=bank&state={params['state']}" + ) + response = site.client.get(location(response)) + assert response.status_code == 200 and response.text == "payouts" + + def test_successful_step_up_replaces_the_session_tokens(self, site): + sign_in(site) + assert site.client.get("/whoami").json()["context"]["acr"] is None + user_id = next(iter(site.oauth._session_manager.user_sessions)) + before = dict(site.oauth.get_tokens(user_id)) + params = start_step_up(site) + + tokens = stepped_up_tokens() + site.http.token_responses.append(tokens) + site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + context = site.client.get("/whoami").json()["context"] + assert context["acr"] == "mfa" and context["amr"] == ["pwd", "totp"] + assert list(site.oauth._session_manager.user_sessions) == [user_id] + after = site.oauth.get_tokens(user_id) + assert after["access_token"] == tokens["access_token"] != before["access_token"] + assert after["id_token"] == tokens["id_token"] != before["id_token"] + assert after["refresh_token"] == "refresh-step-up" != before["refresh_token"] + + def test_a_post_is_not_replayed(self, site): + sign_in(site) + response = site.client.post("/payouts") + params = query(location(response)) + + site.http.token_responses.append(stepped_up_tokens()) + response = site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + assert location(response) == f"http://testserver/?state={params['state']}" + + def test_a_post_does_not_inherit_an_abandoned_return_location(self, site): + sign_in(site) + start_step_up(site, "/payouts?tab=bank") # started, then abandoned + + params = query(location(site.client.post("/payouts"))) + site.http.token_responses.append(stepped_up_tokens()) + response = site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + assert location(response) == f"http://testserver/?state={params['state']}" + + def test_explicit_return_location(self, site): + sign_in(site) + response = site.client.post("/transfer") + params = query(location(response)) + assert params["acr_values"] == "phr" + + site.http.token_responses.append(stepped_up_tokens()) + response = site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + assert ( + location(response) + == f"http://testserver/transfer/confirm?state={params['state']}" + ) + + +class TestFastAPIOlderSessionCookie: + """ + With a cookie session, the stored session is whatever cookie the request + carried. A request sent before the tokens changed carries the old ones. + """ + + @staticmethod + def get_with_cookie(site, path, cookie): + client = TestClient(site.app, follow_redirects=False) + return client.get(path, headers={"cookie": f"session={cookie}"}) + + def test_request_with_the_cookie_from_before_a_step_up(self, site): + sign_in(site) + old_cookie = site.client.cookies.get("session") + params = start_step_up(site, "/payouts") + site.http.token_responses.append(stepped_up_tokens()) + site.client.get( + "/callback", params={"code": "step_up_code", "state": params["state"]} + ) + + # A request the browser had already sent + response = self.get_with_cookie(site, "/whoami", old_cookie) + + assert response.json()["context"]["acr"] == "mfa" + # Its response replaces the old cookie with the current tokens + repaired = response.cookies.get("session") + assert repaired and repaired != old_cookie + assert self.get_with_cookie(site, "/payouts", repaired).status_code == 200 + assert site.client.get("/payouts").status_code == 200 + + def test_request_with_the_cookie_from_before_a_refresh_does_not_refresh_again( + self, site + ): + # Sign in with a refresh token and an access token that has already expired + response = site.client.get("/login") + site.http.token_responses.append({**token_response("login"), "expires_in": -1}) + site.client.get( + "/callback", + params={"code": "login_code", "state": query(location(response))["state"]}, + ) + old_cookie = site.client.cookies.get("session") + site.http.post.reset_mock() + + # The fake token endpoint has one response: a second refresh would fail the test + site.http.token_responses.append( + token_response("refreshed", refresh=False, id_token=False) + ) + assert site.client.get("/whoami").json()["authenticated"] is True + + response = self.get_with_cookie(site, "/whoami", old_cookie) + assert response.json()["authenticated"] is True + assert [request["grant_type"] for request in site.http.token_requests] == [ + "refresh_token" + ] + assert site.http.token_requests[0]["refresh_token"] == "refresh-login" + + +class TestFastAPICallbackErrors: + def test_unmet_error_reaches_the_app(self, site): + seen = [] + + @site.app.exception_handler(UnmetAuthenticationRequirementsError) + async def unmet(request, error): + seen.append(error) + return JSONResponse( + {"reason": "Add an authenticator app to continue"}, status_code=403 + ) + + sign_in(site) + before = site.client.get("/whoami").json() + params = start_step_up(site) + token_requests = site.http.post.call_count + + response = site.client.get( + "/callback", + params={ + "error": UNMET, + "error_description": UNMET_DESCRIPTION, + "state": params["state"], + }, + ) + + # The app's handler got the error, with everything it needs + assert response.status_code == 403 + assert response.json() == {"reason": "Add an authenticator app to continue"} + assert len(seen) == 1 + assert seen[0].error == UNMET + assert seen[0].error_description == UNMET_DESCRIPTION + assert seen[0].state == params["state"] + assert seen[0].acr_values == "mfa" and seen[0].max_age == 300 + # Not a login redirect, not retried, and the user is still signed in as before + assert_not_sent_anywhere(response) + assert site.http.post.call_count == token_requests + assert site.client.get("/whoami").json() == before + + def test_unmet_error_has_a_default_page(self, site): + sign_in(site) + params = start_step_up(site) + + response = site.client.get( + "/callback", + params={ + "error": UNMET, + "error_description": UNMET_DESCRIPTION, + "state": params["state"], + }, + ) + + assert response.status_code == 403 + assert response.headers["content-type"].startswith("text/plain") + assert "couldn't complete the extra verification" in response.text + assert UNMET_DESCRIPTION in response.text + assert_not_sent_anywhere(response) + assert site.client.get("/whoami").json()["authenticated"] is True + + def test_login_required_reaches_the_app(self, site): + seen = [] + + @site.app.exception_handler(LoginRequiredError) + async def login_required(request, error): + seen.append(error) + return PlainTextResponse("sign in again", status_code=401) + + state = query(location(site.client.get("/login")))["state"] + response = site.client.get( + "/callback", params={"error": "login_required", "state": state} + ) + + assert response.status_code == 401 and response.text == "sign in again" + assert seen[0].error == "login_required" and seen[0].state == state + assert_not_sent_anywhere(response) + site.http.post.assert_not_called() + + def test_login_required_has_a_default_page(self, site): + state = query(location(site.client.get("/login")))["state"] + response = site.client.get( + "/callback", params={"error": "login_required", "state": state} + ) + + assert response.status_code == 401 + assert "sign in again" in response.text + assert_not_sent_anywhere(response) + + def test_app_handler_for_all_callback_errors(self, site): + @site.app.exception_handler(KindeCallbackError) + async def any_callback_error(request, error): + return PlainTextResponse(f"app handled {error.error}", status_code=400) + + sign_in(site) + params = start_step_up(site) + response = site.client.get( + "/callback", params={"error": UNMET, "state": params["state"]} + ) + + assert response.text == f"app handled {UNMET}" + + def test_app_handler_registered_before_the_sdk_is_kept(self, fastapi_env): + async def registered_first(request, error): + return PlainTextResponse("registered first", status_code=400) + + app, _oauth = build_app( + lambda app: app.add_exception_handler(KindeCallbackError, registered_first) + ) + client = TestClient(app, follow_redirects=False) + state = query(location(client.get("/login")))["state"] + + response = client.get("/callback", params={"error": UNMET, "state": state}) + + assert response.text == "registered first" + + @pytest.mark.parametrize("state", [None, "forged"]) + def test_state_is_validated_before_the_error_is_reported(self, site, state): + seen = [] + + @site.app.exception_handler(KindeCallbackError) + async def any_callback_error(request, error): + seen.append(error) + return PlainTextResponse("handled", status_code=403) + + sign_in(site) + start_step_up(site) + + params = {"error": UNMET, "error_description": ""} + if state: + params["state"] = state + response = site.client.get("/callback", params=params) + + assert response.status_code == 400 + assert "Invalid state parameter" in response.text + assert ""} + if state: + params["state"] = state + response = site.client.get("/callback", query_string=params) + + assert response.status_code == 400 + assert "Invalid state parameter" in response.get_data(as_text=True) + assert "