🙌 OpenHands: AI-Driven Development
fix: replace jwcrypto with joserfc to address CVE-2024-28102 (#14479)
aivong-openhandsac596597ec4e
diff --git a/enterprise/poetry.lock b/enterprise/poetry.lockindex 0dbbb17892..49c6e4c1fb 100644--- a/enterprise/poetry.lock+++ b/enterprise/poetry.lock@@ -6485,9 +6485,9 @@ httpx-aiohttp = ">=0.1.8"ipywidgets = ">=8.1.5"jinja2 = ">=3.1.6"joblib = "*"+joserfc = ">=1.0.0"json-repair = "*"jupyter-kernel-gateway = "*"-jwcrypto = ">=1.5.6"kubernetes = ">=33.1"libtmux = ">=0.46.2"litellm = ">=1.83.14"@@ -6516,7 +6516,7 @@ pybase62 = ">=1"pygithub = ">=2.5"pyjwt = ">=2.12"pylatexenc = "*"-pypdf = ">=6.9.2"+pypdf = ">=6.10.2"python-docx = "*"python-dotenv = "*"python-frontmatter = ">=1.1"diff --git a/openhands/app_server/services/jwt_service.py b/openhands/app_server/services/jwt_service.pyindex 707f5542e4..0bea35a063 100644--- a/openhands/app_server/services/jwt_service.py+++ b/openhands/app_server/services/jwt_service.py@@ -10,8 +10,8 @@ from typing import Any, AsyncGeneratorimport jwtfrom cryptography.fernet import Fernet, InvalidTokenfrom fastapi import Request-from jwcrypto import jwe as jwcrypto_jwe-from jwcrypto import jwk+from joserfc import jwe+from joserfc.jwk import OctKeyfrom pydantic import BaseModel, PrivateAttrfrom openhands.agent_server.utils import utc_now@@ -23,6 +23,9 @@ from openhands.app_server.utils.encryption_key import (logger = logging.getLogger(__name__)+# Only allow dir + A256GCM to prevent cryptographic agility attacks+_JWE_REGISTRY = jwe.JWERegistry(algorithms=['dir', 'A256GCM'])+class JwtService:"""Service for signing/verifying JWS tokens and encrypting/decrypting JWE tokens."""@@ -180,24 +183,20 @@ class JwtService:# Get the raw key for JWE encryption and derive a 256-bit keysecret_key = self._keys[key_id].key.get_secret_value()key_bytes = secret_key.encode() if isinstance(secret_key, str) else secret_key- # Derive a 256-bit key using SHA256key_256 = hashlib.sha256(key_bytes).digest()+ symmetric_key = OctKey.import_key(key_256)- # Create JWK from symmetric key for jwcrypto- symmetric_key = jwk.JWK(kty='oct', k=jwk.base64url_encode(key_256))-- # Create JWE token with jwcryptoprotected_header = {'alg': 'dir','enc': 'A256GCM','kid': key_id,}- jwe_token = jwcrypto_jwe.JWE(+ return jwe.encrypt_compact(+ protected_header,json.dumps(jwt_payload).encode('utf-8'),- recipient=symmetric_key,- protected=protected_header,+ symmetric_key,+ registry=_JWE_REGISTRY,)- return jwe_token.serialize(compact=True)def decrypt_jwe_token(self, token: str, key_id: str | None = None@@ -216,28 +215,16 @@ class JwtService:ValueError: If token is invalid or key_id is not foundException: If token decryption fails"""- # Deserialize once and reuse for both header extraction and decryption+ # Extract the protected header without decrypting to find the kid.+ # The registry enforces dir + A256GCM (rejects other algorithms).try:- jwe_obj = jwcrypto_jwe.JWE()- jwe_obj.deserialize(token)+ obj = jwe.extract_compact(token.encode('utf-8'), _JWE_REGISTRY)except Exception:raise ValueError('Invalid JWE token format')- # Extract and validate the protected header- try:- protected_header = json.loads(jwe_obj.objects['protected'])- except (KeyError, json.JSONDecodeError) as e:- raise ValueError(f'Invalid JWE token format: {type(e).__name__}')-- # Verify algorithms to prevent cryptographic agility attacks- if (- protected_header.get('alg') != 'dir'- or protected_header.get('enc') != 'A256GCM'- ):- raise ValueError('Unsupported or unexpected JWE algorithm')+ protected_header = obj.protectedif key_id is None:- # Extract key_id from the token's headerkey_id = protected_header.get('kid')if not key_id:raise ValueError("Token does not contain 'kid' header with key ID")@@ -248,19 +235,14 @@ class JwtService:# Get the raw key for JWE decryption and derive a 256-bit keysecret_key = self._keys[key_id].key.get_secret_value()key_bytes = secret_key.encode() if isinstance(secret_key, str) else secret_key- # Derive a 256-bit key using SHA256key_256 = hashlib.sha256(key_bytes).digest()+ symmetric_key = OctKey.import_key(key_256)try:- # Create JWK from symmetric key for jwcrypto- symmetric_key = jwk.JWK(kty='oct', k=jwk.base64url_encode(key_256))-- # Decrypt the JWE token (reusing already deserialized jwe_obj)- jwe_obj.decrypt(symmetric_key)-- # Parse the JSON string back to dictionary- payload = json.loads(jwe_obj.payload.decode('utf-8'))- return payload+ result = jwe.decrypt_compact(token, symmetric_key, registry=_JWE_REGISTRY)+ if result.plaintext is None:+ raise ValueError('Decryption produced no plaintext')+ return json.loads(result.plaintext)except Exception as e:raise Exception(f'Token decryption failed: {str(e)}')diff --git a/poetry.lock b/poetry.lockindex ea16974294..254e04249e 100644--- a/poetry.lock+++ b/poetry.lock@@ -4440,22 +4440,6 @@ files = [{file = "jupyterlab_widgets-3.0.16.tar.gz", hash = "sha256:423da05071d55cf27a9e602216d35a3a65a3e41cdf9c5d3b643b814ce38c19e0"},]-[[package]]-name = "jwcrypto"-version = "1.5.6"-description = "Implementation of JOSE Web standards"-optional = false-python-versions = ">= 3.8"-groups = ["main"]-files = [- {file = "jwcrypto-1.5.6-py3-none-any.whl", hash = "sha256:150d2b0ebbdb8f40b77f543fb44ffd2baeff48788be71f67f03566692fd55789"},- {file = "jwcrypto-1.5.6.tar.gz", hash = "sha256:771a87762a0c081ae6166958a954f80848820b2ab066937dc8b8379d65b1b039"},-]--[package.dependencies]-cryptography = ">=3.4"-typing-extensions = ">=4.5.0"-[[package]]name = "keyring"version = "25.7.0"@@ -14555,4 +14539,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt[metadata]lock-version = "2.1"python-versions = "^3.12,<3.14"-content-hash = "884eef757068a321d2354e2590988e5b57cc2d506b9c259a8ce57931eebacd7b"+content-hash = "7c56c3771efae85e6f3951ba4df0efb73a7f6d623fb3f78191e529ab02432fa9"diff --git a/pyproject.toml b/pyproject.tomlindex f730108c65..98c3b209b9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -46,9 +46,9 @@ dependencies = ["ipywidgets>=8.1.5","jinja2>=3.1.6","joblib",+ "joserfc>=1.0.0","json-repair","jupyter-kernel-gateway",- "jwcrypto>=1.5.6","kubernetes>=33.1","libtmux>=0.46.2","litellm!=1.64.4,!=1.67.*,>=1.83.14",@@ -249,7 +249,7 @@ pybase62 = "^1.0.0"openhands-sdk = "==1.22.1"openhands-agent-server = "==1.22.1"openhands-tools = "==1.22.1"-jwcrypto = ">=1.5.6"+joserfc = ">=1.0.0"sqlalchemy = { extras = [ "asyncio" ], version = "^2.0.40" }pg8000 = "^1.31.5"asyncpg = ">=0.30,<0.32"diff --git a/tests/unit/app_server/test_jwt_service.py b/tests/unit/app_server/test_jwt_service.pyindex 45b4d71d50..36d0c54e48 100644--- a/tests/unit/app_server/test_jwt_service.py+++ b/tests/unit/app_server/test_jwt_service.py@@ -17,8 +17,8 @@ from unittest.mock import patchimport jwtimport pytestfrom cryptography.fernet import Fernet-from jwcrypto import jwe as jwcrypto_jwe-from jwcrypto import jwk+from joserfc import jwe+from joserfc.jwk import OctKeyfrom pydantic import SecretStrfrom openhands.app_server.services.jwt_service import JwtService@@ -272,23 +272,19 @@ class TestJwtService:def test_jwe_token_decryption_no_kid_header(self, jwt_service):"""Test JWE token decryption fails when token has no kid header."""- # Create a JWE token without kid header using jwcrypto directly- payload = {'user_id': '123'}- # Create a proper 32-byte key for A256GCM+ # Create a JWE token without kid header using joserfc directlykey_bytes = b'12345678901234567890123456789012' # Exactly 32 bytes- symmetric_key = jwk.JWK(kty='oct', k=jwk.base64url_encode(key_bytes))+ symmetric_key = OctKey.import_key(key_bytes)+ registry = jwe.JWERegistry(algorithms=['dir', 'A256GCM'])+ payload = json.dumps({'user_id': '123'}).encode('utf-8')# Create JWE token without kid in protected header- protected_header = {- 'alg': 'dir',- 'enc': 'A256GCM',- }- jwe_token = jwcrypto_jwe.JWE(- json.dumps(payload).encode('utf-8'),- recipient=symmetric_key,- protected=protected_header,+ token = jwe.encrypt_compact(+ {'alg': 'dir', 'enc': 'A256GCM'},+ payload,+ symmetric_key,+ registry=registry,)- token = jwe_token.serialize(compact=True)with pytest.raises(ValueError, match="Token does not contain 'kid' header"):jwt_service.decrypt_jwe_token(token)@@ -470,10 +466,9 @@ class TestJwtService:assert jwe_decrypted[key] == valuedef test_jwe_backwards_compatibility_with_python_jose_tokens(self, jwt_service):- """Test that JWE tokens created with python-jose can be decrypted with jwcrypto.+ """Test that JWE tokens created with python-jose can be decrypted.- This test ensures backwards compatibility during the migration from python-jose- to jwcrypto. These tokens were generated using python-jose with the same key+ These tokens were generated using python-jose with the same keyderivation used by jwt_service (SHA256 of the secret key).The tokens use:@@ -529,6 +524,70 @@ class TestJwtService:assert unicode_decrypted['chinese'] == 'ä½ å¥½ä¸–ç•Œ'assert unicode_decrypted['iat'] == 1704067200+ def test_jwe_backwards_compatibility_with_jwcrypto_tokens(self, jwt_service):+ """Test that JWE tokens created with jwcrypto can be decrypted.++ These tokens were generated using jwcrypto 1.5.7 with the same key+ derivation used by jwt_service (SHA256 of the secret key).++ The tokens use:+ - Algorithm: dir (direct encryption)+ - Encryption: A256GCM+ - Key: SHA256 hash of 'test_secret_key_1' (matches key1 fixture)+ """+ # Token with simple payload: {"user_id": "123", "role": "admin", "iat": 1704067200}+ simple_token = (+ 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoia2V5MSJ9'+ '..JzJ3SzPJHPQYg2rR.Mw8WFhpTtsnplJkhcOROeRQ4ua_Vw1TL2arkj-7iNybgXJMnKGkq'+ 'VMnDbOJ_zQe3fSsXOzsk'+ '.OWtgVC_5JvmZvX55EGafKA'+ )++ # Token with complex nested payload+ complex_token = (+ 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoia2V5MSJ9'+ '..b0ZupYA2WHYjomKb.aZuLSB_Vdzo4cTq8EG7It00c5-1h-LaxdGYBHqiHAwiig89lmpKX'+ 'NleshC6EfHSxv4FtqG79mQFIkjpTIyJs11qBw8xCJiyAoQVp5Czi_UrclKEkYvRkxNjJyf1'+ 'j2ASa-amsOaz7edKyhrzzdEeD0ZJa2MQFVOr5IcHvv3XH5ixKORcga0FXRjqvwyJVdFUlD71'+ 'y-1pdrns'+ '.2ZThusOVDIpQWS_tykcAuA'+ )++ # Token with unicode characters in payload+ unicode_token = (+ 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoia2V5MSJ9'+ '..BHHa6cYZeglEHZAQ.sdR_NlK-aIBg-OtAtTVfiT7NFdXl2K6DjeWvAoYwcBLrlujEaEo7'+ 'Bb9AkZMwIJAVBDpJDqGVz0gvQSot6DHrURVMG4ba0Pp8I8OKb3gMoK0ylyqpMWBcQ-myMhj'+ 'ikqa_47RK1zF6zmHPOp4IoFPyQtm0n8tYHoKfpp4yvjY5qXnDvCFUbrm27ETKGr_Bg03ijop'+ 'LnF2XoQ'+ '.Vt7AWibpWpgDD3va_zdLbQ'+ )++ # Test simple token decryption+ simple_decrypted = jwt_service.decrypt_jwe_token(simple_token)+ assert simple_decrypted['user_id'] == '123'+ assert simple_decrypted['role'] == 'admin'+ assert simple_decrypted['iat'] == 1704067200++ # Test complex token decryption with nested structures+ complex_decrypted = jwt_service.decrypt_jwe_token(complex_token)+ assert complex_decrypted['user_id'] == 'user123'+ assert complex_decrypted['metadata']['permissions'] == [+ 'read',+ 'write',+ 'admin',+ ]+ assert complex_decrypted['metadata']['settings']['theme'] == 'dark'+ assert complex_decrypted['metadata']['settings']['notifications'] is True+ assert complex_decrypted['iat'] == 1704067200++ # Test unicode token decryption+ unicode_decrypted = jwt_service.decrypt_jwe_token(unicode_token)+ assert unicode_decrypted['user_name'] == 'José MarÃa'+ assert unicode_decrypted['description'] == 'Testing with émojis 🚀'+ assert unicode_decrypted['chinese'] == 'ä½ å¥½ä¸–ç•Œ'+ assert unicode_decrypted['iat'] == 1704067200+class TestEncryptDecryptValue:"""Tests for JwtService.encrypt_value / decrypt_value (JWE + Fernet fallback)."""diff --git a/uv.lock b/uv.lockindex a0968ddc8b..1c0d404a8a 100644--- a/uv.lock+++ b/uv.lock@@ -2608,19 +2608,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ab/b5/36c712098e6191d1b4e349304ef73a8d06aed77e56ceaac8c0a306c7bda1/jupyterlab_widgets-3.0.16-py3-none-any.whl", hash = "sha256:45fa36d9c6422cf2559198e4db481aa243c7a32d9926b500781c830c80f7ecf8", size = 914926, upload-time = "2025-11-01T21:11:28.008Z" },]-[[package]]-name = "jwcrypto"-version = "1.5.7"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "cryptography" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/8c/90/f065668004d22715c1940d6e88e4c3afc8ee16d5664e4478d2c8fd23a250/jwcrypto-1.5.7.tar.gz", hash = "sha256:70204d7cca406eda8c82352e3c41ba2d946610dafd19e54403f0a1f4f18633c6", size = 89535, upload-time = "2026-04-07T00:35:36.116Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/72/24/fb7da4d6613de7001feaf540d4b5969c6b5a1c42839043b0196cb13aa057/jwcrypto-1.5.7-py3-none-any.whl", hash = "sha256:729463fefe28b6de5cf1ebfda3e94f1a1b41d2799148ef98a01cb9678ebe2bb0", size = 94799, upload-time = "2026-04-07T00:35:35.085Z" },-]-[[package]]name = "keyring"version = "25.7.0"@@ -3570,9 +3557,9 @@ dependencies = [{ name = "ipywidgets" },{ name = "jinja2" },{ name = "joblib" },+ { name = "joserfc" },{ name = "json-repair" },{ name = "jupyter-kernel-gateway" },- { name = "jwcrypto" },{ name = "kubernetes" },{ name = "libtmux" },{ name = "litellm" },@@ -3686,9 +3673,9 @@ requires-dist = [{ name = "ipywidgets", specifier = ">=8.1.5" },{ name = "jinja2", specifier = ">=3.1.6" },{ name = "joblib" },+ { name = "joserfc", specifier = ">=1.0.0" },{ name = "json-repair" },{ name = "jupyter-kernel-gateway" },- { name = "jwcrypto", specifier = ">=1.5.6" },{ name = "kubernetes", specifier = ">=33.1" },{ name = "libtmux", specifier = ">=0.46.2" },{ name = "litellm", specifier = ">=1.83.14" },