[PATCH signedrequest] [py3] Encode strings for hmac.new()

Denis Laxalde denis.laxalde at logilab.fr
Fri Jun 1 16:57:48 CEST 2018

# HG changeset patch
# User Denis Laxalde <denis.laxalde at logilab.fr>
# Date 1527864647 -7200
#      Fri Jun 01 16:50:47 2018 +0200
# Node ID 0d69b46316bbd7a679899b46433ecb34c7bc51df
# Parent  6274245a6c7e8bcca999be5fd7690af5a88d6ea2
# Available At http://hg.logilab.org/review/cubes/signedrequest
#              hg pull http://hg.logilab.org/review/cubes/signedrequest -r 0d69b46316bb
# EXP-Topic py3
[py3] Encode strings for hmac.new()

This is symmetrical to changeset 84943f333ac0 about tests.

On the one hand, we encode the result of tools.build_string_to_sign()
which will be passed down to tools.authenticate_user() (where hmac.new
call happens); we document that expected value in authenticate_user for
"signed_content" should be bytes. On the other hand, we encode the
"secret_key" value which is retrieved from database (as a unicode
string) before passing it to hmac.new as well.

According to its test suite, cubicweb-signedrequest is now

diff --git a/tools.py b/tools.py
--- a/tools.py
+++ b/tools.py
@@ -127,7 +127,7 @@ def build_string_to_sign(request, url=No
         url = request.url
     get_header = lambda field: request.get_header(field, '')  # noqa
     return (request.http_method() + url +
-            ''.join(map(get_header, headers)))
+            ''.join(map(get_header, headers))).encode('utf-8')
 def authenticate_user(session, tokenid, signed_content, signature):
@@ -142,7 +142,7 @@ def authenticate_user(session, tokenid, 
     :request: the http request
     :signature: the signature (usually extracted from the headers
-                using get_credentals_from_headers)
+                using get_credentals_from_headers), as *bytes*
     Warning: it does not check whether the user is enabled or not.
@@ -159,7 +159,7 @@ def authenticate_user(session, tokenid, 
         assert len(rset) == 1
         user_eid, secret_key = rset[0]
-        expected_signature = hmac.new(str(secret_key),
+        expected_signature = hmac.new(secret_key.encode('utf-8'),
         if compare_digest(expected_signature, signature):
             return user_eid

More information about the cubicweb-devel mailing list