Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
259 changes: 180 additions & 79 deletions src/workos/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -188,58 +184,133 @@ 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(
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
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


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
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Loading