Skip to content

Commit 811ae79

Browse files
jdufresnejpadillapre-commit-ci[bot]
authored
Simplify black configuration to be closer to upstream defaults (jpadilla#568)
* Simplify black configuration to be closer to upstream defaults Avoid extra configuration by simply going with Black defaults. This allows removing some configuration options, thus simplifying the overall configuration. It also makes the code style closer to community conventions. As more projects adopt black formatting, more code will look like the black defaults. Further, the default 88 tends to create more readable lines, IMO. The black rationale is located at: https://black.readthedocs.io/en/stable/the_black_code_style.html#line-length * Update tests/test_api_jws.py Co-authored-by: José Padilla <jpadilla@webapplicate.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update tests/test_api_jws.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: José Padilla <jpadilla@webapplicate.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent d5eff64 commit 811ae79

File tree

13 files changed

+51
-163
lines changed

13 files changed

+51
-163
lines changed

docs/conf.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ def find_version(*file_paths):
2020
string inside.
2121
"""
2222
version_file = read(*file_paths)
23-
version_match = re.search(
24-
r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M
25-
)
23+
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
2624
if version_match:
2725
return version_match.group(1)
2826
raise RuntimeError("Unable to find version string.")

jwt/algorithms.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -444,23 +444,17 @@ def from_jwk(jwk):
444444
if len(x) == len(y) == 32:
445445
curve_obj = ec.SECP256R1()
446446
else:
447-
raise InvalidKeyError(
448-
"Coords should be 32 bytes for curve P-256"
449-
)
447+
raise InvalidKeyError("Coords should be 32 bytes for curve P-256")
450448
elif curve == "P-384":
451449
if len(x) == len(y) == 48:
452450
curve_obj = ec.SECP384R1()
453451
else:
454-
raise InvalidKeyError(
455-
"Coords should be 48 bytes for curve P-384"
456-
)
452+
raise InvalidKeyError("Coords should be 48 bytes for curve P-384")
457453
elif curve == "P-521":
458454
if len(x) == len(y) == 66:
459455
curve_obj = ec.SECP521R1()
460456
else:
461-
raise InvalidKeyError(
462-
"Coords should be 66 bytes for curve P-521"
463-
)
457+
raise InvalidKeyError("Coords should be 66 bytes for curve P-521")
464458
else:
465459
raise InvalidKeyError(f"Invalid curve: {curve}")
466460

@@ -568,8 +562,6 @@ def verify(self, msg, key, sig):
568562
if isinstance(key, Ed25519PrivateKey):
569563
key = key.public_key()
570564
key.verify(sig, msg)
571-
return (
572-
True # If no exception was raised, the signature is valid.
573-
)
565+
return True # If no exception was raised, the signature is valid.
574566
except cryptography.exceptions.InvalidSignature:
575567
return False

jwt/api_jwk.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,12 @@ def __init__(self, jwk_data, algorithm=None):
1313
algorithm = self._jwk_data.get("alg", None)
1414

1515
if not algorithm:
16-
raise PyJWKError(
17-
"Unable to find a algorithm for key: %s" % self._jwk_data
18-
)
16+
raise PyJWKError("Unable to find a algorithm for key: %s" % self._jwk_data)
1917

2018
self.Algorithm = self._algorithms.get(algorithm)
2119

2220
if not self.Algorithm:
23-
raise PyJWKError(
24-
"Unable to find a algorithm for key: %s" % self._jwk_data
25-
)
21+
raise PyJWKError("Unable to find a algorithm for key: %s" % self._jwk_data)
2622

2723
self.key = self.Algorithm.from_jwk(self._jwk_data)
2824

jwt/api_jws.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ class PyJWS:
2424
def __init__(self, algorithms=None, options=None):
2525
self._algorithms = get_default_algorithms()
2626
self._valid_algs = (
27-
set(algorithms)
28-
if algorithms is not None
29-
else set(self._algorithms)
27+
set(algorithms) if algorithms is not None else set(self._algorithms)
3028
)
3129

3230
# Remove algorithms that aren't on the whitelist
@@ -148,9 +146,7 @@ def decode_complete(
148146
payload, signing_input, header, signature = self._load(jwt)
149147

150148
if verify_signature:
151-
self._verify_signature(
152-
signing_input, header, signature, key, algorithms
153-
)
149+
self._verify_signature(signing_input, header, signature, key, algorithms)
154150

155151
return {
156152
"payload": payload,
@@ -230,9 +226,7 @@ def _verify_signature(
230226
alg = header.get("alg")
231227

232228
if algorithms is not None and alg not in algorithms:
233-
raise InvalidAlgorithmError(
234-
"The specified alg value is not allowed"
235-
)
229+
raise InvalidAlgorithmError("The specified alg value is not allowed")
236230

237231
try:
238232
alg_obj = self._algorithms[alg]

jwt/api_jwt.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,13 @@ def encode(
5454
for time_claim in ["exp", "iat", "nbf"]:
5555
# Convert datetime to a intDate value in known time-format claims
5656
if isinstance(payload.get(time_claim), datetime):
57-
payload[time_claim] = timegm(
58-
payload[time_claim].utctimetuple()
59-
)
57+
payload[time_claim] = timegm(payload[time_claim].utctimetuple())
6058

6159
json_payload = json.dumps(
6260
payload, separators=(",", ":"), cls=json_encoder
6361
).encode("utf-8")
6462

65-
return api_jws.encode(
66-
json_payload, key, algorithm, headers, json_encoder
67-
)
63+
return api_jws.encode(json_payload, key, algorithm, headers, json_encoder)
6864

6965
def decode_complete(
7066
self,
@@ -154,9 +150,7 @@ def _validate_iat(self, payload, now, leeway):
154150
try:
155151
int(payload["iat"])
156152
except ValueError:
157-
raise InvalidIssuedAtError(
158-
"Issued At claim (iat) must be an integer."
159-
)
153+
raise InvalidIssuedAtError("Issued At claim (iat) must be an integer.")
160154

161155
def _validate_nbf(self, payload, now, leeway):
162156
try:
@@ -171,9 +165,7 @@ def _validate_exp(self, payload, now, leeway):
171165
try:
172166
exp = int(payload["exp"])
173167
except ValueError:
174-
raise DecodeError(
175-
"Expiration Time claim (exp) must be an" " integer."
176-
)
168+
raise DecodeError("Expiration Time claim (exp) must be an" " integer.")
177169

178170
if exp < (now - leeway):
179171
raise ExpiredSignatureError("Signature has expired")

jwt/jwks_client.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@ def get_signing_keys(self):
2727
signing_keys.append(jwk_set_key)
2828

2929
if len(signing_keys) == 0:
30-
raise PyJWKClientError(
31-
"The JWKS endpoint did not contain any signing keys"
32-
)
30+
raise PyJWKClientError("The JWKS endpoint did not contain any signing keys")
3331

3432
return signing_keys
3533

pyproject.toml

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,7 @@ source = ["jwt", ".tox/*/site-packages"]
1515
show_missing = true
1616

1717

18-
[tool.black]
19-
line-length = 79
20-
21-
2218
[tool.isort]
2319
profile = "black"
2420
atomic = true
2521
combine_as_imports = true
26-
line_length = 79

setup.cfg

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ exclude =
6464
tests.*
6565

6666
[flake8]
67-
max-line-length = 79
6867
extend-ignore = E203, E501
6968

7069
[mypy]

tests/test_algorithms.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -238,9 +238,7 @@ def test_ec_jwk_fails_on_invalid_json(self):
238238

239239
# EC coordinates not equally long
240240
with pytest.raises(InvalidKeyError):
241-
algo.from_jwk(
242-
'{"kty": "EC", "x": "dGVzdHRlc3Q=", "y": "dGVzdA=="}'
243-
)
241+
algo.from_jwk('{"kty": "EC", "x": "dGVzdHRlc3Q=", "y": "dGVzdA=="}')
244242

245243
# EC coordinates length invalid
246244
for curve in ("P-256", "P-384", "P-521"):
@@ -575,9 +573,7 @@ def test_hmac_verify_should_return_true_for_test_vector(self):
575573
b"gd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
576574
)
577575

578-
signature = base64url_decode(
579-
b"s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0"
580-
)
576+
signature = base64url_decode(b"s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0")
581577

582578
algo = HMACAlgorithm(HMACAlgorithm.SHA256)
583579
key = algo.prepare_key(load_hmac_key())

tests/test_api_jws.py

Lines changed: 17 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,7 @@ def test_decode_works_with_unicode_token(self, jws):
114114

115115
def test_decode_missing_segments_throws_exception(self, jws):
116116
secret = "secret"
117-
example_jws = (
118-
"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
119-
".eyJoZWxsbyI6ICJ3b3JsZCJ9"
120-
""
121-
) # Missing segment
117+
example_jws = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9" # Missing segment
122118

123119
with pytest.raises(DecodeError) as context:
124120
jws.decode(example_jws, secret, algorithms=["HS256"])
@@ -160,9 +156,7 @@ def test_decode_with_non_mapping_header_throws_exception(self, jws):
160156
exception = context.value
161157
assert str(exception) == "Invalid header string: must be a json object"
162158

163-
def test_encode_algorithm_param_should_be_case_sensitive(
164-
self, jws, payload
165-
):
159+
def test_encode_algorithm_param_should_be_case_sensitive(self, jws, payload):
166160

167161
jws.encode(payload, "secret", algorithm="HS256")
168162

@@ -207,9 +201,7 @@ def test_decodes_valid_jws(self, jws, payload):
207201
b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
208202
)
209203

210-
decoded_payload = jws.decode(
211-
example_jws, example_secret, algorithms=["HS256"]
212-
)
204+
decoded_payload = jws.decode(example_jws, example_secret, algorithms=["HS256"])
213205

214206
assert decoded_payload == payload
215207

@@ -221,9 +213,7 @@ def test_decodes_complete_valid_jws(self, jws, payload):
221213
b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
222214
)
223215

224-
decoded = jws.decode_complete(
225-
example_jws, example_secret, algorithms=["HS256"]
226-
)
216+
decoded = jws.decode_complete(example_jws, example_secret, algorithms=["HS256"])
227217

228218
assert decoded == {
229219
"header": {"alg": "HS256", "typ": "JWT"},
@@ -248,9 +238,7 @@ def test_decodes_valid_es384_jws(self, jws):
248238
b"eyJoZWxsbyI6IndvcmxkIn0.TORyNQab_MoXM7DvNKaTwbrJr4UY"
249239
b"d2SsX8hhlnWelQFmPFSf_JzC2EbLnar92t-bXsDovzxp25ExazrVHkfPkQ"
250240
)
251-
decoded_payload = jws.decode(
252-
example_jws, example_pubkey, algorithms=["ES256"]
253-
)
241+
decoded_payload = jws.decode(example_jws, example_pubkey, algorithms=["ES256"])
254242
json_payload = json.loads(decoded_payload)
255243

256244
assert json_payload == example_payload
@@ -276,9 +264,7 @@ def test_decodes_valid_rs384_jws(self, jws):
276264
b"uwmrtSWCBUjiN8sqJ00CDgycxKqHfUndZbEAOjcCAhBr"
277265
b"qWW3mSVivUfubsYbwUdUG3fSRPjaUPcpe8A"
278266
)
279-
decoded_payload = jws.decode(
280-
example_jws, example_pubkey, algorithms=["RS384"]
281-
)
267+
decoded_payload = jws.decode(example_jws, example_pubkey, algorithms=["RS384"])
282268
json_payload = json.loads(decoded_payload)
283269

284270
assert json_payload == example_payload
@@ -299,9 +285,7 @@ def test_load_verify_valid_jws(self, jws, payload):
299285
def test_allow_skip_verification(self, jws, payload):
300286
right_secret = "foo"
301287
jws_message = jws.encode(payload, right_secret)
302-
decoded_payload = jws.decode(
303-
jws_message, options={"verify_signature": False}
304-
)
288+
decoded_payload = jws.decode(jws_message, options={"verify_signature": False})
305289

306290
assert decoded_payload == payload
307291

@@ -364,14 +348,8 @@ def test_verify_signature_with_no_secret(self, jws, payload):
364348

365349
assert "Signature verification" in str(exc.value)
366350

367-
def test_verify_signature_with_no_algo_header_throws_exception(
368-
self, jws, payload
369-
):
370-
example_jws = (
371-
b"e30"
372-
b".eyJhIjo1fQ"
373-
b".KEh186CjVw_Q8FadjJcaVnE7hO5Z9nHBbU8TgbhHcBY"
374-
)
351+
def test_verify_signature_with_no_algo_header_throws_exception(self, jws, payload):
352+
example_jws = b"e30.eyJhIjo1fQ.KEh186CjVw_Q8FadjJcaVnE7hO5Z9nHBbU8TgbhHcBY"
375353

376354
with pytest.raises(InvalidAlgorithmError):
377355
jws.decode(example_jws, "secret", algorithms=["HS256"])
@@ -467,9 +445,7 @@ def test_decode_with_algo_none_should_fail(self, jws, payload):
467445
with pytest.raises(DecodeError):
468446
jws.decode(jws_message, algorithms=["none"])
469447

470-
def test_decode_with_algo_none_and_verify_false_should_pass(
471-
self, jws, payload
472-
):
448+
def test_decode_with_algo_none_and_verify_false_should_pass(self, jws, payload):
473449
jws_message = jws.encode(payload, key=None, algorithm=None)
474450
jws.decode(jws_message, options={"verify_signature": False})
475451

@@ -486,9 +462,7 @@ def test_get_unverified_header_returns_header_values(self, jws, payload):
486462
assert "kid" in header
487463
assert header["kid"] == "toomanysecrets"
488464

489-
def test_get_unverified_header_fails_on_bad_header_types(
490-
self, jws, payload
491-
):
465+
def test_get_unverified_header_fails_on_bad_header_types(self, jws, payload):
492466
# Contains a bad kid value (int 123 instead of string)
493467
example_jws = (
494468
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6MTIzfQ"
@@ -505,9 +479,7 @@ def test_get_unverified_header_fails_on_bad_header_types(
505479
def test_encode_decode_with_rsa_sha256(self, jws, payload):
506480
# PEM-formatted RSA key
507481
with open(key_path("testkey_rsa.priv"), "rb") as rsa_priv_file:
508-
priv_rsakey = load_pem_private_key(
509-
rsa_priv_file.read(), password=None
510-
)
482+
priv_rsakey = load_pem_private_key(rsa_priv_file.read(), password=None)
511483
jws_message = jws.encode(payload, priv_rsakey, algorithm="RS256")
512484

513485
with open(key_path("testkey_rsa.pub"), "rb") as rsa_pub_file:
@@ -528,9 +500,7 @@ def test_encode_decode_with_rsa_sha256(self, jws, payload):
528500
def test_encode_decode_with_rsa_sha384(self, jws, payload):
529501
# PEM-formatted RSA key
530502
with open(key_path("testkey_rsa.priv"), "rb") as rsa_priv_file:
531-
priv_rsakey = load_pem_private_key(
532-
rsa_priv_file.read(), password=None
533-
)
503+
priv_rsakey = load_pem_private_key(rsa_priv_file.read(), password=None)
534504
jws_message = jws.encode(payload, priv_rsakey, algorithm="RS384")
535505

536506
with open(key_path("testkey_rsa.pub"), "rb") as rsa_pub_file:
@@ -550,9 +520,7 @@ def test_encode_decode_with_rsa_sha384(self, jws, payload):
550520
def test_encode_decode_with_rsa_sha512(self, jws, payload):
551521
# PEM-formatted RSA key
552522
with open(key_path("testkey_rsa.priv"), "rb") as rsa_priv_file:
553-
priv_rsakey = load_pem_private_key(
554-
rsa_priv_file.read(), password=None
555-
)
523+
priv_rsakey = load_pem_private_key(rsa_priv_file.read(), password=None)
556524
jws_message = jws.encode(payload, priv_rsakey, algorithm="RS512")
557525

558526
with open(key_path("testkey_rsa.pub"), "rb") as rsa_pub_file:
@@ -592,9 +560,7 @@ def test_rsa_related_algorithms(self, jws):
592560
def test_encode_decode_with_ecdsa_sha256(self, jws, payload):
593561
# PEM-formatted EC key
594562
with open(key_path("testkey_ec.priv"), "rb") as ec_priv_file:
595-
priv_eckey = load_pem_private_key(
596-
ec_priv_file.read(), password=None
597-
)
563+
priv_eckey = load_pem_private_key(ec_priv_file.read(), password=None)
598564
jws_message = jws.encode(payload, priv_eckey, algorithm="ES256")
599565

600566
with open(key_path("testkey_ec.pub"), "rb") as ec_pub_file:
@@ -615,9 +581,7 @@ def test_encode_decode_with_ecdsa_sha384(self, jws, payload):
615581

616582
# PEM-formatted EC key
617583
with open(key_path("testkey_ec.priv"), "rb") as ec_priv_file:
618-
priv_eckey = load_pem_private_key(
619-
ec_priv_file.read(), password=None
620-
)
584+
priv_eckey = load_pem_private_key(ec_priv_file.read(), password=None)
621585
jws_message = jws.encode(payload, priv_eckey, algorithm="ES384")
622586

623587
with open(key_path("testkey_ec.pub"), "rb") as ec_pub_file:
@@ -637,9 +601,7 @@ def test_encode_decode_with_ecdsa_sha384(self, jws, payload):
637601
def test_encode_decode_with_ecdsa_sha512(self, jws, payload):
638602
# PEM-formatted EC key
639603
with open(key_path("testkey_ec.priv"), "rb") as ec_priv_file:
640-
priv_eckey = load_pem_private_key(
641-
ec_priv_file.read(), password=None
642-
)
604+
priv_eckey = load_pem_private_key(ec_priv_file.read(), password=None)
643605
jws_message = jws.encode(payload, priv_eckey, algorithm="ES512")
644606

645607
with open(key_path("testkey_ec.pub"), "rb") as ec_pub_file:

0 commit comments

Comments
 (0)