From b5711d9293baf6ede0f785a52524734cafbf1277 Mon Sep 17 00:00:00 2001 From: Jared Crawford Date: Fri, 27 Oct 2023 16:54:55 -0400 Subject: [PATCH] ensure digest input is bytes --- lemur/auth/service.py | 5 ++++- lemur/tests/test_auth.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 lemur/tests/test_auth.py diff --git a/lemur/auth/service.py b/lemur/auth/service.py index ad0cef02a7..ac67a514a1 100644 --- a/lemur/auth/service.py +++ b/lemur/auth/service.py @@ -100,7 +100,10 @@ def decode_with_multiple_secrets(encoded_jwt, secrets, algorithms): continue if len(secrets) > 1: digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) - digest.update(secret) + if isinstance(secret, str): + digest.update(secret.encode()) + else: + digest.update(secret) metrics.send("jwt_decode", "counter", 1, metric_tags={**dict(kid=index, fingerprint=digest.finalize().hex()), **payload}) return payload if errors: diff --git a/lemur/tests/test_auth.py b/lemur/tests/test_auth.py new file mode 100644 index 0000000000..ef0cc40c92 --- /dev/null +++ b/lemur/tests/test_auth.py @@ -0,0 +1,30 @@ +from unittest.mock import patch + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.backends import default_backend +import jwt +from lemur.auth.service import decode_with_multiple_secrets + + +@patch("lemur.auth.service.metrics") +def test_decode_with_multiple_secrets(mock_metrics): + # Given + secret = "my_secret" + encoded_jwt = jwt.encode({"foo": "bar"}, secret, algorithm='HS256') + secrets = [secret, secret + "2"] + algorithms = ['HS256'] + + # When + payload = decode_with_multiple_secrets(encoded_jwt, secrets, algorithms) + + # Then + assert payload == {"foo": "bar"} + digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) + digest.update(secret.encode()) + mock_metrics.send.assert_called_once_with( + "jwt_decode", "counter", 1, + metric_tags={ + **dict(kid=0, fingerprint=digest.finalize().hex()), + **{"foo": "bar"} + } + )