Skip to content
Merged
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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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'",
]

Expand Down
266 changes: 248 additions & 18 deletions src/workos/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -266,15 +483,20 @@ 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,
) -> Union[
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,
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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(
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Loading