From c498983c53b836d63f2e0185b9665812edd30f53 Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 17 Jan 2024 11:25:18 +0100 Subject: [PATCH 1/3] Fixed some spelling errors. Slightly improved logging messages. Removed unused imports. --- src/cryptojwt/jwk/ec.py | 2 +- src/cryptojwt/jws/dsa.py | 2 +- src/cryptojwt/key_bundle.py | 4 ++-- src/cryptojwt/key_issuer.py | 4 ++-- src/cryptojwt/key_jar.py | 4 ++-- src/cryptojwt/simple_jwt.py | 2 +- tests/test_04_key_jar.py | 2 +- tests/test_40_serialize.py | 4 ---- 8 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/cryptojwt/jwk/ec.py b/src/cryptojwt/jwk/ec.py index 4acf9d9c..93349221 100644 --- a/src/cryptojwt/jwk/ec.py +++ b/src/cryptojwt/jwk/ec.py @@ -113,7 +113,7 @@ def __init__(self, kty="EC", alg="", use="", kid="", crv="", x="", y="", d="", * def deserialize(self): """ Starting with information gathered from the on-the-wire representation - of an elliptic curve key (a JWK) initiate an + of an elliptic curve key (a JWK) initiate a cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey or EllipticCurvePrivateKey instance. So we have to get from having:: diff --git a/src/cryptojwt/jws/dsa.py b/src/cryptojwt/jws/dsa.py index 59f66046..6ddedcfd 100644 --- a/src/cryptojwt/jws/dsa.py +++ b/src/cryptojwt/jws/dsa.py @@ -85,7 +85,7 @@ def verify(self, msg, sig, key): def _cross_check(self, pub_key): """ In Ecdsa, both the key and the algorithm define the curve. - Therefore, we must cross check them to make sure they're the same. + Therefore, we must crosscheck them to make sure they're the same. :param key: :raises: ValueError is the curves are not the same diff --git a/src/cryptojwt/key_bundle.py b/src/cryptojwt/key_bundle.py index 245b053a..8fa028a8 100755 --- a/src/cryptojwt/key_bundle.py +++ b/src/cryptojwt/key_bundle.py @@ -235,7 +235,7 @@ def __init__( :param keys: A dictionary or a list of dictionaries with the keys ["kty", "key", "alg", "use", "kid"] - :param source: Where the key set can be fetch from + :param source: Where the key set can be fetched from :param fileformat: For a local file either "jwks" or "der" :param keytype: Iff local file and 'der' format what kind of key it is. presently 'rsa' and 'ec' are supported. @@ -467,7 +467,7 @@ def _do_remote(self, set_keys=True): if self.ignore_errors_until and time.time() < self.ignore_errors_until: LOGGER.warning( - "Not reading remote JWKS from %s (in error holddown until %s)", + "Not reading remote JWKS from %s (in error hold down until %s)", self.source, datetime.fromtimestamp(self.ignore_errors_until), ) diff --git a/src/cryptojwt/key_issuer.py b/src/cryptojwt/key_issuer.py index 1151edc0..08e540ac 100755 --- a/src/cryptojwt/key_issuer.py +++ b/src/cryptojwt/key_issuer.py @@ -91,7 +91,7 @@ def add_url(self, url, **kwargs): if not url: raise KeyError("No url given") - logger.debug("httpc_params: %s", self.httpc_params) + logger.debug(f"add_url: httpc_params: {self.httpc_params}") if "/localhost:" in url or "/localhost/" in url: _params = self.httpc_params.copy() @@ -433,7 +433,7 @@ def mark_all_keys_as_inactive(self): self._bundles = kbl - def key_summary(self): + def key_summary(self) -> str: """ Return a text representation of all the keys. diff --git a/src/cryptojwt/key_jar.py b/src/cryptojwt/key_jar.py index 92ecdec2..78727f20 100755 --- a/src/cryptojwt/key_jar.py +++ b/src/cryptojwt/key_jar.py @@ -323,10 +323,10 @@ def load_keys(self, issuer_id, jwks_uri="", jwks=None, replace=False): :param jwks: A dictionary representation of a JWKS :param issuer_id: The provider URL :param replace: If all previously gathered keys from this provider - should be replace. + should be replaced. :return: Dictionary with usage as key and keys as values """ - logger.debug("Initiating key bundle for issuer: %s" % issuer_id) + logger.debug(f"Initiating key bundle for issuer: {issuer_id}") _issuer = self.return_issuer(issuer_id) if replace: diff --git a/src/cryptojwt/simple_jwt.py b/src/cryptojwt/simple_jwt.py index c0ec92f3..fbdaf2b8 100644 --- a/src/cryptojwt/simple_jwt.py +++ b/src/cryptojwt/simple_jwt.py @@ -75,7 +75,7 @@ def pack(self, parts=None, headers=None): else: headers = {"alg": "none"} - logging.debug("JWT header: {}".format(headers)) + logging.debug("(pack) JWT header: {}".format(headers)) if not parts: return ".".join([a.decode() for a in self.b64part]) diff --git a/tests/test_04_key_jar.py b/tests/test_04_key_jar.py index 9e73e9e1..bd12ecf7 100755 --- a/tests/test_04_key_jar.py +++ b/tests/test_04_key_jar.py @@ -822,7 +822,7 @@ def test_key_summary(): kj.add_kb("C", KeyBundle(JWK2["keys"])) out = kj.key_summary("Alice") - assert out + assert out == "RSA::abc" PUBLIC_FILE = "{}/public_jwks.json".format(BASEDIR) diff --git a/tests/test_40_serialize.py b/tests/test_40_serialize.py index 4c7dbb96..f83b9f6a 100644 --- a/tests/test_40_serialize.py +++ b/tests/test_40_serialize.py @@ -1,10 +1,6 @@ import os -from cryptojwt.jwk.hmac import SYMKey -from cryptojwt.jwk.rsa import RSAKey -from cryptojwt.jwk.rsa import import_rsa_key_from_cert_file from cryptojwt.key_bundle import keybundle_from_local_file -from cryptojwt.key_bundle import rsa_init from cryptojwt.key_issuer import KeyIssuer from cryptojwt.serialize import item From 627e078aca6fba051a6c77a741124e8df878cad6 Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 17 Jan 2024 11:39:42 +0100 Subject: [PATCH 2/3] Another spelling error fixed. --- tests/test_09_jwt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_09_jwt.py b/tests/test_09_jwt.py index bb413f0b..59b08b40 100755 --- a/tests/test_09_jwt.py +++ b/tests/test_09_jwt.py @@ -244,7 +244,7 @@ class DummyMsg(object): def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) - self.jws_headers = {} + self.jws_header = {} def verify(self, **kwargs): return True @@ -331,4 +331,4 @@ def test_extra_headers(): bob = JWT(key_jar=_kj, iss=BOB, sign_alg="HS256", typ2msg_cls={"dummy": DummyMsg}) info = bob.unpack(_jwt) assert isinstance(info, DummyMsg) - assert set(info.jws_headers.keys()) == {'xtra', 'typ', 'alg', 'kid'} + assert set(info.jws_header.keys()) == {'xtra', 'typ', 'alg', 'kid'} From ca1618ab2ae4699a626c1277a410c4d00819401c Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 17 Jan 2024 11:46:33 +0100 Subject: [PATCH 3/3] Ran black and isort --- src/cryptojwt/jws/jws.py | 2 +- src/cryptojwt/jwt.py | 62 ++++++++++++++++++++-------------------- src/cryptojwt/jwx.py | 3 +- src/cryptojwt/key_jar.py | 3 +- tests/test_09_jwt.py | 14 ++++----- 5 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/cryptojwt/jws/jws.py b/src/cryptojwt/jws/jws.py index fd12c264..f521cbc9 100644 --- a/src/cryptojwt/jws/jws.py +++ b/src/cryptojwt/jws/jws.py @@ -118,7 +118,7 @@ def sign_compact(self, keys=None, protected=None, **kwargs): key, xargs, _alg = self.alg_keys(keys, "sig", protected) - for param in ['typ']: + for param in ["typ"]: if param in self: xargs[param] = self[param] diff --git a/src/cryptojwt/jwt.py b/src/cryptojwt/jwt.py index 5e22750e..1464d5c3 100755 --- a/src/cryptojwt/jwt.py +++ b/src/cryptojwt/jwt.py @@ -1,13 +1,13 @@ """Basic JSON Web Token implementation.""" import json -from json import JSONDecodeError import logging import time +import uuid +from json import JSONDecodeError from typing import Dict from typing import List from typing import MutableMapping from typing import Optional -import uuid from .exception import HeaderError from .exception import VerificationError @@ -81,24 +81,24 @@ class JWT: """The basic JSON Web Token class.""" def __init__( - self, - key_jar=None, - iss: str="", - lifetime: int = 0, - sign: bool = True, - sign_alg: str = "RS256", - encrypt: bool = False, - enc_enc: str = "A128GCM", - enc_alg: str = "RSA-OAEP-256", - msg_cls: Optional[MutableMapping] = None, - iss2msg_cls: Dict[str, str] = None, - skew: int = 15, - allowed_sign_algs: List[str] = None, - allowed_enc_algs: List[str] = None, - allowed_enc_encs: List[str] = None, - allowed_max_lifetime: int = None, - zip: str = "", - typ2msg_cls: Dict = None + self, + key_jar=None, + iss: str = "", + lifetime: int = 0, + sign: bool = True, + sign_alg: str = "RS256", + encrypt: bool = False, + enc_enc: str = "A128GCM", + enc_alg: str = "RSA-OAEP-256", + msg_cls: Optional[MutableMapping] = None, + iss2msg_cls: Dict[str, str] = None, + skew: int = 15, + allowed_sign_algs: List[str] = None, + allowed_enc_algs: List[str] = None, + allowed_enc_encs: List[str] = None, + allowed_max_lifetime: int = None, + zip: str = "", + typ2msg_cls: Dict = None, ): self.key_jar = key_jar # KeyJar instance self.iss = iss # My identifier @@ -216,15 +216,15 @@ def message(self, signing_key, **kwargs): return json.dumps(kwargs) def pack( - self, - payload: Optional[dict] = None, - kid: Optional[str] = "", - issuer_id: Optional[str] = "", - recv: Optional[str] = "", - aud: Optional[str] = None, - iat: Optional[int] = None, - jws_headers: Dict[str, str] = None, - **kwargs + self, + payload: Optional[dict] = None, + kid: Optional[str] = "", + issuer_id: Optional[str] = "", + recv: Optional[str] = "", + aud: Optional[str] = None, + iat: Optional[int] = None, + jws_headers: Dict[str, str] = None, + **kwargs ) -> str: """ @@ -399,8 +399,8 @@ def unpack(self, token, timestamp=None): # try to find an issuer specific message class if "iss" in _info: _msg_cls = self.iss2msg_cls.get(_info["iss"]) - if not _msg_cls and _jws_header and 'typ' in _jws_header: - _msg_cls = self.typ2msg_cls.get(_jws_header['typ']) + if not _msg_cls and _jws_header and "typ" in _jws_header: + _msg_cls = self.typ2msg_cls.get(_jws_header["typ"]) timestamp = timestamp or utc_time_sans_frac() diff --git a/src/cryptojwt/jwx.py b/src/cryptojwt/jwx.py index 4c16c5ac..52c696b4 100644 --- a/src/cryptojwt/jwx.py +++ b/src/cryptojwt/jwx.py @@ -4,14 +4,15 @@ import warnings import requests + from cryptojwt.jwk import JWK from cryptojwt.key_bundle import KeyBundle from .exception import HeaderError from .jwe import DEPRECATED from .jwk.jwk import key_from_jwk_dict -from .jwk.rsa import import_rsa_key from .jwk.rsa import RSAKey +from .jwk.rsa import import_rsa_key from .jwk.x509 import load_x509_cert from .utils import as_bytes from .utils import as_unicode diff --git a/src/cryptojwt/key_jar.py b/src/cryptojwt/key_jar.py index 78727f20..f1e9cbed 100755 --- a/src/cryptojwt/key_jar.py +++ b/src/cryptojwt/key_jar.py @@ -3,9 +3,10 @@ from typing import List from typing import Optional -from cryptojwt.jwk import JWK from requests import request +from cryptojwt.jwk import JWK + from .exception import IssuerNotFound from .jwe.jwe import alg2keytype as jwe_alg2keytype from .jws.utils import alg2keytype as jws_alg2keytype diff --git a/tests/test_09_jwt.py b/tests/test_09_jwt.py index 59b08b40..452ee8c2 100755 --- a/tests/test_09_jwt.py +++ b/tests/test_09_jwt.py @@ -1,14 +1,15 @@ import os import pytest + from cryptojwt.jws.exception import NoSuitableSigningKeys from cryptojwt.jwt import JWT +from cryptojwt.jwt import VerificationError from cryptojwt.jwt import pick_key from cryptojwt.jwt import utc_time_sans_frac -from cryptojwt.jwt import VerificationError from cryptojwt.key_bundle import KeyBundle -from cryptojwt.key_jar import init_key_jar from cryptojwt.key_jar import KeyJar +from cryptojwt.key_jar import init_key_jar __author__ = "Roland Hedberg" @@ -240,7 +241,6 @@ def test_with_jti(): class DummyMsg(object): - def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) @@ -309,9 +309,9 @@ def test_eddsa_jwt(): ] } JWT_TEST = ( - "eyJraWQiOiItMTkwOTU3MjI1NyIsImFsZyI6IkVkRFNBIn0." - + "eyJqdGkiOiIyMjkxNmYzYy05MDkzLTQ4MTMtODM5Ny1mMTBlNmI3MDRiNjgiLCJkZWxlZ2F0aW9uSWQiOiJiNGFlNDdhNy02MjVhLTQ2MzAtOTcyNy00NTc2NGE3MTJjY2UiLCJleHAiOjE2NTUyNzkxMDksIm5iZiI6MTY1NTI3ODgwOSwic2NvcGUiOiJyZWFkIG9wZW5pZCIsImlzcyI6Imh0dHBzOi8vaWRzdnIuZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VybmFtZSIsImF1ZCI6ImFwaS5leGFtcGxlLmNvbSIsImlhdCI6MTY1NTI3ODgwOSwicHVycG9zZSI6ImFjY2Vzc190b2tlbiJ9." - + "rjeE8D_e4RYzgvpu-nOwwx7PWMiZyDZwkwO6RiHR5t8g4JqqVokUKQt-oST1s45wubacfeDSFogOrIhe3UHDAg" + "eyJraWQiOiItMTkwOTU3MjI1NyIsImFsZyI6IkVkRFNBIn0." + + "eyJqdGkiOiIyMjkxNmYzYy05MDkzLTQ4MTMtODM5Ny1mMTBlNmI3MDRiNjgiLCJkZWxlZ2F0aW9uSWQiOiJiNGFlNDdhNy02MjVhLTQ2MzAtOTcyNy00NTc2NGE3MTJjY2UiLCJleHAiOjE2NTUyNzkxMDksIm5iZiI6MTY1NTI3ODgwOSwic2NvcGUiOiJyZWFkIG9wZW5pZCIsImlzcyI6Imh0dHBzOi8vaWRzdnIuZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VybmFtZSIsImF1ZCI6ImFwaS5leGFtcGxlLmNvbSIsImlhdCI6MTY1NTI3ODgwOSwicHVycG9zZSI6ImFjY2Vzc190b2tlbiJ9." + + "rjeE8D_e4RYzgvpu-nOwwx7PWMiZyDZwkwO6RiHR5t8g4JqqVokUKQt-oST1s45wubacfeDSFogOrIhe3UHDAg" ) ISSUER = "https://idsvr.example.com" kj = KeyJar() @@ -331,4 +331,4 @@ def test_extra_headers(): bob = JWT(key_jar=_kj, iss=BOB, sign_alg="HS256", typ2msg_cls={"dummy": DummyMsg}) info = bob.unpack(_jwt) assert isinstance(info, DummyMsg) - assert set(info.jws_header.keys()) == {'xtra', 'typ', 'alg', 'kid'} + assert set(info.jws_header.keys()) == {"xtra", "typ", "alg", "kid"}