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
27 changes: 19 additions & 8 deletions src/workos/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,17 @@ def _is_user_access_token(claims: Dict[str, Any]) -> bool:
)


def _has_numeric_exp(claims: Dict[str, Any]) -> bool:
"""Whether the ``exp`` claim of verified claims is a JSON number.

PyJWT reads the ``exp`` claim with ``int()``. Thus PyJWT accepts an ``exp``
claim that is a string of digits.
"""
exp = claims.get("exp")
# A JSON boolean is not a number, but ``bool`` is a subclass of ``int``.
return isinstance(exp, (int, float)) and not isinstance(exp, bool)


# ---------------------------------------------------------------------------
# Session (sync)
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -523,7 +534,7 @@ def authenticate(
session["access_token"],
signing_key,
algorithms=self._JWK_ALGORITHMS,
options={"verify_aud": False},
options={"verify_aud": False, "require": ["exp"]},
leeway=self._client._jwt_leeway,
issuer=self._client._jwt_issuer,
)
Expand All @@ -533,7 +544,7 @@ def authenticate(
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
)

if not _is_user_access_token(decoded):
if not _is_user_access_token(decoded) or not _has_numeric_exp(decoded):
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
Expand Down Expand Up @@ -611,7 +622,7 @@ def refresh(
access_token,
signing_key,
algorithms=self._JWK_ALGORITHMS,
options={"verify_aud": False},
options={"verify_aud": False, "require": ["exp"]},
leeway=self._client._jwt_leeway,
issuer=self._client._jwt_issuer,
)
Expand All @@ -625,7 +636,7 @@ def refresh(
)

session_id = decoded.get("sid")
if not session_id:
if not session_id or not _has_numeric_exp(decoded):
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
Expand Down Expand Up @@ -747,7 +758,7 @@ def authenticate(
session["access_token"],
signing_key,
algorithms=self._JWK_ALGORITHMS,
options={"verify_aud": False},
options={"verify_aud": False, "require": ["exp"]},
leeway=self._client._jwt_leeway,
issuer=self._client._jwt_issuer,
)
Expand All @@ -757,7 +768,7 @@ def authenticate(
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
)

if not _is_user_access_token(decoded):
if not _is_user_access_token(decoded) or not _has_numeric_exp(decoded):
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
Expand Down Expand Up @@ -835,7 +846,7 @@ async def refresh(
access_token,
signing_key,
algorithms=self._JWK_ALGORITHMS,
options={"verify_aud": False},
options={"verify_aud": False, "require": ["exp"]},
leeway=self._client._jwt_leeway,
issuer=self._client._jwt_issuer,
)
Expand All @@ -849,7 +860,7 @@ async def refresh(
)

