Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,24 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSE
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

httpsig
- https://github.com/ahknight/httpsig

Copyright (c) 2014 Adam Knight
Copyright (c) 2012 Adam T. Lindsay (original author)

Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,11 @@ redirect_url = client.create_redirect_url('http://google.com/', 'user_id', event
First, make sure you can run the test suite. Tests are run via py.test

```bash
py.test stream/tests.py
py.test
# with coverage
py.test stream/tests.py --cov stream --cov-report html
py.test --cov stream --cov-report html
# against a local API backend
LOCAL=true py.test stream/tests.py
LOCAL=true py.test
```

### Copyright and License Information
Expand Down
5 changes: 3 additions & 2 deletions dev_requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pep8
pytest==3.3.1
python-coveralls
unittest2
pytest-cov==2.5.1
python-dateutil
pytest-cov
-e .
11 changes: 5 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@

unit = 'unittest2py3k' if sys.version_info > (3, 0, 0) else 'unittest2'
tests_require = [
'pep8',
unit,
#'pytest',
'pytest==3.3.1',
'python-coveralls',
'unittest2',
'pytest-cov==1.8.1',
'pytest-cov==2.5.1',
'python-dateutil'
]

Expand All @@ -32,10 +31,10 @@
requests = 'requests[security]>=2.4.1,<3'

install_requires = [
'pycryptodomex==3.4.7',
'pyjwt==1.3.0',
requests,
'six>=1.8.0',
'httpsig==1.1.2'
'six>=1.8.0'
]

class PyTest(TestCommand):
Expand All @@ -49,7 +48,7 @@ def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(
'stream/tests.py --cov stream --cov-report term-missing -v')
'--cov stream --cov-report term-missing -v')
sys.exit(errno)

