From ec88fb8a0f2db0a789349e04caf23e2283daaf13 Mon Sep 17 00:00:00 2001 From: rachmadani haryono Date: Wed, 17 Jul 2019 16:09:09 +0800 Subject: [PATCH] [fix] secret_key can be bytes instead of a string (#1602) Fix #1600 In settings.yml, the secret_key can be written as string or as base64 encoded data using !!binary notation. --- searx/utils.py | 9 ++++++++- tests/unit/test_utils.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/searx/utils.py b/searx/utils.py index dfa22c5f..6619dd0a 100644 --- a/searx/utils.py +++ b/searx/utils.py @@ -384,10 +384,17 @@ def load_module(filename, module_dir): def new_hmac(secret_key, url): + try: + secret_key_bytes = bytes(secret_key, 'utf-8') + except TypeError as err: + if isinstance(secret_key, bytes): + secret_key_bytes = secret_key + else: + raise err if sys.version_info[0] == 2: return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest() else: - return hmac.new(bytes(secret_key, 'utf-8'), url, hashlib.sha256).hexdigest() + return hmac.new(secret_key_bytes, url, hashlib.sha256).hexdigest() def to_string(obj): diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 4854636c..fbaed2bd 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -128,3 +128,17 @@ class TestUnicodeWriter(SearxTestCase): rows = [1, 2, 3] self.unicode_writer.writerows(rows) self.assertEqual(self.unicode_writer.writerow.call_count, len(rows)) + + +class TestNewHmac(SearxTestCase): + + def test_bytes(self): + for secret_key in ['secret', b'secret', 1]: + if secret_key == 1: + with self.assertRaises(TypeError): + utils.new_hmac(secret_key, b'http://example.com') + continue + res = utils.new_hmac(secret_key, b'http://example.com') + self.assertEqual( + res, + '23e2baa2404012a5cc8e4a18b4aabf0dde4cb9b56f679ddc0fd6d7c24339d819')