From 62283b75b02c20e63a15c806142bc2f81342dbf3 Mon Sep 17 00:00:00 2001 From: Shafikul Islam Tanbir <58387559+shafiktanbir@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:46:21 +0600 Subject: [PATCH] fix(session): offload JWKS lookup from event loop in AsyncSession --- src/workos/session.py | 99 +++++++++++++++++++++--------- tests/test_session.py | 138 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 28 deletions(-) diff --git a/src/workos/session.py b/src/workos/session.py index 41dd7143..9d9047b5 100644 --- a/src/workos/session.py +++ b/src/workos/session.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import json from dataclasses import dataclass from enum import Enum @@ -22,7 +23,7 @@ import jwt from cryptography.fernet import Fernet -from jwt import PyJWKClient +from jwt import PyJWK, PyJWKClient from ._errors import ( AuthenticationError, @@ -480,17 +481,9 @@ def __init__( jwks_url = f"{client.base_url}sso/jwks/{client.client_id}" self.jwks = _get_jwks_client(jwks_url) - def authenticate( + def _unseal_access_token( self, - ) -> Union[ - AuthenticateWithSessionCookieSuccessResponse, - AuthenticateWithSessionCookieErrorResponse, - ]: - """Validate the sealed session cookie and return the session claims. - - Note: This method is synchronous because it only performs local - operations (Fernet decryption and JWT validation using cached JWKS). - """ + ) -> Union[Dict[str, Any], AuthenticateWithSessionCookieErrorResponse]: if not self.session_data: return AuthenticateWithSessionCookieErrorResponse( authenticated=False, @@ -511,21 +504,24 @@ def authenticate( reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE, ) - try: - signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"]) - decoded = jwt.decode( - session["access_token"], - signing_key.key, - algorithms=self._JWK_ALGORITHMS, - options={"verify_aud": False}, - leeway=self._client._jwt_leeway, - issuer=self._client._jwt_issuer, - ) - except jwt.exceptions.InvalidTokenError: - return AuthenticateWithSessionCookieErrorResponse( - authenticated=False, - reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT, - ) + return session + + def _decode_access_token( + self, + session: Dict[str, Any], + signing_key: PyJWK, + ) -> Union[ + AuthenticateWithSessionCookieSuccessResponse, + AuthenticateWithSessionCookieErrorResponse, + ]: + decoded = jwt.decode( + session["access_token"], + signing_key.key, + algorithms=self._JWK_ALGORITHMS, + options={"verify_aud": False}, + leeway=self._client._jwt_leeway, + issuer=self._client._jwt_issuer, + ) if not _is_user_access_token(decoded): return AuthenticateWithSessionCookieErrorResponse( @@ -546,6 +542,51 @@ def authenticate( feature_flags=decoded.get("feature_flags"), ) + def authenticate( + self, + ) -> Union[ + AuthenticateWithSessionCookieSuccessResponse, + AuthenticateWithSessionCookieErrorResponse, + ]: + """Validate the sealed session cookie and return the session claims. + + Note: This method is synchronous because it only performs local + operations (Fernet decryption and JWT validation using cached JWKS). + """ + session = self._unseal_access_token() + if isinstance(session, AuthenticateWithSessionCookieErrorResponse): + return session + + try: + signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"]) + return self._decode_access_token(session, signing_key) + except jwt.exceptions.InvalidTokenError: + return AuthenticateWithSessionCookieErrorResponse( + authenticated=False, + reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT, + ) + + async def _authenticate_async( + self, + ) -> Union[ + AuthenticateWithSessionCookieSuccessResponse, + AuthenticateWithSessionCookieErrorResponse, + ]: + session = self._unseal_access_token() + if isinstance(session, AuthenticateWithSessionCookieErrorResponse): + return session + + try: + signing_key = await asyncio.to_thread( + self.jwks.get_signing_key_from_jwt, session["access_token"] + ) + return self._decode_access_token(session, signing_key) + except jwt.exceptions.InvalidTokenError: + return AuthenticateWithSessionCookieErrorResponse( + authenticated=False, + reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT, + ) + async def refresh( self, *, @@ -600,7 +641,9 @@ async def refresh( impersonator = auth_response.get("impersonator") try: - signing_key = self.jwks.get_signing_key_from_jwt(access_token) + signing_key = await asyncio.to_thread( + self.jwks.get_signing_key_from_jwt, access_token + ) decoded = jwt.decode( access_token, signing_key.key, @@ -656,7 +699,7 @@ async def refresh( async def get_logout_url(self, return_to: Optional[str] = None) -> str: """Get the logout URL for the current session.""" - auth_response = self.authenticate() + auth_response = await self._authenticate_async() if isinstance(auth_response, AuthenticateWithSessionCookieErrorResponse): raise ValueError( diff --git a/tests/test_session.py b/tests/test_session.py index 0dc0c811..e245ba50 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1018,3 +1018,141 @@ async def test_async_session_refresh_jwks_error_returns_invalid_jwt( assert isinstance(result, RefreshWithSessionCookieErrorResponse) assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT assert session.session_data == original_sealed + + async def _run_with_slow_jwks(self, public_key, coro_factory): + import asyncio + import http.server + import json + import threading + from jwt import PyJWKClient + from jwt.algorithms import RSAAlgorithm + + jwk = json.loads(RSAAlgorithm.to_jwk(public_key)) + jwk["kid"] = "test-kid" + jwk["use"] = "sig" + jwk["alg"] = "RS256" + jwks_payload = json.dumps({"keys": [jwk]}).encode("utf-8") + + jwks_started = threading.Event() + release_jwks = threading.Event() + + class _SlowJWKSHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + jwks_started.set() + if not release_jwks.wait(timeout=1.5): + self.send_response(504) + self.end_headers() + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(jwks_payload))) + self.end_headers() + self.wfile.write(jwks_payload) + + def log_message(self, format, *args): + return + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _SlowJWKSHandler) + port = server.server_address[1] + server_thread = threading.Thread(target=server.serve_forever, daemon=True) + server_thread.start() + + heartbeat_ran_during_jwks = False + + async def _driver(): + nonlocal heartbeat_ran_during_jwks + while not jwks_started.is_set(): + await asyncio.sleep(0.01) + heartbeat_ran_during_jwks = True + release_jwks.set() + + driver_task = asyncio.create_task(_driver()) + try: + jwks_client = PyJWKClient(f"http://127.0.0.1:{port}/jwks") + result = await asyncio.wait_for(coro_factory(jwks_client), timeout=2.5) + await driver_task + finally: + release_jwks.set() + if not driver_task.done(): + driver_task.cancel() + server.shutdown() + server.server_close() + server_thread.join(timeout=2.0) + + return result, heartbeat_ran_during_jwks + + async def test_async_session_refresh_does_not_block_event_loop_on_jwks( + self, async_workos + ): + from unittest.mock import AsyncMock + + private_key, public_key = _generate_rsa_key_pair() + token = pyjwt.encode( + { + "sid": "session_01", + "iat": int(time.time()), + "auth_time": int(time.time()), + "exp": int(time.time() + 3600), + }, + private_key, + algorithm="RS256", + headers={"kid": "test-kid"}, + ) + sealed = seal_data( + {"refresh_token": "rt_old", "user": {"id": "user_01"}}, + COOKIE_PASSWORD, + ) + session = AsyncSession( + client=async_workos, session_data=sealed, cookie_password=COOKIE_PASSWORD + ) + session._client.request_raw = AsyncMock( + return_value={ + "access_token": token, + "refresh_token": "rt_new", + "user": {"id": "user_01"}, + } + ) + + async def _call(jwks_client): + session.jwks = jwks_client + return await session.refresh() + + result, heartbeat_ran = await self._run_with_slow_jwks(public_key, _call) + assert heartbeat_ran + assert isinstance(result, RefreshWithSessionCookieSuccessResponse) + assert result.session_id == "session_01" + + async def test_async_session_get_logout_url_does_not_block_event_loop_on_jwks( + self, async_workos + ): + private_key, public_key = _generate_rsa_key_pair() + token = pyjwt.encode( + { + "sid": "session_01", + "iat": int(time.time()), + "auth_time": int(time.time()), + "exp": int(time.time() + 3600), + }, + private_key, + algorithm="RS256", + headers={"kid": "test-kid"}, + ) + sealed = seal_data( + { + "access_token": token, + "refresh_token": "rt_old", + "user": {"id": "user_01"}, + }, + COOKIE_PASSWORD, + ) + session = AsyncSession( + client=async_workos, session_data=sealed, cookie_password=COOKIE_PASSWORD + ) + + async def _call(jwks_client): + session.jwks = jwks_client + return await session.get_logout_url() + + logout_url, heartbeat_ran = await self._run_with_slow_jwks(public_key, _call) + assert heartbeat_ran + assert "session_id=session_01" in logout_url