Skip to content

Avoid decoding jwt twice #440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 2, 2025
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
62 changes: 29 additions & 33 deletions tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,7 @@ def test_authenticate_success(self, session_constants, mock_user_management):
"entitlements": ["feature_1"],
}

with patch.object(
Session, "unseal_data", return_value=mock_session
), patch.object(session, "_is_valid_jwt", return_value=True), patch(
with patch.object(Session, "unseal_data", return_value=mock_session), patch(
"jwt.decode", return_value=mock_jwt_payload
), patch.object(
session.jwks,
Expand Down Expand Up @@ -324,22 +322,21 @@ def test_refresh_success(self, session_constants, mock_user_management):
cookie_password=session_constants["COOKIE_PASSWORD"],
)

with patch.object(session, "_is_valid_jwt", return_value=True) as _:
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = session.refresh()
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = session.refresh()

assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]

# Verify the refresh token was used correctly
mock_user_management.authenticate_with_refresh_token.assert_called_once_with(
Expand Down Expand Up @@ -425,22 +422,21 @@ async def test_refresh_success(self, session_constants, mock_user_management):
cookie_password=session_constants["COOKIE_PASSWORD"],
)

with patch.object(session, "_is_valid_jwt", return_value=True) as _:
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = await session.refresh()
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = await session.refresh()

assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]

# Verify the refresh token was used correctly
mock_user_management.authenticate_with_refresh_token.assert_called_once_with(
Expand Down
31 changes: 9 additions & 22 deletions workos/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,20 @@ def authenticate(
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)

if not self._is_valid_jwt(session["access_token"]):
try:
signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"])
decoded = jwt.decode(
session["access_token"],
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
)
except jwt.exceptions.InvalidTokenError:
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
)

signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"])
decoded = jwt.decode(
session["access_token"],
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
)

return AuthenticateWithSessionCookieSuccessResponse(
authenticated=True,
session_id=decoded["sid"],
Expand Down Expand Up @@ -128,19 +128,6 @@ def get_logout_url(self, return_to: Optional[str] = None) -> str:
)
return str(result)

def _is_valid_jwt(self, token: str) -> bool:
try:
signing_key = self.jwks.get_signing_key_from_jwt(token)
jwt.decode(
token,
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
)
return True
except jwt.exceptions.InvalidTokenError:
return False

@staticmethod
def seal_data(data: Dict[str, Any], key: str) -> str:
fernet = Fernet(key)
Expand Down