license: validate via key instance rather than PEM

This commit is contained in:
Jimmy Zelinskie 2016-09-27 23:20:31 -04:00
parent 2b00c644b5
commit ae16d24fd1
2 changed files with 19 additions and 11 deletions

View file

@ -1,11 +1,15 @@
import unittest
import jwt
from datetime import datetime, timedelta
from util.config.provider.license import (decode_license, LICENSE_PRODUCT_NAME,
LicenseValidationError)
import jwt
from Crypto.PublicKey import RSA
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_der_public_key
from util.config.provider.license import (decode_license, LICENSE_PRODUCT_NAME,
LicenseValidationError)
class TestLicense(unittest.TestCase):
@ -13,16 +17,18 @@ class TestLicense(unittest.TestCase):
with open('test/data/test.pem') as f:
private_key = f.read()
return (RSA.importKey(private_key).publickey().exportKey('PEM'), private_key)
public_key = load_der_public_key(RSA.importKey(private_key).publickey().exportKey('DER'),
backend=default_backend())
return (public_key, private_key)
def create_license(self, license_data):
(public_key, private_key) = self.keys()
# Encode the license with the JWT key.
encoded = jwt.encode(license_data, private_key, 'RS256')
encoded = jwt.encode(license_data, private_key, algorithm='RS256')
# Decode it into a license object.
return decode_license(encoded, public_key_contents=public_key)
return decode_license(encoded, public_key_instance=public_key)
def get_license(self, expiration_delta=None, **kwargs):
license_data = {

View file

@ -107,6 +107,7 @@ class License(object):
LICENSE_FILENAME = 'license'
_PROD_LICENSE_PUBLIC_KEY_DATA = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuCkRnkuqox3A0djgRnHR
@ -119,10 +120,13 @@ qwIDAQAB
-----END PUBLIC KEY-----
"""
def decode_license(license_contents, public_key_contents=None):
_PROD_LICENSE_PUBLIC_KEY = load_pem_public_key(_PROD_LICENSE_PUBLIC_KEY_DATA,
backend=default_backend())
def decode_license(license_contents, public_key_instance=None):
""" Decodes the specified license contents, returning the decoded license. """
public_key_data = public_key_contents or _PROD_LICENSE_PUBLIC_KEY_DATA
license_public_key = load_pem_public_key(public_key_data, backend=default_backend())
license_public_key = public_key_instance or _PROD_LICENSE_PUBLIC_KEY
try:
decoded = jwt.decode(license_contents, key=license_public_key)
except jwt.exceptions.DecodeError as de:
@ -130,5 +134,3 @@ def decode_license(license_contents, public_key_contents=None):
raise LicenseDecodeError('Could not decode license found: %s' % de.message)
return License(decoded)