AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/auth): remove legacy HS256 verification path (#14519)
Krzysztof Czerwinski18fde1b9656c
diff --git a/.github/workflows/platform-backend-ci.yml b/.github/workflows/platform-backend-ci.ymlindex 5aea17e9d6..6f0ec6e061 100644--- a/.github/workflows/platform-backend-ci.yml+++ b/.github/workflows/platform-backend-ci.yml@@ -547,7 +547,6 @@ jobs:AGENT_API_PORT: "18006"EXECUTION_SCHEDULER_PORT: "18003"NOTIFICATION_SERVICE_PORT: "18007"- JWT_VERIFY_KEY: "ci-only-jwt-verify-key-with-at-least-32-characters"REDIS_HOST: localhostENCRYPTION_KEY: "dvziYgz0KSK8FENhju0ZYi8-fRTfAdlz6YLhdB_jhNw="TRIAL_TEST_DATABASE: "1"diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/config.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/config.pyindex 5d205f0df9..a299d1fc3b 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/config.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/config.py@@ -13,21 +13,8 @@ class AuthConfigError(ValueError):pass-ALGO_RECOMMENDATION = (- "We highly recommend using an asymmetric algorithm such as ES256, "- "because when leaked, a shared secret would allow anyone to "- "forge valid tokens and impersonate users. "- "Configure JWT_JWKS_URL to verify asymmetric tokens issued by the "- "platform auth service."-)--class Settings:def __init__(self):- self.JWT_VERIFY_KEY: str = os.getenv(- "JWT_VERIFY_KEY", os.getenv("SUPABASE_JWT_SECRET", "")- ).strip()- self.JWT_ALGORITHM: str = os.getenv("JWT_SIGN_ALGORITHM", "HS256").strip()self.JWT_JWKS_URL: str = os.getenv("JWT_JWKS_URL", "").strip()self.JWT_JWKS_ALGORITHMS: list[str] = [algo.strip()@@ -44,9 +31,7 @@ class Settings:"auth service (e.g. https://<frontend-host>/api/auth/jwks). ""Better Auth issues asymmetric (ES256) tokens verified against ""that endpoint, so without it the backend cannot verify any live "- "session. JWT_VERIFY_KEY is not a substitute: it only covers "- "transient legacy (Supabase HS256) tokens during the cutover "- "window."+ "session.")if self.JWT_JWKS_URL and not self.JWT_JWKS_URL.startswith(@@ -93,12 +78,6 @@ class Settings:"tokens. Use https:// unless the path is fully trusted.")- if self.JWT_VERIFY_KEY and len(self.JWT_VERIFY_KEY) < 32:- logger.warning(- "⚠️ JWT_VERIFY_KEY appears weak (less than 32 characters). "- "Consider using a longer, cryptographically secure secret."- )-supported_algorithms = get_default_algorithms().keys()if not has_crypto:@@ -107,16 +86,6 @@ class Settings:"but not installed")- if (- self.JWT_ALGORITHM not in supported_algorithms- or self.JWT_ALGORITHM == "none"- ):- raise AuthConfigError(- f"Invalid JWT_SIGN_ALGORITHM: '{self.JWT_ALGORITHM}'. "- "Supported algorithms are listed on "- "https://pyjwt.readthedocs.io/en/stable/algorithms.html"- )-for algo in self.JWT_JWKS_ALGORITHMS:if (algo not in supported_algorithms@@ -140,12 +109,6 @@ class Settings:"algorithm.")- if self.JWT_VERIFY_KEY and self.JWT_ALGORITHM.startswith("HS"):- logger.warning(- f"⚠️ JWT_SIGN_ALGORITHM is set to '{self.JWT_ALGORITHM}', "- "a symmetric shared-key signature algorithm. " + ALGO_RECOMMENDATION- )-_settings: Settings = None # type: ignorediff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/config_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/config_test.pyindex 14bd581287..58432dc23a 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/config_test.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/config_test.py@@ -1,6 +1,9 @@"""Comprehensive tests for auth configuration to ensure 100% line and branch coverage.These tests verify critical security checks preventing JWT token forgery.++Verification is JWKS-only: JWT_JWKS_URL is the single mandatory setting and+symmetric shared-secret verification has been removed entirely."""import logging@@ -11,37 +14,9 @@ from pytest_mock import MockerFixturefrom autogpt_libs.auth.config import AuthConfigError, Settings-# Better Auth verification requires a JWKS URL, so these tests set one to-# exercise JWT_VERIFY_KEY / algorithm behavior without tripping the guard.VALID_JWKS_URL = "https://app.example/api/auth/jwks"-def test_environment_variable_precedence(mocker: MockerFixture):- """Test that environment variables take precedence over defaults."""- secret = "environment-secret-key-with-proper-length-123456"- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == secret---def test_environment_variable_backwards_compatible(mocker: MockerFixture):- """Test that SUPABASE_JWT_SECRET is read if JWT_VERIFY_KEY is not set."""- secret = "environment-secret-key-with-proper-length-123456"- mocker.patch.dict(- os.environ,- {"SUPABASE_JWT_SECRET": secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == secret--def test_auth_config_error_inheritance():"""Test that AuthConfigError is properly defined as an Exception."""assert issubclass(AuthConfigError, Exception)@@ -51,251 +26,36 @@ def test_auth_config_error_inheritance():def test_settings_static_after_creation(mocker: MockerFixture):"""Test that settings maintain their values after creation."""- secret = "immutable-secret-key-with-proper-length-12345"mocker.patch.dict(os.environ,- {"JWT_VERIFY_KEY": secret, "JWT_JWKS_URL": VALID_JWKS_URL},+ {"JWT_JWKS_URL": VALID_JWKS_URL},clear=True,)settings = Settings()- original_secret = settings.JWT_VERIFY_KEY+ original_url = settings.JWT_JWKS_URL# Changing environment after creation shouldn't affect settings- os.environ["JWT_VERIFY_KEY"] = "different-secret"-- assert settings.JWT_VERIFY_KEY == original_secret-+ os.environ["JWT_JWKS_URL"] = "https://other.example/api/auth/jwks"-def test_settings_load_with_valid_secret(mocker: MockerFixture):- """Test auth enabled with a valid JWT secret."""- valid_secret = "a" * 32 # 32 character secret- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": valid_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == valid_secret+ assert settings.JWT_JWKS_URL == original_url-def test_settings_load_with_strong_secret(mocker: MockerFixture):- """Test auth enabled with a cryptographically strong secret."""- strong_secret = "super-secret-jwt-token-with-at-least-32-characters-long"- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": strong_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == strong_secret- assert len(settings.JWT_VERIFY_KEY) >= 32--- "verify_key_env",- [- pytest.param({}, id="no-verify-key"),- pytest.param({"JWT_VERIFY_KEY": ""}, id="empty-verify-key"),- pytest.param({"JWT_VERIFY_KEY": " \t\n "}, id="whitespace-verify-key"),- pytest.param({"JWT_VERIFY_KEY": "x" * 40}, id="strong-verify-key"),- ],-)-def test_missing_jwks_url_raises_regardless_of_verify_key(- mocker: MockerFixture, verify_key_env: dict[str, str]-):- """JWT_JWKS_URL is the mandatory setting: without it Settings() must raise- about JWT_JWKS_URL specifically, and no state of the optional- JWT_VERIFY_KEY (absent, empty, whitespace, strong) substitutes for it."""- mocker.patch.dict(os.environ, verify_key_env, clear=True)+def test_missing_jwks_url_raises(mocker: MockerFixture):+ """JWT_JWKS_URL is the single mandatory setting: without it Settings()+ must raise about JWT_JWKS_URL."""+ mocker.patch.dict(os.environ, {}, clear=True)with pytest.raises(AuthConfigError, match="JWT_JWKS_URL must be set"):Settings()-def test_secret_weak_logs_warning(- mocker: MockerFixture, caplog: pytest.LogCaptureFixture-):- """Test that weak JWT secret triggers warning log."""- weak_secret = "short" # Less than 32 characters- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": weak_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- with caplog.at_level(logging.WARNING):- settings = Settings()- assert settings.JWT_VERIFY_KEY == weak_secret- assert "key appears weak" in caplog.text.lower()- assert "less than 32 characters" in caplog.text---def test_secret_31_char_logs_warning(- mocker: MockerFixture, caplog: pytest.LogCaptureFixture-):- """Test that 31-character secret triggers warning (boundary test)."""- secret_31 = "a" * 31 # Exactly 31 characters- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": secret_31, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- with caplog.at_level(logging.WARNING):- settings = Settings()- assert len(settings.JWT_VERIFY_KEY) == 31- assert "key appears weak" in caplog.text.lower()---def test_secret_32_char_no_warning(- mocker: MockerFixture, caplog: pytest.LogCaptureFixture-):- """Test that 32-character secret does not trigger warning (boundary test)."""- secret_32 = "a" * 32 # Exactly 32 characters- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": secret_32, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- with caplog.at_level(logging.WARNING):- settings = Settings()- assert len(settings.JWT_VERIFY_KEY) == 32- assert "JWT secret appears weak" not in caplog.text---def test_secret_whitespace_stripped(mocker: MockerFixture):- """Test that JWT secret whitespace is stripped."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": f" {secret} ", "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == secret---def test_secret_with_special_characters(mocker: MockerFixture):- """Test JWT secret with special characters."""- special_secret = "!@#$%^&*()_+-=[]{}|;:,.<>?`~" + "a" * 10 # 40 chars total- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": special_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == special_secret---def test_secret_with_unicode(mocker: MockerFixture):- """Test JWT secret with unicode characters."""- unicode_secret = "秘密🔐キー" + "a" * 25 # Ensure >32 bytes- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": unicode_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == unicode_secret---def test_secret_very_long(mocker: MockerFixture):- """Test JWT secret with excessive length."""- long_secret = "a" * 1000 # 1000 character secret- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": long_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == long_secret- assert len(settings.JWT_VERIFY_KEY) == 1000---def test_secret_with_newline(mocker: MockerFixture):- """Test JWT secret containing newlines."""- multiline_secret = "secret\nwith\nnewlines" + "a" * 20+def test_no_crypto_raises_error(mocker: MockerFixture):+ """A missing crypto package raises a clear error, since asymmetric+ verification cannot proceed without it."""mocker.patch.dict(os.environ,- {"JWT_VERIFY_KEY": multiline_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == multiline_secret---def test_secret_base64_encoded(mocker: MockerFixture):- """Test JWT secret that looks like base64."""- base64_secret = "dGhpc19pc19hX3NlY3JldF9rZXlfd2l0aF9wcm9wZXJfbGVuZ3Ro"- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": base64_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == base64_secret---def test_secret_numeric_only(mocker: MockerFixture):- """Test JWT secret with only numbers."""- numeric_secret = "1234567890" * 4 # 40 character numeric secret- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": numeric_secret, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_VERIFY_KEY == numeric_secret---def test_algorithm_default_hs256(mocker: MockerFixture):- """Test that JWT algorithm defaults to HS256."""- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": "a" * 32, "JWT_JWKS_URL": VALID_JWKS_URL},- clear=True,- )-- settings = Settings()- assert settings.JWT_ALGORITHM == "HS256"---def test_algorithm_whitespace_stripped(mocker: MockerFixture):- """Test that JWT algorithm whitespace is stripped."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": secret,- "JWT_SIGN_ALGORITHM": " HS256 ",- "JWT_JWKS_URL": VALID_JWKS_URL,- },- clear=True,- )-- settings = Settings()- assert settings.JWT_ALGORITHM == "HS256"---def test_no_crypto_warning(mocker: MockerFixture, caplog: pytest.LogCaptureFixture):- """Test that a missing crypto package raises a clear error when- JWT_JWKS_URL is set, since JWT_JWKS_URL is now mandatory and asymmetric- verification can't silently fall back to a warning anymore."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": secret, "JWT_JWKS_URL": VALID_JWKS_URL},+ {"JWT_JWKS_URL": VALID_JWKS_URL},clear=True,)@@ -307,94 +67,8 @@ def test_no_crypto_warning(mocker: MockerFixture, caplog: pytest.LogCaptureFixtuassert "cryptography" in str(exc_info.value)-def test_algorithm_invalid_raises_error(mocker: MockerFixture):- """Test that invalid JWT algorithm raises AuthConfigError."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": secret,- "JWT_SIGN_ALGORITHM": "INVALID_ALG",- "JWT_JWKS_URL": VALID_JWKS_URL,- },- clear=True,- )-- with pytest.raises(AuthConfigError) as exc_info:- Settings()- assert "Invalid JWT_SIGN_ALGORITHM" in str(exc_info.value)- assert "INVALID_ALG" in str(exc_info.value)---def test_algorithm_none_raises_error(mocker: MockerFixture):- """Test that 'none' algorithm raises AuthConfigError."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": secret,- "JWT_SIGN_ALGORITHM": "none",- "JWT_JWKS_URL": VALID_JWKS_URL,- },- clear=True,- )-- with pytest.raises(AuthConfigError) as exc_info:- Settings()- assert "Invalid JWT_SIGN_ALGORITHM" in str(exc_info.value)--[email protected]("algorithm", ["HS256", "HS384", "HS512"])-def test_algorithm_symmetric_warning(- mocker: MockerFixture, caplog: pytest.LogCaptureFixture, algorithm: str-):- """Test warning for symmetric algorithms (HS256, HS384, HS512)."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": secret,- "JWT_SIGN_ALGORITHM": algorithm,- "JWT_JWKS_URL": VALID_JWKS_URL,- },- clear=True,- )-- with caplog.at_level(logging.WARNING):- settings = Settings()- assert algorithm in caplog.text- assert "symmetric shared-key signature algorithm" in caplog.text- assert settings.JWT_ALGORITHM == algorithm--- "algorithm",- ["ES256", "ES384", "ES512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512"],-)-def test_algorithm_asymmetric_no_warning(- mocker: MockerFixture, caplog: pytest.LogCaptureFixture, algorithm: str-):- """Test that asymmetric algorithms do not trigger warning."""- secret = "a" * 32- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": secret,- "JWT_SIGN_ALGORITHM": algorithm,- "JWT_JWKS_URL": VALID_JWKS_URL,- },- clear=True,- )-- with caplog.at_level(logging.WARNING):- settings = Settings()- # Should not contain the symmetric algorithm warning- assert "symmetric shared-key signature algorithm" not in caplog.text- assert settings.JWT_ALGORITHM == algorithm--def test_jwks_url_alone_is_sufficient(mocker: MockerFixture):- """Test that JWT_JWKS_URL without a shared secret passes validation."""+ """Test that JWT_JWKS_URL passes validation on its own."""mocker.patch.dict(os.environ,{"JWT_JWKS_URL": "http://localhost:3000/api/auth/jwks"},@@ -403,7 +77,6 @@ def test_jwks_url_alone_is_sufficient(mocker: MockerFixture):settings = Settings()assert settings.JWT_JWKS_URL == "http://localhost:3000/api/auth/jwks"- assert settings.JWT_VERIFY_KEY == ""def test_jwks_algorithms_default(mocker: MockerFixture):@@ -450,16 +123,6 @@ def test_jwks_algorithms_rejects_unsafe_entries(mocker: MockerFixture, algorithmassert "JWT_JWKS_ALGORITHMS" in str(exc_info.value)-def test_neither_key_nor_jwks_raises_error(mocker: MockerFixture):- """Test that missing both verification mechanisms raises AuthConfigError."""- mocker.patch.dict(os.environ, {}, clear=True)-- with pytest.raises(AuthConfigError) as exc_info:- Settings()- assert "JWT_JWKS_URL" in str(exc_info.value)- assert "JWT_VERIFY_KEY" in str(exc_info.value)--@pytest.mark.parametrize("bad_url",["localhost:3000/jwks", "ftp://host/jwks", "/api/auth/jwks", "not a url"],diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.pyindex d4ed449808..fe0455bcd4 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py@@ -174,29 +174,34 @@ class TestAuthDependencies:class TestAuthDependenciesIntegration:"""Integration tests for auth dependencies with FastAPI."""- acceptable_jwt_secret = "test-secret-with-proper-length-123456"-@pytest.fixturedef create_token(self, mocker: MockerFixture):- """Helper to create JWT tokens."""+ """Helper to create ES256 tokens verified against a mocked JWK set."""import jwt+ from cryptography.hazmat.primitives.asymmetric import ec+ from jwt.algorithms import ECAlgorithm++ from autogpt_libs.auth import jwt_utils++ kid = "test-key-1"+ private_key = ec.generate_private_key(ec.SECP256R1())+ jwk = ECAlgorithm.to_jwk(private_key.public_key(), as_dict=True)+ jwk.update({"kid": kid, "alg": "ES256", "use": "sig"})- # JWT_JWKS_URL is required by Settings.validate(); HS256 tokens verify- # against JWT_VERIFY_KEY and never touch the JWKS client, so a- # present-but-unused URL is enough. Reset the cached settings so- # get_settings() rebuilds under this patched environment.mocker.patch.dict(os.environ,- {- "JWT_VERIFY_KEY": self.acceptable_jwt_secret,- "JWT_JWKS_URL": "http://localhost:3000/api/auth/jwks",- },+ {"JWT_JWKS_URL": "http://localhost:3000/api/auth/jwks"},clear=True,)mocker.patch.object(config, "_settings", Settings())+ mocker.patch.object(jwt_utils, "_jwks_client", None)+ mocker.patch.object(jwt_utils, "_jwks_client_url", None)+ mocker.patch.object(jwt.PyJWKClient, "fetch_data", return_value={"keys": [jwk]})- def _create_token(payload, secret=self.acceptable_jwt_secret):- return jwt.encode(payload, secret, algorithm="HS256")+ def _create_token(payload):+ return jwt.encode(+ payload, private_key, algorithm="ES256", headers={"kid": kid}+ )return _create_token@@ -228,7 +233,6 @@ class TestAuthDependenciesIntegration:token = create_token({"sub": "test-user", "role": "user", "aud": "authenticated"},- secret=self.acceptable_jwt_secret,)response = client.get("/test", headers={"Authorization": f"Bearer {token}"})@@ -249,7 +253,6 @@ class TestAuthDependenciesIntegration:# Regular user tokenuser_token = create_token({"sub": "regular-user", "role": "user", "aud": "authenticated"},- secret=self.acceptable_jwt_secret,)response = client.get(@@ -260,7 +263,6 @@ class TestAuthDependenciesIntegration:# Admin tokenadmin_token = create_token({"sub": "admin-user", "role": "admin", "aud": "authenticated"},- secret=self.acceptable_jwt_secret,)response = client.get(diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils.pyindex e0b8a9ec0c..98ea625d50 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils.py@@ -78,11 +78,11 @@ def parse_jwt_token(token: str, audience: str = "authenticated") -> dict[str, An"""Parse and validate a JWT token.- Symmetric (HS*) tokens are verified with the shared secret- (`JWT_VERIFY_KEY`); asymmetric tokens are verified against the JWK set- published by the platform auth service (`JWT_JWKS_URL`). Both paths can be- active at once, which keeps sessions issued by a previous auth provider- valid during a migration window.+ Tokens are verified against the JWK set published by the platform auth+ service (`JWT_JWKS_URL`), which issues asymmetric (ES256) tokens only.+ Symmetrically signed (HS*) tokens are rejected outright; the shared-secret+ path that carried Supabase-issued sessions across the Better Auth cutover+ is no longer needed now that those sessions have expired.:param token: The token to parse:param audience: The `aud` claim the token must carry. Defaults to the@@ -97,40 +97,27 @@ def parse_jwt_token(token: str, audience: str = "authenticated") -> dict[str, Anexcept jwt.InvalidTokenError as e:raise ValueError(f"Invalid token: {str(e)}") from e- algorithm = header.get("alg", "")+ # Validate the algorithm before touching the JWK set: a non-string or+ # unsupported `alg` must fail as a 401, not surface as a server error or+ # trigger a JWKS fetch for a token that can never verify.+ algorithm = header.get("alg")+ if not isinstance(algorithm, str):+ raise ValueError("Invalid token: signing algorithm is not accepted")if algorithm.startswith("HS"):- if not settings.JWT_VERIFY_KEY:- raise ValueError("Invalid token: symmetric tokens are not accepted")- key = settings.JWT_VERIFY_KEY- algorithms = [settings.JWT_ALGORITHM]- else:- if not settings.JWT_JWKS_URL:- raise ValueError("Invalid token: asymmetric tokens are not accepted")- try:- key = _get_jwks_client().get_signing_key_from_jwt(token).key- algorithms = settings.JWT_JWKS_ALGORITHMS- except jwt.PyJWKClientError as e:- # The legacy verifier supported — and its config text recommended —- # asymmetric algorithms, with the public key in JWT_VERIFY_KEY. A- # token whose kid isn't in the Better Auth JWK set can therefore- # still be a live legacy session from that configuration, so the- # migration-window grace extends here too: fall back to the shared- # legacy key when it's configured for a matching asymmetric alg.- if (- settings.JWT_VERIFY_KEY- and not settings.JWT_ALGORITHM.startswith("HS")- and algorithm == settings.JWT_ALGORITHM- ):- key = settings.JWT_VERIFY_KEY- algorithms = [settings.JWT_ALGORITHM]- else:- raise ValueError(f"Invalid token: {str(e)}") from e+ raise ValueError("Invalid token: symmetric tokens are not accepted")+ if algorithm not in settings.JWT_JWKS_ALGORITHMS:+ raise ValueError("Invalid token: signing algorithm is not accepted")++ try:+ key = _get_jwks_client().get_signing_key_from_jwt(token).key+ except jwt.PyJWKClientError as e:+ raise ValueError(f"Invalid token: {str(e)}") from etry:payload = jwt.decode(token,key,- algorithms=algorithms,+ algorithms=settings.JWT_JWKS_ALGORITHMS,audience=audience,)return payloaddiff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.pyindex fa22b04993..49641377c8 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/jwt_utils_test.py@@ -1,8 +1,13 @@"""Comprehensive tests for JWT token parsing and validation.Ensures 100% line and branch coverage for JWT security functions.++Verification is JWKS-only: the platform auth service issues asymmetric+(ES256) tokens, and symmetric (HS*) tokens are rejected outright."""+import base64+import jsonimport osfrom datetime import datetime, timedelta, timezone@@ -18,8 +23,8 @@ from autogpt_libs.auth import config, jwt_utilsfrom autogpt_libs.auth.config import Settingsfrom autogpt_libs.auth.models import User-MOCK_JWT_SECRET = "test-secret-key-with-at-least-32-characters"MOCK_JWKS_URL = "http://localhost:3000/api/auth/jwks"+_SIGNING_KID = "test-key-1"TEST_USER_PAYLOAD = {"sub": "test-user-id","role": "user",@@ -33,28 +38,40 @@ TEST_ADMIN_PAYLOAD = {"email": "[email protected]",}+# The active JWKS signing key, installed by the autouse fixture so the+# module-level create_token() helper can sign tokens the mocked JWK set trusts.+_signing_key: ec.EllipticCurvePrivateKey | None = None+++def make_es256_keypair(kid: str = _SIGNING_KID):+ """Generate an EC P-256 keypair and the matching JWK set document."""+ private_key = ec.generate_private_key(ec.SECP256R1())+ jwk = ECAlgorithm.to_jwk(private_key.public_key(), as_dict=True)+ jwk.update({"kid": kid, "alg": "ES256", "use": "sig"})+ return private_key, {"keys": [jwk]}+@pytest.fixture(autouse=True)def mock_config(mocker: MockerFixture):- # JWT_JWKS_URL is required by Settings.validate(); the HS256 tests never- # touch the JWKS client (they verify against JWT_VERIFY_KEY), so a URL that- # is present-but-unused is enough to satisfy config validation.- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": MOCK_JWT_SECRET, "JWT_JWKS_URL": MOCK_JWKS_URL},- clear=True,- )+ """Configure a JWKS endpoint and serve a single ES256 signing key."""+ global _signing_key+ private_key, jwk_set = make_es256_keypair()+ _signing_key = private_key++ mocker.patch.dict(os.environ, {"JWT_JWKS_URL": MOCK_JWKS_URL}, clear=True)mocker.patch.object(config, "_settings", Settings())mocker.patch.object(jwt_utils, "_jwks_client", None)mocker.patch.object(jwt_utils, "_jwks_client_url", None)+ mocker.patch.object(jwt.PyJWKClient, "fetch_data", return_value=jwk_set)yield+ _signing_key = None-def create_token(payload, secret=None, algorithm="HS256"):- """Helper to create JWT tokens."""- if secret is None:- secret = MOCK_JWT_SECRET- return jwt.encode(payload, secret, algorithm=algorithm)+def create_token(payload, private_key=None, kid: str = _SIGNING_KID) -> str:+ """Helper to create ES256 JWT tokens signed by the active JWKS key."""+ if private_key is None:+ private_key = _signing_key+ return jwt.encode(payload, private_key, algorithm="ES256", headers={"kid": kid})def test_parse_jwt_token_valid():@@ -81,9 +98,9 @@ def test_parse_jwt_token_expired():def test_parse_jwt_token_invalid_signature():- """Test parsing a token with invalid signature."""- # Create token with different secret- token = create_token(TEST_USER_PAYLOAD, secret="wrong-secret")+ """A token signed by a key that is not in the JWK set is rejected."""+ other_key, _ = make_es256_keypair(kid=_SIGNING_KID)+ token = create_token(TEST_USER_PAYLOAD, private_key=other_key)with pytest.raises(ValueError) as exc_info:jwt_utils.parse_jwt_token(token)@@ -300,125 +317,81 @@ def test_jwt_with_future_iat():jwt_utils.parse_jwt_token(token)-def test_jwt_with_different_algorithms():- """Test that only HS256 algorithm is accepted."""- payload = {- "sub": "user-id",- "role": "user",- "aud": "authenticated",- }-- # Try different algorithms- algorithms = ["HS384", "HS512", "none"]- for algo in algorithms:- if algo == "none":- # Special case for 'none' algorithm (security vulnerability if accepted)- token = create_token(payload, "", algorithm="none")- else:- token = create_token(payload, algorithm=algo)-- with pytest.raises(ValueError) as exc_info:- jwt_utils.parse_jwt_token(token)- assert "Invalid token" in str(exc_info.value)-+# =============== SYMMETRIC (HS*) TOKENS ARE REJECTED =============== #-# ==================== JWKS (ASYMMETRIC) VERIFICATION ==================== #---def make_es256_keypair(kid: str = "test-key-1"):- """Generate an EC P-256 keypair and the matching JWK set document."""- private_key = ec.generate_private_key(ec.SECP256R1())- jwk = ECAlgorithm.to_jwk(private_key.public_key(), as_dict=True)- jwk.update({"kid": kid, "alg": "ES256", "use": "sig"})- return private_key, {"keys": [jwk]}---def create_es256_token(payload, private_key, kid: str = "test-key-1") -> str:- return jwt.encode(payload, private_key, algorithm="ES256", headers={"kid": kid})---def jwks_config(mocker: MockerFixture):- """Configure both the legacy shared secret and a JWKS endpoint."""- mocker.patch.dict(- os.environ,- {"JWT_VERIFY_KEY": MOCK_JWT_SECRET, "JWT_JWKS_URL": MOCK_JWKS_URL},- clear=True,- )- mocker.patch.object(config, "_settings", Settings())- mocker.patch.object(jwt_utils, "_jwks_client", None)- mocker.patch.object(jwt_utils, "_jwks_client_url", None)-- private_key, jwk_set = make_es256_keypair()- mocker.patch.object(jwt.PyJWKClient, "fetch_data", return_value=jwk_set)- yield private_key---def test_parse_jwt_token_es256_via_jwks(jwks_config):- """An asymmetric token signed by the JWKS key is accepted."""- token = create_es256_token(TEST_USER_PAYLOAD, jwks_config)- result = jwt_utils.parse_jwt_token(token)-- assert result["sub"] == "test-user-id"- assert result["role"] == "user"[email protected]("algorithm", ["HS256", "HS384", "HS512"])+def test_parse_jwt_token_symmetric_rejected(algorithm: str):+ """Symmetric tokens are refused outright.-def test_parse_jwt_token_hs256_still_works_alongside_jwks(jwks_config):- """Legacy shared-secret tokens remain valid while JWKS is configured."""- token = create_token(TEST_USER_PAYLOAD)- result = jwt_utils.parse_jwt_token(token)-- assert result["sub"] == "test-user-id"---def test_parse_jwt_token_es256_expired(jwks_config):- """An expired asymmetric token is rejected as expired."""- expired_payload = {- **TEST_USER_PAYLOAD,- "exp": datetime.now(timezone.utc) - timedelta(hours=1),- }- token = create_es256_token(expired_payload, jwks_config)+ The platform auth service only issues asymmetric (ES256) tokens, so the+ HS* path is never verified, regardless of configuration.+ """+ payload = {"sub": "user-id", "role": "admin", "aud": "authenticated"}+ secret = "shared-secret-at-least-64-bytes-long-for-hs512-hmac-key-padding!!"+ token = jwt.encode(payload, secret, algorithm=algorithm)- with pytest.raises(ValueError, match="Token has expired"):+ with pytest.raises(ValueError, match="symmetric tokens are not accepted"):jwt_utils.parse_jwt_token(token)-def test_parse_jwt_token_es256_wrong_audience(jwks_config):- """An asymmetric token without the expected audience is rejected."""- wrong_aud_payload = {**TEST_USER_PAYLOAD, "aud": "wrong-audience"}- token = create_es256_token(wrong_aud_payload, jwks_config)+def test_parse_jwt_token_none_algorithm_rejected():+ """The unsigned 'none' algorithm must never verify."""+ payload = {"sub": "user-id", "role": "admin", "aud": "authenticated"}+ token = jwt.encode(payload, "", algorithm="none")with pytest.raises(ValueError, match="Invalid token"):jwt_utils.parse_jwt_token(token)-def test_parse_jwt_token_es256_wrong_key(jwks_config):- """A token signed by a key that is not in the JWK set is rejected."""- other_private_key, _ = make_es256_keypair(kid="other-key")- token = create_es256_token(TEST_USER_PAYLOAD, other_private_key, kid="other-key")+def _token_with_header(header: dict) -> str:+ """Build a syntactically valid JWT with an arbitrary (unsigned) header.- with pytest.raises(ValueError, match="Invalid token"):- jwt_utils.parse_jwt_token(token)+ jwt.encode() always writes a string `alg`, so malformed headers have to be+ assembled by hand. The signature is garbage: these tokens must be rejected+ before verification is ever attempted.+ """+ segments = [+ json.dumps(header).encode(),+ json.dumps(TEST_USER_PAYLOAD).encode(),+ b"not-a-signature",+ ]+ return ".".join(base64.urlsafe_b64encode(s).rstrip(b"=").decode() for s in segments)+++ "header",+ [+ pytest.param({"alg": None, "kid": _SIGNING_KID}, id="null-alg"),+ pytest.param({"alg": 256, "kid": _SIGNING_KID}, id="numeric-alg"),+ pytest.param({"kid": _SIGNING_KID}, id="missing-alg"),+ pytest.param({"alg": "none", "kid": _SIGNING_KID}, id="none-alg"),+ pytest.param({"alg": "ES384", "kid": _SIGNING_KID}, id="unlisted-alg"),+ ],+)+def test_parse_jwt_token_bad_algorithm_rejected_before_jwks(+ mocker: MockerFixture, header: dict+):+ """A non-string, missing or unlisted `alg` fails as an auth error (401 at+ the HTTP layer), not an AttributeError → 500, and never reaches the JWK+ set — so junk headers can't trigger a JWKS fetch."""+ jwks_client = mocker.patch.object(jwt_utils, "_get_jwks_client")+ token = _token_with_header(header)+ with pytest.raises(ValueError, match="signing algorithm is not accepted"):+ jwt_utils.parse_jwt_token(token)+ jwks_client.assert_not_called()-# Note: "asymmetric rejected without JWKS_URL" is not testable via a valid-# Settings() — JWT_JWKS_URL is now mandatory (config.validate raises without-# it), so that guard in parse_jwt_token is unreachable dead code. The positive-# path is covered by test_parse_jwt_token_es256_via_jwks.+# ==================== JWKS (ASYMMETRIC) VERIFICATION ==================== #-def test_parse_jwt_token_symmetric_rejected_without_shared_secret(- mocker: MockerFixture,-):- """Symmetric tokens are rejected when only JWKS verification is configured."""- mocker.patch.dict(os.environ, {"JWT_JWKS_URL": MOCK_JWKS_URL}, clear=True)- mocker.patch.object(config, "_settings", Settings())- mocker.patch.object(jwt_utils, "_jwks_client", None)- mocker.patch.object(jwt_utils, "_jwks_client_url", None)- token = create_token(TEST_USER_PAYLOAD)+def test_parse_jwt_token_unknown_kid_rejected():+ """A token whose kid is absent from the JWK set is rejected."""+ other_key, _ = make_es256_keypair(kid="unknown-key")+ token = create_token(TEST_USER_PAYLOAD, private_key=other_key, kid="unknown-key")- with pytest.raises(ValueError, match="symmetric tokens are not accepted"):+ with pytest.raises(ValueError, match="Invalid token"):jwt_utils.parse_jwt_token(token)@@ -454,65 +427,3 @@ def test_verify_user_missing_role_is_not_a_server_error():assert user.user_id == "user-id"assert user.role == "user"---def _public_pem(private_key) -> str:- from cryptography.hazmat.primitives import serialization-- return (- private_key.public_key()- .public_bytes(- encoding=serialization.Encoding.PEM,- format=serialization.PublicFormat.SubjectPublicKeyInfo,- )- .decode()- )---def test_parse_jwt_token_legacy_asymmetric_token_falls_back_to_verify_key(- mocker: MockerFixture,-):- """Migration grace must cover the RECOMMENDED legacy config, not just HS256.-- The legacy verifier was jwt.decode(token, JWT_VERIFY_KEY,- algorithms=[JWT_ALGORITHM]) and its config text recommended ES256 — so- JWT_VERIFY_KEY can hold an asymmetric public key. A legacy ES256 token's- kid is not in the Better Auth JWK set; on that miss the parser must fall- back to the legacy key instead of rejecting every live session from that- configuration.- """- legacy_private, _ = make_es256_keypair(kid="legacy-key")- mocker.patch.dict(- os.environ,- {- "JWT_VERIFY_KEY": _public_pem(legacy_private),- "JWT_SIGN_ALGORITHM": "ES256",- "JWT_JWKS_URL": MOCK_JWKS_URL,- },- clear=True,- )- mocker.patch.object(config, "_settings", Settings())- mocker.patch.object(jwt_utils, "_jwks_client", None)- mocker.patch.object(jwt_utils, "_jwks_client_url", None)-- # The JWKS endpoint serves a DIFFERENT (Better Auth) key set, so the- # legacy token's kid misses.- _, better_auth_jwks = make_es256_keypair(kid="better-auth-key")- mocker.patch.object(jwt.PyJWKClient, "fetch_data", return_value=better_auth_jwks)-- token = create_es256_token(TEST_USER_PAYLOAD, legacy_private, kid="legacy-key")- result = jwt_utils.parse_jwt_token(token)-- assert result["sub"] == "test-user-id"---def test_parse_jwt_token_unknown_kid_still_rejected_without_asymmetric_legacy_key(- jwks_config,-):- """The fallback must not weaken the default config: with an HS-configured- JWT_ALGORITHM, an unknown-kid asymmetric token stays rejected."""- other_private_key, _ = make_es256_keypair(kid="unknown-key")- token = create_es256_token(TEST_USER_PAYLOAD, other_private_key, kid="unknown-key")-- with pytest.raises(ValueError, match="Invalid token"):- jwt_utils.parse_jwt_token(token)diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.pyindex d36d7d95b7..bdb05d97f9 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py@@ -58,9 +58,16 @@ def requires_frontend_service(scope: str):raise fastapi.HTTPException(status_code=401, detail=f"Invalid token: {e}") from e- # Service tokens are only ever JWKS-signed; the legacy HS256 shared- # secret must not be able to mint one.- if header.get("alg", "").startswith("HS"):+ # Service tokens are only ever JWKS-signed. Check the algorithm's+ # type before inspecting it: a non-string `alg` must fail as a 401,+ # not surface as an AttributeError (500).+ algorithm = header.get("alg")+ if not isinstance(algorithm, str):+ raise fastapi.HTTPException(+ status_code=401,+ detail="Invalid token: signing algorithm is not accepted",+ )+ if algorithm.startswith("HS"):raise fastapi.HTTPException(status_code=401,detail=(diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.pyindex 6b35b1ce22..572ce18a4b 100644--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py@@ -5,6 +5,8 @@ Service tokens ride the same JWKS trust as user tokens but with a distinctaudience and subject; these tests pin the separation between the two planes."""+import base64+import jsonimport osfrom datetime import datetime, timedelta, timezone@@ -60,10 +62,10 @@ def create_es256_token(payload, private_key, kid: str = "test-key-1") -> str:@pytest.fixturedef jwks_config(mocker: MockerFixture):- """Configure both the legacy shared secret and a JWKS endpoint."""+ """Configure a JWKS endpoint serving a single ES256 signing key."""mocker.patch.dict(os.environ,- {"JWT_VERIFY_KEY": MOCK_JWT_SECRET, "JWT_JWKS_URL": MOCK_JWKS_URL},+ {"JWT_JWKS_URL": MOCK_JWKS_URL},clear=True,)mocker.patch.object(config, "_settings", Settings())@@ -123,6 +125,29 @@ def test_symmetric_service_token_is_rejected(jwks_config):assert "symmetric" in response.json()["detail"]+def _service_token_with_header(header: dict) -> str:+ """Build a JWT with an arbitrary header; jwt.encode() always writes a+ string `alg`, so malformed headers are assembled by hand. The signature is+ garbage: these tokens must be rejected before verification."""+ segments = [+ json.dumps(header).encode(),+ json.dumps(SERVICE_PAYLOAD).encode(),+ b"not-a-signature",+ ]+ return ".".join(base64.urlsafe_b64encode(s).rstrip(b"=").decode() for s in segments)++[email protected]("alg", [None, 256], ids=["null-alg", "numeric-alg"])+def test_non_string_algorithm_is_401_not_500(jwks_config, alg):+ """A malformed `alg` header is an auth failure, not a server error.+ TestClient re-raises server exceptions, so an AttributeError here would+ fail the test rather than hide behind a 500."""+ token = _service_token_with_header({"alg": alg, "kid": "test-key-1"})+ response = _post(token)+ assert response.status_code == 401+ assert "signing algorithm" in response.json()["detail"]++def test_expired_service_token_is_401(jwks_config):payload = {**SERVICE_PAYLOAD,diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 57510daf19..6037704873 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -45,9 +45,6 @@ JWT_JWKS_URL=http://localhost:3000/api/auth/jwks# forge tokens. Set this to true to boot anyway on a trusted network path# (a startup warning stays on record).# JWKS_ALLOW_INSECURE_TRANSPORT=false-# Legacy shared-secret verification (HS256). Only needed while sessions issued-# by Supabase GoTrue are still in circulation; safe to remove afterwards.-JWT_VERIFY_KEY=your-super-secret-jwt-token-with-at-least-32-characters-long## ===== REQUIRED SECURITY KEYS ===== ### Generate using: from cryptography.fernet import Fernet;Fernet.generate_key().decode()diff --git a/autogpt_platform/docker-compose.platform.yml b/autogpt_platform/docker-compose.platform.ymlindex c65dc7409f..2da5c53b66 100644--- a/autogpt_platform/docker-compose.platform.yml+++ b/autogpt_platform/docker-compose.platform.yml@@ -29,8 +29,6 @@ x-backend-env:GRAPHITI_FALKORDB_PORT: "6379"# JWKS endpoint of the Better Auth service embedded in the frontend.# Containers reach it via the compose service name, not localhost.- # JWT_VERIFY_KEY (legacy HS256, from backend/.env.default) stays in place- # for the migration window while old Supabase-issued tokens circulate.JWT_JWKS_URL: http://frontend:3000/api/auth/jwks# Database connection string for Docker network# This cannot be constructed like in .env because we cannot interpolate values set here (DB_HOST)