From dbd4498a9b03107e258fef1d8d4e62a1944a4597 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Fri, 4 Dec 2026 04:54:25 -0500 Subject: [PATCH] fix(session): accept each JWT algorithm that the JWKS key can verify A list from #788 permits only RS256 and ES256 access tokens. This change removes that list. The JWKS key that the kid of the token names decides the algorithm. PyJWT makes each decision from the alg, type and curve of that key. A test adds an algorithm to the PyJWT registry, and its token verifies. The SDK uses public keys only. Unsigned and MAC tokens never verify. A token that PyJWT cannot verify gives the failure reason invalid_jwt. --- src/workos/session.py | 259 +++++--- tests/test_session.py | 1347 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 1481 insertions(+), 125 deletions(-) diff --git a/src/workos/session.py b/src/workos/session.py index 8efc9f96..419ebe23 100644 --- a/src/workos/session.py +++ b/src/workos/session.py @@ -20,19 +20,15 @@ List, Optional, Sequence, - Tuple, Union, cast, ) import jwt from cryptography.fernet import Fernet -from cryptography.hazmat.primitives.asymmetric.ec import ( - SECP256R1, - EllipticCurvePublicKey, -) -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes from jwt import PyJWK, PyJWKClient, PyJWKSet +from jwt.algorithms import HMACAlgorithm, NoneAlgorithm, get_default_algorithms from ._base_client import VERSION as _SDK_VERSION from ._errors import ( @@ -188,38 +184,80 @@ 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") +class _JWKSKey(PyJWK): + """A JWKS key that keeps its JWK. + + ``PyJWK`` has no public name for the JWK. The SDK reads the JWK to know + if the key has an ``alg`` member. + """ + + def __init__(self, jwk: Dict[str, Any], algorithm: Optional[str] = None) -> None: + super().__init__(jwk, algorithm) + self.jwk = jwk -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. +class _JWKSKeySet(PyJWKSet): + """A key set that holds the keys that the SDK read. - 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``. + ``PyJWKSet`` reads each key again with no algorithm. Thus it cannot hold + a key that PyJWT reads only for a given algorithm. """ - 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 + + def __init__(self, keys: List[PyJWK]) -> None: + self.keys = keys + + +def _key_for_algorithm(signing_key: PyJWK, algorithm: Optional[str]) -> Optional[PyJWK]: + """The JWKS key as a key for the signature algorithm of a token, or None. + + The SDK has no list of algorithms. The JWKS key decides the algorithm, + and PyJWT makes each decision: + + - PyJWT gives one algorithm to a key when it reads the key. It uses the + ``alg`` member of the key. If the key has no ``alg`` member, it uses + the type and the curve of the key. ``_read_jwk`` gives the rule for a + key that gets no algorithm in that way. + - If the key has an ``alg`` member, ``algorithm`` must be equal to it. + - If the key has no ``alg`` member, PyJWT reads the key again for + ``algorithm``. PyJWT refuses an algorithm that is not for the type of + the key. + - PyJWT refuses a key that is not on the curve of its algorithm. + + A key from a replacement for ``Session.jwks`` is a ``PyJWK``. It does + not show if its JWK has an ``alg`` member. Thus ``algorithm`` must be + equal to the algorithm that PyJWT gave to that key. + + The key must be a public key. A symmetric key and a private key are not + keys for an access token. If the key has a ``use`` member, that member + must be ``sig``. + + Returns: + The key, or None if the key is not a key for ``algorithm``. + """ + try: + if ( + signing_key.algorithm_name != algorithm + and isinstance(signing_key, _JWKSKey) + and "alg" not in signing_key.jwk + ): + # ``PyJWK`` does not compare a given algorithm with the ``alg`` + # member of the key. Thus the SDK gives an algorithm only for a + # key that has no ``alg`` member. + signing_key = PyJWK(signing_key.jwk, algorithm) + # ``jwt.decode`` makes this check again, but its error for a key of + # an incorrect type or curve is not an ``InvalidTokenError``. + key = signing_key.Algorithm.prepare_key(signing_key.key) + except Exception: + # PyJWT does not accept the algorithm for the key. The error can + # have a type that PyJWT does not document. + return None + if ( + signing_key.algorithm_name == algorithm + and isinstance(key, PublicKeyTypes) and signing_key.public_key_use in (None, "sig") - ) + ): + return signing_key + return None def _match_key( @@ -227,10 +265,42 @@ def _match_key( ) -> 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 + if signing_key.key_id == kid: + key = _key_for_algorithm(signing_key, algorithm) + if key is not None: + return key + return None + + +def _read_jwk(jwk: Dict[str, Any]) -> Optional[PyJWK]: + """Read one key of a JWKS, or give None if PyJWT cannot read the key. + + PyJWT gets the algorithm of a key from its ``alg`` member. If the key + has no ``alg`` member, PyJWT gets the algorithm from the type and the + curve of the key. For some keys, PyJWT gets no algorithm in that way. + An algorithm of PyJWT can read some of these keys. + + Thus the SDK asks each algorithm of PyJWT to read a key that has no + ``alg`` member. The first algorithm that reads the key becomes the + algorithm of the key. ``_key_for_algorithm`` reads the key again for a + token that has a different algorithm. + """ + try: + return _JWKSKey(jwk) + except Exception: + # PyJWT cannot read the key. The error can have a type that PyJWT + # does not document. For example, PyJWT raises TypeError for a key + # whose ``alg`` member is a list and KeyError for an ``oct`` key + # without ``k``. + if "alg" in jwk: + # The ``alg`` member decides the algorithm. The SDK does not + # read the key for a different algorithm. + return None + for name in get_default_algorithms(): + try: + return _JWKSKey(jwk, name) + except Exception: + continue return None @@ -238,8 +308,9 @@ 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. + read, for example a key whose ``alg`` member is a list, 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 @@ -251,23 +322,16 @@ def _read_jwk_set(document: Any) -> PyJWKSet: if not isinstance(members, list): raise jwt.exceptions.PyJWKSetError("The JWKS document has no keys array") - readable: List[Dict[str, Any]] = [] + keys: List[PyJWK] = [] 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: + key = _read_jwk(cast(Dict[str, Any], member)) + if key is not None: + keys.append(key) + if not keys: raise jwt.exceptions.PyJWKSetError("PyJWT can read no key of the JWKS") - return PyJWKSet(readable) + return _JWKSKeySet(keys) class _JWKSClient(PyJWKClient): @@ -347,22 +411,41 @@ def _get_jwks_client(jwks_url: str) -> _JWKSClient: 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. + The key decides the algorithm of the token. ``_key_for_algorithm`` gives + the rules. The SDK makes these checks before it gives the key to PyJWT. 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.InvalidTokenError: One of these conditions is true: + + - PyJWT cannot read the token. + - PyJWT has no public key algorithm with the name in the token. + - The token has a ``crit`` header. + - No usable JWKS key has the ``kid`` of the token. + - PyJWT can read no key of the JWKS. + - 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) + try: + header = jwt.get_unverified_header(token) + except jwt.exceptions.InvalidTokenError: + raise + except Exception as error: + # PyJWT cannot read the token. For example, PyJWT raises + # UnicodeEncodeError for a token that has a lone surrogate. + raise jwt.exceptions.InvalidTokenError("PyJWT cannot read the token") from error algorithm = header.get("alg") - if not isinstance(algorithm, str) or algorithm not in _ACCESS_TOKEN_ALGORITHMS: + signature_algorithm = ( + get_default_algorithms().get(algorithm) if isinstance(algorithm, str) else None + ) + if signature_algorithm is None or isinstance( + signature_algorithm, (HMACAlgorithm, NoneAlgorithm) + ): + # PyJWT does not know the algorithm, or the algorithm is a MAC or + # gives no signature. No JWKS key can verify the token, thus the SDK + # makes no JWKS request. raise jwt.exceptions.InvalidAlgorithmError( - "The algorithm of the token is not RS256 or ES256" + "PyJWT has no public key algorithm with the name in the token" ) if "crit" in header: # RFC 7515, section 4.1.11: the SDK must understand each extension @@ -388,11 +471,35 @@ def _get_signing_key(jwks: PyJWKClient, token: str) -> PyJWK: # ``_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): + key = _key_for_algorithm(signing_key, algorithm) + if key is None: raise jwt.exceptions.InvalidAlgorithmError( "The algorithm of the token does not agree with its JWKS key" ) - return signing_key + return key + + +def _decode(token: str, signing_key: PyJWK, **arguments: Any) -> Dict[str, Any]: + """Verify an access token with PyJWT, and give the claims of the token. + + PyJWT gives an ``InvalidTokenError`` for a signature that is not + correct. The signature check can also raise an error of a different + type. For example, ``cryptography`` raises ``ValueError`` for an RSA key + that is too small for the hash of the algorithm. PyJWT cannot verify the + token then. Thus this function changes each error of a different type to + an ``InvalidTokenError``. + + Raises: + jwt.exceptions.InvalidTokenError: PyJWT cannot verify the token. + """ + try: + return jwt.decode(token, signing_key, **arguments) + except jwt.exceptions.InvalidTokenError: + raise + except Exception as error: + raise jwt.exceptions.InvalidTokenError( + "PyJWT cannot verify the token" + ) from error def seal_data(data: Dict[str, Any], key: str) -> str: @@ -462,12 +569,11 @@ def _is_user_access_token(claims: Dict[str, Any]) -> bool: class Session: """Server-side session management using sealed cookies and JWT validation. - The access token must have an RS256 or ES256 signature. The key for the - signature comes from the JWKS of the environment. + The key for the signature of the access token comes from the JWKS of the + environment. That key decides the signature algorithm. The SDK has no + list of algorithms. """ - _JWK_ALGORITHMS: List[str] = list(_ACCESS_TOKEN_ALGORITHMS) - def __init__( self, *, @@ -519,10 +625,9 @@ def authenticate( try: signing_key = _get_signing_key(self.jwks, session["access_token"]) - decoded = jwt.decode( + decoded = _decode( session["access_token"], signing_key, - algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, issuer=self._client._jwt_issuer, @@ -607,10 +712,9 @@ def refresh( try: signing_key = _get_signing_key(self.jwks, access_token) - decoded = jwt.decode( + decoded = _decode( access_token, signing_key, - algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, issuer=self._client._jwt_issuer, @@ -683,12 +787,11 @@ def get_logout_url(self, return_to: Optional[str] = None) -> str: class AsyncSession: """Async server-side session management using sealed cookies and JWT validation. - The access token must have an RS256 or ES256 signature. The key for the - signature comes from the JWKS of the environment. + The key for the signature of the access token comes from the JWKS of the + environment. That key decides the signature algorithm. The SDK has no + list of algorithms. """ - _JWK_ALGORITHMS: List[str] = list(_ACCESS_TOKEN_ALGORITHMS) - def __init__( self, *, @@ -743,10 +846,9 @@ def authenticate( try: signing_key = _get_signing_key(self.jwks, session["access_token"]) - decoded = jwt.decode( + decoded = _decode( session["access_token"], signing_key, - algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, issuer=self._client._jwt_issuer, @@ -831,10 +933,9 @@ async def refresh( try: signing_key = _get_signing_key(self.jwks, access_token) - decoded = jwt.decode( + decoded = _decode( access_token, signing_key, - algorithms=self._JWK_ALGORITHMS, options={"verify_aud": False}, leeway=self._client._jwt_leeway, issuer=self._client._jwt_issuer, diff --git a/tests/test_session.py b/tests/test_session.py index c888328f..ea510504 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -9,11 +9,20 @@ import jwt as pyjwt import pytest from cryptography import x509 +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa +from cryptography.hazmat.primitives.asymmetric import ( + ec, + ed448, + ed25519, + mldsa, + padding, + rsa, +) from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature from cryptography.x509.oid import NameOID +from jwt.algorithms import Algorithm, RSAAlgorithm, get_default_algorithms import workos.session as session_module from workos import AsyncWorkOSClient, WorkOSClient @@ -112,9 +121,12 @@ def _rsa_jwk(public_key, kid, **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 - ] + crv, alg = { + "secp256r1": ("P-256", "ES256"), + "secp384r1": ("P-384", "ES384"), + "secp521r1": ("P-521", "ES512"), + "secp256k1": ("secp256k1", "ES256K"), + }[public_key.curve.name] return { "kty": "EC", "kid": kid, @@ -127,6 +139,53 @@ def _ec_jwk(public_key, kid, **members): } +def _okp_jwk(public_key, kid, **members): + return { + "kty": "OKP", + "kid": kid, + "use": "sig", + "alg": "EdDSA", + "crv": "Ed448" if isinstance(public_key, ed448.Ed448PublicKey) else "Ed25519", + "x": _b64url( + public_key.public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + ), + **members, + } + + +def _private_members(private_key): + """The JWK members that hold a private key. A JWKS must not have them.""" + if isinstance(private_key, rsa.RSAPrivateKey): + numbers = private_key.private_numbers() + return { + "d": _b64url_uint(numbers.d), + "p": _b64url_uint(numbers.p), + "q": _b64url_uint(numbers.q), + "dp": _b64url_uint(numbers.dmp1), + "dq": _b64url_uint(numbers.dmq1), + "qi": _b64url_uint(numbers.iqmp), + } + if isinstance(private_key, ec.EllipticCurvePrivateKey): + size = (private_key.curve.key_size + 7) // 8 + return {"d": _b64url_uint(private_key.private_numbers().private_value, size)} + return { + "d": _b64url( + private_key.private_bytes( + serialization.Encoding.Raw, + serialization.PrivateFormat.Raw, + serialization.NoEncryption(), + ) + ) + } + + +def _oct_jwk(secret, kid, **members): + """A symmetric key. A JWKS for access tokens must not have such a key.""" + return {"kty": "oct", "kid": kid, "use": "sig", "k": _b64url(secret), **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")]) @@ -169,9 +228,12 @@ def _rsa_signature(private_key, signing_input, hash_algorithm=None): ) -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 _rsa_pss_signature(private_key, signing_input, hash_algorithm=None): + hash_algorithm = hash_algorithm or hashes.SHA256() + pss = padding.PSS( + mgf=padding.MGF1(hash_algorithm), salt_length=hash_algorithm.digest_size + ) + return private_key.sign(signing_input, pss, hash_algorithm) def _ecdsa_der_signature(private_key, signing_input, hash_algorithm=None): @@ -187,6 +249,23 @@ def _ecdsa_signature(private_key, signing_input, hash_algorithm=None): return r.to_bytes(size, "big") + s.to_bytes(size, "big") +def _signer(private_key, algorithm): + """A function that makes the signature of ``algorithm`` with ``private_key``. + + The function does not make sure that the key is a key for the algorithm. + Thus a test can sign with a key of another type or curve. + """ + if algorithm == "EdDSA": + return private_key.sign + hash_algorithm = {"256": hashes.SHA256, "384": hashes.SHA384, "512": hashes.SHA512}[ + algorithm[2:5] + ]() + sign = {"RS": _rsa_signature, "PS": _rsa_pss_signature, "ES": _ecdsa_signature}[ + algorithm[:2] + ] + return lambda data: sign(private_key, data, hash_algorithm) + + def _compact_jws(header, sign, claims=None): """Make a compact JWS by hand, so that a test controls each part.""" signing_input = ".".join( @@ -196,6 +275,13 @@ def _compact_jws(header, sign, claims=None): return f"{signing_input}.{_b64url(sign(signing_input.encode('ascii')))}" +def _signed_token(algorithm, kid, private_key, **header): + """A token with the header ``alg`` and a signature of that algorithm.""" + return _compact_jws( + {"alg": algorithm, "kid": kid, **header}, _signer(private_key, algorithm) + ) + + def _with_signature(token, change): """Replace the signature of a compact JWS with ``change(signature)``.""" signing_input, signature = token.rsplit(".", 1) @@ -207,6 +293,42 @@ def _flip_last_bit(signature): return signature[:-1] + bytes([signature[-1] ^ 0x01]) +class _LaterAlgorithm(Algorithm): + """ML-DSA-65 for PyJWT, as a later PyJWT version can have it. + + PyJWT 2.15 has no algorithm with this name and cannot read an ``AKP`` key. + """ + + def prepare_key(self, key): + if not isinstance(key, mldsa.MLDSA65PublicKey): + raise pyjwt.exceptions.InvalidKeyError("Not an ML-DSA-65 public key") + return key + + def sign(self, msg, key): + raise NotImplementedError + + def verify(self, msg, key, sig): + try: + key.verify(sig, msg) + except InvalidSignature: + return False + return True + + @staticmethod + def to_jwk(key_obj, as_dict=False): + raise NotImplementedError + + @staticmethod + def from_jwk(jwk): + members = json.loads(jwk) if isinstance(jwk, str) else jwk + if members.get("kty") != "AKP": + raise pyjwt.exceptions.InvalidKeyError("Not an AKP key") + public_key = members["pub"] + return mldsa.MLDSA65PublicKey.from_public_bytes( + base64.urlsafe_b64decode(public_key + "=" * (-len(public_key) % 4)) + ) + + class _FixedJWKSResponse(pyjwt.PyJWKClient): """Replaces the HTTP request of a ``PyJWKClient`` with a fixed result.""" @@ -266,7 +388,16 @@ def __init__(self): 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.p521_private = ec.generate_private_key(ec.SECP521R1()) + self.secp256k1_private = ec.generate_private_key(ec.SECP256K1()) self.okp_private = ed25519.Ed25519PrivateKey.generate() + self.ed448_private = ed448.Ed448PrivateKey.generate() + self.rsa_3072_private = rsa.generate_private_key( + public_exponent=65537, key_size=3072 + ) + self.rsa_4096_private = rsa.generate_private_key( + public_exponent=65537, key_size=4096 + ) # The RSA member has the same members as a key from the WorkOS API. self.rsa_jwk = _rsa_jwk( @@ -276,20 +407,51 @@ def __init__(self): ) 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", + self.p521_jwk = _ec_jwk(self.p521_private.public_key(), "p521-1") + self.secp256k1_jwk = _ec_jwk(self.secp256k1_private.public_key(), "k256-1") + self.okp_jwk = _okp_jwk(self.okp_private.public_key(), "okp-1") + self.ed448_jwk = _okp_jwk(self.ed448_private.public_key(), "ed448-1") + self.rsa_3072_jwk = _rsa_jwk(self.rsa_3072_private.public_key(), "rsa-3072") + self.rsa_4096_jwk = _rsa_jwk(self.rsa_4096_private.public_key(), "rsa-4096") + + # Keys without an ``alg`` member. PyJWT gets the algorithm of such a + # key from the type and the curve of the key. + self.rsa_no_alg_jwk = _without( + _rsa_jwk(self.rsa_private.public_key(), "rsa-no-alg"), "alg" + ) + self.ec_no_alg_jwk = _without( + _ec_jwk(self.ec_private.public_key(), "ec-no-alg"), "alg" + ) + self.p384_no_alg_jwk = _without( + _ec_jwk(self.p384_private.public_key(), "p384-no-alg"), "alg" + ) + self.p521_no_alg_jwk = _without( + _ec_jwk(self.p521_private.public_key(), "p521-no-alg"), "alg" + ) + self.secp256k1_no_alg_jwk = _without( + _ec_jwk(self.secp256k1_private.public_key(), "k256-no-alg"), "alg" + ) + self.okp_no_alg_jwk = _without( + _okp_jwk(self.okp_private.public_key(), "okp-no-alg"), "alg" + ) + # PyJWT gets no algorithm from the type and the curve of this key. + # One algorithm of PyJWT reads the key. The SDK uses that algorithm. + self.ed448_no_alg_jwk = _without( + _okp_jwk(self.ed448_private.public_key(), "ed448-no-alg"), "alg" + ) + # An RSA key of 511 bits without an ``alg`` member. ``cryptography`` + # makes no RSA key pair below 1024 bits. Thus the modulus is the + # product of two known primes. The key is too small for a PSS + # signature with SHA-512. + self.small_rsa_no_alg_jwk = { + "kty": "RSA", + "kid": "rsa-small", "use": "sig", - "alg": "EdDSA", - "crv": "Ed25519", - "x": _b64url( - self.okp_private.public_key().public_bytes( - serialization.Encoding.Raw, serialization.PublicFormat.Raw - ) - ), + "n": _b64url_uint((2**256 - 189) * (2**255 - 19)), + "e": "AQAB", } + + # Keys that PyJWT cannot read. They must have no effect. self.akp_jwk = { "kty": "AKP", "kid": "akp-1", @@ -305,6 +467,23 @@ def __init__(self): "material": {"nested": [1, 2, 3]}, } + def unreadable_keys(self): + """Well-formed JWKS members of a type or a curve that PyJWT cannot read.""" + return [ + self.akp_jwk, + self.unknown_kty_jwk, + {**self.ec_jwk, "kid": "ec-unknown-crv", "crv": "P-999"}, + {**self.ec_no_alg_jwk, "kid": "ec-unknown-crv-no-alg", "crv": "P-999"}, + {**self.okp_jwk, "kid": "okp-unknown-crv", "crv": "X25519"}, + # The key has no ``alg`` member. No algorithm of PyJWT reads a + # key on this curve. + { + **self.okp_no_alg_jwk, + "kid": "okp-unknown-crv-no-alg", + "crv": "X25519", + }, + ] + def malformed_members(self): """JWKS members that are not keys, or keys with a defect.""" return [ @@ -429,6 +608,182 @@ def _valid_token_cases(keys): [{**keys.p384_jwk, "kid": "shared"}, shared_ec_jwk], shared_es256, ), + **_key_decides_cases(keys), + } + + +# A secret for the MAC tokens of the tests. +_MAC_SECRET = hashlib.sha256(b"workos-python tests").digest() + +# The RSA algorithms of PyJWT other than RS256. The SDK source has no name of +# an algorithm. The tests have names, because a test makes each signature. +_OTHER_RSA_ALGORITHMS = ("RS384", "RS512", "PS256", "PS384", "PS512") + + +def _key_decides_cases(keys): + """Map each case to ``(JWKS members, token)``. Each token must verify. + + The JWKS key decides the algorithm. The SDK has no list of algorithms. + """ + rsa_jwk, ec_jwk = keys.rsa_jwk, keys.ec_jwk + jwks = [rsa_jwk, ec_jwk] + rs256 = keys.rs256_token() + es384 = _signed_token("ES384", "p384-1", keys.p384_private) + shared_rsa_jwk = {**rsa_jwk, "kid": "shared"} + return { + "rs256_rsa_3072_key": ( + [keys.rsa_3072_jwk], + _signed_token("RS256", "rsa-3072", keys.rsa_3072_private), + ), + "rs256_rsa_4096_key": ( + [keys.rsa_4096_jwk], + _signed_token("RS256", "rsa-4096", keys.rsa_4096_private), + ), + "es384_p384_key": ([*jwks, keys.p384_jwk], es384), + "es384_p384_key_without_alg": ( + [keys.p384_no_alg_jwk], + _signed_token("ES384", "p384-no-alg", keys.p384_private), + ), + "es512_p521_key": ( + [*jwks, keys.p521_jwk], + _signed_token("ES512", "p521-1", keys.p521_private), + ), + "es512_p521_key_without_alg": ( + [keys.p521_no_alg_jwk], + _signed_token("ES512", "p521-no-alg", keys.p521_private), + ), + "es256k_secp256k1_key": ( + [*jwks, keys.secp256k1_jwk], + _signed_token("ES256K", "k256-1", keys.secp256k1_private), + ), + "es256k_secp256k1_key_without_alg": ( + [keys.secp256k1_no_alg_jwk], + _signed_token("ES256K", "k256-no-alg", keys.secp256k1_private), + ), + "eddsa_okp_key": ( + [*jwks, keys.okp_jwk], + _signed_token("EdDSA", "okp-1", keys.okp_private), + ), + "eddsa_okp_key_without_alg": ( + [keys.okp_no_alg_jwk], + _signed_token("EdDSA", "okp-no-alg", keys.okp_private), + ), + "eddsa_ed448_key": ( + [*jwks, keys.ed448_jwk], + _signed_token("EdDSA", "ed448-1", keys.ed448_private), + ), + # The Ed448 key has no ``alg`` member. PyJWT gets no algorithm from + # the type and the curve of the key. One algorithm of PyJWT reads the + # key. The key is the only key of the JWKS, or one of many keys. + "eddsa_only_ed448_key_without_alg": ( + [keys.ed448_no_alg_jwk], + _signed_token("EdDSA", "ed448-no-alg", keys.ed448_private), + ), + "eddsa_ed448_key_without_alg_with_other_keys": ( + [ + *keys.unreadable_keys(), + *jwks, + keys.okp_no_alg_jwk, + keys.ed448_no_alg_jwk, + *keys.malformed_members(), + ], + _signed_token("EdDSA", "ed448-no-alg", keys.ed448_private), + ), + "rs256_with_ed448_key_without_alg": ( + [keys.ed448_no_alg_jwk, rsa_jwk], + rs256, + ), + "eddsa_okp_key_without_alg_with_ed448_key_without_alg": ( + [keys.ed448_no_alg_jwk, keys.okp_no_alg_jwk], + _signed_token("EdDSA", "okp-no-alg", keys.okp_private), + ), + # The RSA key has an ``alg`` member that is the algorithm of the token. + **{ + f"{algorithm.lower()}_rsa_key_with_alg": ( + [{**rsa_jwk, "alg": algorithm}, ec_jwk], + _signed_token(algorithm, "rsa-1", keys.rsa_private), + ) + for algorithm in _OTHER_RSA_ALGORITHMS + }, + # The RSA key has no ``alg`` member. PyJWT accepts each RSA + # algorithm for the key. + **{ + f"{algorithm.lower()}_rsa_key_without_alg": ( + [keys.rsa_no_alg_jwk, ec_jwk], + _signed_token(algorithm, "rsa-no-alg", keys.rsa_private), + ) + for algorithm in _OTHER_RSA_ALGORITHMS + }, + # Two keys have the kid of the token. The SDK selects the key for + # the algorithm of the token. + "es384_shared_kid_rsa_then_p384": ( + [shared_rsa_jwk, {**keys.p384_jwk, "kid": "shared"}], + _signed_token("ES384", "shared", keys.p384_private), + ), + "ps256_shared_kid_rs256_key_first": ( + [shared_rsa_jwk, {**shared_rsa_jwk, "alg": "PS256"}], + _signed_token("PS256", "shared", keys.rsa_private), + ), + # PyJWT raises an error for the first key with the kid, because that + # key is not a key for the algorithm. The SDK continues with the next + # key. + "es256_shared_kid_p384_key_with_alg_es256_first": ( + [ + {**keys.p384_jwk, "kid": "shared", "alg": "ES256"}, + {**ec_jwk, "kid": "shared"}, + ], + keys.es256_token(kid="shared"), + ), + "es256_shared_kid_rsa_key_without_alg_first": ( + [ + {**keys.rsa_no_alg_jwk, "kid": "shared"}, + {**keys.ec_no_alg_jwk, "kid": "shared"}, + ], + keys.es256_token(kid="shared"), + ), + "rs256_shared_kid_ec_key_without_alg_first": ( + [ + {**keys.ec_no_alg_jwk, "kid": "shared"}, + {**keys.rsa_no_alg_jwk, "kid": "shared"}, + ], + keys.rs256_token(kid="shared"), + ), + # PyJWT cannot read some keys of the JWKS. The other keys verify. + "rs256_with_unreadable_keys": ([*keys.unreadable_keys(), rsa_jwk], rs256), + "es384_with_unreadable_and_malformed_keys": ( + [*keys.malformed_members(), keys.p384_jwk, *keys.unreadable_keys()], + es384, + ), + # The JWKS has a symmetric key and a key with private members. The + # SDK does not use them. The other keys verify. + "rs256_with_oct_key": ( + [_oct_jwk(_MAC_SECRET, "oct-1", alg="HS256"), rsa_jwk], + rs256, + ), + "es384_with_key_with_private_members": ( + [ + {**ec_jwk, "kid": "ec-2", **_private_members(keys.ec_private)}, + keys.p384_jwk, + ], + es384, + ), + # The token cannot give or change the key. These header members have + # no effect. + "rs256_with_jwk_jku_x5u_and_x5c_headers": ( + jwks, + _signed_token("RS256", "rsa-1", keys.rsa_private, **_key_headers(keys)), + ), + } + + +def _key_headers(keys): + """Token header members that name a key that is not in the JWKS.""" + other_key = keys.other_rsa_private + return { + "jwk": _rsa_jwk(other_key.public_key(), "rsa-1"), + "jku": "https://attacker.example/jwks", + "x5u": "https://attacker.example/certificate", + "x5c": _certificate_members(other_key)["x5c"], } @@ -436,7 +791,7 @@ 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. + the token. The SDK must refuse the token before ``jwt.decode`` gets it. """ rsa_jwk, ec_jwk = keys.rsa_jwk, keys.ec_jwk jwks = [rsa_jwk, ec_jwk] @@ -451,10 +806,12 @@ def _refused_token_cases(keys): 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) + def sign_hmac(secret, digest=hashlib.sha256): return lambda data: hmac.new(secret, data, digest).digest() + def sign_hmac_with(private_key, digest=hashlib.sha256): + return sign_hmac(_public_pem(private_key), 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. @@ -509,7 +866,18 @@ def sign_hmac_with(private_key, digest=hashlib.sha256): _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. + # A correct signature, but the ``alg`` member of the header is not a + # string. A JSON array and a JSON object are not names of algorithms. + "alg_is_a_list": ( + jwks, + _compact_jws({"alg": ["RS256"], "kid": "rsa-1"}, sign_rs256), + ), + "alg_is_an_object": ( + [keys.rsa_no_alg_jwk], + _compact_jws({"alg": {"name": "RS256"}, "kid": "rsa-no-alg"}, sign_rs256), + ), + # A correct signature, but PyJWT has no algorithm with this name. + # Names are case-sensitive. "rs256_in_lowercase": ( jwks, _compact_jws({"alg": "rs256", "kid": "rsa-1"}, sign_rs256), @@ -518,6 +886,8 @@ def sign_hmac_with(private_key, digest=hashlib.sha256): jwks, _compact_jws({"alg": "es256", "kid": "ec-1"}, sign_es256), ), + # A correct signature, but the ``alg`` member of the key is not the + # algorithm of the token. "ps256_rsa_key": ( jwks, _compact_jws( @@ -539,16 +909,207 @@ def sign_hmac_with(private_key, digest=hashlib.sha256): lambda data: _rsa_signature(keys.rsa_private, data, hashes.SHA512()), ), ), - "es384_p384_key": ( - [*jwks, keys.p384_jwk], + "ps256_rsa_key_with_alg_ps384": ( + [{**rsa_jwk, "alg": "PS384"}], + _signed_token("PS256", "rsa-1", keys.rsa_private), + ), + "rs256_rsa_key_with_alg_rs384": ([{**rsa_jwk, "alg": "RS384"}], rs256), + "es384_p384_key_with_alg_es512": ( + [{**keys.p384_jwk, "alg": "ES512"}], + _signed_token("ES384", "p384-1", keys.p384_private), + ), + "eddsa_okp_key_with_alg_es256": ( + [{**keys.okp_jwk, "alg": "ES256"}], + _signed_token("EdDSA", "okp-1", keys.okp_private), + ), + # A correct signature, but the ``alg`` member of the Ed448 key is not + # the algorithm of the token. The SDK does not read such a key for a + # different algorithm. + "eddsa_ed448_key_with_alg_es256": ( + [{**keys.ed448_jwk, "alg": "ES256"}], + _signed_token("EdDSA", "ed448-1", keys.ed448_private), + ), + "eddsa_ed448_key_with_alg_ed448": ( + [{**keys.ed448_jwk, "alg": "Ed448"}], + _signed_token("EdDSA", "ed448-1", keys.ed448_private), + ), + # The key has no ``alg`` member. The algorithm of the token is not an + # algorithm for the type of the key. + **{ + f"{algorithm.lower()}_header_{kid.replace('-', '_')}_key_{signature.lower()}_signature": ( + [ + keys.rsa_no_alg_jwk, + keys.ec_no_alg_jwk, + keys.okp_no_alg_jwk, + keys.ed448_no_alg_jwk, + ], + _compact_jws( + {"alg": algorithm, "kid": kid}, _signer(private_key, signature) + ), + ) + for algorithm, kid, private_key, signature in [ + # The signature is correct for the key that the kid names. + ("RS256", "ec-no-alg", keys.ec_private, "ES256"), + ("PS256", "ec-no-alg", keys.ec_private, "ES256"), + ("RS256", "okp-no-alg", keys.okp_private, "EdDSA"), + ("ES256", "rsa-no-alg", keys.rsa_private, "RS256"), + ("ES256", "okp-no-alg", keys.okp_private, "EdDSA"), + ("EdDSA", "rsa-no-alg", keys.rsa_private, "RS256"), + ("EdDSA", "ec-no-alg", keys.ec_private, "ES256"), + ("RS256", "ed448-no-alg", keys.ed448_private, "EdDSA"), + ("ES256", "ed448-no-alg", keys.ed448_private, "EdDSA"), + # The signature is correct for the algorithm of the header. + ("RS256", "ec-no-alg", keys.rsa_private, "RS256"), + ("ES256", "rsa-no-alg", keys.ec_private, "ES256"), + ("EdDSA", "rsa-no-alg", keys.okp_private, "EdDSA"), + ("RS256", "ed448-no-alg", keys.rsa_private, "RS256"), + ] + }, + # The key has no ``alg`` member. The curve of the key is not the + # curve of the algorithm of the token. + **{ + f"{algorithm.lower()}_header_{kid.replace('-', '_')}_key": ( + [ + keys.ec_no_alg_jwk, + keys.p384_no_alg_jwk, + keys.p521_no_alg_jwk, + keys.secp256k1_no_alg_jwk, + ], + _signed_token(algorithm, kid, private_key), + ) + for algorithm, kid, private_key in [ + ("ES384", "ec-no-alg", keys.ec_private), + ("ES512", "ec-no-alg", keys.ec_private), + ("ES256K", "ec-no-alg", keys.ec_private), + ("ES256", "p384-no-alg", keys.p384_private), + ("ES512", "p384-no-alg", keys.p384_private), + ("ES256", "p521-no-alg", keys.p521_private), + ("ES384", "p521-no-alg", keys.p521_private), + ("ES256", "k256-no-alg", keys.secp256k1_private), + ] + }, + # The key has no ``alg`` member. A MAC token and an unsigned token do + # not verify with a public key. + **{ + f"{algorithm.lower()}_{kid.replace('-', '_')}_public_key_as_secret": ( + [ + keys.rsa_no_alg_jwk, + keys.ec_no_alg_jwk, + keys.okp_no_alg_jwk, + keys.ed448_no_alg_jwk, + ], + _compact_jws( + {"alg": algorithm, "kid": kid}, sign_hmac_with(private_key, digest) + ), + ) + for algorithm, digest, kid, private_key in [ + ("HS256", hashlib.sha256, "rsa-no-alg", keys.rsa_private), + ("HS384", hashlib.sha384, "rsa-no-alg", keys.rsa_private), + ("HS512", hashlib.sha512, "rsa-no-alg", keys.rsa_private), + ("HS256", hashlib.sha256, "ec-no-alg", keys.ec_private), + ("HS256", hashlib.sha256, "okp-no-alg", keys.okp_private), + ("HS256", hashlib.sha256, "ed448-no-alg", keys.ed448_private), + ] + }, + "alg_none_rsa_key_without_alg": ( + [keys.rsa_no_alg_jwk], + _compact_jws({"alg": "none", "kid": "rsa-no-alg"}, lambda data: b""), + ), + "alg_none_ec_key_without_alg_with_ecdsa_signature": ( + [keys.ec_no_alg_jwk], + _compact_jws({"alg": "none", "kid": "ec-no-alg"}, sign_es256), + ), + "alg_none_ed448_key_without_alg_with_eddsa_signature": ( + [keys.ed448_no_alg_jwk], _compact_jws( - {"alg": "ES384", "kid": "p384-1"}, - lambda data: _ecdsa_signature(keys.p384_private, data, hashes.SHA384()), + {"alg": "none", "kid": "ed448-no-alg"}, keys.ed448_private.sign ), ), - "eddsa_okp_key": ( - [*jwks, keys.okp_jwk], - _compact_jws({"alg": "EdDSA", "kid": "okp-1"}, keys.okp_private.sign), + # The JWKS has a symmetric key with the kid of the token. The SDK + # does not use a symmetric key. + **{ + f"{algorithm.lower()}_oct_key_with_kid_of_token": ( + [*jwks, _oct_jwk(_MAC_SECRET, "oct-1", alg=algorithm)], + _compact_jws( + {"alg": algorithm, "kid": "oct-1"}, sign_hmac(_MAC_SECRET, digest) + ), + ) + for algorithm, digest in [ + ("HS256", hashlib.sha256), + ("HS384", hashlib.sha384), + ("HS512", hashlib.sha512), + ] + }, + "hs256_oct_key_without_alg_with_kid_of_token": ( + [_oct_jwk(_MAC_SECRET, "oct-1"), *jwks], + _compact_jws({"alg": "HS256", "kid": "oct-1"}, sign_hmac(_MAC_SECRET)), + ), + # The symmetric key has the kid and the public key bytes of the RSA key. + "hs256_oct_key_first_with_kid_and_bytes_of_rsa_key": ( + [_oct_jwk(_public_pem(keys.rsa_private), "rsa-1", alg="HS256"), *jwks], + _compact_jws( + {"alg": "HS256", "kid": "rsa-1"}, sign_hmac_with(keys.rsa_private) + ), + ), + "hs256_oct_key_last_with_kid_and_bytes_of_rsa_key": ( + [*jwks, _oct_jwk(_public_pem(keys.rsa_private), "rsa-1")], + _compact_jws( + {"alg": "HS256", "kid": "rsa-1"}, sign_hmac_with(keys.rsa_private) + ), + ), + "alg_none_oct_key_with_kid_of_token": ( + [*jwks, _oct_jwk(_MAC_SECRET, "oct-1")], + _compact_jws({"alg": "none", "kid": "oct-1"}, lambda data: b""), + ), + # The key that the kid names has private members. The SDK does not + # use such a key. + "rs256_key_with_private_members": ( + [{**rsa_jwk, **_private_members(keys.rsa_private)}], + rs256, + ), + "es256_key_with_private_member": ( + [{**ec_jwk, **_private_members(keys.ec_private)}], + es256, + ), + "eddsa_key_with_private_member": ( + [{**keys.okp_jwk, **_private_members(keys.okp_private)}], + _signed_token("EdDSA", "okp-1", keys.okp_private), + ), + "eddsa_ed448_key_without_alg_with_private_member": ( + [{**keys.ed448_no_alg_jwk, **_private_members(keys.ed448_private)}], + _signed_token("EdDSA", "ed448-no-alg", keys.ed448_private), + ), + # The Ed448 key has no ``alg`` member, and its ``use`` member is not + # ``sig``. + "eddsa_ed448_key_without_alg_with_use_enc": ( + [{**keys.ed448_no_alg_jwk, "use": "enc"}], + _signed_token("EdDSA", "ed448-no-alg", keys.ed448_private), + ), + # No JWT library has an algorithm with the name in the token. + "alg_that_no_library_has": ( + jwks, + _compact_jws({"alg": "WORKOS-TEST-1", "kid": "rsa-1"}, sign_rs256), + ), + # No JWT library can read the key that the kid names. + "es256_key_with_unknown_crv": ( + [*jwks, *keys.unreadable_keys()], + keys.es256_token(kid="ec-unknown-crv"), + ), + "es256_key_without_alg_with_unknown_crv": ( + [*jwks, *keys.unreadable_keys()], + keys.es256_token(kid="ec-unknown-crv-no-alg"), + ), + "eddsa_okp_key_with_unknown_crv": ( + [*jwks, *keys.unreadable_keys()], + _signed_token("EdDSA", "okp-unknown-crv", keys.okp_private), + ), + "eddsa_okp_key_without_alg_with_unknown_crv": ( + [*jwks, *keys.unreadable_keys()], + _signed_token("EdDSA", "okp-unknown-crv-no-alg", keys.okp_private), + ), + "rs256_key_with_unknown_kty": ( + [*jwks, *keys.unreadable_keys()], + keys.rs256_token(kid="future-1"), ), # A correct signature, but the header has a "crit" member. "rs256_crit_unknown_extension": ( @@ -595,6 +1156,10 @@ def sign_hmac_with(private_key, digest=hashlib.sha256): ), # 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), + "es384_kid_names_p256_key_with_alg_es384": ( + [{**ec_jwk, "alg": "ES384"}], + _signed_token("ES384", "ec-1", keys.ec_private), + ), "es256_kid_names_p384_key_with_alg_es256": ( [*jwks, {**keys.p384_jwk, "alg": "ES256"}], es256_for_p384, @@ -640,13 +1205,47 @@ def sign_hmac_with(private_key, digest=hashlib.sha256): } +def _skipped_key_cases(keys): + """Map each case to ``(JWKS members, token)``. No token must verify. + + The PyJWT version of today cannot read the key that the kid names, and + the SDK skips the key. A later PyJWT version can read such a key. The + token does not verify then, because its signature is not correct. + """ + jwks = [keys.rsa_jwk, keys.ec_jwk, *keys.unreadable_keys()] + return { + "ml_dsa_44_akp_key": ( + jwks, + _compact_jws( + {"alg": "ML-DSA-44", "kid": "akp-1"}, lambda data: bytes(2420) + ), + ), + # PyJWT gets no algorithm from the type and the curve of the Ed448 + # key. One algorithm of PyJWT reads the key. Thus the SDK does not + # skip the key. The token does not verify, because its signature is + # not correct. + "eddsa_ed448_key_without_alg": ( + [*jwks, keys.ed448_no_alg_jwk], + _compact_jws( + {"alg": "EdDSA", "kid": "ed448-no-alg"}, lambda data: bytes(114) + ), + ), + } + + 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] + new_jwks = [keys.rsa_no_alg_jwk, keys.p384_jwk, keys.p521_jwk, keys.okp_jwk] + okp_no_alg_jwks = [keys.okp_no_alg_jwk, keys.ed448_no_alg_jwk] rs256, es256 = keys.rs256_token(), keys.es256_token() + es384 = _signed_token("ES384", "p384-1", keys.p384_private) + es512 = _signed_token("ES512", "p521-1", keys.p521_private) + eddsa = _signed_token("EdDSA", "okp-1", keys.okp_private) + ed448_token = _signed_token("EdDSA", "ed448-no-alg", keys.ed448_private) return { "rs256_other_key": ( jwks, @@ -680,13 +1279,210 @@ def _bad_signature_cases(keys): lambda data: _ecdsa_der_signature(keys.ec_private, data), ), ), + # The algorithms that the JWKS key decides. The signature of an ES384 + # token has 96 bytes. The signature of an ES512 token has 132 bytes. + "es384_tampered_signature": (new_jwks, _with_signature(es384, _flip_last_bit)), + "es384_signature_95_bytes": ( + new_jwks, + _with_signature(es384, lambda signature: signature[:-1]), + ), + "es384_signature_97_bytes": ( + new_jwks, + _with_signature(es384, lambda signature: signature + b"\x00"), + ), + "es384_signature_64_bytes": ( + new_jwks, + _with_signature(es384, lambda signature: signature[:64]), + ), + "es384_signature_in_der_form": ( + new_jwks, + _compact_jws( + {"alg": "ES384", "kid": "p384-1"}, + lambda data: _ecdsa_der_signature( + keys.p384_private, data, hashes.SHA384() + ), + ), + ), + "es384_signature_with_sha256": ( + new_jwks, + _compact_jws( + {"alg": "ES384", "kid": "p384-1"}, _signer(keys.p384_private, "ES256") + ), + ), + "es512_tampered_signature": (new_jwks, _with_signature(es512, _flip_last_bit)), + "es512_signature_131_bytes": ( + new_jwks, + _with_signature(es512, lambda signature: signature[:-1]), + ), + "es512_signature_133_bytes": ( + new_jwks, + _with_signature(es512, lambda signature: signature + b"\x00"), + ), + "es512_signature_in_der_form": ( + new_jwks, + _compact_jws( + {"alg": "ES512", "kid": "p521-1"}, + lambda data: _ecdsa_der_signature( + keys.p521_private, data, hashes.SHA512() + ), + ), + ), + "eddsa_tampered_signature": (new_jwks, _with_signature(eddsa, _flip_last_bit)), + "eddsa_signature_63_bytes": ( + new_jwks, + _with_signature(eddsa, lambda signature: signature[:-1]), + ), + "eddsa_signature_65_bytes": ( + new_jwks, + _with_signature(eddsa, lambda signature: signature + b"\x00"), + ), + # The Ed448 key has no ``alg`` member. The signature of a token for + # an Ed448 key has 114 bytes. + "eddsa_ed448_tampered_signature": ( + okp_no_alg_jwks, + _with_signature(ed448_token, _flip_last_bit), + ), + "eddsa_ed448_signature_113_bytes": ( + okp_no_alg_jwks, + _with_signature(ed448_token, lambda signature: signature[:-1]), + ), + "eddsa_ed448_signature_115_bytes": ( + okp_no_alg_jwks, + _with_signature(ed448_token, lambda signature: signature + b"\x00"), + ), + "eddsa_ed448_signature_of_zero_bytes": ( + okp_no_alg_jwks, + _with_signature(ed448_token, lambda signature: bytes(114)), + ), + # The two keys are keys for the algorithm of the token. The signature + # is a signature of the key that the kid does not name. + "eddsa_ed448_key_ed25519_signature": ( + okp_no_alg_jwks, + _signed_token("EdDSA", "ed448-no-alg", keys.okp_private), + ), + "eddsa_ed25519_key_ed448_signature": ( + okp_no_alg_jwks, + _signed_token("EdDSA", "okp-no-alg", keys.ed448_private), + ), + # The RSA key has no ``alg`` member. The signature must be a signature + # of the algorithm of the token, not of another RSA algorithm. + "ps256_header_pkcs1_signature": ( + new_jwks, + _compact_jws( + {"alg": "PS256", "kid": "rsa-no-alg"}, + _signer(keys.rsa_private, "RS256"), + ), + ), + "rs256_header_pss_signature": ( + new_jwks, + _compact_jws( + {"alg": "RS256", "kid": "rsa-no-alg"}, + _signer(keys.rsa_private, "PS256"), + ), + ), + "rs384_header_sha256_signature": ( + new_jwks, + _compact_jws( + {"alg": "RS384", "kid": "rsa-no-alg"}, + _signer(keys.rsa_private, "RS256"), + ), + ), + "ps384_other_key": ( + new_jwks, + _signed_token("PS384", "rsa-no-alg", keys.other_rsa_private), + ), + # The token gives a key in its header and has a signature of that + # key. The SDK uses the JWKS key only. + "rs256_signature_of_key_in_jwk_header": ( + jwks, + _signed_token( + "RS256", "rsa-1", keys.other_rsa_private, **_key_headers(keys) + ), + ), } +def _small_rsa_key_cases(keys): + """Map each case to ``(JWKS members, token)``. No token must verify. + + PyJWT reads the RSA key and accepts the algorithm for the key. The key + is too small for the hash of the algorithm. Thus the signature check of + PyJWT raises an error that is not an ``InvalidTokenError``. + """ + token = _compact_jws({"alg": "PS512", "kid": "rsa-small"}, lambda data: bytes(64)) + return { + "ps512_small_rsa_key_without_alg": ([keys.small_rsa_no_alg_jwk], token), + "ps512_small_rsa_key_with_alg": ( + [{**keys.small_rsa_no_alg_jwk, "alg": "PS512"}], + token, + ), + } + + +# Error types that are not an ``InvalidTokenError``. PyJWT does not change an +# error of these types when its signature check raises it. +_SIGNATURE_CHECK_ERRORS = [ + ValueError, + TypeError, + UnsupportedAlgorithm, + pyjwt.exceptions.InvalidKeyError, +] + + +def _raise_in_rsa_signature_check(monkeypatch, error): + """Make the RSA signature check of PyJWT raise an error of type ``error``.""" + + def verify(self, msg, key, sig): + raise error("The signature check cannot continue") + + monkeypatch.setattr(RSAAlgorithm, "verify", verify) + + +def _lone_surrogate_token_cases(keys): + """Map each case to ``(JWKS members, token)``. No token must verify. + + Each token has a lone surrogate. A JSON string can hold that character, + thus a sealed session can hold such a token. PyJWT cannot encode the + token, and its error is not an ``InvalidTokenError``. + """ + token = keys.rs256_token() + header, payload, signature = token.split(".") + jwks_keys = [keys.rsa_jwk] + return { + "lone_surrogate_only": (jwks_keys, "\ud800"), + "lone_surrogate_after_token": (jwks_keys, token + "\ud800"), + "lone_surrogate_before_token": (jwks_keys, "\udc00" + token), + "lone_surrogate_in_signature": ( + jwks_keys, + f"{header}.{payload}.\ud83d{signature}", + ), + } + + +# Error types that are not an ``InvalidTokenError``. A later PyJWT version can +# raise an error of these types when it reads the header of a token. +_HEADER_READ_ERRORS = [TypeError, RecursionError] + + +def _raise_in_header_read(monkeypatch, error): + """Make PyJWT raise an error of type ``error`` when it reads a header.""" + + def get_unverified_header(token): + raise error("PyJWT cannot read the header") + + monkeypatch.setattr(pyjwt, "get_unverified_header", get_unverified_header) + + _KEYS = _SigningKeys() _VALID_TOKENS = _valid_token_cases(_KEYS) _REFUSED_TOKENS = _refused_token_cases(_KEYS) -_INVALID_TOKENS = {**_REFUSED_TOKENS, **_bad_signature_cases(_KEYS)} +_INVALID_TOKENS = { + **_REFUSED_TOKENS, + **_skipped_key_cases(_KEYS), + **_bad_signature_cases(_KEYS), +} +_SMALL_RSA_KEY_TOKENS = _small_rsa_key_cases(_KEYS) +_LONE_SURROGATE_TOKENS = _lone_surrogate_token_cases(_KEYS) class TestSealUnseal: @@ -1405,7 +2201,13 @@ def _jwks_connection_reset(): "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_unusable_keys": {"keys": _KEYS.unreadable_keys()}, + "only_symmetric_and_private_keys": { + "keys": [ + _oct_jwk(_MAC_SECRET, "ec-1"), + {**_KEYS.ec_jwk, **_private_members(_KEYS.ec_private)}, + ] + }, "only_unreadable_keys": { "keys": [ {"kty": "FOO", "kid": "foo-1", "alg": "none"}, @@ -1421,8 +2223,36 @@ def _jwks_connection_reset(): } +# Tokens for the tests of the call that the SDK makes to ``jwt.decode``. +_PYJWT_CALL_CASES = [ + "rs256", + "es256", + "es384_p384_key", + "eddsa_okp_key", + "eddsa_only_ed448_key_without_alg", + "ps256_rsa_key_with_alg", + "ps384_rsa_key_without_alg", +] + + +def _assert_pyjwt_got_key_and_no_list_of_algorithms(decode, token, calls): + """Each call to ``jwt.decode`` has a key with one algorithm and no list. + + PyJWT then accepts the algorithm of the key only. + """ + assert decode.call_count == calls + for (decoded_token, signing_key), options in decode.call_args_list: + assert decoded_token == token + assert isinstance(signing_key, pyjwt.PyJWK) + assert signing_key.algorithm_name == pyjwt.get_unverified_header(token)["alg"] + assert "algorithms" not in options + + class TestSessionSigningKeys: - """RS256 and ES256 access tokens, verified with the JWKS key that the kid names.""" + """Access tokens, verified with the JWKS key that the kid names. + + The JWKS key decides the signature algorithm. + """ def setup_method(self): self.workos = WorkOSClient( @@ -1451,10 +2281,22 @@ def _refresh(self, jwks, 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"] + def test_session_has_no_list_of_algorithms(self): + assert not hasattr(session_module, "_ACCESS_TOKEN_ALGORITHMS") + assert not hasattr(Session, "_JWK_ALGORITHMS") + assert not hasattr(AsyncSession, "_JWK_ALGORITHMS") + + @pytest.mark.parametrize("case", _PYJWT_CALL_CASES) + def test_session_gives_pyjwt_the_key_and_no_list_of_algorithms( + self, monkeypatch, case + ): + jwks_keys, token = _VALID_TOKENS[case] + decode = MagicMock(wraps=pyjwt.decode) + monkeypatch.setattr(session_module.jwt, "decode", decode) + assert self._authenticate(jwks_keys, token).authenticated + _, _, refreshed = self._refresh(_StaticJWKSClient(jwks_keys), token) + assert refreshed.authenticated + _assert_pyjwt_got_key_and_no_list_of_algorithms(decode, token, calls=2) @pytest.mark.parametrize("case", _VALID_TOKENS) def test_session_authenticate_accepts_token(self, case): @@ -1476,9 +2318,9 @@ def test_session_authenticate_rejects_token(self, case): 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")) + # The SDK uses the key logic of PyJWT to make the algorithm and key + # checks. It makes them before ``jwt.decode`` gets the token. + decode = MagicMock(side_effect=AssertionError("The SDK called jwt.decode")) monkeypatch.setattr(session_module.jwt, "decode", decode) result = self._authenticate(*_REFUSED_TOKENS[case]) assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) @@ -1508,6 +2350,56 @@ def test_session_refresh_rejects_token(self, case): assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT assert session.session_data == original_sealed + def _assert_invalid_jwt_from_authenticate_and_refresh(self, jwks_keys, token): + result = self._authenticate(jwks_keys, token) + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + session, original_sealed, refreshed = self._refresh( + _StaticJWKSClient(jwks_keys), token + ) + assert isinstance(refreshed, RefreshWithSessionCookieErrorResponse) + assert ( + refreshed.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + ) + assert session.session_data == original_sealed + + # PyJWT gives a warning for an RSA key below 2048 bits. The test ignores + # that warning. + @pytest.mark.filterwarnings("ignore::jwt.warnings.InsecureKeyLengthWarning") + @pytest.mark.parametrize("case", _SMALL_RSA_KEY_TOKENS) + def test_session_rejects_token_when_rsa_key_is_too_small_for_hash(self, case): + # ``cryptography`` raises ValueError for this key, and PyJWT does not + # change that error. The SDK gives the usual failure. + self._assert_invalid_jwt_from_authenticate_and_refresh( + *_SMALL_RSA_KEY_TOKENS[case] + ) + + @pytest.mark.parametrize("error", _SIGNATURE_CHECK_ERRORS) + def test_session_rejects_token_when_signature_check_raises_other_error( + self, monkeypatch, error + ): + # The signature of the token is correct. The test makes the signature + # check raise an error, as a later library or an old runtime can do. + _raise_in_rsa_signature_check(monkeypatch, error) + self._assert_invalid_jwt_from_authenticate_and_refresh(*_VALID_TOKENS["rs256"]) + + @pytest.mark.parametrize("case", _LONE_SURROGATE_TOKENS) + def test_session_rejects_token_that_pyjwt_cannot_encode(self, case): + # PyJWT raises UnicodeEncodeError for this token, and PyJWT does not + # change that error. The SDK gives the usual failure. + self._assert_invalid_jwt_from_authenticate_and_refresh( + *_LONE_SURROGATE_TOKENS[case] + ) + + @pytest.mark.parametrize("error", _HEADER_READ_ERRORS) + def test_session_rejects_token_when_header_read_raises_other_error( + self, monkeypatch, error + ): + # The token is correct. The test makes PyJWT raise an error when it + # reads the header, as a later library can do. + _raise_in_header_read(monkeypatch, error) + self._assert_invalid_jwt_from_authenticate_and_refresh(*_VALID_TOKENS["rs256"]) + @pytest.mark.parametrize( "claims", [ @@ -1553,30 +2445,74 @@ def test_session_authenticate_keeps_issuer_check_for_es256_token( ) @pytest.mark.parametrize( - "case", ["es384_p384_key", "eddsa_okp_key", "hs256_rsa_public_key_as_secret"] + "case", + [ + "hs256_rsa_public_key_as_secret", + "hs256_rsa_no_alg_public_key_as_secret", + "hs256_oct_key_with_kid_of_token", + "alg_none", + "alg_none_rsa_key_without_alg", + "ps256_rsa_key", + "es384_header_ec_no_alg_key", + ], ) - def test_session_allow_list_does_not_follow_the_class_attribute( + def test_session_algorithms_do_not_follow_a_class_attribute( self, monkeypatch, case ): + # The JWKS key decides the algorithm. A list of names in a class + # attribute has no effect. monkeypatch.setattr( Session, "_JWK_ALGORITHMS", - ["RS256", "ES256", "ES384", "EdDSA", "HS256", "none"], + ["RS256", "ES256", "ES384", "PS256", "EdDSA", "HS256", "none"], + raising=False, ) 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"] + "case", + [ + "hs256_rsa_public_key_as_secret", + "hs384_rsa_public_key_as_secret", + "hs512_rsa_public_key_as_secret", + "hs256_rsa_no_alg_public_key_as_secret", + "hs256_oct_key_with_kid_of_token", + "hs256_oct_key_first_with_kid_and_bytes_of_rsa_key", + "alg_none", + "alg_none_rsa_key_without_alg", + "alg_none_oct_key_with_kid_of_token", + "alg_missing", + "alg_is_a_list", + "alg_is_an_object", + "rs256_in_lowercase", + "alg_that_no_library_has", + ], ) def test_session_makes_no_jwks_request_for_other_algorithms(self, case): + # PyJWT has no algorithm with the name in the token, or the algorithm + # is a MAC or gives no signature. No JWKS key can verify the token. + # An ``alg`` member that is not a string is not a name. 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 + @pytest.mark.parametrize( + "case", ["ps256_rsa_key", "rs384_rsa_key", "es384_header_ec_no_alg_key"] + ) + def test_session_makes_jwks_request_when_the_key_decides(self, case): + # PyJWT has a public key algorithm with the name in the token. The + # JWKS key decides, thus the SDK must get the JWKS. + jwks_keys, token = _INVALID_TOKENS[case] + jwks = _StaticJWKSClient(jwks_keys) + result = self._session(jwks, token).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert jwks.fetch_count == 1 + def test_session_get_logout_url_with_es256_token(self): session = self._session( _StaticJWKSClient([_KEYS.rsa_jwk, _KEYS.ec_jwk]), _KEYS.es256_token() @@ -1625,6 +2561,35 @@ def test_session_jwks_client_keeps_keys_for_lifespan(self, monkeypatch): assert session.authenticate().authenticated assert jwks.fetch_count == 2 + @pytest.mark.parametrize( + "new_keys", + [[], _UNUSABLE_JWKS_DOCUMENTS["only_unreadable_keys"]["keys"]], + ids=["empty_keys", "only_unreadable_keys"], + ) + def test_session_jwks_client_keeps_keys_when_new_jwks_has_no_readable_key( + self, monkeypatch, new_keys + ): + # The client has the keys of a correct JWKS. A token with an unknown + # kid then makes the client get the JWKS again. PyJWT can read no key + # of that JWKS. The client keeps the keys that it has. A token for + # one of these keys still verifies, with no new request. + clock = _Clock(monkeypatch) + jwks = _StaticJWKSClient([_KEYS.rsa_jwk], cooldown_duration=30) + session = self._session(jwks, _KEYS.rs256_token()) + assert session.authenticate().authenticated + assert jwks.fetch_count == 1 + + clock.advance(30) + jwks.keys = list(new_keys) + unknown_kid = self._session(jwks, _KEYS.es256_token(kid="ec-unknown")) + result = unknown_kid.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert jwks.fetch_count == 2 + + assert session.authenticate().authenticated + assert jwks.fetch_count == 2 + def test_session_jwks_client_ignores_keys_that_pyjwt_cannot_read(self): jwks = _StaticJWKSClient( [ @@ -1639,6 +2604,28 @@ def test_session_jwks_client_ignores_keys_that_pyjwt_cannot_read(self): 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_keeps_key_that_one_algorithm_of_pyjwt_reads(self): + # The keys have no ``alg`` member. PyJWT cannot read them from their + # type and curve alone. One algorithm of PyJWT reads the Ed448 key. + # Thus the client keeps that key. No algorithm reads the other keys. + jwks = _StaticJWKSClient( + [ + {**_KEYS.okp_no_alg_jwk, "kid": "okp-unknown-crv", "crv": "X25519"}, + {"kty": "oct", "kid": "sym-1"}, + {**_KEYS.ec_no_alg_jwk, "kid": "ec-unknown-crv", "crv": "P-999"}, + _KEYS.ed448_no_alg_jwk, + ] + ) + jwk_set = jwks.get_jwk_set() + assert isinstance(jwk_set, pyjwt.PyJWKSet) + assert [key.key_id for key in jwk_set] == ["ed448-no-alg"] + token = _signed_token("EdDSA", "ed448-no-alg", _KEYS.ed448_private) + signing_key = jwks.get_signing_key_from_jwt(token) + assert signing_key is jwk_set["ed448-no-alg"] + assert isinstance(signing_key.key, ed448.Ed448PublicKey) + assert signing_key.algorithm_name == "EdDSA" + 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"}] @@ -1649,8 +2636,75 @@ def test_session_jwks_client_selects_key_by_kid_and_algorithm(self): assert (ec_key.key_id, ec_key.key_type) == ("shared", "EC") assert jwks.fetch_count == 1 + def test_session_jwks_client_gives_key_with_algorithm_of_token(self): + # The RSA key has no ``alg`` member. One key verifies tokens of each + # RSA algorithm, and the client does not change the key that it keeps. + jwks = _StaticJWKSClient([_KEYS.rsa_no_alg_jwk]) + for algorithm in ("RS256", "PS256", "RS384", "RS256"): + token = _signed_token(algorithm, "rsa-no-alg", _KEYS.rsa_private) + signing_key = jwks.get_signing_key_from_jwt(token) + assert signing_key.algorithm_name == algorithm + assert self._session(jwks, token).authenticate().authenticated + assert [key.algorithm_name for key in jwks.get_jwk_set()] == ["RS256"] + assert jwks.fetch_count == 1 + @pytest.mark.parametrize( - "case", ["rs256", "es256", "rs256_ec_then_rsa", "es256_rsa_then_ec"] + "case", + [ + "alg_none_rsa_key_without_alg", + "alg_none_ec_key_without_alg_with_ecdsa_signature", + "alg_none_oct_key_with_kid_of_token", + "hs256_rsa_no_alg_public_key_as_secret", + "hs384_rsa_no_alg_public_key_as_secret", + "hs512_rsa_no_alg_public_key_as_secret", + "hs256_ec_no_alg_public_key_as_secret", + "hs256_okp_no_alg_public_key_as_secret", + "hs256_oct_key_with_kid_of_token", + "hs384_oct_key_with_kid_of_token", + "hs512_oct_key_with_kid_of_token", + "hs256_oct_key_without_alg_with_kid_of_token", + "hs256_oct_key_first_with_kid_and_bytes_of_rsa_key", + "hs256_oct_key_last_with_kid_and_bytes_of_rsa_key", + "es256_key_with_private_member", + "rs256_key_with_private_members", + "eddsa_key_with_private_member", + "es384_header_ec_no_alg_key", + "rs256_header_ec_no_alg_key_es256_signature", + "alg_none_ed448_key_without_alg_with_eddsa_signature", + "hs256_ed448_no_alg_public_key_as_secret", + "eddsa_ed448_key_without_alg_with_private_member", + "eddsa_ed448_key_without_alg_with_use_enc", + "rs256_header_ed448_no_alg_key_eddsa_signature", + "es256_header_ed448_no_alg_key_eddsa_signature", + "alg_is_a_list", + "alg_is_an_object", + ], + ) + def test_session_jwks_client_gives_no_key_for_token(self, case): + # The client gets the token directly, without the checks that the + # session makes on the header. The key logic of PyJWT gives no key + # for an unsigned token or a MAC token. The client gives no + # symmetric key and no private key. + jwks_keys, token = _REFUSED_TOKENS[case] + jwks = _StaticJWKSClient(jwks_keys) + with pytest.raises(pyjwt.exceptions.PyJWKClientError): + jwks.get_signing_key_from_jwt(token) + + @pytest.mark.parametrize( + "case", + [ + "rs256", + "es256", + "rs256_ec_then_rsa", + "es256_rsa_then_ec", + "es384_p384_key", + "es384_p384_key_without_alg", + "es512_p521_key", + "eddsa_okp_key", + "eddsa_okp_key_without_alg", + "ps256_rsa_key_with_alg", + "rs384_rsa_key_with_alg", + ], ) def test_session_accepts_token_from_replacement_jwks_client(self, case): # Code that replaces ``session.jwks`` can give any ``PyJWKClient``. @@ -1668,12 +2722,23 @@ def test_session_accepts_token_from_replacement_jwks_client(self, case): "es256_kid_names_p384_key", "es256_kid_names_p384_key_with_alg_es256", "rs256_unknown_kid", + "ps256_rsa_key", + "es384_kid_names_p256_key_with_alg_es384", + "es384_header_ec_no_alg_key", + "rs256_header_ec_no_alg_key_es256_signature", + "es256_header_rsa_no_alg_key_rs256_signature", + "hs256_oct_key_with_kid_of_token", + "hs256_rsa_no_alg_public_key_as_secret", + "alg_none_rsa_key_without_alg", + "es256_key_with_private_member", + "rs256_key_with_private_members", + "eddsa_key_with_private_member", ], ) 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")) + decode = MagicMock(side_effect=AssertionError("The SDK called jwt.decode")) monkeypatch.setattr(session_module.jwt, "decode", decode) jwks_keys, token = _REFUSED_TOKENS[case] result = self._session(_PlainJWKSClient(jwks_keys), token).authenticate() @@ -1681,6 +2746,117 @@ def test_session_checks_key_from_replacement_jwks_client(self, monkeypatch, case assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT decode.assert_not_called() + @pytest.mark.parametrize( + "jwk, token", + [ + ( + {**_KEYS.ec_jwk, **_private_members(_KEYS.ec_private)}, + _KEYS.es256_token(), + ), + ( + {**_KEYS.okp_jwk, **_private_members(_KEYS.okp_private)}, + _signed_token("EdDSA", "okp-1", _KEYS.okp_private), + ), + ( + {**_KEYS.rsa_jwk, **_private_members(_KEYS.rsa_private)}, + _KEYS.rs256_token(), + ), + ({**_KEYS.rsa_jwk, "use": "enc"}, _KEYS.rs256_token()), + ({**_KEYS.ec_jwk, "use": "enc"}, _KEYS.es256_token()), + ({**_KEYS.ec_jwk, "use": "sig-and-enc"}, _KEYS.es256_token()), + ], + ids=[ + "ec_key_with_private_member", + "okp_key_with_private_member", + "rsa_key_with_private_members", + "rsa_key_with_use_enc", + "ec_key_with_use_enc", + "ec_key_with_unknown_use", + ], + ) + def test_session_refuses_key_that_replacement_jwks_client_must_not_give( + self, monkeypatch, jwk, token + ): + # A replacement for ``session.jwks`` gives the key directly. PyJWT + # reads a key with private members as a private key, and it does not + # read the ``use`` member. Thus the SDK makes these two checks. + decode = MagicMock(side_effect=AssertionError("The SDK called jwt.decode")) + monkeypatch.setattr(session_module.jwt, "decode", decode) + jwks = MagicMock() + jwks.get_signing_key_from_jwt.return_value = pyjwt.PyJWK(jwk) + result = self._session(jwks, token).authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + decode.assert_not_called() + + def test_session_replacement_jwks_client_uses_algorithm_that_pyjwt_gave_to_key( + self, + ): + # A ``PyJWK`` from a replacement client does not show if its JWK has + # an ``alg`` member. PyJWT gives RS256 to an RSA key without ``alg``. + # For such a key, the SDK then accepts RS256 only. The client of the + # SDK knows that the key has no ``alg`` member, and accepts PS256. + jwks_keys = [_KEYS.rsa_no_alg_jwk] + rs256 = _signed_token("RS256", "rsa-no-alg", _KEYS.rsa_private) + ps256 = _signed_token("PS256", "rsa-no-alg", _KEYS.rsa_private) + accepted = self._session(_PlainJWKSClient(jwks_keys), rs256).authenticate() + refused = self._session(_PlainJWKSClient(jwks_keys), ps256).authenticate() + assert isinstance(accepted, AuthenticateWithSessionCookieSuccessResponse) + assert isinstance(refused, AuthenticateWithSessionCookieErrorResponse) + assert refused.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + assert self._authenticate(jwks_keys, ps256).authenticated + + def test_session_accepts_algorithm_that_pyjwt_gets_later(self, monkeypatch): + # The SDK has no list of algorithms. This test gives PyJWT one more + # algorithm, as a later PyJWT version can have it. The SDK code does + # not change, and the SDK accepts a token of that algorithm. + try: + private_key = mldsa.MLDSA65PrivateKey.generate() + except UnsupportedAlgorithm: + pytest.skip("The OpenSSL of this cryptography build has no ML-DSA") + algorithms = { + **get_default_algorithms(), + "ML-DSA-65": _LaterAlgorithm(), + } + monkeypatch.setattr(pyjwt.api_jwk, "get_default_algorithms", lambda: algorithms) + monkeypatch.setattr( + session_module, "get_default_algorithms", lambda: algorithms + ) + akp_jwk = { + "kty": "AKP", + "kid": "akp-2", + "use": "sig", + "alg": "ML-DSA-65", + "pub": _b64url(private_key.public_key().public_bytes_raw()), + } + jwks_keys = [_KEYS.rsa_jwk, akp_jwk, _KEYS.ec_jwk] + token = _compact_jws({"alg": "ML-DSA-65", "kid": "akp-2"}, private_key.sign) + + result = self._authenticate(jwks_keys, token) + assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse) + assert result.session_id == "session_01" + _, _, refreshed = self._refresh(_StaticJWKSClient(jwks_keys), token) + assert isinstance(refreshed, RefreshWithSessionCookieSuccessResponse) + replaced = self._session(_PlainJWKSClient(jwks_keys), token).authenticate() + assert isinstance(replaced, AuthenticateWithSessionCookieSuccessResponse) + assert self._authenticate(jwks_keys, _KEYS.rs256_token()).authenticated + assert self._authenticate(jwks_keys, _KEYS.es256_token()).authenticated + + # The rules for the later algorithm are the rules for each algorithm. + refused_tokens = [ + _with_signature(token, _flip_last_bit), + _compact_jws({"alg": "ML-DSA-65", "kid": "rsa-1"}, private_key.sign), + _compact_jws({"alg": "ML-DSA-87", "kid": "akp-2"}, private_key.sign), + _compact_jws({"alg": "RS256", "kid": "akp-2"}, _KEYS.sign_rs256), + _compact_jws({"alg": "none", "kid": "akp-2"}, lambda data: b""), + ] + for refused_token in refused_tokens: + refused = self._authenticate(jwks_keys, refused_token) + assert isinstance(refused, AuthenticateWithSessionCookieErrorResponse) + assert ( + refused.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + ) + 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() @@ -1769,6 +2945,34 @@ async def _refresh(self, client, jwks, new_access_token): ) return session, session.session_data, await session.refresh() + @pytest.mark.parametrize("case", _PYJWT_CALL_CASES) + async def test_async_session_gives_pyjwt_the_key_and_no_list_of_algorithms( + self, async_workos, monkeypatch, case + ): + jwks_keys, token = _VALID_TOKENS[case] + decode = MagicMock(wraps=pyjwt.decode) + monkeypatch.setattr(session_module.jwt, "decode", decode) + session = self._session(async_workos, _StaticJWKSClient(jwks_keys), token) + assert session.authenticate().authenticated + _, _, refreshed = await self._refresh( + async_workos, _StaticJWKSClient(jwks_keys), token + ) + assert refreshed.authenticated + _assert_pyjwt_got_key_and_no_list_of_algorithms(decode, token, calls=2) + + @pytest.mark.parametrize("case", _REFUSED_TOKENS) + async def test_async_session_authenticate_refuses_token_before_verification( + self, async_workos, monkeypatch, case + ): + decode = MagicMock(side_effect=AssertionError("The SDK called jwt.decode")) + monkeypatch.setattr(session_module.jwt, "decode", decode) + jwks_keys, token = _REFUSED_TOKENS[case] + session = self._session(async_workos, _StaticJWKSClient(jwks_keys), token) + result = session.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + decode.assert_not_called() + @pytest.mark.parametrize("case", _VALID_TOKENS) async def test_async_session_authenticate_accepts_token(self, async_workos, case): jwks_keys, token = _VALID_TOKENS[case] @@ -1811,6 +3015,57 @@ async def test_async_session_refresh_rejects_token(self, async_workos, case): assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT assert session.session_data == original_sealed + async def _assert_invalid_jwt_from_authenticate_and_refresh( + self, client, jwks_keys, token + ): + session = self._session(client, _StaticJWKSClient(jwks_keys), token) + result = session.authenticate() + assert isinstance(result, AuthenticateWithSessionCookieErrorResponse) + assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + session, original_sealed, refreshed = await self._refresh( + client, _StaticJWKSClient(jwks_keys), token + ) + assert isinstance(refreshed, RefreshWithSessionCookieErrorResponse) + assert ( + refreshed.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT + ) + assert session.session_data == original_sealed + + @pytest.mark.filterwarnings("ignore::jwt.warnings.InsecureKeyLengthWarning") + @pytest.mark.parametrize("case", _SMALL_RSA_KEY_TOKENS) + async def test_async_session_rejects_token_when_rsa_key_is_too_small_for_hash( + self, async_workos, case + ): + await self._assert_invalid_jwt_from_authenticate_and_refresh( + async_workos, *_SMALL_RSA_KEY_TOKENS[case] + ) + + @pytest.mark.parametrize("error", _SIGNATURE_CHECK_ERRORS) + async def test_async_session_rejects_token_when_signature_check_raises_other_error( + self, async_workos, monkeypatch, error + ): + _raise_in_rsa_signature_check(monkeypatch, error) + await self._assert_invalid_jwt_from_authenticate_and_refresh( + async_workos, *_VALID_TOKENS["rs256"] + ) + + @pytest.mark.parametrize("case", _LONE_SURROGATE_TOKENS) + async def test_async_session_rejects_token_that_pyjwt_cannot_encode( + self, async_workos, case + ): + await self._assert_invalid_jwt_from_authenticate_and_refresh( + async_workos, *_LONE_SURROGATE_TOKENS[case] + ) + + @pytest.mark.parametrize("error", _HEADER_READ_ERRORS) + async def test_async_session_rejects_token_when_header_read_raises_other_error( + self, async_workos, monkeypatch, error + ): + _raise_in_header_read(monkeypatch, error) + await self._assert_invalid_jwt_from_authenticate_and_refresh( + async_workos, *_VALID_TOKENS["rs256"] + ) + async def test_async_session_get_logout_url_with_es256_token(self, async_workos): session = self._session( async_workos,