From 435e826da56a105da51176355a29cdc00420f4c1 Mon Sep 17 00:00:00 2001 From: Julian Maurin Date: Mon, 1 Aug 2022 12:30:38 +0200 Subject: [PATCH] Improve PyJWKSet error accuracy (#786) * refacto(TestPyJWKSet): crypto_required decorator at the class level * refacto(TestPyJWKSet): add test to validate the constructor behaviour * fix(PyJWKSet): improve error accuracy Co-authored-by: JulianMaurin --- jwt/api_jwk.py | 12 +++++++----- tests/test_api_jwk.py | 15 +++++++++++---- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/jwt/api_jwk.py b/jwt/api_jwk.py index aae2cf12..bbd8a9e1 100644 --- a/jwt/api_jwk.py +++ b/jwt/api_jwk.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import json from .algorithms import get_default_algorithms @@ -74,15 +76,15 @@ def public_key_use(self): class PyJWKSet: - def __init__(self, keys): + def __init__(self, keys: list[dict]) -> None: self.keys = [] - if not keys or not isinstance(keys, list): - raise PyJWKSetError("Invalid JWK Set value") - - if len(keys) == 0: + if not keys: raise PyJWKSetError("The JWK Set did not contain any keys") + if not isinstance(keys, list): + raise PyJWKSetError("Invalid JWK Set value") + for key in keys: try: self.keys.append(PyJWK(key)) diff --git a/tests/test_api_jwk.py b/tests/test_api_jwk.py index 94eb498c..040e81b9 100644 --- a/tests/test_api_jwk.py +++ b/tests/test_api_jwk.py @@ -208,8 +208,8 @@ def test_from_dict_should_throw_exception_if_arg_is_invalid(self): PyJWK.from_dict(v) +@crypto_required class TestPyJWKSet: - @crypto_required def test_should_load_keys_from_jwk_data_dict(self): algo = RSAAlgorithm(RSAAlgorithm.SHA256) @@ -231,7 +231,6 @@ def test_should_load_keys_from_jwk_data_dict(self): assert jwk.key_id == "keyid-abc123" assert jwk.public_key_use == "sig" - @crypto_required def test_should_load_keys_from_jwk_data_json_string(self): algo = RSAAlgorithm(RSAAlgorithm.SHA256) @@ -253,7 +252,6 @@ def test_should_load_keys_from_jwk_data_json_string(self): assert jwk.key_id == "keyid-abc123" assert jwk.public_key_use == "sig" - @crypto_required def test_keyset_should_index_by_kid(self): algo = RSAAlgorithm(RSAAlgorithm.SHA256) @@ -276,7 +274,6 @@ def test_keyset_should_index_by_kid(self): with pytest.raises(KeyError): _ = jwk_set["this-kid-does-not-exist"] - @crypto_required def test_keyset_with_unknown_alg(self): # first keyset with unusable key and usable key with open(key_path("jwk_keyset_with_unknown_alg.json")) as keyfile: @@ -293,3 +290,13 @@ def test_keyset_with_unknown_alg(self): assert len(jwks.get("keys")) == 1 with pytest.raises(PyJWKSetError): _ = PyJWKSet.from_json(jwks_text) + + def test_invalid_keys_list(self): + with pytest.raises(PyJWKSetError) as err: + PyJWKSet(keys="string") + assert str(err.value) == "Invalid JWK Set value" + + def test_empty_keys_list(self): + with pytest.raises(PyJWKSetError) as err: + PyJWKSet(keys=[]) + assert str(err.value) == "The JWK Set did not contain any keys"