session_id = decoded.get("sid")
if not session_id:
if not session_id or not _has_numeric_exp(decoded):
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
Expand Down
220 changes: 220 additions & 0 deletions tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2154,3 +2154,223 @@ async def test_async_session_refresh_jwks_error_returns_invalid_jwt(
assert isinstance(result, RefreshWithSessionCookieErrorResponse)
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
assert session.session_data == original_sealed


_NO_EXP = object()

# ``exp`` claims that the SDK refuses. The string of digits names a time in
# the future.
_REFUSED_EXP_CLAIMS = {
"no_exp": _NO_EXP,
"exp_null": None,
"exp_string_of_digits": str(int(time.time()) + 3600),
}

# ``exp`` claims that the SDK accepts. Each number names a time in the future.
_ACCEPTED_EXP_CLAIMS = {
"exp_integer": int(time.time()) + 3600,
"exp_number_with_fraction": int(time.time()) + 3600.5,
}


def _token_with_exp(exp):
"""An RS256 access token with a correct signature.

``exp`` is the value of the ``exp`` claim. ``_NO_EXP`` gives a token that
has no ``exp`` claim.
"""
payload = _jwt_payload()
if exp is _NO_EXP:
del payload["exp"]
else:
payload["exp"] = exp
signing_input = ".".join(
_b64url(json.dumps(part, separators=(",", ":")).encode("utf-8"))
for part in ({"typ": "JWT", "alg": "RS256", "kid": "rsa-1"}, payload)
)
signature = _KEYS.sign_rs256(signing_input.encode("ascii"))
return f"{signing_input}.{_b64url(signature)}"


# Map each case to ``(claims, whether the exp claim is a JSON number)``.
_EXP_CLAIM_TYPES = {
"integer": ({"exp": 1700000000}, True),
"number_with_fraction": ({"exp": 1700000000.5}, True),
"no_exp": ({}, False),
"null": ({"exp": None}, False),
"string_of_digits": ({"exp": "1700000000"}, False),
"boolean": ({"exp": True}, False),
"array": ({"exp": [1700000000]}, False),
}


@pytest.mark.parametrize("case", _EXP_CLAIM_TYPES)
def test_has_numeric_exp(case):
claims, numeric = _EXP_CLAIM_TYPES[case]
assert session_module._has_numeric_exp(claims) is numeric


@pytest.fixture
def without_exp_type_check(monkeypatch):
"""Stops the type check of the SDK. Then only PyJWT examines ``exp``."""
monkeypatch.setattr(session_module, "_has_numeric_exp", lambda claims: True)


class TestSessionExpClaim:
"""An access token must have an ``exp`` claim that is a number."""

def setup_method(self):
self.workos = WorkOSClient(
api_key="sk_test_123", client_id="client_test_123", max_retries=0
)

def teardown_method(self):
self.workos.close()

def _session(self, access_token):
session = Session(
client=self.workos,
session_data=_seal_access_token(access_token),
cookie_password=COOKIE_PASSWORD,
)
session.jwks = _StaticJWKSClient([_KEYS.rsa_jwk])
return session

def _refresh(self, new_access_token):
session = self._session("at_old")
session._client.request_raw = MagicMock(
return_value=_refresh_response(new_access_token)
)
return session, session.session_data, session.refresh()

@pytest.mark.parametrize("case", _REFUSED_EXP_CLAIMS)
def test_session_authenticate_rejects_token_without_numeric_exp(self, case):
token = _token_with_exp(_REFUSED_EXP_CLAIMS[case])
result = self._session(token).authenticate()
assert isinstance(result, AuthenticateWithSessionCookieErrorResponse)
assert not result.authenticated
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT

@pytest.mark.parametrize("case", _REFUSED_EXP_CLAIMS)
def test_session_refresh_rejects_token_without_numeric_exp(self, case):
token = _token_with_exp(_REFUSED_EXP_CLAIMS[case])
session, original_sealed, result = self._refresh(token)
assert isinstance(result, RefreshWithSessionCookieErrorResponse)
assert not result.authenticated
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
assert session.session_data == original_sealed

# PyJWT gets ``exp`` as a required claim. Thus PyJWT refuses a token that
# has no ``exp`` claim.
@pytest.mark.usefixtures("without_exp_type_check")
def test_session_authenticate_requires_exp_in_pyjwt(self):
result = self._session(_token_with_exp(_NO_EXP)).authenticate()
assert isinstance(result, AuthenticateWithSessionCookieErrorResponse)
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT

@pytest.mark.usefixtures("without_exp_type_check")
def test_session_refresh_requires_exp_in_pyjwt(self):
session, original_sealed, result = self._refresh(_token_with_exp(_NO_EXP))
assert isinstance(result, RefreshWithSessionCookieErrorResponse)
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
assert session.session_data == original_sealed

@pytest.mark.parametrize("case", _ACCEPTED_EXP_CLAIMS)
def test_session_authenticate_accepts_token_with_numeric_exp(self, case):
token = _token_with_exp(_ACCEPTED_EXP_CLAIMS[case])
result = self._session(token).authenticate()
assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse)
assert result.authenticated
assert result.session_id == "session_01"

