diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index f2c3d0b8..00000000 --- a/.coveragerc +++ /dev/null @@ -1,7 +0,0 @@ -[run] -branch = True - -[report] -exclude_lines = - pragma: no cover - raise NotImplementedError diff --git a/.travis.yml b/.travis.yml index 12fd07a6..4da6eb14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,12 +13,9 @@ addons: install: - pip install codecov - pip install tox tox-travis - - pip install isort black script: - codecov --version - tox - - isort --check src tests - - black -l 100 --check src tests after_success: - codecov notifications: diff --git a/doc/conf.py b/doc/conf.py index 1cc6d858..28cd9204 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -31,36 +31,38 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.coverage', - 'sphinx.ext.viewcode'] +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", +] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'CryptoJWT' -copyright = '2018, Roland Hedberg' -author = 'Roland Hedberg' +project = "CryptoJWT" +copyright = "2018, Roland Hedberg" +author = "Roland Hedberg" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.4' +version = "0.4" # The full version, including alpha/beta/rc tags. -release = '0.4' +release = "0.4" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -72,10 +74,10 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -86,7 +88,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'default' +html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -97,7 +99,7 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. @@ -105,9 +107,9 @@ # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { - '**': [ - 'relations.html', # needs 'show_related': True theme option to display - 'searchbox.html', + "**": [ + "relations.html", # needs 'show_related': True theme option to display + "searchbox.html", ] } @@ -115,7 +117,7 @@ # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. -htmlhelp_basename = 'CryptoJWTdoc' +htmlhelp_basename = "CryptoJWTdoc" # -- Options for LaTeX output --------------------------------------------- @@ -124,15 +126,12 @@ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # # 'preamble': '', - # Latex figure (float) alignment # # 'figure_align': 'htbp', @@ -142,8 +141,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'CryptoJWT.tex', 'CryptoJWT Documentation', - 'Roland Hedberg', 'manual'), + (master_doc, "CryptoJWT.tex", "CryptoJWT Documentation", "Roland Hedberg", "manual"), ] @@ -151,10 +149,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'cryptojwt', 'CryptoJWT Documentation', - [author], 1) -] +man_pages = [(master_doc, "cryptojwt", "CryptoJWT Documentation", [author], 1)] # -- Options for Texinfo output ------------------------------------------- @@ -163,13 +158,17 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'CryptoJWT', 'CryptoJWT Documentation', - author, 'CryptoJWT', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "CryptoJWT", + "CryptoJWT Documentation", + author, + "CryptoJWT", + "One line description of project.", + "Miscellaneous", + ), ] - - # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'https://docs.python.org/': None} +intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..d639eb5e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,21 @@ +# PEP 518: https://www.python.org/dev/peps/pep-0518/ + +[tool.black] +line-length = 100 + +[tool.isort] +force_single_line = true +known_first_party = "cryptojwt" +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +line_length = 100 + +[tool.coverage.run] +branch = true + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "raise NotImplementedError", +] diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 6a04d9e3..00000000 --- a/setup.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[isort] -force_single_line = 1 -known_first_party = cryptojwt -include_trailing_comma = True -force_grid_wrap = 0 -use_parentheses = True -line_length = 100 diff --git a/setup.py b/setup.py index fe415e37..d62ad040 100644 --- a/setup.py +++ b/setup.py @@ -20,13 +20,12 @@ from setuptools import setup -__author__ = 'Roland Hedberg' +__author__ = "Roland Hedberg" -with open('src/cryptojwt/__init__.py', 'r') as fd: - version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open("src/cryptojwt/__init__.py", "r") as fd: + version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) -tests_requires = ['responses', 'pytest', 'isort>=5.0.2', 'black'] +tests_requires = ["responses", "pytest", "isort>=5.0.2", "black"] setup( name="cryptojwt", @@ -35,8 +34,14 @@ author="Roland Hedberg", author_email="roland@catalogix.se", license="Apache 2.0", - packages=["cryptojwt", "cryptojwt/jwe", "cryptojwt/jwk", "cryptojwt/jws", "cryptojwt/tools", - "cryptojwt/serialize"], + packages=[ + "cryptojwt", + "cryptojwt/jwe", + "cryptojwt/jwk", + "cryptojwt/jws", + "cryptojwt/tools", + "cryptojwt/serialize", + ], package_dir={"": "src"}, classifiers=[ "Development Status :: 4 - Beta", @@ -45,22 +50,22 @@ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8" + "Programming Language :: Python :: 3.8", ], install_requires=["cryptography", "requests"], - tests_require=['pytest'], + tests_require=["pytest"], zip_safe=False, extras_require={ - 'testing': tests_requires, - 'docs': ['Sphinx', 'sphinx-autobuild', 'alabaster'], - 'quality': ['isort>=5.0.2', 'black'], + "testing": tests_requires, + "docs": ["Sphinx", "sphinx-autobuild", "alabaster"], + "quality": ["isort>=5.0.2", "black"], }, - scripts=glob.glob('script/*.py'), + scripts=glob.glob("script/*.py"), entry_points={ "console_scripts": [ "jwkgen = cryptojwt.tools.keygen:main", "jwkconv = cryptojwt.tools.keyconv:main", "jwtpeek = cryptojwt.tools.jwtpeek:main", ] - } + }, ) diff --git a/src/cryptojwt/__init__.py b/src/cryptojwt/__init__.py index a2eb935d..1ae167ce 100644 --- a/src/cryptojwt/__init__.py +++ b/src/cryptojwt/__init__.py @@ -21,7 +21,7 @@ except ImportError: pass -__version__ = "1.1.0" +__version__ = "1.2.0" logger = logging.getLogger(__name__) diff --git a/src/cryptojwt/jwe/__init__.py b/src/cryptojwt/jwe/__init__.py index 17776e0e..f0e511bb 100644 --- a/src/cryptojwt/jwe/__init__.py +++ b/src/cryptojwt/jwe/__init__.py @@ -22,7 +22,14 @@ "ECDH-ES+A192KW", "ECDH-ES+A256KW", ], - "enc": ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512", "A128GCM", "A192GCM", "A256GCM",], + "enc": [ + "A128CBC-HS256", + "A192CBC-HS384", + "A256CBC-HS512", + "A128GCM", + "A192GCM", + "A256GCM", + ], } diff --git a/src/cryptojwt/jwe/aes.py b/src/cryptojwt/jwe/aes.py index 625d0a6e..20ea7d78 100644 --- a/src/cryptojwt/jwe/aes.py +++ b/src/cryptojwt/jwe/aes.py @@ -18,8 +18,7 @@ class AES_CBCEncrypter(Encrypter): - """ - """ + """""" def __init__(self, key_len=32, key=None, msg_padding="PKCS7"): Encrypter.__init__(self) diff --git a/src/cryptojwt/jwe/jwe_ec.py b/src/cryptojwt/jwe/jwe_ec.py index 911a6ea3..3321a8e1 100644 --- a/src/cryptojwt/jwe/jwe_ec.py +++ b/src/cryptojwt/jwe/jwe_ec.py @@ -157,7 +157,12 @@ def dec_setup(self, token, key=None, **kwargs): raise Exception("Unknown key length for algorithm") self.cek = ecdh_derive_key( - key, epubkey.pub_key, apu, apv, str(self.headers["enc"]).encode(), dk_len, + key, + epubkey.pub_key, + apu, + apv, + str(self.headers["enc"]).encode(), + dk_len, ) elif self.headers["alg"] in [ "ECDH-ES+A128KW", diff --git a/src/cryptojwt/jwe/jwe_rsa.py b/src/cryptojwt/jwe/jwe_rsa.py index dd4324d8..f34b1331 100644 --- a/src/cryptojwt/jwe/jwe_rsa.py +++ b/src/cryptojwt/jwe/jwe_rsa.py @@ -85,7 +85,7 @@ def encrypt(self, key, iv="", cek="", **kwargs): return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag]) def decrypt(self, token, key, cek=None): - """ Decrypts a JWT + """Decrypts a JWT :param token: The JWT :param key: A key to use for decrypting diff --git a/src/cryptojwt/jwe/jwekey.py b/src/cryptojwt/jwe/jwekey.py index faa6093e..31a1c8ae 100644 --- a/src/cryptojwt/jwe/jwekey.py +++ b/src/cryptojwt/jwe/jwekey.py @@ -38,7 +38,7 @@ def alg2keytype(self, alg): return alg2keytype(alg) def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""): - """ Encrypt JWE content. + """Encrypt JWE content. :param enc_alg: The JWE "enc" value specifying the encryption algorithm :param msg: The plain text message @@ -62,7 +62,7 @@ def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""): @staticmethod def _decrypt(enc, key, ctxt, iv, tag, auth_data=b""): - """ Decrypt JWE content. + """Decrypt JWE content. :param enc: The JWE "enc" value specifying the encryption algorithm :param key: Key (CEK) diff --git a/src/cryptojwt/jwe/rsa.py b/src/cryptojwt/jwe/rsa.py index 691c3e59..8e7cc4fe 100644 --- a/src/cryptojwt/jwe/rsa.py +++ b/src/cryptojwt/jwe/rsa.py @@ -20,7 +20,9 @@ def encrypt(self, msg, key, sign_padding="pkcs1_padding"): return key.encrypt( msg, _padding( - mgf=padding.MGF1(algorithm=_chosen_hash()), algorithm=_chosen_hash(), label=None, + mgf=padding.MGF1(algorithm=_chosen_hash()), + algorithm=_chosen_hash(), + label=None, ), ) diff --git a/src/cryptojwt/jwk/jwk.py b/src/cryptojwt/jwk/jwk.py index 86f41c47..c9e32904 100644 --- a/src/cryptojwt/jwk/jwk.py +++ b/src/cryptojwt/jwk/jwk.py @@ -93,7 +93,9 @@ def key_from_jwk_dict(jwk_dict, private=None): else: # Ecdsa public key. ec_pub_numbers = ec.EllipticCurvePublicNumbers( - base64url_to_long(_jwk_dict["x"]), base64url_to_long(_jwk_dict["y"]), curve, + base64url_to_long(_jwk_dict["x"]), + base64url_to_long(_jwk_dict["y"]), + curve, ) _jwk_dict["pub_key"] = ec_pub_numbers.public_key(backends.default_backend()) return ECKey(**_jwk_dict) diff --git a/src/cryptojwt/jwk/rsa.py b/src/cryptojwt/jwk/rsa.py index 07de5a6a..e98cb236 100644 --- a/src/cryptojwt/jwk/rsa.py +++ b/src/cryptojwt/jwk/rsa.py @@ -128,7 +128,7 @@ def rsa_eq(key1, key2): def x509_rsa_load(txt): - """ So I get the same output format as loads produces + """So I get the same output format as loads produces :param txt: :return: """ @@ -172,10 +172,10 @@ def rsa_construct_private(numbers): try: cnum["iqmp"] = numbers["di"] except KeyError: - cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"]) + cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"]) else: if not numbers["di"]: - cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"]) + cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"]) rpubn = rsa.RSAPublicNumbers(e=numbers["e"], n=numbers["n"]) rprivn = rsa.RSAPrivateNumbers(public_numbers=rpubn, **cnum) diff --git a/src/cryptojwt/jws/jws.py b/src/cryptojwt/jws/jws.py index b24b0919..c9b334ee 100644 --- a/src/cryptojwt/jws/jws.py +++ b/src/cryptojwt/jws/jws.py @@ -321,7 +321,11 @@ def verify_json(self, jws, keys=None, allow_none=False, at_least_one=False): for _sign in _signs: protected_headers = _sign.get("protected", "") token = b".".join( - [protected_headers.encode(), _payload.encode(), _sign["signature"].encode(),] + [ + protected_headers.encode(), + _payload.encode(), + _sign["signature"].encode(), + ] ) unprotected_headers = _sign.get("header", {}) diff --git a/src/cryptojwt/jws/pss.py b/src/cryptojwt/jws/pss.py index 71cbb3d6..a7443ddb 100644 --- a/src/cryptojwt/jws/pss.py +++ b/src/cryptojwt/jws/pss.py @@ -38,7 +38,8 @@ def sign(self, msg, key): sig = key.sign( digest, padding.PSS( - mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH, + mgf=padding.MGF1(self.hash_algorithm()), + salt_length=padding.PSS.MAX_LENGTH, ), utils.Prehashed(self.hash_algorithm()), ) @@ -59,7 +60,8 @@ def verify(self, msg, signature, key): signature, msg, padding.PSS( - mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH, + mgf=padding.MGF1(self.hash_algorithm()), + salt_length=padding.PSS.MAX_LENGTH, ), self.hash_algorithm(), ) diff --git a/src/cryptojwt/jws/utils.py b/src/cryptojwt/jws/utils.py index 171e7d00..8ee30953 100644 --- a/src/cryptojwt/jws/utils.py +++ b/src/cryptojwt/jws/utils.py @@ -11,7 +11,7 @@ def left_hash(msg, func="HS256"): - """ Calculate left hash as described in + """Calculate left hash as described in https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken for at_hash and in for c_hash diff --git a/src/cryptojwt/key_bundle.py b/src/cryptojwt/key_bundle.py index 9e7e7520..9b2f200a 100755 --- a/src/cryptojwt/key_bundle.py +++ b/src/cryptojwt/key_bundle.py @@ -402,7 +402,9 @@ def do_remote(self): else: LOGGER.warning( - "HTTP status %d reading remote JWKS from %s", _http_resp.status_code, self.source, + "HTTP status %d reading remote JWKS from %s", + _http_resp.status_code, + self.source, ) raise UpdateFailed(REMOTE_FAILED.format(self.source, _http_resp.status_code)) self.last_updated = time.time() diff --git a/src/cryptojwt/key_jar.py b/src/cryptojwt/key_jar.py index 9c040b70..4b58bfe7 100755 --- a/src/cryptojwt/key_jar.py +++ b/src/cryptojwt/key_jar.py @@ -762,7 +762,12 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N @deprecated_alias(issuer="issuer_id", owner="issuer_id") def init_key_jar( - public_path="", private_path="", key_defs="", issuer_id="", read_only=True, storage=None, + public_path="", + private_path="", + key_defs="", + issuer_id="", + read_only=True, + storage=None, ): """ A number of cases here: @@ -805,7 +810,10 @@ def init_key_jar( """ _issuer = init_key_issuer( - public_path=public_path, private_path=private_path, key_defs=key_defs, read_only=read_only, + public_path=public_path, + private_path=private_path, + key_defs=key_defs, + read_only=read_only, ) if _issuer is None: diff --git a/src/cryptojwt/tools/keyconv.py b/src/cryptojwt/tools/keyconv.py index c12c8d5c..83f0b2d0 100644 --- a/src/cryptojwt/tools/keyconv.py +++ b/src/cryptojwt/tools/keyconv.py @@ -115,7 +115,10 @@ def pem2jwk( def export_jwk( - jwk: JWK, private: bool = False, encrypt: bool = False, passphrase: Optional[str] = None, + jwk: JWK, + private: bool = False, + encrypt: bool = False, + passphrase: Optional[str] = None, ) -> bytes: """Export JWK as PEM/bin""" diff --git a/src/cryptojwt/utils.py b/src/cryptojwt/utils.py index d0c6d97f..b0619f74 100644 --- a/src/cryptojwt/utils.py +++ b/src/cryptojwt/utils.py @@ -158,8 +158,7 @@ def as_unicode(b): def bytes2str_conv(item): - """ - """ + """""" if isinstance(item, bytes): return item.decode("utf-8") elif item is None or isinstance(item, (str, int, bool)): diff --git a/tests/test_01_simplejwt.py b/tests/test_01_simplejwt.py index 02a944be..9d94a172 100644 --- a/tests/test_01_simplejwt.py +++ b/tests/test_01_simplejwt.py @@ -10,7 +10,10 @@ def _eq(l1, l2): def test_pack_jwt(): _jwt = SimpleJWT(**{"alg": "none", "cty": "jwt"}) jwt = _jwt.pack( - parts=[{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}, "",] + parts=[ + {"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}, + "", + ] ) p = jwt.split(".") diff --git a/tests/test_02_jwk.py b/tests/test_02_jwk.py index 02900600..a9307b8b 100644 --- a/tests/test_02_jwk.py +++ b/tests/test_02_jwk.py @@ -515,6 +515,9 @@ def test_key_from_jwk_dict_rsa(): _key = key_from_jwk_dict(jwk) assert isinstance(_key, RSAKey) assert _key.has_private_key() + _key2 = RSAKey(**jwk) + assert isinstance(_key2, RSAKey) + assert _key2.has_private_key() def test_key_from_jwk_dict_ec(): @@ -707,7 +710,10 @@ def test_x5t_calculation(): @pytest.mark.parametrize( "filename,key_type", - [("ec-public.pem", ec.EllipticCurvePublicKey), ("rsa-public.pem", rsa.RSAPublicKey),], + [ + ("ec-public.pem", ec.EllipticCurvePublicKey), + ("rsa-public.pem", rsa.RSAPublicKey), + ], ) def test_import_public_key_from_pem_file(filename, key_type): _file = full_path(filename) diff --git a/tests/test_04_key_issuer.py b/tests/test_04_key_issuer.py index 5e5fba7d..fedad978 100755 --- a/tests/test_04_key_issuer.py +++ b/tests/test_04_key_issuer.py @@ -221,7 +221,11 @@ def test_build_keyissuer_usage(): def test_build_keyissuer_missing(tmpdir): keys = [ - {"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],} + { + "type": "RSA", + "key": os.path.join(tmpdir.dirname, "missing_file"), + "use": ["enc", "sig"], + } ] key_issuer = build_keyissuer(keys) @@ -239,7 +243,11 @@ def test_build_RSA_keyissuer_from_file(tmpdir): def test_build_EC_keyissuer_missing(tmpdir): keys = [ - {"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],} + { + "type": "EC", + "key": os.path.join(tmpdir.dirname, "missing_file"), + "use": ["enc", "sig"], + } ] key_issuer = build_keyissuer(keys) @@ -616,7 +624,10 @@ def test_init_key_issuer_update(): # New set of keys, JWKSs with keys and public written to file _keyissuer_1 = init_key_issuer( - private_path=PRIVATE_FILE, key_defs=KEYSPEC, public_path=PUBLIC_FILE, read_only=False, + private_path=PRIVATE_FILE, + key_defs=KEYSPEC, + public_path=PUBLIC_FILE, + read_only=False, ) assert len(_keyissuer_1) == 2 @@ -646,7 +657,10 @@ def test_init_key_issuer_update(): assert len(_keyissuer_3.get("sig", "EC")) == 1 _keyissuer_4 = init_key_issuer( - private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False, + private_path=PRIVATE_FILE, + key_defs=KEYSPEC_2, + public_path=PUBLIC_FILE, + read_only=False, ) # Now it should diff --git a/tests/test_04_key_jar.py b/tests/test_04_key_jar.py index fcc19773..b31e5ba8 100755 --- a/tests/test_04_key_jar.py +++ b/tests/test_04_key_jar.py @@ -2,6 +2,7 @@ import os import shutil import time +import warnings import pytest @@ -228,7 +229,11 @@ def test_build_keyjar_usage(): def test_build_keyjar_missing(tmpdir): keys = [ - {"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],} + { + "type": "RSA", + "key": os.path.join(tmpdir.dirname, "missing_file"), + "use": ["enc", "sig"], + } ] key_jar = build_keyjar(keys) @@ -246,7 +251,11 @@ def test_build_RSA_keyjar_from_file(tmpdir): def test_build_EC_keyjar_missing(tmpdir): keys = [ - {"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],} + { + "type": "EC", + "key": os.path.join(tmpdir.dirname, "missing_file"), + "use": ["enc", "sig"], + } ] key_jar = build_keyjar(keys) @@ -302,7 +311,8 @@ def test_items(self): ), ) ks.add_kb( - "http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), + "http://www.example.org", + keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), ) assert len(ks.items()) == 2 @@ -328,7 +338,8 @@ def test_issuer_extra_slash(self): ), ) ks.add_kb( - "http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), + "http://www.example.org", + keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), ) assert ks.get("sig", "RSA", "http://www.example.org/") @@ -354,7 +365,8 @@ def test_issuer_missing_slash(self): ), ) ks.add_kb( - "http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), + "http://www.example.org/", + keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), ) assert ks.get("sig", "RSA", "http://www.example.org") @@ -380,7 +392,8 @@ def test_get_enc(self): ), ) ks.add_kb( - "http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), + "http://www.example.org/", + keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), ) assert ks.get("enc", "oct") @@ -406,7 +419,8 @@ def test_get_enc_not_mine(self): ), ) ks.add_kb( - "http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), + "http://www.example.org/", + keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]), ) assert ks.get("enc", "oct", "http://www.example.org/") @@ -443,13 +457,20 @@ def test_no_use(self): assert enc_key != [] @pytest.mark.network + @pytest.mark.skip("connect-op.herokuapp.com is broken") def test_provider(self): kj = KeyJar() + _url = "https://connect-op.herokuapp.com/jwks.json" kj.load_keys( - "https://connect-op.heroku.com", jwks_uri="https://connect-op.herokuapp.com/jwks.json", + "https://connect-op.heroku.com", + jwks_uri=_url, ) - - assert kj.get_issuer_keys("https://connect-op.heroku.com")[0].keys() + iss_keys = kj.get_issuer_keys("https://connect-op.heroku.com") + if not iss_keys: + _msg = "{} is not available at this moment!".format(_url) + warnings.warn(_msg) + else: + assert iss_kes[0].keys() def test_import_jwks(): @@ -961,7 +982,10 @@ def test_init_key_jar_update(): assert len(_keyjar_3.get_signing_key("EC")) == 1 _keyjar_4 = init_key_jar( - private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False, + private_path=PRIVATE_FILE, + key_defs=KEYSPEC_2, + public_path=PUBLIC_FILE, + read_only=False, ) # Now it should diff --git a/tests/test_06_jws.py b/tests/test_06_jws.py index 96b15ac2..c452e0b5 100644 --- a/tests/test_06_jws.py +++ b/tests/test_06_jws.py @@ -431,7 +431,8 @@ def test_jws_mm(): @pytest.mark.parametrize( - "ec_func,alg", [(ec.SECP256R1, "ES256"), (ec.SECP384R1, "ES384"), (ec.SECP521R1, "ES512")], + "ec_func,alg", + [(ec.SECP256R1, "ES256"), (ec.SECP384R1, "ES384"), (ec.SECP521R1, "ES512")], ) def test_signer_es(ec_func, alg): payload = "Please take a moment to register today" @@ -706,7 +707,9 @@ def test_sign_json_dont_flatten_if_multiple_signatures(): key = ECKey().load_key(P256()) unprotected_headers = {"foo": "bar"} _jwt = JWS(msg="hello world", alg="ES256").sign_json( - headers=[(None, unprotected_headers), (None, {"abc": "xyz"})], keys=[key], flatten=True, + headers=[(None, unprotected_headers), (None, {"abc": "xyz"})], + keys=[key], + flatten=True, ) assert "signatures" in json.loads(_jwt) diff --git a/tests/test_09_jwt.py b/tests/test_09_jwt.py index 26398575..71b019d5 100755 --- a/tests/test_09_jwt.py +++ b/tests/test_09_jwt.py @@ -26,10 +26,16 @@ def full_path(local_file): # k2 = import_private_rsa_key_from_file(full_path('size2048.key')) kb1 = KeyBundle( - source="file://{}".format(full_path("rsa.key")), fileformat="der", keyusage="sig", kid="1", + source="file://{}".format(full_path("rsa.key")), + fileformat="der", + keyusage="sig", + kid="1", ) kb2 = KeyBundle( - source="file://{}".format(full_path("size2048.key")), fileformat="der", keyusage="enc", kid="2", + source="file://{}".format(full_path("size2048.key")), + fileformat="der", + keyusage="enc", + kid="2", ) ALICE_KEY_JAR = KeyJar() @@ -37,7 +43,10 @@ def full_path(local_file): ALICE_KEY_JAR.add_kb(ALICE, kb2) kb3 = KeyBundle( - source="file://{}".format(full_path("server.key")), fileformat="der", keyusage="enc", kid="3", + source="file://{}".format(full_path("server.key")), + fileformat="der", + keyusage="enc", + kid="3", ) BOB_KEY_JAR = KeyJar() diff --git a/tests/test_50_argument_alias.py b/tests/test_50_argument_alias.py index 98b09479..746ab600 100644 --- a/tests/test_50_argument_alias.py +++ b/tests/test_50_argument_alias.py @@ -168,7 +168,10 @@ def test_init_key_jar_update(): assert len(_keyjar_3.get_signing_key("EC")) == 1 _keyjar_4 = init_key_jar( - private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False, + private_path=PRIVATE_FILE, + key_defs=KEYSPEC_2, + public_path=PUBLIC_FILE, + read_only=False, ) # Now it should diff --git a/tox.ini b/tox.ini index c3b44dff..def7f92e 100644 --- a/tox.ini +++ b/tox.ini @@ -4,13 +4,15 @@ envlist = py{36,37,38},quality [testenv] passenv = CI TRAVIS TRAVIS_* commands = - py.test --cov=cryptojwt tests/ {posargs} + py.test --cov=cryptojwt --isort --black {posargs} codecov extras = testing deps = codecov + pytest-black pytest-cov pytest-httpserver + pytest-isort [pep8] max-line-length=100 @@ -20,10 +22,10 @@ addopts = --color=yes markers = network [testenv:quality] -# Black need python 3.6 -basepython = python3.6 +basepython = python3.8 ignore_errors = True deps = twine extras = quality commands = - isort --recursive --diff --check-only src/ tests/ + isort --check --diff src tests + black --check src tests