setup(
Expand Down
2 changes: 2 additions & 0 deletions stream/httpsig/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .sign import Signer, HeaderSigner
from .verify import Verifier, HeaderVerifier
37 changes: 37 additions & 0 deletions stream/httpsig/requests_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from requests.auth import AuthBase
try:
# Python 3
from urllib.parse import urlparse
except ImportError:
# Python 2
from urlparse import urlparse

from .sign import HeaderSigner


class HTTPSignatureAuth(AuthBase):
'''
Sign a request using the http-signature scheme.
https://github.com/joyent/node-http-signature/blob/master/http_signing.md

key_id is the mandatory label indicating to the server which secret to use
secret is the filename of a pem file in the case of rsa, a password string in the case of an hmac algorithm
algorithm is one of the six specified algorithms
headers is a list of http headers to be included in the signing string, defaulting to "Date" alone.
'''
def __init__(self, key_id='', secret='', algorithm=None, headers=None):
headers = headers or []
self.header_signer = HeaderSigner(key_id=key_id, secret=secret,
algorithm=algorithm, headers=headers)
self.uses_host = 'host' in [h.lower() for h in headers]

def __call__(self, r):
headers = self.header_signer.sign(
r.headers,
# 'Host' header unavailable in request object at this point
# if 'host' header is needed, extract it from the url
host=urlparse(r.url).netloc if self.uses_host else None,
method=r.method,
path=r.path_url)
r.headers.update(headers)
return r
106 changes: 106 additions & 0 deletions stream/httpsig/sign.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import base64
import six

from Cryptodome.Hash import HMAC
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5

from .utils import *


DEFAULT_SIGN_ALGORITHM = "hmac-sha256"


class Signer(object):
"""
When using an RSA algo, the secret is a PEM-encoded private key.
When using an HMAC algo, the secret is the HMAC signing secret.

Password-protected keyfiles are not supported.
"""
def __init__(self, secret, algorithm=None):
if algorithm is None:
algorithm = DEFAULT_SIGN_ALGORITHM

assert algorithm in ALGORITHMS, "Unknown algorithm"
if isinstance(secret, six.string_types): secret = secret.encode("ascii")

self._rsa = None
self._hash = None
self.sign_algorithm, self.hash_algorithm = algorithm.split('-')

if self.sign_algorithm == 'rsa':
try:
rsa_key = RSA.importKey(secret)
self._rsa = PKCS1_v1_5.new(rsa_key)
self._hash = HASHES[self.hash_algorithm]
except ValueError:
raise HttpSigException("Invalid key.")

elif self.sign_algorithm == 'hmac':
self._hash = HMAC.new(secret, digestmod=HASHES[self.hash_algorithm])

@property
def algorithm(self):
return '%s-%s' % (self.sign_algorithm, self.hash_algorithm)

def _sign_rsa(self, data):
if isinstance(data, six.string_types): data = data.encode("ascii")
h = self._hash.new()
h.update(data)
return self._rsa.sign(h)

def _sign_hmac(self, data):
if isinstance(data, six.string_types): data = data.encode("ascii")
hmac = self._hash.copy()
hmac.update(data)
return hmac.digest()

def _sign(self, data):
if isinstance(data, six.string_types): data = data.encode("ascii")
signed = None
if self._rsa:
signed = self._sign_rsa(data)
elif self._hash:
signed = self._sign_hmac(data)
if not signed:
raise SystemError('No valid encryptor found.')
return base64.b64encode(signed).decode("ascii")


class HeaderSigner(Signer):
'''
Generic object that will sign headers as a dictionary using the http-signature scheme.
https://github.com/joyent/node-http-signature/blob/master/http_signing.md

:arg key_id: the mandatory label indicating to the server which secret to use
:arg secret: a PEM-encoded RSA private key or an HMAC secret (must match the algorithm)
:arg algorithm: one of the six specified algorithms
:arg headers: a list of http headers to be included in the signing string, defaulting to ['date'].
'''
def __init__(self, key_id, secret, algorithm=None, headers=None):
if algorithm is None:
algorithm = DEFAULT_SIGN_ALGORITHM

super(HeaderSigner, self).__init__(secret=secret, algorithm=algorithm)
self.headers = headers or ['date']
self.signature_template = build_signature_template(key_id, algorithm, headers)

def sign(self, headers, host=None, method=None, path=None):
"""
Add Signature Authorization header to case-insensitive header dict.

headers is a case-insensitive dict of mutable headers.
host is a override for the 'host' header (defaults to value in headers).
method is the HTTP method (required when using '(request-target)').
path is the HTTP path (required when using '(request-target)').
"""
headers = CaseInsensitiveDict(headers)
required_headers = self.headers or ['date']
signable = generate_message(required_headers, headers, host, method, path)

signature = self._sign(signable)
headers['authorization'] = self.signature_template % signature

return headers

3 changes: 3 additions & 0 deletions stream/httpsig/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .test_signature import *
from .test_utils import *
from .test_verify import *
15 changes: 15 additions & 0 deletions stream/httpsig/tests/rsa_private.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF
NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F
UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB
AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA
QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK
kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg
f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u
412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc
mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7
kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA
gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW
G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI
7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA==
-----END RSA PRIVATE KEY-----
6 changes: 6 additions & 0 deletions stream/httpsig/tests/rsa_public.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3
6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6
Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw
oYi+1hqp1fIekaxsyQIDAQAB
-----END PUBLIC KEY-----
72 changes: 72 additions & 0 deletions stream/httpsig/tests/test_signature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#!/usr/bin/env python
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

import json
import unittest

import stream.httpsig.sign as sign
from stream.httpsig.utils import parse_authorization_header


class TestSign(unittest.TestCase):
DEFAULT_SIGN_ALGORITHM = sign.DEFAULT_SIGN_ALGORITHM

def setUp(self):
sign.DEFAULT_SIGN_ALGORITHM = "rsa-sha256"
self.key_path = os.path.join(os.path.dirname(__file__), 'rsa_private.pem')
with open(self.key_path, 'rb') as f:
self.key = f.read()

def tearDown(self):
sign.DEFAULT_SIGN_ALGORITHM = self.DEFAULT_SIGN_ALGORITHM

def test_default(self):
hs = sign.HeaderSigner(key_id='Test', secret=self.key)
unsigned = {
'Date': 'Thu, 05 Jan 2012 21:31:40 GMT'
}
signed = hs.sign(unsigned)
self.assertIn('Date', signed)
self.assertEqual(unsigned['Date'], signed['Date'])
self.assertIn('Authorization', signed)
auth = parse_authorization_header(signed['authorization'])
params = auth[1]
self.assertIn('keyId', params)
self.assertIn('algorithm', params)
self.assertIn('signature', params)
self.assertEqual(params['keyId'], 'Test')
self.assertEqual(params['algorithm'], 'rsa-sha256')
self.assertEqual(params['signature'], 'ATp0r26dbMIxOopqw0OfABDT7CKMIoENumuruOtarj8n/97Q3htHFYpH8yOSQk3Z5zh8UxUym6FYTb5+A0Nz3NRsXJibnYi7brE/4tx5But9kkFGzG+xpUmimN4c3TMN7OFH//+r8hBf7BT9/GmHDUVZT2JzWGLZES2xDOUuMtA=')

def test_all(self):
hs = sign.HeaderSigner(key_id='Test', secret=self.key, headers=[
'(request-target)',
'host',
'date',
'content-type',
'content-md5',
'content-length'
])
unsigned = {
'Host': 'example.com',
'Date': 'Thu, 05 Jan 2012 21:31:40 GMT',
'Content-Type': 'application/json',
'Content-MD5': 'Sd/dVLAcvNLSq16eXua5uQ==',
'Content-Length': '18',
}
signed = hs.sign(unsigned, method='POST', path='/foo?param=value&pet=dog')

self.assertIn('Date', signed)
self.assertEqual(unsigned['Date'], signed['Date'])
self.assertIn('Authorization', signed)
auth = parse_authorization_header(signed['authorization'])
params = auth[1]
self.assertIn('keyId', params)
self.assertIn('algorithm', params)
self.assertIn('signature', params)
self.assertEqual(params['keyId'], 'Test')
self.assertEqual(params['algorithm'], 'rsa-sha256')
self.assertEqual(params['headers'], '(request-target) host date content-type content-md5 content-length')
self.assertEqual(params['signature'], 'G8/Uh6BBDaqldRi3VfFfklHSFoq8CMt5NUZiepq0q66e+fS3Up3BmXn0NbUnr3L1WgAAZGplifRAJqp2LgeZ5gXNk6UX9zV3hw5BERLWscWXlwX/dvHQES27lGRCvyFv3djHP6Plfd5mhPWRkmjnvqeOOSS0lZJYFYHJz994s6w=')
17 changes: 17 additions & 0 deletions stream/httpsig/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env python
import os
import re
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

import unittest

from stream.httpsig.utils import get_fingerprint

class TestUtils(unittest.TestCase):

def test_get_fingerprint(self):
with open(os.path.join(os.path.dirname(__file__), 'rsa_public.pem'), 'r') as k:
key = k.read()
fingerprint = get_fingerprint(key)
self.assertEqual(fingerprint, "73:61:a2:21:67:e0:df:be:7e:4b:93:1e:15:98:a5:b7")
Loading