Skip to content

Commit

Permalink
More flexibility for key= argument to jws.verify()
Browse files Browse the repository at this point in the history
  • Loading branch information
bjmc committed Jul 18, 2016
1 parent a001a7e commit 6ed322d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
21 changes: 15 additions & 6 deletions jose/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
import six

from collections import Mapping
from collections import Mapping, Iterable

from jose import jwk
from jose.constants import ALGORITHMS
Expand Down Expand Up @@ -213,6 +213,19 @@ def _sig_matches_keys(keys, signing_input, signature, alg):
return False


def _get_keys(key):
if 'keys' in key: # JWK Set per RFC 7517
if not isinstance(key, Mapping): # Caller didn't JSON-decode
key = json.loads(key)
return key['keys']
# Iterable but not text or mapping => list- or tuple-like
elif (isinstance(key, Iterable) and
not (isinstance(key, six.string_types) or isinstance(key, Mapping))):
return key
else: # Scalar value, wrap in list.
return [key]


def _verify_signature(signing_input, header, signature, key='', algorithms=None):

alg = header.get('alg')
Expand All @@ -222,11 +235,7 @@ def _verify_signature(signing_input, header, signature, key='', algorithms=None)
if algorithms is not None and alg not in algorithms:
raise JWSError('The specified alg value is not allowed')

if 'keys' in key: # JWK Set per RFC 7517
keys = key['keys']
else:
keys = [key]

keys = _get_keys(key)
try:
if not _sig_matches_keys(keys, signing_input, signature, alg):
raise JWSSignatureError()
Expand Down
30 changes: 30 additions & 0 deletions tests/test_jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,36 @@ def jwk_set():
'WNz7vOIbvIlBR9Jrq5MIqbkkg'
)


class TestGetKeys(object):

def test_dict(self):
assert [{}] == jws._get_keys({})

def test_custom_object(self):
class MyDict(dict):
pass
mydict = MyDict()
assert [mydict] == jws._get_keys(mydict)

def test_RFC7517_string(self):
key = '{"keys": [{}, {}]}'
assert [{}, {}] == jws._get_keys(key)

def test_RFC7517_mapping(self):
key = {"keys": [{}, {}]}
assert [{}, {}] == jws._get_keys(key)

def test_string(self):
assert ['test'] == jws._get_keys('test')

def test_tuple(self):
assert ('test', 'key') == jws._get_keys(('test', 'key'))

def test_list(self):
assert ['test', 'key'] == jws._get_keys(['test', 'key'])


class TestRSA(object):

def test_jwk_set(self, jwk_set):
Expand Down

0 comments on commit 6ed322d

Please sign in to comment.