on master help sign in
[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.

commitec88fb8a0f2db0a789349e04caf23e2283daaf13 authorrachmadani haryono <rachmadaniHaryono@users.noreply.github.com> dateWed 17 Jul 2019, 16:09 (7 years ago) parent8f44014
2 files changed+22−1
searx/utils.py+8−1 tests/unit/test_utils.py+14
searx/utils.py+8−1
@@ -384,10 +384,17 @@ def load_module(filename, module_dir):
384384
385385
386386def new_hmac(secret_key, url):
387+ try:
388+ secret_key_bytes = bytes(secret_key, 'utf-8')
389+ except TypeError as err:
390+ if isinstance(secret_key, bytes):
391+ secret_key_bytes = secret_key
392+ else:
393+ raise err
387394 if sys.version_info[0] == 2:
388395 return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest()
389396 else:
390− return hmac.new(bytes(secret_key, 'utf-8'), url, hashlib.sha256).hexdigest()
397+ return hmac.new(secret_key_bytes, url, hashlib.sha256).hexdigest()
391398
392399
393400def to_string(obj):
tests/unit/test_utils.py+14
@@ -128,3 +128,17 @@ class TestUnicodeWriter(SearxTestCase):
128128 rows = [1, 2, 3]
129129 self.unicode_writer.writerows(rows)
130130 self.assertEqual(self.unicode_writer.writerow.call_count, len(rows))
131+
132+
133+class TestNewHmac(SearxTestCase):
134+
135+ def test_bytes(self):
136+ for secret_key in ['secret', b'secret', 1]:
137+ if secret_key == 1:
138+ with self.assertRaises(TypeError):
139+ utils.new_hmac(secret_key, b'http://example.com')
140+ continue
141+ res = utils.new_hmac(secret_key, b'http://example.com')
142+ self.assertEqual(
143+ res,
144+ '23e2baa2404012a5cc8e4a18b4aabf0dde4cb9b56f679ddc0fd6d7c24339d819')