diff --git a/pyproject.toml b/pyproject.toml index 7a599a9c..19ee680e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ requires-python = ">=3.10" dependencies = [ "cryptography~=50.0", "httpx2~=2.13", - "pyjwt~=2.12", + "pyjwt~=2.15", "typing_extensions~=4.0; python_version < '3.11'", ] diff --git a/src/workos/session.py b/src/workos/session.py index 41dd7143..8efc9f96 100644 --- a/src/workos/session.py +++ b/src/workos/session.py @@ -6,6 +6,10 @@ from __future__ import annotations import json +import math +import platform +import threading +import time from dataclasses import dataclass from enum import Enum from functools import lru_cache @@ -16,14 +20,21 @@ List, Optional, Sequence, + Tuple, Union, cast, ) import jwt from cryptography.fernet import Fernet -from jwt import PyJWKClient +from cryptography.hazmat.primitives.asymmetric.ec import ( + SECP256R1, + EllipticCurvePublicKey, +) +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +from jwt import PyJWK, PyJWKClient, PyJWKSet +from ._base_client import VERSION as _SDK_VERSION from ._errors import ( AuthenticationError, AuthenticationMethodNotAllowedError, @@ -177,9 +188,211 @@ class RefreshWithSessionCookieErrorResponse: # --------------------------------------------------------------------------- +# The signature algorithms that the SDK accepts for access tokens. The list is +# fixed. The token header, the JWKS and the caller cannot add an algorithm. +# Do not add a symmetric algorithm (HS256, HS384, HS512) or "none". +_ACCESS_TOKEN_ALGORITHMS: Tuple[str, ...] = ("RS256", "ES256") + + +def _key_agrees_with_algorithm(signing_key: PyJWK, algorithm: Optional[str]) -> bool: + """Whether a JWKS key is a key for the signature algorithm of a token. + + RS256 uses an RSA public key only. ES256 uses an EC public key on the + P-256 curve only. If the key has an ``alg`` member, that member must be + equal to ``algorithm``. If the key has a ``use`` member, that member must + be ``sig``. + """ + key = signing_key.key + if algorithm == "RS256": + key_agrees = signing_key.key_type == "RSA" and isinstance(key, RSAPublicKey) + elif algorithm == "ES256": + key_agrees = ( + signing_key.key_type == "EC" + and isinstance(key, EllipticCurvePublicKey) + and isinstance(key.curve, SECP256R1) + ) + else: + key_agrees = False + return ( + key_agrees + # PyJWK gets this name from the ``alg`` member of the key. If the key + # has no ``alg`` member, PyJWK gets the name from the key type. + and signing_key.algorithm_name == algorithm + and signing_key.public_key_use in (None, "sig") + ) + + +def _match_key( + signing_keys: Sequence[PyJWK], kid: Optional[str], algorithm: Optional[str] +) -> Optional[PyJWK]: + """The first key that has ``kid`` and is a key for ``algorithm``.""" + for signing_key in signing_keys: + if signing_key.key_id == kid and _key_agrees_with_algorithm( + signing_key, algorithm + ): + return signing_key + return None + + +def _read_jwk_set(document: Any) -> PyJWKSet: + """Read a JWKS document one key at a time. + + ``PyJWKSet`` reads the document as one unit. A key that PyJWT cannot + read, for example a key with ``"alg": "none"``, makes the whole document + unusable. This function ignores such a key and keeps the other keys. + + Raises: + jwt.exceptions.PyJWKSetError: The document is not a JWKS, or PyJWT + can read none of its keys. + """ + if not isinstance(document, dict): + raise jwt.exceptions.PyJWKSetError("The JWKS document is not a JSON object") + members = cast(Dict[str, Any], document).get("keys") + if not isinstance(members, list): + raise jwt.exceptions.PyJWKSetError("The JWKS document has no keys array") + + readable: List[Dict[str, Any]] = [] + for member in cast(List[Any], members): + if not isinstance(member, dict): + continue + jwk = cast(Dict[str, Any], member) + try: + PyJWK(jwk) + except Exception: + # PyJWT cannot read the key. The error can have a type that + # PyJWT does not document. For example, PyJWT raises + # NotImplementedError for a key with ``"alg": "none"`` and + # KeyError for an ``oct`` key without ``k``. + continue + readable.append(jwk) + if not readable: + raise jwt.exceptions.PyJWKSetError("PyJWT can read no key of the JWKS") + return PyJWKSet(readable) + + +class _JWKSClient(PyJWKClient): + """A ``PyJWKClient`` that reads the JWKS one key at a time and selects + a key by its ``kid`` and the algorithm of the token. + + ``PyJWKClient`` reads the JWKS as one document. A key that PyJWT cannot + read makes the whole document unusable, and no token verifies. It also + selects a key by its ``kid`` only. When an RSA key and an EC key have + the same ``kid``, only the first key in the JWKS verifies tokens. + + The client keeps the keys for ``lifespan`` seconds. For a token whose + key is not in the JWKS, it gets the JWKS again, one time at most in + each ``cooldown_duration`` seconds. + """ + + def __init__(self, uri: str, lifespan: float = 300, **options: Any) -> None: + # The JWKS cache of PyJWKClient reads the document as one unit, thus + # the client keeps the keys that it read in a cache of its own. + super().__init__(uri, cache_jwk_set=False, **options) + self._lifespan = lifespan + self._jwk_set: Optional[PyJWKSet] = None + self._fetched_at: Optional[float] = None + self._lock = threading.RLock() + + def get_jwk_set(self, refresh: bool = False) -> PyJWKSet: + """The keys of the JWKS. + + The client gets the JWKS again if ``refresh`` is true, or if the + keys are ``lifespan`` seconds old or older. + """ + with self._lock: + if refresh or self._jwk_set is None or self._age() >= self._lifespan: + self._jwk_set = _read_jwk_set(self.fetch_data()) + self._fetched_at = time.monotonic() + return self._jwk_set + + def get_signing_key_from_jwt(self, token: Union[str, bytes]) -> PyJWK: + """The key that has the ``kid`` of the token and is a key for the + algorithm of the token.""" + header = jwt.get_unverified_header(token) + return self.get_signing_key_for_algorithm(header.get("kid"), header.get("alg")) + + def get_signing_key_for_algorithm( + self, kid: Optional[str], algorithm: Optional[str] + ) -> PyJWK: + """The first key that has ``kid`` and is a key for ``algorithm``. + + Raises: + jwt.exceptions.PyJWKClientError: The JWKS has no such key, also + after the client got the JWKS again. + """ + with self._lock: + signing_key = _match_key(self.get_signing_keys(), kid, algorithm) + if signing_key is None and self._age() >= self.cooldown_duration: + signing_keys = self.get_signing_keys(refresh=True) + signing_key = _match_key(signing_keys, kid, algorithm) + if signing_key is None: + raise jwt.exceptions.PyJWKClientError( + f'Unable to find a signing key that matches: "{kid}"' + ) + return signing_key + + def _age(self) -> float: + """Seconds since the client got the JWKS. Infinite before the first time.""" + if self._fetched_at is None: + return math.inf + return time.monotonic() - self._fetched_at + + @lru_cache(maxsize=None) -def _get_jwks_client(jwks_url: str) -> PyJWKClient: - return PyJWKClient(jwks_url) +def _get_jwks_client(jwks_url: str) -> _JWKSClient: + user_agent = f"WorkOS Python/{platform.python_version()} Python SDK/{_SDK_VERSION}" + return _JWKSClient(jwks_url, headers={"User-Agent": user_agent}) + + +def _get_signing_key(jwks: PyJWKClient, token: str) -> PyJWK: + """Find the JWKS key that verifies the signature of an access token. + + The SDK makes these checks before it gives the key to PyJWT, because not + all PyJWT versions make them. + + Raises: + jwt.exceptions.InvalidTokenError: The algorithm of the token is not + RS256 or ES256, the token has a ``crit`` header, no usable JWKS + key has the ``kid`` of the token, PyJWT can read no key of the + JWKS, or the key is not a key for the algorithm of the token. + jwt.exceptions.PyJWKClientConnectionError: The JWKS request failed. + OSError: The connection stopped in the body of the JWKS response. + """ + header = jwt.get_unverified_header(token) + algorithm = header.get("alg") + if not isinstance(algorithm, str) or algorithm not in _ACCESS_TOKEN_ALGORITHMS: + raise jwt.exceptions.InvalidAlgorithmError( + "The algorithm of the token is not RS256 or ES256" + ) + if "crit" in header: + # RFC 7515, section 4.1.11: the SDK must understand each extension + # that the "crit" header names. The SDK understands no extension. + raise jwt.exceptions.InvalidTokenError( + 'The token has a "crit" header, which the SDK does not accept' + ) + + try: + signing_key = jwks.get_signing_key_from_jwt(token) + except (jwt.exceptions.PyJWKClientConnectionError, OSError): + # The JWKS request failed. This is not a defect of the token, thus + # the callers keep their usual result for this error. PyJWT raises + # OSError when the connection stops in the body of the response. + raise + except Exception as error: + # The JWKS has no key for the token, or PyJWT can read no key of the + # JWKS. A replacement for ``Session.jwks`` can raise an error of a + # type that PyJWT does not document. + raise jwt.exceptions.InvalidTokenError( + "The JWKS has no usable key for the key ID of the token" + ) from error + + # ``_JWKSClient`` selects a key for the algorithm of the token. A + # replacement for ``Session.jwks`` can select a key by its ``kid`` only. + if not _key_agrees_with_algorithm(signing_key, algorithm): + raise jwt.exceptions.InvalidAlgorithmError( + "The algorithm of the token does not agree with its JWKS key" + ) + return signing_key def seal_data(data: Dict[str, Any], key: str) -> str: @@ -247,9 +460,13 @@ def _is_user_access_token(claims: Dict[str, Any]) -> bool: class Session: - """Server-side session management using sealed cookies and JWT validation.""" + """Server-side session management using sealed cookies and JWT validation. - _JWK_ALGORITHMS: List[str] = ["RS256"] + The access token must have an RS256 or ES256 signature. The key for the + signature comes from the JWKS of the environment. + """ + + _JWK_ALGORITHMS: List[str] = list(_ACCESS_TOKEN_ALGORITHMS) def __init__( self, @@ -266,7 +483,7 @@ def __init__( self.cookie_password = cookie_password jwks_url = f"{client.base_url}sso/jwks/{client.client_id}" - self.jwks = _get_jwks_client(jwks_url) + self.jwks: PyJWKClient = _get_jwks_client(jwks_url) def authenticate( self, @@ -274,7 +491,12 @@ def authenticate( AuthenticateWithSessionCookieSuccessResponse, AuthenticateWithSessionCookieErrorResponse, ]: - """Validate the sealed session cookie and return the session claims.""" + """Validate the sealed session cookie and return the session claims. + + Raises: + jwt.exceptions.PyJWKClientConnectionError: The JWKS request failed. + OSError: The connection stopped in the body of the JWKS response. + """ if not self.session_data: return AuthenticateWithSessionCookieErrorResponse( authenticated=False, @@ -296,10 +518,10 @@ def authenticate( ) try: - signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"]) + signing_key = _get_signing_key(self.jwks, session["access_token"]) decoded = jwt.decode( session["access_token"], - signing_key.key, + signing_key, algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, @@ -384,10 +606,10 @@ def refresh( impersonator = auth_response.get("impersonator") try: - signing_key = self.jwks.get_signing_key_from_jwt(access_token) + signing_key = _get_signing_key(self.jwks, access_token) decoded = jwt.decode( access_token, - signing_key.key, + signing_key, algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, @@ -459,9 +681,13 @@ def get_logout_url(self, return_to: Optional[str] = None) -> str: class AsyncSession: - """Async server-side session management using sealed cookies and JWT validation.""" + """Async server-side session management using sealed cookies and JWT validation. - _JWK_ALGORITHMS: List[str] = ["RS256"] + The access token must have an RS256 or ES256 signature. The key for the + signature comes from the JWKS of the environment. + """ + + _JWK_ALGORITHMS: List[str] = list(_ACCESS_TOKEN_ALGORITHMS) def __init__( self, @@ -478,7 +704,7 @@ def __init__( self.cookie_password = cookie_password jwks_url = f"{client.base_url}sso/jwks/{client.client_id}" - self.jwks = _get_jwks_client(jwks_url) + self.jwks: PyJWKClient = _get_jwks_client(jwks_url) def authenticate( self, @@ -490,6 +716,10 @@ def authenticate( Note: This method is synchronous because it only performs local operations (Fernet decryption and JWT validation using cached JWKS). + + Raises: + jwt.exceptions.PyJWKClientConnectionError: The JWKS request failed. + OSError: The connection stopped in the body of the JWKS response. """ if not self.session_data: return AuthenticateWithSessionCookieErrorResponse( @@ -512,10 +742,10 @@ def authenticate( ) try: - signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"]) + signing_key = _get_signing_key(self.jwks, session["access_token"]) decoded = jwt.decode( session["access_token"], - signing_key.key, + signing_key, algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, @@ -600,10 +830,10 @@ async def refresh( impersonator = auth_response.get("impersonator") try: - signing_key = self.jwks.get_signing_key_from_jwt(access_token) + signing_key = _get_signing_key(self.jwks, access_token) decoded = jwt.decode( access_token, - signing_key.key, + signing_key, algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, diff --git a/tests/test_session.py b/tests/test_session.py index 0dc0c811..c888328f 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1,11 +1,21 @@ +import base64 +import datetime +import hashlib +import hmac +import json import time -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import jwt as pyjwt import pytest +from cryptography import x509 from cryptography.fernet import Fernet, InvalidToken -from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa +from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature +from cryptography.x509.oid import NameOID +import workos.session as session_module from workos import AsyncWorkOSClient, WorkOSClient from workos._errors import ( AuthenticationError, @@ -41,7 +51,7 @@ def _generate_rsa_key_pair(): return private_key, public_key -def _make_jwt(private_key, claims=None, expired=False): +def _jwt_payload(claims=None, expired=False): now = time.time() payload = { "sid": "session_01", @@ -57,12 +67,628 @@ def _make_jwt(private_key, claims=None, expired=False): } if claims: payload.update(claims) - return pyjwt.encode(payload, private_key, algorithm="RS256") + return payload + + +def _make_jwt(private_key, claims=None, expired=False): + return pyjwt.encode(_jwt_payload(claims, expired), private_key, algorithm="RS256") COOKIE_PASSWORD = Fernet.generate_key().decode("utf-8") +# --------------------------------------------------------------------------- +# JWKS and token helpers +# +# The helpers make each JWK and each signature without PyJWT, so that the +# tests do not use the library under test to make their inputs. All keys are +# made for one test run. +# --------------------------------------------------------------------------- + + +def _b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def _b64url_uint(value, size=None): + if size is None: + size = (value.bit_length() + 7) // 8 + return _b64url(value.to_bytes(size, "big")) + + +def _rsa_jwk(public_key, kid, **members): + numbers = public_key.public_numbers() + return { + "kty": "RSA", + "kid": kid, + "use": "sig", + "alg": "RS256", + "n": _b64url_uint(numbers.n), + "e": _b64url_uint(numbers.e), + **members, + } + + +def _ec_jwk(public_key, kid, **members): + numbers = public_key.public_numbers() + size = (public_key.curve.key_size + 7) // 8 + crv, alg = {"secp256r1": ("P-256", "ES256"), "secp384r1": ("P-384", "ES384")}[ + public_key.curve.name + ] + return { + "kty": "EC", + "kid": kid, + "use": "sig", + "alg": alg, + "crv": crv, + "x": _b64url_uint(numbers.x, size), + "y": _b64url_uint(numbers.y, size), + **members, + } + + +def _certificate_members(private_key): + """The ``x5c`` and ``x5t#S256`` members for a self-signed certificate.""" + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "workos-python tests")]) + now = datetime.datetime.now(datetime.timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(private_key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=1)) + .sign(private_key, hashes.SHA256()) + ) + der = certificate.public_bytes(serialization.Encoding.DER) + return { + "x5c": [base64.b64encode(der).decode("ascii")], + "x5t#S256": _b64url(hashlib.sha256(der).digest()), + } + + +def _without(jwk, *members): + return {name: value for name, value in jwk.items() if name not in members} + + +def _signing_key(public_key): + """A ``PyJWK`` for an RSA public key, as ``PyJWKClient`` returns it.""" + return pyjwt.PyJWK(_rsa_jwk(public_key, "test-key")) + + +def _public_pem(private_key): + return private_key.public_key().public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + + +def _rsa_signature(private_key, signing_input, hash_algorithm=None): + return private_key.sign( + signing_input, padding.PKCS1v15(), hash_algorithm or hashes.SHA256() + ) + + +def _rsa_pss_signature(private_key, signing_input): + pss = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32) + return private_key.sign(signing_input, pss, hashes.SHA256()) + + +def _ecdsa_der_signature(private_key, signing_input, hash_algorithm=None): + return private_key.sign(signing_input, ec.ECDSA(hash_algorithm or hashes.SHA256())) + + +def _ecdsa_signature(private_key, signing_input, hash_algorithm=None): + """The JWS form of an ECDSA signature: r || s, each of the curve size.""" + r, s = decode_dss_signature( + _ecdsa_der_signature(private_key, signing_input, hash_algorithm) + ) + size = (private_key.curve.key_size + 7) // 8 + return r.to_bytes(size, "big") + s.to_bytes(size, "big") + + +def _compact_jws(header, sign, claims=None): + """Make a compact JWS by hand, so that a test controls each part.""" + signing_input = ".".join( + _b64url(json.dumps(part, separators=(",", ":")).encode("utf-8")) + for part in ({"typ": "JWT", **header}, _jwt_payload(claims)) + ) + return f"{signing_input}.{_b64url(sign(signing_input.encode('ascii')))}" + + +def _with_signature(token, change): + """Replace the signature of a compact JWS with ``change(signature)``.""" + signing_input, signature = token.rsplit(".", 1) + raw = base64.urlsafe_b64decode(signature + "=" * (-len(signature) % 4)) + return f"{signing_input}.{_b64url(change(raw))}" + + +def _flip_last_bit(signature): + return signature[:-1] + bytes([signature[-1] ^ 0x01]) + + +class _FixedJWKSResponse(pyjwt.PyJWKClient): + """Replaces the HTTP request of a ``PyJWKClient`` with a fixed result.""" + + def __init__(self, keys=(), document=None, error=None, **options): + super().__init__("https://api.workos.test/sso/jwks/client_test_123", **options) + self.keys = list(keys) + self.document = document + self.error = error + self.fetch_count = 0 + + def fetch_data(self): + self.fetch_count += 1 + if self.error is not None: + raise self.error + if self.document is not None: + return self.document + return {"keys": list(self.keys)} + + +class _StaticJWKSClient(_FixedJWKSResponse, session_module._JWKSClient): + """The JWKS client of the SDK, with a fixed result for its HTTP request. + + Only the HTTP request is replaced. The client reads the document, selects + the key and keeps its cache as it does for a document from the network. + """ + + +class _PlainJWKSClient(_FixedJWKSResponse): + """A ``PyJWKClient`` that is not the client of the SDK. + + Code that replaces ``session.jwks`` can give such a client. It reads the + document as one unit and selects a key by its kid only. + """ + + +class _Clock: + """Replaces ``time.monotonic`` with a clock that the test moves.""" + + def __init__(self, monkeypatch): + self.now = 1000.0 + monkeypatch.setattr(session_module.time, "monotonic", lambda: self.now) + + def advance(self, seconds): + self.now += seconds + + +class _SigningKeys: + """Key pairs for one test run and the JWKS members that publish them.""" + + def __init__(self): + self.rsa_private = rsa.generate_private_key( + public_exponent=65537, key_size=2048 + ) + self.other_rsa_private = rsa.generate_private_key( + public_exponent=65537, key_size=2048 + ) + self.ec_private = ec.generate_private_key(ec.SECP256R1()) + self.other_ec_private = ec.generate_private_key(ec.SECP256R1()) + self.p384_private = ec.generate_private_key(ec.SECP384R1()) + self.okp_private = ed25519.Ed25519PrivateKey.generate() + + # The RSA member has the same members as a key from the WorkOS API. + self.rsa_jwk = _rsa_jwk( + self.rsa_private.public_key(), + "rsa-1", + **_certificate_members(self.rsa_private), + ) + self.ec_jwk = _ec_jwk(self.ec_private.public_key(), "ec-1") + self.p384_jwk = _ec_jwk(self.p384_private.public_key(), "p384-1") + + # Keys of types that the SDK cannot use. They must have no effect. + self.okp_jwk = { + "kty": "OKP", + "kid": "okp-1", + "use": "sig", + "alg": "EdDSA", + "crv": "Ed25519", + "x": _b64url( + self.okp_private.public_key().public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + ), + } + self.akp_jwk = { + "kty": "AKP", + "kid": "akp-1", + "use": "sig", + "alg": "ML-DSA-44", + "pub": _b64url(bytes(1312)), + } + self.unknown_kty_jwk = { + "kty": "FUTURE", + "kid": "future-1", + "use": "sig", + "alg": "FUTURE-1", + "material": {"nested": [1, 2, 3]}, + } + + def malformed_members(self): + """JWKS members that are not keys, or keys with a defect.""" + return [ + "not-a-key", + 7, + None, + [], + {}, + {"kid": "no-kty"}, + {"kty": "RSA", "kid": "rsa-no-modulus", "e": "AQAB"}, + {"kty": "RSA", "kid": "rsa-number-modulus", "n": 12345, "e": "AQAB"}, + _without({**self.ec_jwk, "kid": "ec-no-point"}, "x", "y"), + {**self.ec_jwk, "kid": "ec-number-point", "x": 5}, + {**self.ec_jwk, "kid": "ec-short-point", "x": _b64url(bytes(31))}, + { + **self.ec_jwk, + "kid": "ec-off-curve", + "x": _b64url_uint(1, 32), + "y": _b64url_uint(1, 32), + }, + ] + + def sign_rs256(self, data): + return _rsa_signature(self.rsa_private, data) + + def sign_es256(self, data): + return _ecdsa_signature(self.ec_private, data) + + def rs256_token(self, kid="rsa-1", claims=None): + return _compact_jws({"alg": "RS256", "kid": kid}, self.sign_rs256, claims) + + def es256_token(self, kid="ec-1", claims=None): + return _compact_jws({"alg": "ES256", "kid": kid}, self.sign_es256, claims) + + +def _valid_token_cases(keys): + """Map each case to ``(JWKS members, token)``. Each token must verify.""" + rsa_jwk, ec_jwk = keys.rsa_jwk, keys.ec_jwk + future_keys = [keys.okp_jwk, keys.akp_jwk, keys.unknown_kty_jwk] + rs256, es256 = keys.rs256_token(), keys.es256_token() + shared_rsa_jwk, shared_ec_jwk = ( + {**rsa_jwk, "kid": "shared"}, + {**ec_jwk, "kid": "shared"}, + ) + shared_rs256 = keys.rs256_token(kid="shared") + shared_es256 = keys.es256_token(kid="shared") + return { + "rs256": ([rsa_jwk], rs256), + "es256": ([ec_jwk], es256), + "rs256_rsa_then_ec": ([rsa_jwk, ec_jwk], rs256), + "rs256_ec_then_rsa": ([ec_jwk, rsa_jwk], rs256), + "es256_rsa_then_ec": ([rsa_jwk, ec_jwk], es256), + "es256_ec_then_rsa": ([ec_jwk, rsa_jwk], es256), + "rs256_with_okp_akp_and_unknown_kty": ( + [*future_keys, rsa_jwk, ec_jwk], + rs256, + ), + "es256_with_okp_akp_and_unknown_kty": ( + [rsa_jwk, ec_jwk, *future_keys], + es256, + ), + "rs256_with_p384_key": ([keys.p384_jwk, rsa_jwk], rs256), + "es256_with_p384_key": ([keys.p384_jwk, ec_jwk], es256), + "rs256_with_malformed_members": ( + [*keys.malformed_members(), rsa_jwk, ec_jwk], + rs256, + ), + "es256_with_malformed_members": ( + [rsa_jwk, ec_jwk, *keys.malformed_members()], + es256, + ), + "rs256_key_without_x5c_and_x5t": ( + [_without(rsa_jwk, "x5c", "x5t#S256"), ec_jwk], + rs256, + ), + "rs256_key_without_optional_members": ( + [_without(rsa_jwk, "alg", "use", "x5c", "x5t#S256")], + rs256, + ), + "es256_key_without_optional_members": ( + [_without(ec_jwk, "alg", "use")], + es256, + ), + # PyJWT cannot read these keys. The SDK ignores them and keeps the + # other keys of the JWKS. + "rs256_with_oct_key_without_k": ( + [rsa_jwk, ec_jwk, {"kty": "oct", "kid": "oct-1"}], + rs256, + ), + "es256_with_oct_key_without_k": ( + [{"kty": "oct", "kid": "oct-1", "use": "sig", "alg": "HS256"}, ec_jwk], + es256, + ), + "rs256_with_key_with_alg_none": ( + [{"kty": "FUTURE", "kid": "future-2", "alg": "none"}, rsa_jwk, ec_jwk], + rs256, + ), + "es256_with_key_with_alg_none": ( + [rsa_jwk, ec_jwk, {**rsa_jwk, "kid": "rsa-2", "alg": "none"}], + es256, + ), + "rs256_with_key_with_alg_list": ( + [{**ec_jwk, "kid": "ec-2", "alg": ["ES256"]}, rsa_jwk], + rs256, + ), + "es256_with_key_with_alg_object": ( + [ec_jwk, {**rsa_jwk, "kid": "rsa-2", "alg": {"name": "RS256"}}], + es256, + ), + # An RSA key and an EC key have the same kid. The SDK selects the + # key for the algorithm of the token, in each order of the keys. + "rs256_shared_kid_rsa_then_ec": ([shared_rsa_jwk, shared_ec_jwk], shared_rs256), + "rs256_shared_kid_ec_then_rsa": ([shared_ec_jwk, shared_rsa_jwk], shared_rs256), + "es256_shared_kid_rsa_then_ec": ([shared_rsa_jwk, shared_ec_jwk], shared_es256), + "es256_shared_kid_ec_then_rsa": ([shared_ec_jwk, shared_rsa_jwk], shared_es256), + # The first key with the kid is not a key for the algorithm. + "rs256_shared_kid_ps256_key_first": ( + [{**shared_rsa_jwk, "alg": "PS256"}, shared_rsa_jwk], + shared_rs256, + ), + "es256_shared_kid_p384_key_first": ( + [{**keys.p384_jwk, "kid": "shared"}, shared_ec_jwk], + shared_es256, + ), + } + + +def _refused_token_cases(keys): + """Map each case to ``(JWKS members, token)``. No token must verify. + + The header of the token is not acceptable, or the JWKS has no key for + the token. The SDK must refuse the token before PyJWT verifies it. + """ + rsa_jwk, ec_jwk = keys.rsa_jwk, keys.ec_jwk + jwks = [rsa_jwk, ec_jwk] + rs256, es256 = keys.rs256_token(), keys.es256_token() + sign_rs256, sign_es256 = keys.sign_rs256, keys.sign_es256 + shared_rsa_jwk, shared_ec_jwk = ( + {**rsa_jwk, "kid": "shared"}, + {**ec_jwk, "kid": "shared"}, + ) + shared_p384_jwk = {**keys.p384_jwk, "kid": "shared"} + + def sign_p384(data): + return _ecdsa_signature(keys.p384_private, data) + + def sign_hmac_with(private_key, digest=hashlib.sha256): + secret = _public_pem(private_key) + return lambda data: hmac.new(secret, data, digest).digest() + + es256_for_p384 = _compact_jws({"alg": "ES256", "kid": "p384-1"}, sign_p384) + return { + # Algorithm confusion: the header algorithm and the key do not agree. + "rs256_header_ec_kid_ecdsa_signature": ( + jwks, + _compact_jws({"alg": "RS256", "kid": "ec-1"}, sign_es256), + ), + "rs256_header_ec_kid_rsa_signature": ( + jwks, + _compact_jws({"alg": "RS256", "kid": "ec-1"}, sign_rs256), + ), + "es256_header_rsa_kid_rsa_signature": ( + jwks, + _compact_jws({"alg": "ES256", "kid": "rsa-1"}, sign_rs256), + ), + "es256_header_rsa_kid_ecdsa_signature": ( + jwks, + _compact_jws({"alg": "ES256", "kid": "rsa-1"}, sign_es256), + ), + "hs256_rsa_public_key_as_secret": ( + jwks, + _compact_jws( + {"alg": "HS256", "kid": "rsa-1"}, sign_hmac_with(keys.rsa_private) + ), + ), + "hs256_ec_public_key_as_secret": ( + jwks, + _compact_jws( + {"alg": "HS256", "kid": "ec-1"}, sign_hmac_with(keys.ec_private) + ), + ), + "hs384_rsa_public_key_as_secret": ( + jwks, + _compact_jws( + {"alg": "HS384", "kid": "rsa-1"}, + sign_hmac_with(keys.rsa_private, hashlib.sha384), + ), + ), + "hs512_rsa_public_key_as_secret": ( + jwks, + _compact_jws( + {"alg": "HS512", "kid": "rsa-1"}, + sign_hmac_with(keys.rsa_private, hashlib.sha512), + ), + ), + "alg_none": ( + jwks, + _compact_jws({"alg": "none", "kid": "rsa-1"}, lambda data: b""), + ), + "alg_none_with_rsa_signature": ( + jwks, + _compact_jws({"alg": "none", "kid": "rsa-1"}, sign_rs256), + ), + "alg_missing": (jwks, _compact_jws({"kid": "rsa-1"}, sign_rs256)), + # A correct signature, but the algorithm is not in the allow-list. + "rs256_in_lowercase": ( + jwks, + _compact_jws({"alg": "rs256", "kid": "rsa-1"}, sign_rs256), + ), + "es256_in_lowercase": ( + jwks, + _compact_jws({"alg": "es256", "kid": "ec-1"}, sign_es256), + ), + "ps256_rsa_key": ( + jwks, + _compact_jws( + {"alg": "PS256", "kid": "rsa-1"}, + lambda data: _rsa_pss_signature(keys.rsa_private, data), + ), + ), + "rs384_rsa_key": ( + jwks, + _compact_jws( + {"alg": "RS384", "kid": "rsa-1"}, + lambda data: _rsa_signature(keys.rsa_private, data, hashes.SHA384()), + ), + ), + "rs512_rsa_key": ( + jwks, + _compact_jws( + {"alg": "RS512", "kid": "rsa-1"}, + lambda data: _rsa_signature(keys.rsa_private, data, hashes.SHA512()), + ), + ), + "es384_p384_key": ( + [*jwks, keys.p384_jwk], + _compact_jws( + {"alg": "ES384", "kid": "p384-1"}, + lambda data: _ecdsa_signature(keys.p384_private, data, hashes.SHA384()), + ), + ), + "eddsa_okp_key": ( + [*jwks, keys.okp_jwk], + _compact_jws({"alg": "EdDSA", "kid": "okp-1"}, keys.okp_private.sign), + ), + # A correct signature, but the header has a "crit" member. + "rs256_crit_unknown_extension": ( + jwks, + _compact_jws( + { + "alg": "RS256", + "kid": "rsa-1", + "crit": ["urn:example:ext"], + "urn:example:ext": True, + }, + sign_rs256, + ), + ), + "es256_crit_unknown_extension": ( + jwks, + _compact_jws( + { + "alg": "ES256", + "kid": "ec-1", + "crit": ["urn:example:ext"], + "urn:example:ext": True, + }, + sign_es256, + ), + ), + "rs256_crit_b64": ( + jwks, + _compact_jws( + {"alg": "RS256", "kid": "rsa-1", "crit": ["b64"], "b64": True}, + sign_rs256, + ), + ), + "es256_crit_b64": ( + jwks, + _compact_jws( + {"alg": "ES256", "kid": "ec-1", "crit": ["b64"], "b64": True}, + sign_es256, + ), + ), + "es256_crit_empty": ( + jwks, + _compact_jws({"alg": "ES256", "kid": "ec-1", "crit": []}, sign_es256), + ), + # The key that the kid names is not a key for the algorithm. + "es256_kid_names_p384_key": ([*jwks, keys.p384_jwk], es256_for_p384), + "es256_kid_names_p384_key_with_alg_es256": ( + [*jwks, {**keys.p384_jwk, "alg": "ES256"}], + es256_for_p384, + ), + "rs256_key_with_alg_ps256": ([{**rsa_jwk, "alg": "PS256"}, ec_jwk], rs256), + "rs256_key_with_alg_es256": ([{**rsa_jwk, "alg": "ES256"}, ec_jwk], rs256), + "es256_key_with_alg_es384": ([rsa_jwk, {**ec_jwk, "alg": "ES384"}], es256), + "es256_key_with_alg_rs256": ([rsa_jwk, {**ec_jwk, "alg": "RS256"}], es256), + "es256_key_with_alg_in_lowercase": ( + [rsa_jwk, {**ec_jwk, "alg": "es256"}], + es256, + ), + "rs256_key_with_use_enc": ([{**rsa_jwk, "use": "enc"}, ec_jwk], rs256), + "es256_key_with_use_enc": ([rsa_jwk, {**ec_jwk, "use": "enc"}], es256), + "rs256_key_with_alg_none": ([{**rsa_jwk, "alg": "none"}, ec_jwk], rs256), + "es256_key_with_alg_none": ([rsa_jwk, {**ec_jwk, "alg": "none"}], es256), + # No usable key has the kid of the token. + "rs256_unknown_kid": (jwks, keys.rs256_token(kid="rsa-unknown")), + "es256_unknown_kid": (jwks, keys.es256_token(kid="ec-unknown")), + "rs256_no_kid": (jwks, _compact_jws({"alg": "RS256"}, sign_rs256)), + "es256_no_kid": (jwks, _compact_jws({"alg": "ES256"}, sign_es256)), + "rs256_kid_is_a_number": ( + jwks, + _compact_jws({"alg": "RS256", "kid": 7}, sign_rs256), + ), + "es256_key_off_curve": ( + [rsa_jwk, {**ec_jwk, "x": _b64url_uint(1, 32), "y": _b64url_uint(1, 32)}], + es256, + ), + "es256_key_with_alg_list": ([rsa_jwk, {**ec_jwk, "alg": ["ES256"]}], es256), + "es256_only_key_without_point": ([_without(ec_jwk, "x", "y")], es256), + "rs256_empty_jwks": ([], rs256), + # Two keys have the kid of the token. No key is a key for the + # algorithm of the token. + "rs256_shared_kid_without_rsa_key": ( + [shared_ec_jwk, shared_p384_jwk], + keys.rs256_token(kid="shared"), + ), + "es256_shared_kid_without_p256_key": ( + [shared_rsa_jwk, shared_p384_jwk], + keys.es256_token(kid="shared"), + ), + } + + +def _bad_signature_cases(keys): + """Map each case to ``(JWKS members, token)``. No token must verify. + + The header and the key are acceptable, but the signature is not correct. + """ + jwks = [keys.rsa_jwk, keys.ec_jwk] + rs256, es256 = keys.rs256_token(), keys.es256_token() + return { + "rs256_other_key": ( + jwks, + _compact_jws( + {"alg": "RS256", "kid": "rsa-1"}, + lambda data: _rsa_signature(keys.other_rsa_private, data), + ), + ), + "es256_other_key": ( + jwks, + _compact_jws( + {"alg": "ES256", "kid": "ec-1"}, + lambda data: _ecdsa_signature(keys.other_ec_private, data), + ), + ), + "rs256_tampered_signature": (jwks, _with_signature(rs256, _flip_last_bit)), + "es256_tampered_signature": (jwks, _with_signature(es256, _flip_last_bit)), + "es256_signature_63_bytes": ( + jwks, + _with_signature(es256, lambda signature: signature[:-1]), + ), + "es256_signature_65_bytes": ( + jwks, + _with_signature(es256, lambda signature: signature + b"\x00"), + ), + "es256_signature_empty": (jwks, _with_signature(es256, lambda signature: b"")), + "es256_signature_in_der_form": ( + jwks, + _compact_jws( + {"alg": "ES256", "kid": "ec-1"}, + lambda data: _ecdsa_der_signature(keys.ec_private, data), + ), + ), + } + + +_KEYS = _SigningKeys() +_VALID_TOKENS = _valid_token_cases(_KEYS) +_REFUSED_TOKENS = _refused_token_cases(_KEYS) +_INVALID_TOKENS = {**_REFUSED_TOKENS, **_bad_signature_cases(_KEYS)} + + class TestSealUnseal: def test_seal_unseal_roundtrip(self): data = {"access_token": "abc", "user": {"id": "user_01"}} @@ -138,9 +764,7 @@ def _make_sealed_session(self, access_token, refresh_token="rt_123", user=None): def _mock_jwks(self): mock_jwks = MagicMock() - mock_signing_key = MagicMock() - mock_signing_key.key = self.public_key - mock_jwks.get_signing_key_from_jwt.return_value = mock_signing_key + mock_jwks.get_signing_key_from_jwt.return_value = _signing_key(self.public_key) return mock_jwks def test_session_cookie_password_required(self): @@ -635,9 +1259,7 @@ def test_session_refresh_invalid_jwt_returns_invalid_jwt(self): client=self.workos, session_data=sealed, cookie_password=COOKIE_PASSWORD ) mock_jwks = MagicMock() - mock_signing_key = MagicMock() - mock_signing_key.key = other_public_key - mock_jwks.get_signing_key_from_jwt.return_value = mock_signing_key + mock_jwks.get_signing_key_from_jwt.return_value = _signing_key(other_public_key) session.jwks = mock_jwks api_response = { @@ -742,13 +1364,527 @@ def test_unknown_exception_falls_back_to_string(self): assert result == "boom" +def _seal_access_token(access_token): + return seal_data( + { + "access_token": access_token, + "refresh_token": "rt_old", + "user": {"id": "user_01"}, + }, + COOKIE_PASSWORD, + ) + + +def _refresh_response(access_token): + return { + "access_token": access_token, + "refresh_token": "rt_new", + "user": {"id": "user_01"}, + } + + +def _jwks_request_failure(): + return pyjwt.exceptions.PyJWKClientConnectionError( + 'Fail to fetch data from the url, err: "HTTP Error 503: Service Unavailable"' + ) + + +def _jwks_connection_reset(): + """The error for a connection that stops in the body of the JWKS response. + + PyJWT does not change this error to ``PyJWKClientConnectionError``. + """ + return ConnectionResetError("Connection reset by peer") + + +# JWKS documents from which PyJWT gets no usable key. The last entries are +# errors that the JWKS request raises: for a body that is not JSON, for a body +# with too many levels, and an error of a type that PyJWT does not document. +_UNUSABLE_JWKS_DOCUMENTS = { + "empty_keys": {"document": {"keys": []}}, + "no_keys_member": {"document": {}}, + "keys_not_a_list": {"document": {"keys": "rsa-1"}}, + "not_an_object": {"document": ["rsa-1"]}, + "only_unusable_keys": {"keys": [_KEYS.akp_jwk, _KEYS.unknown_kty_jwk]}, + "only_unreadable_keys": { + "keys": [ + {"kty": "FOO", "kid": "foo-1", "alg": "none"}, + {"kty": "oct", "kid": "sym-1"}, + {**_KEYS.ec_jwk, "alg": ["ES256"]}, + ] + }, + "not_json": {"error": json.JSONDecodeError("Expecting value", "", 0)}, + "too_many_levels": { + "error": RecursionError("maximum recursion depth exceeded while decoding") + }, + "error_of_another_type": {"error": RuntimeError("the JWKS is not correct")}, +} + + +class TestSessionSigningKeys: + """RS256 and ES256 access tokens, verified with the JWKS key that the kid names.""" + + def setup_method(self): + self.workos = WorkOSClient( + api_key="sk_test_123", client_id="client_test_123", max_retries=0 + ) + + def teardown_method(self): + self.workos.close() + + def _session(self, jwks, access_token, client=None): + session = Session( + client=client or self.workos, + session_data=_seal_access_token(access_token), + cookie_password=COOKIE_PASSWORD, + ) + session.jwks = jwks + return session + + def _authenticate(self, jwks_keys, access_token): + return self._session(_StaticJWKSClient(jwks_keys), access_token).authenticate() + + def _refresh(self, jwks, new_access_token): + session = self._session(jwks, "at_old") + session._client.request_raw = MagicMock( + return_value=_refresh_response(new_access_token) + ) + return session, session.session_data, session.refresh() + + def test_access_token_algorithms_are_rs256_and_es256(self): + assert session_module._ACCESS_TOKEN_ALGORITHMS == ("RS256", "ES256") + assert Session._JWK_ALGORITHMS == ["RS256", "ES256"] + assert AsyncSession._JWK_ALGORITHMS == ["RS256", "ES256"] + + @pytest.mark.parametrize("case", _VALID_TOKENS) + def test_session_authenticate_accepts_token(self, case): + result = self._authenticate(*_VALID_TOKENS[case]) + assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse) + assert result.authenticated + assert result.session_id == "session_01" + assert result.organization_id == "org_01" + assert result.user == {"id": "user_01"} + + @pytest.mark.parametrize("case", _INVALID_TOKENS) + def test_session_authenticate_rejects_token(self, case): + result = self._authenticate(*_INVALID_TOKENS[case]) + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert not result.authenticated + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize("case", _REFUSED_TOKENS) + def test_session_authenticate_refuses_token_before_verification( + self, monkeypatch, case + ): + # The SDK makes the algorithm and key checks. It does not rely on + # the checks of the PyJWT version in use. + decode = MagicMock(side_effect=AssertionError("jwt.decode was called")) + monkeypatch.setattr(session_module.jwt, "decode", decode) + result = self._authenticate(*_REFUSED_TOKENS[case]) + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + decode.assert_not_called() + + @pytest.mark.parametrize("case", _VALID_TOKENS) + def test_session_refresh_accepts_token(self, case): + jwks_keys, token = _VALID_TOKENS[case] + session, _, result = self._refresh(_StaticJWKSClient(jwks_keys), token) + assert isinstance(result, RefreshWithSessionCookieSuccessResponse) + assert result.authenticated + assert result.session_id == "session_01" + unsealed = unseal_data(result.sealed_session, COOKIE_PASSWORD) + assert unsealed["access_token"] == token + assert unsealed["refresh_token"] == "rt_new" + assert session.session_data == result.sealed_session + + @pytest.mark.parametrize("case", _INVALID_TOKENS) + def test_session_refresh_rejects_token(self, case): + jwks_keys, token = _INVALID_TOKENS[case] + session, original_sealed, result = self._refresh( + _StaticJWKSClient(jwks_keys), token + ) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert not result.authenticated + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + @pytest.mark.parametrize( + "claims", + [ + {"exp": 1}, + {"sub_profile": "ai_agent"}, + {"sub_type": "authkit"}, + {"auth_time": None}, + {"sid": None}, + ], + ) + def test_session_authenticate_keeps_claim_checks_for_es256_token(self, claims): + result = self._authenticate([_KEYS.ec_jwk], _KEYS.es256_token(claims=claims)) + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize( + "iss, accepted", + [("https://api.workos.com", True), ("https://other.example.com", False)], + ) + def test_session_authenticate_keeps_issuer_check_for_es256_token( + self, iss, accepted + ): + client = WorkOSClient( + api_key="sk_test_123", + client_id="client_test_123", + jwt_issuer="https://api.workos.com", + max_retries=0, + ) + try: + session = self._session( + _StaticJWKSClient([_KEYS.ec_jwk]), + _KEYS.es256_token(claims={"iss": iss}), + client=client, + ) + result = session.authenticate() + finally: + client.close() + assert result.authenticated is accepted + if not accepted: + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert ( + result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + ) + + @pytest.mark.parametrize( + "case", ["es384_p384_key", "eddsa_okp_key", "hs256_rsa_public_key_as_secret"] + ) + def test_session_allow_list_does_not_follow_the_class_attribute( + self, monkeypatch, case + ): + monkeypatch.setattr( + Session, + "_JWK_ALGORITHMS", + ["RS256", "ES256", "ES384", "EdDSA", "HS256", "none"], + ) + result = self._authenticate(*_INVALID_TOKENS[case]) + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize( + "case", ["hs256_rsa_public_key_as_secret", "alg_none", "ps256_rsa_key"] + ) + def test_session_makes_no_jwks_request_for_other_algorithms(self, case): + jwks_keys, token = _INVALID_TOKENS[case] + jwks = _StaticJWKSClient(jwks_keys) + result = self._session(jwks, token).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert jwks.fetch_count == 0 + + def test_session_get_logout_url_with_es256_token(self): + session = self._session( + _StaticJWKSClient([_KEYS.rsa_jwk, _KEYS.ec_jwk]), _KEYS.es256_token() + ) + assert "session_id=session_01" in session.get_logout_url() + + def test_session_unknown_kid_does_not_get_jwks_again_in_cooldown(self): + # The first request for the JWKS starts the cooldown. + jwks = _StaticJWKSClient([_KEYS.rsa_jwk, _KEYS.ec_jwk]) + session = self._session(jwks, _KEYS.es256_token(kid="ec-unknown")) + for _ in range(3): + result = session.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert ( + result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + ) + assert jwks.fetch_count == 1 + + def test_session_unknown_kid_gets_jwks_again_after_cooldown(self, monkeypatch): + clock = _Clock(monkeypatch) + jwks = _StaticJWKSClient([_KEYS.rsa_jwk], cooldown_duration=30) + session = self._session(jwks, _KEYS.es256_token()) + assert not session.authenticate().authenticated + assert jwks.fetch_count == 1 + + jwks.keys.append(_KEYS.ec_jwk) + clock.advance(29) + assert not session.authenticate().authenticated + assert jwks.fetch_count == 1 + + clock.advance(1) + assert session.authenticate().authenticated + assert jwks.fetch_count == 2 + + def test_session_jwks_client_keeps_keys_for_lifespan(self, monkeypatch): + clock = _Clock(monkeypatch) + jwks = _StaticJWKSClient([_KEYS.rsa_jwk], lifespan=300) + session = self._session(jwks, _KEYS.rs256_token()) + for _ in range(3): + assert session.authenticate().authenticated + clock.advance(299) + assert session.authenticate().authenticated + assert jwks.fetch_count == 1 + + clock.advance(1) + assert session.authenticate().authenticated + assert jwks.fetch_count == 2 + + def test_session_jwks_client_ignores_keys_that_pyjwt_cannot_read(self): + jwks = _StaticJWKSClient( + [ + {"kty": "FOO", "kid": "foo-1", "alg": "none"}, + {"kty": "oct", "kid": "sym-1"}, + {**_KEYS.ec_jwk, "kid": "ec-2", "alg": ["ES256"]}, + "not-a-key", + _KEYS.rsa_jwk, + _KEYS.ec_jwk, + ] + ) + assert [key.key_id for key in jwks.get_jwk_set()] == ["rsa-1", "ec-1"] + assert jwks.fetch_count == 1 + + def test_session_jwks_client_selects_key_by_kid_and_algorithm(self): + jwks = _StaticJWKSClient( + [{**_KEYS.ec_jwk, "kid": "shared"}, {**_KEYS.rsa_jwk, "kid": "shared"}] + ) + rsa_key = jwks.get_signing_key_from_jwt(_KEYS.rs256_token(kid="shared")) + ec_key = jwks.get_signing_key_from_jwt(_KEYS.es256_token(kid="shared")) + assert (rsa_key.key_id, rsa_key.key_type) == ("shared", "RSA") + assert (ec_key.key_id, ec_key.key_type) == ("shared", "EC") + assert jwks.fetch_count == 1 + + @pytest.mark.parametrize( + "case", ["rs256", "es256", "rs256_ec_then_rsa", "es256_rsa_then_ec"] + ) + def test_session_accepts_token_from_replacement_jwks_client(self, case): + # Code that replaces ``session.jwks`` can give any ``PyJWKClient``. + jwks_keys, token = _VALID_TOKENS[case] + result = self._session(_PlainJWKSClient(jwks_keys), token).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse) + assert result.session_id == "session_01" + + @pytest.mark.parametrize( + "case", + [ + "rs256_key_with_alg_ps256", + "es256_key_with_alg_rs256", + "rs256_key_with_use_enc", + "es256_kid_names_p384_key", + "es256_kid_names_p384_key_with_alg_es256", + "rs256_unknown_kid", + ], + ) + def test_session_checks_key_from_replacement_jwks_client(self, monkeypatch, case): + # A ``PyJWKClient`` selects a key by its kid only. The SDK makes sure + # that the key is a key for the algorithm of the token. + decode = MagicMock(side_effect=AssertionError("jwt.decode was called")) + monkeypatch.setattr(session_module.jwt, "decode", decode) + jwks_keys, token = _REFUSED_TOKENS[case] + result = self._session(_PlainJWKSClient(jwks_keys), token).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + decode.assert_not_called() + + def test_session_authenticate_finds_key_added_to_jwks(self): + jwks = _StaticJWKSClient([_KEYS.rsa_jwk], cooldown_duration=0) + first = self._session(jwks, _KEYS.rs256_token()).authenticate() + assert isinstance(first, AuthenticateWithSessionCookieSuccessResponse) + + jwks.keys.append(_KEYS.ec_jwk) + second = self._session(jwks, _KEYS.es256_token()).authenticate() + assert isinstance(second, AuthenticateWithSessionCookieSuccessResponse) + assert jwks.fetch_count == 2 + + @pytest.mark.parametrize("case", _UNUSABLE_JWKS_DOCUMENTS) + def test_session_authenticate_rejects_token_when_jwks_has_no_usable_key(self, case): + jwks = _StaticJWKSClient(**_UNUSABLE_JWKS_DOCUMENTS[case]) + result = self._session(jwks, _KEYS.es256_token()).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize("case", _UNUSABLE_JWKS_DOCUMENTS) + def test_session_refresh_rejects_token_when_jwks_has_no_usable_key(self, case): + jwks = _StaticJWKSClient(**_UNUSABLE_JWKS_DOCUMENTS[case]) + session, original_sealed, result = self._refresh(jwks, _KEYS.es256_token()) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + def test_session_authenticate_raises_when_jwks_request_fails(self): + # A JWKS request failure is not a defect of the token. This change + # keeps the result that each method had for it. + jwks = _StaticJWKSClient(error=_jwks_request_failure()) + session = self._session(jwks, _KEYS.es256_token()) + with pytest.raises(pyjwt.exceptions.PyJWKClientConnectionError): + session.authenticate() + + def test_session_refresh_returns_invalid_jwt_when_jwks_request_fails(self): + jwks = _StaticJWKSClient(error=_jwks_request_failure()) + session, original_sealed, result = self._refresh(jwks, _KEYS.es256_token()) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + def test_session_authenticate_raises_when_jwks_connection_resets(self): + # This error is also a JWKS request failure, not a defect of the + # JWKS. Each method keeps the result that it had for it. + jwks = _StaticJWKSClient(error=_jwks_connection_reset()) + session = self._session(jwks, _KEYS.es256_token()) + with pytest.raises(ConnectionResetError): + session.authenticate() + + def test_session_refresh_keeps_reason_when_jwks_connection_resets(self): + error = _jwks_connection_reset() + jwks = _StaticJWKSClient(error=error) + session, original_sealed, result = self._refresh(jwks, _KEYS.es256_token()) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == str(error) + assert session.session_data == original_sealed + + def test_session_jwks_client_sends_user_agent_and_limits_refetch_rate(self): + session = Session( + client=self.workos, session_data="sealed", cookie_password=COOKIE_PASSWORD + ) + assert isinstance(session.jwks, pyjwt.PyJWKClient) + assert isinstance(session.jwks, session_module._JWKSClient) + assert session.jwks.uri == f"{self.workos.base_url}sso/jwks/client_test_123" + api_headers = self.workos._build_headers("get", None, None) + assert session.jwks.headers == {"User-Agent": api_headers["User-Agent"]} + assert session.jwks.cooldown_duration > 0 + + +@pytest.mark.asyncio +class TestAsyncSessionSigningKeys: + """The checks of ``TestSessionSigningKeys``, for ``AsyncSession``.""" + + def _session(self, client, jwks, access_token): + session = AsyncSession( + client=client, + session_data=_seal_access_token(access_token), + cookie_password=COOKIE_PASSWORD, + ) + session.jwks = jwks + return session + + async def _refresh(self, client, jwks, new_access_token): + session = self._session(client, jwks, "at_old") + session._client.request_raw = AsyncMock( + return_value=_refresh_response(new_access_token) + ) + return session, session.session_data, await session.refresh() + + @pytest.mark.parametrize("case", _VALID_TOKENS) + async def test_async_session_authenticate_accepts_token(self, async_workos, case): + jwks_keys, token = _VALID_TOKENS[case] + session = self._session(async_workos, _StaticJWKSClient(jwks_keys), token) + result = session.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse) + assert result.authenticated + assert result.session_id == "session_01" + + @pytest.mark.parametrize("case", _INVALID_TOKENS) + async def test_async_session_authenticate_rejects_token(self, async_workos, case): + jwks_keys, token = _INVALID_TOKENS[case] + session = self._session(async_workos, _StaticJWKSClient(jwks_keys), token) + result = session.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert not result.authenticated + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize("case", _VALID_TOKENS) + async def test_async_session_refresh_accepts_token(self, async_workos, case): + jwks_keys, token = _VALID_TOKENS[case] + session, _, result = await self._refresh( + async_workos, _StaticJWKSClient(jwks_keys), token + ) + assert isinstance(result, RefreshWithSessionCookieSuccessResponse) + assert result.authenticated + assert result.session_id == "session_01" + unsealed = unseal_data(result.sealed_session, COOKIE_PASSWORD) + assert unsealed["access_token"] == token + assert session.session_data == result.sealed_session + + @pytest.mark.parametrize("case", _INVALID_TOKENS) + async def test_async_session_refresh_rejects_token(self, async_workos, case): + jwks_keys, token = _INVALID_TOKENS[case] + session, original_sealed, result = await self._refresh( + async_workos, _StaticJWKSClient(jwks_keys), token + ) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert not result.authenticated + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + async def test_async_session_get_logout_url_with_es256_token(self, async_workos): + session = self._session( + async_workos, + _StaticJWKSClient([_KEYS.rsa_jwk, _KEYS.ec_jwk]), + _KEYS.es256_token(), + ) + assert "session_id=session_01" in await session.get_logout_url() + + @pytest.mark.parametrize("case", _UNUSABLE_JWKS_DOCUMENTS) + async def test_async_session_authenticate_rejects_token_when_jwks_has_no_usable_key( + self, async_workos, case + ): + jwks = _StaticJWKSClient(**_UNUSABLE_JWKS_DOCUMENTS[case]) + result = self._session(async_workos, jwks, _KEYS.es256_token()).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + + @pytest.mark.parametrize("case", _UNUSABLE_JWKS_DOCUMENTS) + async def test_async_session_refresh_rejects_token_when_jwks_has_no_usable_key( + self, async_workos, case + ): + jwks = _StaticJWKSClient(**_UNUSABLE_JWKS_DOCUMENTS[case]) + session, original_sealed, result = await self._refresh( + async_workos, jwks, _KEYS.es256_token() + ) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + async def test_async_session_authenticate_raises_when_jwks_request_fails( + self, async_workos + ): + jwks = _StaticJWKSClient(error=_jwks_request_failure()) + session = self._session(async_workos, jwks, _KEYS.es256_token()) + with pytest.raises(pyjwt.exceptions.PyJWKClientConnectionError): + session.authenticate() + + async def test_async_session_refresh_returns_invalid_jwt_when_jwks_request_fails( + self, async_workos + ): + jwks = _StaticJWKSClient(error=_jwks_request_failure()) + session, original_sealed, result = await self._refresh( + async_workos, jwks, _KEYS.es256_token() + ) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert session.session_data == original_sealed + + async def test_async_session_authenticate_raises_when_jwks_connection_resets( + self, async_workos + ): + jwks = _StaticJWKSClient(error=_jwks_connection_reset()) + session = self._session(async_workos, jwks, _KEYS.es256_token()) + with pytest.raises(ConnectionResetError): + session.authenticate() + + async def test_async_session_refresh_keeps_reason_when_jwks_connection_resets( + self, async_workos + ): + error = _jwks_connection_reset() + jwks = _StaticJWKSClient(error=error) + session, original_sealed, result = await self._refresh( + async_workos, jwks, _KEYS.es256_token() + ) + assert isinstance(result, RefreshWithSessionCookieErrorResponse) + assert result.reason == str(error) + assert session.session_data == original_sealed + + @pytest.mark.asyncio class TestAsyncSession: def _mock_jwks(self, public_key): mock_jwks = MagicMock() - mock_signing_key = MagicMock() - mock_signing_key.key = public_key - mock_jwks.get_signing_key_from_jwt.return_value = mock_signing_key + mock_jwks.get_signing_key_from_jwt.return_value = _signing_key(public_key) return mock_jwks async def test_async_session_authenticate_no_data(self, async_workos): diff --git a/uv.lock b/uv.lock index 5abdaf26..3479a166 100644 --- a/uv.lock +++ b/uv.lock @@ -1400,7 +1400,7 @@ type-check = [ requires-dist = [ { name = "cryptography", specifier = "~=50.0" }, { name = "httpx2", specifier = "~=2.13" }, - { name = "pyjwt", specifier = "~=2.12" }, + { name = "pyjwt", specifier = "~=2.15" }, { name = "typing-extensions", marker = "python_full_version < '3.11'", specifier = "~=4.0" }, ]