@pytest.mark.parametrize("case", _ACCEPTED_EXP_CLAIMS)
def test_session_refresh_accepts_token_with_numeric_exp(self, case):
token = _token_with_exp(_ACCEPTED_EXP_CLAIMS[case])
session, _, result = self._refresh(token)
assert isinstance(result, RefreshWithSessionCookieSuccessResponse)
assert result.authenticated
assert result.session_id == "session_01"
unsealed = unseal_data(result.sealed_session, COOKIE_PASSWORD)
assert unsealed["access_token"] == token
assert session.session_data == result.sealed_session


@pytest.mark.asyncio
class TestAsyncSessionExpClaim:
"""The checks of ``TestSessionExpClaim``, for ``AsyncSession``."""

def _session(self, client, access_token):
session = AsyncSession(
client=client,
session_data=_seal_access_token(access_token),
cookie_password=COOKIE_PASSWORD,
)
session.jwks = _StaticJWKSClient([_KEYS.rsa_jwk])
return session

async def _refresh(self, client, new_access_token):
session = self._session(client, "at_old")
session._client.request_raw = AsyncMock(
return_value=_refresh_response(new_access_token)
)
return session, session.session_data, await session.refresh()

@pytest.mark.parametrize("case", _REFUSED_EXP_CLAIMS)
async def test_async_session_authenticate_rejects_token_without_numeric_exp(
self, async_workos, case
):
token = _token_with_exp(_REFUSED_EXP_CLAIMS[case])
result = self._session(async_workos, token).authenticate()
assert isinstance(result, AuthenticateWithSessionCookieErrorResponse)
assert not result.authenticated
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT

@pytest.mark.parametrize("case", _REFUSED_EXP_CLAIMS)
async def test_async_session_refresh_rejects_token_without_numeric_exp(
self, async_workos, case
):
token = _token_with_exp(_REFUSED_EXP_CLAIMS[case])
session, original_sealed, result = await self._refresh(async_workos, token)
assert isinstance(result, RefreshWithSessionCookieErrorResponse)
assert not result.authenticated
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
assert session.session_data == original_sealed

@pytest.mark.usefixtures("without_exp_type_check")
async def test_async_session_authenticate_requires_exp_in_pyjwt(self, async_workos):
session = self._session(async_workos, _token_with_exp(_NO_EXP))
result = session.authenticate()
assert isinstance(result, AuthenticateWithSessionCookieErrorResponse)
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT

@pytest.mark.usefixtures("without_exp_type_check")
async def test_async_session_refresh_requires_exp_in_pyjwt(self, async_workos):
session, original_sealed, result = await self._refresh(
async_workos, _token_with_exp(_NO_EXP)
)
assert isinstance(result, RefreshWithSessionCookieErrorResponse)
assert result.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
assert session.session_data == original_sealed

@pytest.mark.parametrize("case", _ACCEPTED_EXP_CLAIMS)
async def test_async_session_authenticate_accepts_token_with_numeric_exp(
self, async_workos, case
):
token = _token_with_exp(_ACCEPTED_EXP_CLAIMS[case])
result = self._session(async_workos, token).authenticate()
assert isinstance(result, AuthenticateWithSessionCookieSuccessResponse)
assert result.authenticated
assert result.session_id == "session_01"

@pytest.mark.parametrize("case", _ACCEPTED_EXP_CLAIMS)
async def test_async_session_refresh_accepts_token_with_numeric_exp(
self, async_workos, case
):
token = _token_with_exp(_ACCEPTED_EXP_CLAIMS[case])
session, _, result = await self._refresh(async_workos, token)
assert isinstance(result, RefreshWithSessionCookieSuccessResponse)
assert result.authenticated
assert result.session_id == "session_01"
unsealed = unseal_data(result.sealed_session, COOKIE_PASSWORD)
assert unsealed["access_token"] == token
assert session.session_data == result.sealed_session