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
44 changes: 28 additions & 16 deletions stytch/b2b/api/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -918,14 +918,20 @@ def _authenticate_jwt_local_common(
) -> Optional[LocalJWTResponse]:
_session_claim = "https://stytch.com/session"
_organization_claim = "https://stytch.com/organization"
generic_claims = jwt_helpers.authenticate_jwt_local(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
try:
generic_claims = jwt_helpers.authenticate_jwt_local(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
except jwt.PyJWKClientError:
# No usable signing key was found for this JWT (an unknown kid, a key
# type that PyJWT does not support, or a failed JWKS fetch), so return
# None and let callers fall back to the API.
return None
if generic_claims is None:
return None

Expand Down Expand Up @@ -974,14 +980,20 @@ async def _authenticate_jwt_local_common_async(
) -> Optional[LocalJWTResponse]:
_session_claim = "https://stytch.com/session"
_organization_claim = "https://stytch.com/organization"
generic_claims = await jwt_helpers.authenticate_jwt_local_async(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
try:
generic_claims = await jwt_helpers.authenticate_jwt_local_async(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
except jwt.PyJWKClientError:
# No usable signing key was found for this JWT (an unknown kid, a key
# type that PyJWT does not support, or a failed JWKS fetch), so return
# None and let callers fall back to the API.
return None
if generic_claims is None:
return None

Expand Down
44 changes: 28 additions & 16 deletions stytch/consumer/api/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,14 +662,20 @@ def authenticate_jwt_local(
authorization_check: Optional[AuthorizationCheck] = None,
) -> Optional[Session]:
_session_claim = "https://stytch.com/session"
generic_claims = jwt_helpers.authenticate_jwt_local(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
try:
generic_claims = jwt_helpers.authenticate_jwt_local(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
except jwt.PyJWKClientError:
# No usable signing key was found for this JWT (an unknown kid, a key
# type that PyJWT does not support, or a failed JWKS fetch), so return
# None and let callers fall back to the API.
return None
if generic_claims is None:
return None

Expand Down Expand Up @@ -711,14 +717,20 @@ async def authenticate_jwt_local_async(
authorization_check: Optional[AuthorizationCheck] = None,
) -> Optional[Session]:
_session_claim = "https://stytch.com/session"
generic_claims = await jwt_helpers.authenticate_jwt_local_async(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
try:
generic_claims = await jwt_helpers.authenticate_jwt_local_async(
project_id=self.project_id,
jwks_client=self.jwks_client,
jwt=session_jwt,
max_token_age_seconds=max_token_age_seconds,
leeway=leeway,
base_url=self.api_base.base_url,
)
except jwt.PyJWKClientError:
# No usable signing key was found for this JWT (an unknown kid, a key
# type that PyJWT does not support, or a failed JWKS fetch), so return
# None and let callers fall back to the API.
return None
if generic_claims is None:
return None

Expand Down
150 changes: 150 additions & 0 deletions stytch/shared/tests/test_session_jwt_unknown_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
#!/usr/bin/env python3

import base64
import json
import time
import unittest
from typing import Any, Dict
from unittest.mock import AsyncMock, MagicMock

import jwt
from cryptography.hazmat.primitives.asymmetric import rsa

from stytch.b2b.api.sessions import Sessions as B2BSessions
from stytch.consumer.api.sessions import Sessions as ConsumerSessions

PROJECT_ID = "project-test-abc123"
RSA_KID = "jwk-test-rsa"
MLDSA_KID = "jwk-test-mldsa"
_SESSION_CLAIM = "https://stytch.com/session"
_ORG_CLAIM = "https://stytch.com/organization"

PRIVATE_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)

# A JWKS with an RSA key and an ML-DSA-44 key. PyJWT does not support the AKP
# key type, so it leaves that key out of the set that it builds from the JWKS.
JWKS: Dict[str, Any] = {
"keys": [
{
**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(PRIVATE_KEY.public_key())),
"kid": RSA_KID,
"alg": "RS256",
"use": "sig",
},
{
"kty": "AKP",
"alg": "ML-DSA-44",
"kid": MLDSA_KID,
"pub": base64.urlsafe_b64encode(b"\x00" * 1312).rstrip(b"=").decode(),
},
]
}


class _FellBackToAPI(Exception):
pass


def _b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def _session_payload() -> Dict[str, Any]:
now = int(time.time())
return {
"aud": [PROJECT_ID],
"iss": f"stytch.com/{PROJECT_ID}",
"sub": "user-test-123",
"exp": now + 300,
"iat": now,
"nbf": now,
_SESSION_CLAIM: {
"id": "session-test-123",
"attributes": {},
"authentication_factors": [],
"last_accessed_at": "2026-01-01T00:00:00Z",
"started_at": "2026-01-01T00:00:00Z",
"expires_at": "2026-01-01T01:00:00Z",
"roles": ["stytch_member"],
},
_ORG_CLAIM: {"organization_id": "org-test-123", "slug": "test-org"},
}


def _rs256_jwt() -> str:
return jwt.encode(
_session_payload(), PRIVATE_KEY, algorithm="RS256", headers={"kid": RSA_KID}
)


def _mldsa_jwt() -> str:
# The SDK cannot verify ML-DSA, so a placeholder signature is enough here.
header = {"alg": "ML-DSA-44", "kid": MLDSA_KID, "typ": "JWT"}
return ".".join(
[
_b64url(json.dumps(header).encode()),
_b64url(json.dumps(_session_payload()).encode()),
_b64url(b"\x00" * 2420),
]
)


def _jwks_client() -> jwt.PyJWKClient:
client = jwt.PyJWKClient("https://test.stytch.com/v1/sessions/jwks/" + PROJECT_ID)
client.fetch_data = MagicMock(return_value=JWKS) # type: ignore[method-assign]
return client


def _make_sessions(sessions_cls):
mock_api_base = MagicMock()
mock_api_base.base_url = "https://test.stytch.com/"
sessions = sessions_cls(
api_base=mock_api_base,
sync_client=MagicMock(),
async_client=MagicMock(),
jwks_client=_jwks_client(),
project_id=PROJECT_ID,
policy_cache=MagicMock(),
)
sessions.authenticate = MagicMock(side_effect=_FellBackToAPI)
sessions.authenticate_async = AsyncMock(side_effect=_FellBackToAPI)
return sessions


SESSIONS_CLASSES = [ConsumerSessions, B2BSessions]


class TestSessionJWTWithUnknownSigningKey(unittest.IsolatedAsyncioTestCase):
def test_authenticate_jwt_falls_back_to_api(self) -> None:
for sessions_cls in SESSIONS_CLASSES:
with self.subTest(sessions_cls.__module__):
sessions = _make_sessions(sessions_cls)
with self.assertRaises(_FellBackToAPI):
sessions.authenticate_jwt(session_jwt=_mldsa_jwt())

async def test_authenticate_jwt_async_falls_back_to_api(self) -> None:
for sessions_cls in SESSIONS_CLASSES:
with self.subTest(sessions_cls.__module__):
sessions = _make_sessions(sessions_cls)
with self.assertRaises(_FellBackToAPI):
await sessions.authenticate_jwt_async(session_jwt=_mldsa_jwt())

def test_authenticate_jwt_verifies_rs256_locally(self) -> None:
for sessions_cls in SESSIONS_CLASSES:
with self.subTest(sessions_cls.__module__):
sessions = _make_sessions(sessions_cls)
resp = sessions.authenticate_jwt(session_jwt=_rs256_jwt())
self.assertEqual(resp.status_code, 200)
sessions.authenticate.assert_not_called()

async def test_authenticate_jwt_async_verifies_rs256_locally(self) -> None:
for sessions_cls in SESSIONS_CLASSES:
with self.subTest(sessions_cls.__module__):
sessions = _make_sessions(sessions_cls)
resp = await sessions.authenticate_jwt_async(session_jwt=_rs256_jwt())
self.assertEqual(resp.status_code, 200)
sessions.authenticate_async.assert_not_awaited()


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion stytch/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "15.3.0"
__version__ = "15.3.1"
Loading