From 0f6bc093094c8e54d74cbcbf308ef095002b6335 Mon Sep 17 00:00:00 2001 From: Koosha Owji Date: Fri, 13 Nov 2026 13:45:12 +1100 Subject: [PATCH 01/10] fix(auth): prevent deadlock when refreshing an expired access token TokenManager.get_access_token() holds the token lock while it calls refresh_access_token(), which stores the new tokens through set_tokens(). set_tokens() takes the same lock, and threading.Lock is not re-entrant, so any refresh of an expired access token hung the calling thread forever. Use a re-entrant lock. The existing test mocked refresh_access_token(), so this adds one that goes through the real refresh path. --- kinde_sdk/auth/token_manager.py | 4 +++- testv2/testv2_auth/test_token_manager.py | 29 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/kinde_sdk/auth/token_manager.py b/kinde_sdk/auth/token_manager.py index 3411fc39..6ba9adc1 100644 --- a/kinde_sdk/auth/token_manager.py +++ b/kinde_sdk/auth/token_manager.py @@ -33,7 +33,9 @@ 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 self.initialized = True diff --git a/testv2/testv2_auth/test_token_manager.py b/testv2/testv2_auth/test_token_manager.py index 713b45d2..b63f1ede 100644 --- a/testv2/testv2_auth/test_token_manager.py +++ b/testv2/testv2_auth/test_token_manager.py @@ -384,6 +384,35 @@ 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") + # Helper function to run async tests def asyncio_test(coro): """Run a coroutine in the event loop and return its result.""" From dd92adb084b015fe06c0bb172c59abc1cd498634 Mon Sep 17 00:00:00 2001 From: Koosha Owji Date: Fri, 13 Nov 2026 13:46:00 +1100 Subject: [PATCH 02/10] feat(auth): add acr_values and max_age login options Add LoginOptions.ACR_VALUES and LoginOptions.MAX_AGE for login() and register(), mapped to the acr_values and max_age authorization parameters (RFC 9470 step-up authentication). - Nothing is sent when an option is unset, so existing login URLs are byte-for-byte unchanged. - acr_values accepts "mfa" or "phr" (or a list, sent space-separated). - max_age must be a non-negative int. Anything else, including bool and float, raises ValueError before the URL is built: Kinde reads a malformed max_age as "re-authenticate", which would hide the bug. - The auth_params passthrough no longer sends an unset acr_values or max_age (it sent "max_age=" for None), and rejects an invalid max_age. --- kinde_sdk/__init__.py | 2 + kinde_sdk/auth/login_options.py | 4 + kinde_sdk/auth/oauth.py | 24 ++++ kinde_sdk/auth/step_up.py | 132 ++++++++++++++++++++ testv2/conftest.py | 33 +++++ testv2/step_up_helpers.py | 82 +++++++++++++ testv2/testv2_auth/test_step_up.py | 191 +++++++++++++++++++++++++++++ 7 files changed, 468 insertions(+) create mode 100644 kinde_sdk/auth/step_up.py create mode 100644 testv2/conftest.py create mode 100644 testv2/step_up_helpers.py create mode 100644 testv2/testv2_auth/test_step_up.py diff --git a/kinde_sdk/__init__.py b/kinde_sdk/__init__.py index 1283d617..4e29dcbe 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 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,7 @@ "permissions", "claims", "async_claims", + "AcrValues", "portals", "feature_flags", "StorageFactory", 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..2513aec3 100644 --- a/kinde_sdk/auth/oauth.py +++ b/kinde_sdk/auth/oauth.py @@ -19,6 +19,11 @@ KindeTokenException, KindeRetrieveException, ) +from .step_up import ( + normalize_acr_values, + normalize_max_age, + normalize_step_up_auth_param, +) class OAuth: def __init__( @@ -277,6 +282,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", @@ -314,6 +322,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 +341,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 +411,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 +452,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: diff --git a/kinde_sdk/auth/step_up.py b/kinde_sdk/auth/step_up.py new file mode 100644 index 00000000..853b8f5a --- /dev/null +++ b/kinde_sdk/auth/step_up.py @@ -0,0 +1,132 @@ +""" +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 +from typing import Any, List, 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} + +_DIGITS = re.compile(r"[0-9]+") + + +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") diff --git a/testv2/conftest.py b/testv2/conftest.py new file mode 100644 index 00000000..c6f85ffc --- /dev/null +++ b/testv2/conftest.py @@ -0,0 +1,33 @@ +"""Fixtures shared by the test suite.""" + +from unittest.mock import AsyncMock + +import pytest +import requests + +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) + 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..47a75b95 --- /dev/null +++ b/testv2/step_up_helpers.py @@ -0,0 +1,82 @@ +""" +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. +""" + +from unittest.mock import MagicMock +from urllib.parse import parse_qs, urlparse + +import jwt + +HOST = "https://test.kinde.com" +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 = [] + 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" + response = MagicMock() + response.status_code = 200 + response.json.return_value = self.token_responses.pop(0) + return response + + @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}", **(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/testv2_auth/test_step_up.py b/testv2/testv2_auth/test_step_up.py new file mode 100644 index 00000000..c5a65b4f --- /dev/null +++ b/testv2/testv2_auth/test_step_up.py @@ -0,0 +1,191 @@ +""" +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 pytest + +from kinde_sdk import AcrValues +from kinde_sdk.auth.login_options import LoginOptions +from kinde_sdk.auth.oauth import OAuth +from kinde_sdk.auth.step_up import ( + normalize_acr_values, + normalize_max_age, + normalize_step_up_auth_param, +) +from kinde_sdk.core.storage.storage_manager import StorageManager +from testv2.step_up_helpers import HOST, query + +# 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() + + +def stored_state(): + return StorageManager().get("user:state") + + +# --------------------------------------------------------------------------- +# 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") From 0f88e751f79c4ca175e66f80362f636cbf2d5c80 Mon Sep 17 00:00:00 2001 From: Koosha Owji Date: Fri, 13 Nov 2026 13:46:16 +1100 Subject: [PATCH 03/10] feat(auth): replace the session's tokens on an authorization callback handle_redirect() merged the new token response into the stored tokens, so a refresh token or ID token from an earlier sign-in was kept whenever the new response had none. After a step-up that is wrong: a token refreshed from a pre-step-up refresh token keeps the old acr, amr and auth_time. The tokens from an authorization callback now replace the stored access, ID and refresh tokens. TokenManager.set_tokens() gains replace=False and UserSession.set_user_data() gains replace_tokens=False; both default to the previous merge, which a token refresh still uses. --- kinde_sdk/auth/oauth.py | 6 ++-- kinde_sdk/auth/token_manager.py | 16 ++++++++-- kinde_sdk/auth/user_session.py | 15 ++++++++-- testv2/testv2_auth/test_token_manager.py | 38 ++++++++++++++++++++++++ testv2/testv2_auth/test_user_session.py | 30 +++++++++++++++++++ 5 files changed, 98 insertions(+), 7 deletions(-) diff --git a/kinde_sdk/auth/oauth.py b/kinde_sdk/auth/oauth.py index 2513aec3..a27ee345 100644 --- a/kinde_sdk/auth/oauth.py +++ b/kinde_sdk/auth/oauth.py @@ -571,8 +571,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) diff --git a/kinde_sdk/auth/token_manager.py b/kinde_sdk/auth/token_manager.py index 6ba9adc1..5317e21d 100644 --- a/kinde_sdk/auth/token_manager.py +++ b/kinde_sdk/auth/token_manager.py @@ -48,9 +48,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"), diff --git a/kinde_sdk/auth/user_session.py b/kinde_sdk/auth/user_session.py index 19d9ca07..d4c80be4 100644 --- a/kinde_sdk/auth/user_session.py +++ b/kinde_sdk/auth/user_session.py @@ -10,8 +10,14 @@ def __init__(self): 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 @@ -35,7 +41,10 @@ def set_user_data(self, user_id: str, user_info: Dict[str, Any], token_data: Dic self.user_sessions[user_id]["user_info"] = user_info # Set tokens in token manager - self.user_sessions[user_id]["token_manager"].set_tokens(token_data) + if replace_tokens: + self.user_sessions[user_id]["token_manager"].set_tokens(token_data, replace=True) + else: + self.user_sessions[user_id]["token_manager"].set_tokens(token_data) # Save to persistent storage self._save_to_storage(user_id) diff --git a/testv2/testv2_auth/test_token_manager.py b/testv2/testv2_auth/test_token_manager.py index b63f1ede..466f8cde 100644 --- a/testv2/testv2_auth/test_token_manager.py +++ b/testv2/testv2_auth/test_token_manager.py @@ -413,6 +413,44 @@ def test_get_access_token_refreshes_without_deadlock(self): # 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..a6f4415a 100644 --- a/testv2/testv2_auth/test_user_session.py +++ b/testv2/testv2_auth/test_user_session.py @@ -71,6 +71,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 From 317b17ab450454f8ef06737615a88f87d593d5a5 Mon Sep 17 00:00:00 2001 From: Koosha Owji Date: Fri, 13 Nov 2026 13:46:32 +1100 Subject: [PATCH 04/10] feat(auth): add step_up() and authentication context checks Phase 1 of step-up authentication (RFC 9470) on OAuth, AsyncOAuth and SmartOAuth: - step_up(acr, max_age, login_options, post_login_redirect_url) builds an interactive authorization URL. It rejects prompt=none, including through auth_params, and requires acr or max_age. The current tokens are kept until the callback replaces them. - handle_redirect() takes the callback's error and error_description. It validates state, then raises UnmetAuthenticationRequirementsError or LoginRequiredError. Nothing is retried and stored tokens are untouched. - The two errors are new. Both extend the new KindeCallbackError (itself a KindeLoginException) and carry error, error_description and state, plus the acr_values and max_age that were requested when known. - get_authentication_context() returns acr, amr and auth_time, with auth_time read from the ID token. - has_authentication_context(acr, max_age) checks the current session: an absent acr is baseline, phr meets mfa, and a missing auth_time fails max_age. kinde_sdk.has_authentication_context is the same check as a pure function. - is_step_up_supported() reads acr_values_supported from the discovery document fetched at start-up. While the document is unavailable it returns False and retries the fetch at most once a minute. On an environment without step-up, auth_time is reported as None, and step_up() raises KindeConfigurationException for acr and for max_age instead of sending a parameter Kinde would ignore. A prompt=login fallback for max_age would loop: a page guarded by has_authentication_context(max_age=...) would redirect to Kinde on every request. While the discovery document is unavailable, step_up() raises KindeRetrieveException, so the two cases can be told apart. It retries the fetch at most once every 5 seconds, because the fetch is a blocking request with a 5 second timeout and would otherwise stall every guarded request, and the event loop on FastAPI. FrameworkInterface gains an optional set_post_login_redirect_url() hook (a no-op by default) so framework integrations can bring the user back. --- kinde_sdk/__init__.py | 3 +- kinde_sdk/auth/async_oauth.py | 46 +- kinde_sdk/auth/base_oauth.py | 40 +- kinde_sdk/auth/oauth.py | 315 +++++- kinde_sdk/auth/smart_oauth.py | 46 +- kinde_sdk/auth/step_up.py | 171 +++- kinde_sdk/core/exceptions.py | 51 + .../core/framework/framework_interface.py | 14 + testv2/testv2_auth/test_step_up.py | 919 +++++++++++++++++- 9 files changed, 1594 insertions(+), 11 deletions(-) diff --git a/kinde_sdk/__init__.py b/kinde_sdk/__init__.py index 4e29dcbe..1d6c8a5b 100644 --- a/kinde_sdk/__init__.py +++ b/kinde_sdk/__init__.py @@ -19,7 +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 +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 @@ -39,6 +39,7 @@ "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/oauth.py b/kinde_sdk/auth/oauth.py index a27ee345..fefb471f 100644 --- a/kinde_sdk/auth/oauth.py +++ b/kinde_sdk/auth/oauth.py @@ -1,8 +1,9 @@ +import hmac import os import requests import logging 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,13 +19,26 @@ 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 + class OAuth: def __init__( self, @@ -66,6 +80,10 @@ 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 + # Initialize API endpoints self._set_api_endpoints() @@ -230,6 +248,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") @@ -475,6 +497,229 @@ 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. + + 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") + + # 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 = self._get_openid_configuration(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 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. + """ + config = getattr(self, "_openid_configuration", None) + if config is not None: + return config + + now = time.time() + if now - getattr(self, "_openid_configuration_tried_at", 0.0) < retry_after: + return None + self._openid_configuration_tried_at = now + + 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)}") + 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. @@ -527,18 +772,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") @@ -597,11 +866,53 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] = # 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 _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..393e25b8 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,51 @@ 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, + ) + + def get_authentication_context(self) -> Dict[str, Any]: + """Get the acr, amr and auth_time of the current session.""" + 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.""" + 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.""" + 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/step_up.py b/kinde_sdk/auth/step_up.py index 853b8f5a..66c6f151 100644 --- a/kinde_sdk/auth/step_up.py +++ b/kinde_sdk/auth/step_up.py @@ -15,7 +15,9 @@ """ import re -from typing import Any, List, Optional, Union +import time +from enum import Enum +from typing import Any, Dict, List, Mapping, Optional, Union class AcrValues: @@ -30,6 +32,13 @@ class AcrValues: # 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]+") @@ -130,3 +139,163 @@ def normalize_step_up_auth_param(key: str, value: Any) -> Optional[str]: 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 + id_sub = id_claims.get("sub") + access_sub = access_claims.get("sub") + if id_sub and access_sub and 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. + + 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() + if now - auth_time > max_age + leeway: + return False + + return True 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/testv2_auth/test_step_up.py b/testv2/testv2_auth/test_step_up.py index c5a65b4f..3c3d8129 100644 --- a/testv2/testv2_auth/test_step_up.py +++ b/testv2/testv2_auth/test_step_up.py @@ -6,18 +6,45 @@ nothing leaves the machine. """ +import time +from unittest.mock import MagicMock + 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 HOST, query +from testv2.step_up_helpers import ( + 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 = { @@ -59,6 +86,23 @@ 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") @@ -189,3 +233,876 @@ def test_normalize_max_age(self): 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() + + +# --------------------------------------------------------------------------- +# 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} + + +# --------------------------------------------------------------------------- +# 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 + ) + + 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 + ): + assert oauth.is_step_up_supported() is False # uses up this minute's retry + 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 + + +# --------------------------------------------------------------------------- +# 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) + + @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" From 8f555354d14c64704cc8b0c3fa54d6c479b68b38 Mon Sep 17 00:00:00 2001 From: Koosha Owji Date: Fri, 13 Nov 2026 13:47:11 +1100 Subject: [PATCH 05/10] feat(flask,fastapi): hand step-up callback errors to the app Neither /callback route let the app see error=unmet_authentication_requirements. Flask answered with a generic "Missing authorization code" page. FastAPI ignored the error parameter and tried to exchange a missing code, so it surfaced as a token exchange failure. - Both routes now pass unmet_authentication_requirements and login_required to the core, which validates state and raises UnmetAuthenticationRequirementsError or LoginRequiredError. Handle them with @app.errorhandler(...) on Flask or @app.exception_handler(...) on FastAPI. There is no login redirect and no retry, and stored tokens are untouched. - Without a handler of its own, the app gets a plain-text default page (403 or 401). - After step_up(), the callback returns the user to the page they were on, through the existing post_login_redirect_url session value. - step_up() from a non-GET request with no explicit URL clears any earlier return location, so the user cannot land on a page from an abandoned step-up. - The return location is dropped only once the callback has been accepted. The Flask route used to remove it before validating the callback, so a request such as /callback?code=x&state=forged made the genuine callback land on "/". Other callback errors behave as before. --- kinde_fastapi/framework/fastapi_framework.py | 82 +++- kinde_flask/framework/flask_framework.py | 87 +++- .../testv2_framework/test_step_up_fastapi.py | 440 ++++++++++++++++++ testv2/testv2_framework/test_step_up_flask.py | 427 +++++++++++++++++ 4 files changed, 1033 insertions(+), 3 deletions(-) create mode 100644 testv2/testv2_framework/test_step_up_fastapi.py create mode 100644 testv2/testv2_framework/test_step_up_flask.py 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/testv2/testv2_framework/test_step_up_fastapi.py b/testv2/testv2_framework/test_step_up_fastapi.py new file mode 100644 index 00000000..e18004db --- /dev/null +++ b/testv2/testv2_framework/test_step_up_fastapi.py @@ -0,0 +1,440 @@ +""" +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 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 "