2016-10-10 20:23:42 +00:00
|
|
|
import json
|
2015-10-30 19:48:29 +00:00
|
|
|
import logging
|
2016-10-10 20:23:42 +00:00
|
|
|
import multiprocessing
|
|
|
|
import time
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-10 20:23:42 +00:00
|
|
|
from ctypes import c_bool
|
2015-10-30 19:48:29 +00:00
|
|
|
from datetime import datetime, timedelta
|
2016-10-10 20:23:42 +00:00
|
|
|
from threading import Thread
|
2016-10-18 22:47:51 +00:00
|
|
|
from functools import total_ordering
|
|
|
|
from enum import Enum, IntEnum
|
|
|
|
from collections import namedtuple
|
2016-10-10 20:23:42 +00:00
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
2016-10-10 20:23:42 +00:00
|
|
|
from dateutil import parser
|
2016-10-17 19:20:09 +00:00
|
|
|
from flask import make_response
|
2015-10-30 19:48:29 +00:00
|
|
|
|
|
|
|
import jwt
|
2016-10-10 20:23:42 +00:00
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2016-10-10 20:23:42 +00:00
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
TRIAL_GRACE_PERIOD = timedelta(7, 0) # 1 week
|
2016-10-18 22:46:40 +00:00
|
|
|
MONTHLY_GRACE_PERIOD = timedelta(335, 0) # 11 months
|
2015-10-30 19:48:29 +00:00
|
|
|
YEARLY_GRACE_PERIOD = timedelta(90, 0) # 3 months
|
2016-10-10 20:23:42 +00:00
|
|
|
LICENSE_FILENAME = 'license'
|
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
class LicenseDecodeError(Exception):
|
2015-10-30 19:48:29 +00:00
|
|
|
""" Exception raised if the license could not be read, decoded or has expired. """
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def _get_date(decoded, field, default_date=datetime.min):
|
|
|
|
""" Retrieves the encoded date found at the given field under the decoded license block. """
|
|
|
|
date_str = decoded.get(field)
|
|
|
|
return parser.parse(date_str).replace(tzinfo=None) if date_str else default_date
|
2015-10-30 19:48:29 +00:00
|
|
|
|
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
@total_ordering
|
|
|
|
class Entitlement(object):
|
|
|
|
""" An entitlement is a specific piece of software or functionality granted
|
|
|
|
by a license. It has an expiration date, as well as the count of the
|
|
|
|
things being granted. Entitlements are orderable by their counts.
|
|
|
|
"""
|
|
|
|
def __init__(self, entitlement_name, count, product_name, expiration):
|
|
|
|
self.name = entitlement_name
|
|
|
|
self.count = count
|
|
|
|
self.product_name = product_name
|
|
|
|
self.expiration = expiration
|
|
|
|
|
|
|
|
def __lt__(self, rhs):
|
|
|
|
return self.count < rhs.count
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return str(dict(
|
|
|
|
name=self.name,
|
|
|
|
count=self.count,
|
|
|
|
product_name=self.product_name,
|
|
|
|
expiration=repr(self.expiration),
|
|
|
|
))
|
|
|
|
|
|
|
|
class ExpirationType(Enum):
|
|
|
|
""" An enum which represents the different possible types of expirations. If
|
|
|
|
you posess an expired enum, you can use this to figure out at what level
|
|
|
|
the expiration was most restrictive.
|
|
|
|
"""
|
|
|
|
license_wide = 'License Wide Expiration'
|
|
|
|
trial_only = 'Trial Only Expiration'
|
|
|
|
in_trial = 'In-Trial Expiration'
|
|
|
|
monthly = 'Monthly Subscription Expiration'
|
|
|
|
yearly = 'Yearly Subscription Expiration'
|
|
|
|
|
|
|
|
|
|
|
|
@total_ordering
|
|
|
|
class Expiration(object):
|
|
|
|
""" An Expiration is an orderable representation of an expiration date and a
|
|
|
|
grace period. If you sort Expiration objects, they will be sorted by the
|
|
|
|
actual cutoff date, which is the combination of the expiration date and
|
|
|
|
the grace period.
|
|
|
|
"""
|
|
|
|
def __init__(self, expiration_type, exp_date, grace_period=timedelta(seconds=0)):
|
|
|
|
self.expiration_type = expiration_type
|
|
|
|
self.expiration_date = exp_date
|
|
|
|
self.grace_period = grace_period
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
@property
|
|
|
|
def expires_at(self):
|
|
|
|
return self.expiration_date + self.grace_period
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def is_expired(self, now):
|
|
|
|
""" Check if the current object should already be considered expired when
|
|
|
|
compared with the passed in datetime object.
|
|
|
|
"""
|
|
|
|
return self.expires_at < now
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def __lt__(self, rhs):
|
|
|
|
return self.expires_at < rhs.expires_at
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return str(dict(
|
|
|
|
expiration_type=repr(self.expiration_type),
|
|
|
|
expiration_date=repr(self.expiration_date),
|
|
|
|
grace_period=repr(self.grace_period),
|
|
|
|
))
|
2016-10-11 19:16:28 +00:00
|
|
|
|
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
class EntitlementStatus(IntEnum):
|
|
|
|
""" An EntitlementStatus represent the current effectiveness of an
|
|
|
|
Entitlement when compared with its corresponding requirement. As an
|
|
|
|
example, if the software requires 9 items, and the Entitlement only
|
|
|
|
provides for 7, you would use an insufficient_count status.
|
|
|
|
"""
|
|
|
|
met = 0
|
|
|
|
expired = 1
|
|
|
|
insufficient_count = 2
|
|
|
|
no_matching = 3
|
|
|
|
|
|
|
|
|
|
|
|
@total_ordering
|
|
|
|
class EntitlementValidationResult(object):
|
|
|
|
""" An EntitlementValidationResult encodes the combination of a specific
|
|
|
|
entitlement and the software requirement which caused it to be examined.
|
|
|
|
They are orderable by the value of the EntitlementStatus enum, and will
|
|
|
|
in general be sorted by most to least satisfiable status type.
|
|
|
|
"""
|
|
|
|
def __init__(self, requirement, created_at, entitlement=None):
|
|
|
|
self.requirement = requirement
|
|
|
|
self._created_at = created_at
|
|
|
|
self.entitlement = entitlement
|
|
|
|
|
|
|
|
def get_status(self):
|
|
|
|
""" Returns the EntitlementStatus when comparing the specified Entitlement
|
|
|
|
with the corresponding requirement.
|
|
|
|
"""
|
|
|
|
if self.entitlement is not None:
|
|
|
|
if self.entitlement.expiration.is_expired(self._created_at):
|
|
|
|
return EntitlementStatus.expired
|
|
|
|
|
|
|
|
if self.entitlement.count < self.requirement.count:
|
|
|
|
return EntitlementStatus.insufficient_count
|
|
|
|
|
|
|
|
return EntitlementStatus.met
|
|
|
|
|
|
|
|
return EntitlementStatus.no_matching
|
|
|
|
|
|
|
|
def is_met(self):
|
|
|
|
""" Returns whether this specific EntitlementValidationResult meets all
|
|
|
|
of the criteria for being sufficient, including unexpired (or in the
|
|
|
|
grace period), and with a sufficient count.
|
|
|
|
"""
|
|
|
|
return self.get_status() == EntitlementStatus.met
|
|
|
|
|
|
|
|
def __lt__(self, rhs):
|
|
|
|
return self.get_status() < rhs.get_status()
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return str(dict(
|
|
|
|
requirement=repr(self.requirement),
|
|
|
|
created_at=repr(self._created_at),
|
|
|
|
entitlement=repr(self.entitlement),
|
|
|
|
))
|
2016-10-11 19:16:28 +00:00
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
|
|
|
|
class License(object):
|
|
|
|
""" License represents a fully decoded and validated (but potentially expired) license. """
|
|
|
|
def __init__(self, decoded):
|
|
|
|
self.decoded = decoded
|
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def validate_entitlement_requirement(self, entitlement_req, check_time):
|
|
|
|
all_active_entitlements = list(self._find_entitlements(entitlement_req.name))
|
|
|
|
|
|
|
|
if len(all_active_entitlements) == 0:
|
|
|
|
return EntitlementValidationResult(entitlement_req, check_time)
|
|
|
|
|
|
|
|
entitlement_results = [EntitlementValidationResult(entitlement_req, check_time, ent)
|
|
|
|
for ent in all_active_entitlements]
|
|
|
|
entitlement_results.sort()
|
|
|
|
return entitlement_results[0]
|
|
|
|
|
|
|
|
def _find_entitlements(self, entitlement_name):
|
|
|
|
license_expiration = Expiration(
|
|
|
|
ExpirationType.license_wide,
|
|
|
|
_get_date(self.decoded, 'expirationDate'),
|
|
|
|
)
|
|
|
|
|
2015-12-08 20:00:50 +00:00
|
|
|
for sub in self.decoded.get('subscriptions', {}).values():
|
2016-10-18 22:47:51 +00:00
|
|
|
entitlement_count = sub.get('entitlements', {}).get(entitlement_name)
|
2015-12-08 20:00:50 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
if entitlement_count is not None:
|
|
|
|
entitlement_expiration = min(self._sub_expiration(sub), license_expiration)
|
|
|
|
yield Entitlement(
|
|
|
|
entitlement_name,
|
|
|
|
entitlement_count,
|
|
|
|
sub.get('productName', 'unknown'),
|
|
|
|
entitlement_expiration,
|
|
|
|
)
|
2015-12-08 20:00:50 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
@staticmethod
|
|
|
|
def _sub_expiration(subscription):
|
|
|
|
# A trial license has its own end logic, and uses the trialEnd property
|
|
|
|
if subscription.get('trialOnly', False):
|
|
|
|
trial_expiration = Expiration(
|
|
|
|
ExpirationType.trial_only,
|
|
|
|
_get_date(subscription, 'trialEnd'),
|
|
|
|
TRIAL_GRACE_PERIOD,
|
|
|
|
)
|
|
|
|
return trial_expiration
|
2015-12-08 20:00:50 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
# From here we always use the serviceEnd
|
|
|
|
service_end = _get_date(subscription, 'serviceEnd')
|
|
|
|
|
|
|
|
if subscription.get('inTrial', False):
|
|
|
|
return Expiration(ExpirationType.in_trial, service_end, TRIAL_GRACE_PERIOD)
|
2015-10-30 19:48:29 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
if subscription.get('durationPeriod') == 'yearly':
|
|
|
|
return Expiration(ExpirationType.yearly, service_end, YEARLY_GRACE_PERIOD)
|
|
|
|
|
|
|
|
# We assume monthly license unless specified otherwise
|
|
|
|
return Expiration(ExpirationType.monthly, service_end, MONTHLY_GRACE_PERIOD)
|
|
|
|
|
|
|
|
def validate(self, config):
|
|
|
|
""" Returns a list of EntitlementValidationResult objects, one per requirement.
|
|
|
|
"""
|
|
|
|
requirements = _gen_entitlement_requirements(config)
|
|
|
|
now = datetime.now()
|
|
|
|
return [self.validate_entitlement_requirement(req, now) for req in requirements]
|
2015-10-30 19:48:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
_PROD_LICENSE_PUBLIC_KEY_DATA = """
|
|
|
|
-----BEGIN PUBLIC KEY-----
|
|
|
|
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuCkRnkuqox3A0djgRnHR
|
|
|
|
e3U3jHrcbd5iUqdbfO/8E2TMbiByIy3NzUyJrMIzrTjdxTVIZF/ueaHLEtgaofUA
|
|
|
|
1X73OZlsaGyNVDFA2eGZRgyNrmfLFoxnN2KB+gEJ88nPkHZXY+4ncZBjVMKfHQEv
|
|
|
|
busC7xpnF7Diy2GxZKDZRnvjL4ZNrocdoeE0GuroWwebtck5Ea7LqzRxCJ5T3UWt
|
|
|
|
EozttOBQAqCmKxSDdtdw+CsK/uTfl6Yh9xCZUrCeh5taSOHOvU0ne/p3gM+AsjU4
|
|
|
|
ScjObTKaSUOGen6aYFF5Bd6V/ucxHmcmJlycwNZOKGFpbhLU173/oBJ+okvDbJpN
|
|
|
|
qwIDAQAB
|
|
|
|
-----END PUBLIC KEY-----
|
|
|
|
"""
|
2016-09-28 03:20:31 +00:00
|
|
|
_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):
|
2015-10-30 19:48:29 +00:00
|
|
|
""" Decodes the specified license contents, returning the decoded license. """
|
2016-09-28 03:20:31 +00:00
|
|
|
license_public_key = public_key_instance or _PROD_LICENSE_PUBLIC_KEY
|
2015-10-30 19:48:29 +00:00
|
|
|
try:
|
2015-12-08 20:00:50 +00:00
|
|
|
jwt_data = jwt.decode(license_contents, key=license_public_key)
|
2015-10-30 19:48:29 +00:00
|
|
|
except jwt.exceptions.DecodeError as de:
|
|
|
|
logger.exception('Could not decode license file')
|
|
|
|
raise LicenseDecodeError('Could not decode license found: %s' % de.message)
|
|
|
|
|
2015-12-08 20:00:50 +00:00
|
|
|
try:
|
|
|
|
decoded = json.loads(jwt_data.get('license', '{}'))
|
|
|
|
except ValueError as ve:
|
|
|
|
logger.exception('Could not decode license file')
|
|
|
|
raise LicenseDecodeError('Could not decode license found: %s' % ve.message)
|
|
|
|
|
2015-10-30 19:48:29 +00:00
|
|
|
return License(decoded)
|
2016-10-10 20:23:42 +00:00
|
|
|
|
|
|
|
|
|
|
|
LICENSE_VALIDATION_INTERVAL = 3600 # seconds
|
|
|
|
LICENSE_VALIDATION_EXPIRED_INTERVAL = 60 # seconds
|
|
|
|
|
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
EntitlementRequirement = namedtuple('EntitlementRequirements', ['name', 'count'])
|
|
|
|
|
|
|
|
|
|
|
|
def _gen_entitlement_requirements(config_obj):
|
|
|
|
config_regions = len(config_obj.get('DISTRIBUTED_STORAGE_CONFIG', []))
|
|
|
|
return [
|
|
|
|
EntitlementRequirement('software.quay', 1),
|
|
|
|
EntitlementRequirement('software.quay.regions', config_regions),
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2016-10-10 20:23:42 +00:00
|
|
|
class LicenseValidator(Thread):
|
|
|
|
"""
|
|
|
|
LicenseValidator is a thread that asynchronously reloads and validates license files.
|
|
|
|
|
|
|
|
This thread is meant to be run before registry gunicorn workers fork and uses shared memory as a
|
|
|
|
synchronization primitive.
|
|
|
|
"""
|
2016-10-18 15:44:13 +00:00
|
|
|
def __init__(self, config_provider, *args, **kwargs):
|
2016-10-19 03:44:08 +00:00
|
|
|
config = config_provider.get_config() or {}
|
|
|
|
|
2016-10-18 15:44:13 +00:00
|
|
|
self._config_provider = config_provider
|
2016-10-19 03:44:08 +00:00
|
|
|
self._entitlement_requirements = _gen_entitlement_requirements(config)
|
2016-10-10 20:23:42 +00:00
|
|
|
|
|
|
|
# multiprocessing.Value does not ensure consistent write-after-reads, but we don't need that.
|
2016-10-18 22:47:51 +00:00
|
|
|
self._license_is_insufficient = multiprocessing.Value(c_bool, True)
|
2016-10-10 20:23:42 +00:00
|
|
|
|
2016-10-17 19:20:09 +00:00
|
|
|
super(LicenseValidator, self).__init__(*args, **kwargs)
|
|
|
|
self.daemon = True
|
2016-10-10 20:23:42 +00:00
|
|
|
|
|
|
|
@property
|
2016-10-18 22:47:51 +00:00
|
|
|
def insufficient(self):
|
|
|
|
return self._license_is_insufficient.value
|
2016-10-10 20:23:42 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
def compute_license_sufficiency(self):
|
|
|
|
""" Check whether all of our requirements are met, and set the status of
|
|
|
|
the result of the check, which will be used to disable the software.
|
|
|
|
Returns True if any requirements are not met, and False if all are met.
|
|
|
|
"""
|
2016-10-10 20:23:42 +00:00
|
|
|
try:
|
2016-10-18 15:44:13 +00:00
|
|
|
current_license = self._config_provider.get_license()
|
2016-10-18 22:47:51 +00:00
|
|
|
now = datetime.now()
|
|
|
|
any_invalid = not all(current_license.validate_entitlement_requirement(req, now).is_met()
|
|
|
|
for req in self._entitlement_requirements)
|
|
|
|
logger.debug('updating license license_is_insufficient to %s', any_invalid)
|
|
|
|
except (IOError, LicenseDecodeError):
|
2016-10-10 20:23:42 +00:00
|
|
|
logger.exception('failed to validate license')
|
2016-10-18 22:47:51 +00:00
|
|
|
any_invalid = True
|
2016-10-17 19:20:09 +00:00
|
|
|
|
2016-10-18 22:47:51 +00:00
|
|
|
self._license_is_insufficient.value = any_invalid
|
|
|
|
return any_invalid
|
2016-10-10 20:23:42 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
logger.debug('Starting license validation thread')
|
|
|
|
while True:
|
2016-10-18 22:47:51 +00:00
|
|
|
invalid = self.compute_license_sufficiency()
|
|
|
|
sleep_time = LICENSE_VALIDATION_EXPIRED_INTERVAL if invalid else LICENSE_VALIDATION_INTERVAL
|
2016-10-10 20:23:42 +00:00
|
|
|
logger.debug('waiting %d seconds before retrying to validate license', sleep_time)
|
|
|
|
time.sleep(sleep_time)
|
|
|
|
|
2016-10-17 19:20:09 +00:00
|
|
|
def enforce_license_before_request(self, blueprint, response_func=None):
|
|
|
|
"""
|
|
|
|
Adds a pre-check to a Flask blueprint such that if the provided license_validator determines the
|
|
|
|
license has become invalid, the client will receive a HTTP 402 response.
|
|
|
|
"""
|
|
|
|
if response_func is None:
|
|
|
|
def _response_func():
|
2016-10-18 22:47:51 +00:00
|
|
|
return make_response('License is insufficient.', 402)
|
2016-10-17 19:20:09 +00:00
|
|
|
response_func = _response_func
|
|
|
|
|
|
|
|
def _enforce_license():
|
2016-10-18 22:47:51 +00:00
|
|
|
if self.insufficient:
|
|
|
|
logger.debug('blocked interaction due to insufficient license')
|
2016-10-17 19:20:09 +00:00
|
|
|
return response_func()
|
|
|
|
blueprint.before_request(_enforce_license)
|