Skip to content
This repository has been archived by the owner on Feb 20, 2024. It is now read-only.

Commit

Permalink
Py3 and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Ian Sparks committed Jun 15, 2016
1 parent 72f3c94 commit ac5beb0
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 25 deletions.
2 changes: 1 addition & 1 deletion requests_mauth/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
__author__ = 'isparks'

from client import MAuth
from .client import MAuth
__version__ = '1.0.0'

12 changes: 9 additions & 3 deletions requests_mauth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@

import requests
import time
from rsa_sign import RSARawSigner
from urlparse import urlparse
from .rsa_sign import RSARawSigner

# Python 2/3 differences
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse


class MAuth(requests.auth.AuthBase):
"""Custom requests authorizer for MAuth"""
Expand Down Expand Up @@ -61,7 +67,7 @@ def make_signature_string(self, verb, url_path, body, seconds_since_epoch=None)
app_uid=self.app_uuid,
seconds_since_epoch=seconds_since_epoch)

string_to_sign = '{verb}\n{url_path}\n{body}\n{app_uid}\n{seconds_since_epoch!s}'.format(**vals)
string_to_sign = u'{verb}\n{url_path}\n{body}\n{app_uid}\n{seconds_since_epoch!s}'.format(**vals)
return string_to_sign, seconds_since_epoch


37 changes: 24 additions & 13 deletions requests_mauth/rsa_sign.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,43 @@

from hashlib import sha512
from rsa import common, core, transform, PrivateKey
import base64

#---- Original code from RSA ------------------------------------------------------------------------------------------

def byte_literal(s):
return s

b = byte_literal

#----------------------------------------------------------------------------------------------------------------------
def make_bytes(val):
"""Ensure in python 2/3 we are working with bytes when we need to"""
try:
if isinstance(val, unicode):
return val.encode('US-ASCII')
except NameError:
if isinstance(val, bytes):
return val
elif isinstance(val, str):
return val.encode('US-ASCII')
return val


class RSARawSigner(object):
def __init__(self, private_key_data):
self.private_key_data = private_key_data
self.pk = PrivateKey.load_pkcs1(private_key_data, 'PEM')

def sign(self, string_to_sign):
"""Sign the data in a emulation of the OpenSSL private_encrypt method"""
hashed = sha512(string_to_sign.encode('US-ASCII')).hexdigest()
# Working in 2.7

string_to_sign = make_bytes(string_to_sign)
hashed = sha512(string_to_sign).hexdigest().encode('US-ASCII')
keylength = common.byte_size(self.pk.n)
padded = self.pad_for_signing(hashed, keylength)

padded = make_bytes(padded)
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, self.pk.d, self.pk.n)
signature = transform.int2bytes(encrypted, keylength).encode('base64').replace('\n','')
signature = transform.int2bytes(encrypted, keylength)
signature = base64.b64encode(signature).decode('US-ASCII').replace('\n','')
return signature


def pad_for_signing(self, message, target_length):
r'''Pulled from rsa pkcs1.py,
Expand Down Expand Up @@ -64,7 +75,7 @@ def pad_for_signing(self, message, target_length):

padding_length = target_length - msglength - 3

return b('').join([b('\x00\x01'),
padding_length * b('\xff'),
b('\x00'),
return b''.join([b'\x00\x01',
padding_length * b'\xff',
b'\x00',
message])
7 changes: 7 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# -*- coding: utf-8 -*-
__author__ = 'isparks'

import unittest
from . import client_test

def requests_mauth_suite():
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(client_test)
return suite
14 changes: 6 additions & 8 deletions tests/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from requests_mauth.client import MAuth
import time
from requests import Request
import os


class RequestMock(object):
Expand All @@ -20,7 +21,9 @@ def setUp(self):
self.app_id = "5ff4257e-9c16-11e0-b048-0026bbfffe5e"

# Note, private key used here is just a dummy. Not registered to anythiung, cannot sign live requests.
example_private_key = open("test_mauth.priv.key",'r').read()
dir = os.path.dirname(__file__)
with open(os.path.join(dir, "test_mauth.priv.key"),'r') as f:
example_private_key = f.read()
self.client = MAuth(self.app_id, example_private_key)


Expand Down Expand Up @@ -59,11 +62,10 @@ def test_string_to_sign_no_epoch(self):
class TestSign(MAuthBaseTest):
def test_sign(self):
"""
Test that signing a string doesn't throw an error. Not checking validity of sign
Test that signing a string doesn't throw an error and signature correct
"""
tested = self.client.signer.sign("Hello world")
self.assertNotEqual(tested, '') # Just making sure we get a result from above

self.assertEqual(tested, 'F/GAuGYEykrtrmIE/XtETSi0QUoKxUwwTXljT1tUiqNHmyH2NRhKQ1flqusaB7H6bwPBb+FzXzfmiO32lJs6SxMjltqM/FjwucVNhn1BW+KXFnZniPh3M0+FwwspksX9xc/KcWEPebtIIEM5cX2rBl43xlvwYtS/+D+obo1AVPv2l5qd+Gwl9b61kYF/aoPGx+bVnmWZK8e8BZxZOjjGjmQAOYRYgGWzolLLnzIZ6xy6efY3D9jPXXDqgnqWQvwLStkKJIydrkXUTd0m36X6mD00qHgI7xoYSLgqxNSg1EgO8yuette8BKl9D+YbIEJ3xFnaZmCfVGks0M9tmZ2PXg==')

class TestMakeAuthHeaders(MAuthBaseTest):
def test_headers(self):
Expand All @@ -86,7 +88,3 @@ def test_get(self):
authentication_header = r.headers['X-MWS-Authentication']
header_app_id = authentication_header.split(':')[0]
self.assertEqual('MWS ' + self.app_id, header_app_id)


if __name__ == '__main__':
unittest.main()
3 changes: 3 additions & 0 deletions tests/test_mauth.priv.key
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ bpPVxhECgYAFRJ3qF9kj3TIqupZRknwvEVYMMOK4L8v8zaYjM9WQobcPkROmu7nn
BzqqXY1SzEH4xRed4OqtTPtglA4jRC4Kr0V0H7terM9u3+p1OIWl7/5X79DYfqyW
ugSNZFZUII03sibgNFxMnj+5s6Bj3PvKjmUnd+Hrt4upKaHH0aRBtA==
-----END RSA PRIVATE KEY-----



0 comments on commit ac5beb0

Please sign in to comment.