def test_function_key(self): protected = {'alg': 'HS256'} header = [ { 'protected': protected, 'header': { 'kid': 'a' } }, { 'protected': protected, 'header': { 'kid': 'b' } }, ] def load_key(header, payload): self.assertEqual(payload, b'hello') kid = header.get('kid') if kid == 'a': return 'secret-a' return 'secret-b' jws = JWS(algorithms=JWS_ALGORITHMS) s = jws.serialize(header, b'hello', load_key) self.assertIsInstance(s, dict) self.assertIn('signatures', s) data = jws.deserialize(json.dumps(s), load_key) header, payload = data['header'], data['payload'] self.assertEqual(payload, b'hello') self.assertEqual(header[0]['alg'], 'HS256') self.assertNotIn('signature', data)
def test_compact_jws(self): jws = JWS(algorithms=JWS_ALGORITHMS) s = jws.serialize({'alg': 'HS256'}, 'hello', 'secret') data = jws.deserialize(s, 'secret') header, payload = data['header'], data['payload'] self.assertEqual(payload, b'hello') self.assertEqual(header['alg'], 'HS256') self.assertNotIn('signature', data)
def test_compact_rsa(self): jws = JWS(algorithms=JWS_ALGORITHMS) s = jws.serialize({'alg': 'RS256'}, 'hello', read_file_path('rsa_private.pem')) data = jws.deserialize(s, read_file_path('rsa_public.pem')) header, payload = data['header'], data['payload'] self.assertEqual(payload, b'hello') self.assertEqual(header['alg'], 'RS256')
def test_validate_header(self): jws = JWS(algorithms=JWS_ALGORITHMS) protected = {'alg': 'HS256', 'invalid': 'k'} header = {'protected': protected, 'header': {'kid': 'a'}} self.assertRaises(errors.InvalidHeaderParameterName, jws.serialize, header, b'hello', 'secret') jws = JWS(algorithms=JWS_ALGORITHMS, private_headers=['invalid']) s = jws.serialize(header, b'hello', 'secret') self.assertIsInstance(s, dict)
def test_flattened_json_jws(self): jws = JWS(algorithms=JWS_ALGORITHMS) protected = {'alg': 'HS256'} header = {'protected': protected, 'header': {'kid': 'a'}} s = jws.serialize(header, 'hello', 'secret') self.assertIsInstance(s, dict) data = jws.deserialize(s, 'secret') header, payload = data['header'], data['payload'] self.assertEqual(payload, b'hello') self.assertEqual(header['alg'], 'HS256') self.assertNotIn('protected', data)
def test_nested_json_jws(self): jws = JWS(algorithms=JWS_ALGORITHMS) protected = {'alg': 'HS256'} header = {'protected': protected, 'header': {'kid': 'a'}} s = jws.serialize([header], 'hello', 'secret') self.assertIsInstance(s, dict) self.assertIn('signatures', s) data = jws.deserialize(s, 'secret') header, payload = data['header'], data['payload'] self.assertEqual(payload, b'hello') self.assertEqual(header[0]['alg'], 'HS256') self.assertNotIn('signatures', data) # test bad signature self.assertRaises(errors.BadSignatureError, jws.deserialize, s, 'f')