authentik.enterprise.license

Enterprise license

  1"""Enterprise license"""
  2
  3from base64 import b64decode
  4from binascii import Error
  5from dataclasses import asdict, dataclass, field
  6from datetime import UTC, datetime, timedelta
  7from enum import Enum
  8from functools import lru_cache
  9from time import mktime
 10
 11from cryptography.exceptions import InvalidSignature
 12from cryptography.x509 import Certificate, load_der_x509_certificate, load_pem_x509_certificate
 13from dacite import DaciteError, from_dict
 14from django.core.cache import cache
 15from django.db.models.query import QuerySet
 16from django.utils.timezone import now
 17from jwt import PyJWTError, decode, get_unverified_header
 18from jwt.algorithms import ECAlgorithm
 19from rest_framework.exceptions import ValidationError
 20from rest_framework.fields import (
 21    ChoiceField,
 22    DateTimeField,
 23    IntegerField,
 24    ListField,
 25)
 26
 27from authentik.core.api.utils import PassiveSerializer
 28from authentik.core.models import User, UserTypes
 29from authentik.enterprise.models import (
 30    THRESHOLD_READ_ONLY_WEEKS,
 31    THRESHOLD_WARNING_ADMIN_WEEKS,
 32    THRESHOLD_WARNING_EXPIRY_WEEKS,
 33    THRESHOLD_WARNING_USER_WEEKS,
 34    License,
 35    LicenseUsage,
 36    LicenseUsageStatus,
 37)
 38from authentik.root.cache import in_memory_cache
 39from authentik.root.install_id import get_install_id
 40
 41CACHE_KEY_ENTERPRISE_LICENSE = "goauthentik.io/enterprise/license"
 42CACHE_EXPIRY_ENTERPRISE_LICENSE = 12 * 60 * 60  # 12 Hours
 43
 44
 45@lru_cache
 46def get_licensing_key() -> Certificate:
 47    """Get Root CA PEM"""
 48    with open("authentik/enterprise/public.pem", "rb") as _key:
 49        return load_pem_x509_certificate(_key.read())
 50
 51
 52def get_license_aud() -> str:
 53    """Get the JWT audience field"""
 54    return f"enterprise.goauthentik.io/license/{get_install_id()}"
 55
 56
 57class LicenseFlags(Enum):
 58    """License flags"""
 59
 60    TRIAL = "trial"
 61    NON_PRODUCTION = "non_production"
 62
 63
 64@dataclass
 65class LicenseSummary:
 66    """Internal representation of a license summary"""
 67
 68    internal_users: int
 69    external_users: int
 70    status: LicenseUsageStatus
 71    latest_valid: datetime
 72    license_flags: list[LicenseFlags]
 73
 74
 75class LicenseSummarySerializer(PassiveSerializer):
 76    """Serializer for license status"""
 77
 78    internal_users = IntegerField(required=True)
 79    external_users = IntegerField(required=True)
 80    status = ChoiceField(choices=LicenseUsageStatus.choices)
 81    latest_valid = DateTimeField()
 82    license_flags = ListField(child=ChoiceField(choices=tuple(x.value for x in LicenseFlags)))
 83
 84
 85@dataclass
 86class LicenseKey:
 87    """License JWT claims"""
 88
 89    aud: str
 90    exp: int
 91
 92    name: str
 93    internal_users: int = 0
 94    external_users: int = 0
 95    license_flags: list[LicenseFlags] = field(default_factory=list)
 96
 97    @staticmethod
 98    def validate(jwt: str, check_expiry=True) -> LicenseKey:
 99        """Validate the license from a given JWT"""
100        try:
101            headers = get_unverified_header(jwt)
102        except PyJWTError:
103            raise ValidationError("Unable to verify license") from None
104        x5c: list[str] = headers.get("x5c", [])
105        if len(x5c) < 1:
106            raise ValidationError("Unable to verify license")
107        try:
108            our_cert = load_der_x509_certificate(b64decode(x5c[0]))
109            intermediate = load_der_x509_certificate(b64decode(x5c[1]))
110            our_cert.verify_directly_issued_by(intermediate)
111            intermediate.verify_directly_issued_by(get_licensing_key())
112        except InvalidSignature, TypeError, ValueError, Error:
113            raise ValidationError("Unable to verify license") from None
114        _validate_curve_original = ECAlgorithm._validate_curve
115        try:
116            # authentik's license are generated with `algorithm="ES512"` and signed with
117            # a key of curve `secp384r1`. Starting with version 2.11.0, pyjwt enforces the spec, see
118            # https://github.com/jpadilla/pyjwt/commit/5b8622773358e56d3d3c0a9acf404809ff34433a
119            # authentik will change its license generation to `algorithm="ES384"` in 2026.
120            # TODO: remove this when the last incompatible license runs out.
121            ECAlgorithm._validate_curve = lambda *_: True
122            body = from_dict(
123                LicenseKey,
124                decode(
125                    jwt,
126                    our_cert.public_key(),
127                    algorithms=["ES384", "ES512"],
128                    audience=get_license_aud(),
129                    options={"verify_exp": check_expiry, "verify_signature": check_expiry},
130                ),
131            )
132        except PyJWTError:
133            unverified = decode(jwt, options={"verify_signature": False})
134            if unverified["aud"] != get_license_aud():
135                raise ValidationError("Invalid Install ID in license") from None
136            raise ValidationError("Unable to verify license") from None
137        finally:
138            ECAlgorithm._validate_curve = _validate_curve_original
139        return body
140
141    @staticmethod
142    def get_total() -> LicenseKey:
143        """Get a summarized version of all (not expired) licenses"""
144        total = LicenseKey(get_license_aud(), 0, "Summarized license", 0, 0)
145        for lic in License.objects.all():
146            if lic.is_valid:
147                total.internal_users += lic.internal_users
148                total.external_users += lic.external_users
149                total.license_flags.extend(lic.status.license_flags)
150            exp_ts = int(mktime(lic.expiry.timetuple()))
151            if total.exp == 0:
152                total.exp = exp_ts
153            total.exp = max(total.exp, exp_ts)
154        return total
155
156    @staticmethod
157    def base_user_qs() -> QuerySet:
158        """Base query set for all users"""
159        return User.objects.all().exclude_anonymous().exclude(is_active=False)
160
161    @staticmethod
162    def get_internal_user_count():
163        """Get current default user count"""
164        return LicenseKey.base_user_qs().filter(type=UserTypes.INTERNAL).count()
165
166    @staticmethod
167    def get_external_user_count():
168        """Get current external user count"""
169        return LicenseKey.base_user_qs().filter(type=UserTypes.EXTERNAL).count()
170
171    def _last_valid_date(self):
172        last_valid_date = (
173            LicenseUsage.objects.order_by("-record_date")
174            .filter(status=LicenseUsageStatus.VALID)
175            .first()
176        )
177        if not last_valid_date:
178            return datetime.fromtimestamp(0, UTC)
179        return last_valid_date.record_date
180
181    def status(self) -> LicenseUsageStatus:
182        """Check if the given license body covers all users, and is valid."""
183        last_valid = self._last_valid_date()
184        if self.exp == 0 and not License.objects.exists():
185            return LicenseUsageStatus.UNLICENSED
186        _now = now()
187        # Check limit-exceeded based status
188        internal_users = self.get_internal_user_count()
189        external_users = self.get_external_user_count()
190        if internal_users > self.internal_users or external_users > self.external_users:
191            if last_valid < _now - timedelta(weeks=THRESHOLD_READ_ONLY_WEEKS):
192                return LicenseUsageStatus.READ_ONLY
193            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_USER_WEEKS):
194                return LicenseUsageStatus.LIMIT_EXCEEDED_USER
195            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_ADMIN_WEEKS):
196                return LicenseUsageStatus.LIMIT_EXCEEDED_ADMIN
197        # Check expiry based status
198        if datetime.fromtimestamp(self.exp, UTC) < _now:
199            if datetime.fromtimestamp(self.exp, UTC) < _now - timedelta(
200                weeks=THRESHOLD_READ_ONLY_WEEKS
201            ):
202                return LicenseUsageStatus.READ_ONLY
203            return LicenseUsageStatus.EXPIRED
204        # Expiry warning
205        if datetime.fromtimestamp(self.exp, UTC) <= _now + timedelta(
206            weeks=THRESHOLD_WARNING_EXPIRY_WEEKS
207        ):
208            return LicenseUsageStatus.EXPIRY_SOON
209        return LicenseUsageStatus.VALID
210
211    def record_usage(self):
212        """Capture the current validity status and metrics and save them"""
213        threshold = now() - timedelta(hours=8)
214        usage = (
215            LicenseUsage.objects.order_by("-record_date").filter(record_date__gte=threshold).first()
216        )
217        if not usage:
218            usage = LicenseUsage.objects.create(
219                internal_user_count=self.get_internal_user_count(),
220                external_user_count=self.get_external_user_count(),
221                status=self.status(),
222            )
223        return usage
224
225    def summary(self) -> LicenseSummary:
226        """Summary of license status"""
227        status = self.status()
228        latest_valid = datetime.fromtimestamp(self.exp).replace(tzinfo=UTC)
229        summary = LicenseSummary(
230            latest_valid=latest_valid,
231            internal_users=self.internal_users,
232            external_users=self.external_users,
233            status=status,
234            license_flags=self.license_flags,
235        )
236        cache.set(
237            CACHE_KEY_ENTERPRISE_LICENSE,
238            asdict(summary),
239            timeout=CACHE_EXPIRY_ENTERPRISE_LICENSE,
240        )
241        return summary
242
243    @staticmethod
244    # Checked on every request and audited model save, so don't go to the cache each time
245    @in_memory_cache(key=lambda: None, timeout=30)
246    def cached_summary() -> LicenseSummary:
247        """Helper method which looks up the last summary"""
248        summary = cache.get(CACHE_KEY_ENTERPRISE_LICENSE)
249        if not summary:
250            return LicenseKey.get_total().summary()
251        try:
252            return from_dict(LicenseSummary, summary)
253        except DaciteError:
254            cache.delete(CACHE_KEY_ENTERPRISE_LICENSE)
255            return LicenseKey.get_total().summary()
CACHE_KEY_ENTERPRISE_LICENSE = 'goauthentik.io/enterprise/license'
CACHE_EXPIRY_ENTERPRISE_LICENSE = 43200
@lru_cache
def get_licensing_key() -> cryptography.hazmat.bindings._rust.x509.Certificate:
46@lru_cache
47def get_licensing_key() -> Certificate:
48    """Get Root CA PEM"""
49    with open("authentik/enterprise/public.pem", "rb") as _key:
50        return load_pem_x509_certificate(_key.read())

Get Root CA PEM

def get_license_aud() -> str:
53def get_license_aud() -> str:
54    """Get the JWT audience field"""
55    return f"enterprise.goauthentik.io/license/{get_install_id()}"

Get the JWT audience field

class LicenseFlags(enum.Enum):
58class LicenseFlags(Enum):
59    """License flags"""
60
61    TRIAL = "trial"
62    NON_PRODUCTION = "non_production"

License flags

TRIAL = <LicenseFlags.TRIAL: 'trial'>
NON_PRODUCTION = <LicenseFlags.NON_PRODUCTION: 'non_production'>
@dataclass
class LicenseSummary:
65@dataclass
66class LicenseSummary:
67    """Internal representation of a license summary"""
68
69    internal_users: int
70    external_users: int
71    status: LicenseUsageStatus
72    latest_valid: datetime
73    license_flags: list[LicenseFlags]

Internal representation of a license summary

LicenseSummary( internal_users: int, external_users: int, status: authentik.enterprise.models.LicenseUsageStatus, latest_valid: datetime.datetime, license_flags: list[LicenseFlags])
internal_users: int
external_users: int
latest_valid: datetime.datetime
license_flags: list[LicenseFlags]
class LicenseSummarySerializer(authentik.core.api.utils.PassiveSerializer):
76class LicenseSummarySerializer(PassiveSerializer):
77    """Serializer for license status"""
78
79    internal_users = IntegerField(required=True)
80    external_users = IntegerField(required=True)
81    status = ChoiceField(choices=LicenseUsageStatus.choices)
82    latest_valid = DateTimeField()
83    license_flags = ListField(child=ChoiceField(choices=tuple(x.value for x in LicenseFlags)))

Serializer for license status

internal_users
external_users
status
latest_valid
license_flags
@dataclass
class LicenseKey:
 86@dataclass
 87class LicenseKey:
 88    """License JWT claims"""
 89
 90    aud: str
 91    exp: int
 92
 93    name: str
 94    internal_users: int = 0
 95    external_users: int = 0
 96    license_flags: list[LicenseFlags] = field(default_factory=list)
 97
 98    @staticmethod
 99    def validate(jwt: str, check_expiry=True) -> LicenseKey:
100        """Validate the license from a given JWT"""
101        try:
102            headers = get_unverified_header(jwt)
103        except PyJWTError:
104            raise ValidationError("Unable to verify license") from None
105        x5c: list[str] = headers.get("x5c", [])
106        if len(x5c) < 1:
107            raise ValidationError("Unable to verify license")
108        try:
109            our_cert = load_der_x509_certificate(b64decode(x5c[0]))
110            intermediate = load_der_x509_certificate(b64decode(x5c[1]))
111            our_cert.verify_directly_issued_by(intermediate)
112            intermediate.verify_directly_issued_by(get_licensing_key())
113        except InvalidSignature, TypeError, ValueError, Error:
114            raise ValidationError("Unable to verify license") from None
115        _validate_curve_original = ECAlgorithm._validate_curve
116        try:
117            # authentik's license are generated with `algorithm="ES512"` and signed with
118            # a key of curve `secp384r1`. Starting with version 2.11.0, pyjwt enforces the spec, see
119            # https://github.com/jpadilla/pyjwt/commit/5b8622773358e56d3d3c0a9acf404809ff34433a
120            # authentik will change its license generation to `algorithm="ES384"` in 2026.
121            # TODO: remove this when the last incompatible license runs out.
122            ECAlgorithm._validate_curve = lambda *_: True
123            body = from_dict(
124                LicenseKey,
125                decode(
126                    jwt,
127                    our_cert.public_key(),
128                    algorithms=["ES384", "ES512"],
129                    audience=get_license_aud(),
130                    options={"verify_exp": check_expiry, "verify_signature": check_expiry},
131                ),
132            )
133        except PyJWTError:
134            unverified = decode(jwt, options={"verify_signature": False})
135            if unverified["aud"] != get_license_aud():
136                raise ValidationError("Invalid Install ID in license") from None
137            raise ValidationError("Unable to verify license") from None
138        finally:
139            ECAlgorithm._validate_curve = _validate_curve_original
140        return body
141
142    @staticmethod
143    def get_total() -> LicenseKey:
144        """Get a summarized version of all (not expired) licenses"""
145        total = LicenseKey(get_license_aud(), 0, "Summarized license", 0, 0)
146        for lic in License.objects.all():
147            if lic.is_valid:
148                total.internal_users += lic.internal_users
149                total.external_users += lic.external_users
150                total.license_flags.extend(lic.status.license_flags)
151            exp_ts = int(mktime(lic.expiry.timetuple()))
152            if total.exp == 0:
153                total.exp = exp_ts
154            total.exp = max(total.exp, exp_ts)
155        return total
156
157    @staticmethod
158    def base_user_qs() -> QuerySet:
159        """Base query set for all users"""
160        return User.objects.all().exclude_anonymous().exclude(is_active=False)
161
162    @staticmethod
163    def get_internal_user_count():
164        """Get current default user count"""
165        return LicenseKey.base_user_qs().filter(type=UserTypes.INTERNAL).count()
166
167    @staticmethod
168    def get_external_user_count():
169        """Get current external user count"""
170        return LicenseKey.base_user_qs().filter(type=UserTypes.EXTERNAL).count()
171
172    def _last_valid_date(self):
173        last_valid_date = (
174            LicenseUsage.objects.order_by("-record_date")
175            .filter(status=LicenseUsageStatus.VALID)
176            .first()
177        )
178        if not last_valid_date:
179            return datetime.fromtimestamp(0, UTC)
180        return last_valid_date.record_date
181
182    def status(self) -> LicenseUsageStatus:
183        """Check if the given license body covers all users, and is valid."""
184        last_valid = self._last_valid_date()
185        if self.exp == 0 and not License.objects.exists():
186            return LicenseUsageStatus.UNLICENSED
187        _now = now()
188        # Check limit-exceeded based status
189        internal_users = self.get_internal_user_count()
190        external_users = self.get_external_user_count()
191        if internal_users > self.internal_users or external_users > self.external_users:
192            if last_valid < _now - timedelta(weeks=THRESHOLD_READ_ONLY_WEEKS):
193                return LicenseUsageStatus.READ_ONLY
194            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_USER_WEEKS):
195                return LicenseUsageStatus.LIMIT_EXCEEDED_USER
196            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_ADMIN_WEEKS):
197                return LicenseUsageStatus.LIMIT_EXCEEDED_ADMIN
198        # Check expiry based status
199        if datetime.fromtimestamp(self.exp, UTC) < _now:
200            if datetime.fromtimestamp(self.exp, UTC) < _now - timedelta(
201                weeks=THRESHOLD_READ_ONLY_WEEKS
202            ):
203                return LicenseUsageStatus.READ_ONLY
204            return LicenseUsageStatus.EXPIRED
205        # Expiry warning
206        if datetime.fromtimestamp(self.exp, UTC) <= _now + timedelta(
207            weeks=THRESHOLD_WARNING_EXPIRY_WEEKS
208        ):
209            return LicenseUsageStatus.EXPIRY_SOON
210        return LicenseUsageStatus.VALID
211
212    def record_usage(self):
213        """Capture the current validity status and metrics and save them"""
214        threshold = now() - timedelta(hours=8)
215        usage = (
216            LicenseUsage.objects.order_by("-record_date").filter(record_date__gte=threshold).first()
217        )
218        if not usage:
219            usage = LicenseUsage.objects.create(
220                internal_user_count=self.get_internal_user_count(),
221                external_user_count=self.get_external_user_count(),
222                status=self.status(),
223            )
224        return usage
225
226    def summary(self) -> LicenseSummary:
227        """Summary of license status"""
228        status = self.status()
229        latest_valid = datetime.fromtimestamp(self.exp).replace(tzinfo=UTC)
230        summary = LicenseSummary(
231            latest_valid=latest_valid,
232            internal_users=self.internal_users,
233            external_users=self.external_users,
234            status=status,
235            license_flags=self.license_flags,
236        )
237        cache.set(
238            CACHE_KEY_ENTERPRISE_LICENSE,
239            asdict(summary),
240            timeout=CACHE_EXPIRY_ENTERPRISE_LICENSE,
241        )
242        return summary
243
244    @staticmethod
245    # Checked on every request and audited model save, so don't go to the cache each time
246    @in_memory_cache(key=lambda: None, timeout=30)
247    def cached_summary() -> LicenseSummary:
248        """Helper method which looks up the last summary"""
249        summary = cache.get(CACHE_KEY_ENTERPRISE_LICENSE)
250        if not summary:
251            return LicenseKey.get_total().summary()
252        try:
253            return from_dict(LicenseSummary, summary)
254        except DaciteError:
255            cache.delete(CACHE_KEY_ENTERPRISE_LICENSE)
256            return LicenseKey.get_total().summary()

License JWT claims

LicenseKey( aud: str, exp: int, name: str, internal_users: int = 0, external_users: int = 0, license_flags: list[LicenseFlags] = <factory>)
aud: str
exp: int
name: str
internal_users: int = 0
external_users: int = 0
license_flags: list[LicenseFlags]
@staticmethod
def validate(jwt: str, check_expiry=True) -> LicenseKey:
 98    @staticmethod
 99    def validate(jwt: str, check_expiry=True) -> LicenseKey:
100        """Validate the license from a given JWT"""
101        try:
102            headers = get_unverified_header(jwt)
103        except PyJWTError:
104            raise ValidationError("Unable to verify license") from None
105        x5c: list[str] = headers.get("x5c", [])
106        if len(x5c) < 1:
107            raise ValidationError("Unable to verify license")
108        try:
109            our_cert = load_der_x509_certificate(b64decode(x5c[0]))
110            intermediate = load_der_x509_certificate(b64decode(x5c[1]))
111            our_cert.verify_directly_issued_by(intermediate)
112            intermediate.verify_directly_issued_by(get_licensing_key())
113        except InvalidSignature, TypeError, ValueError, Error:
114            raise ValidationError("Unable to verify license") from None
115        _validate_curve_original = ECAlgorithm._validate_curve
116        try:
117            # authentik's license are generated with `algorithm="ES512"` and signed with
118            # a key of curve `secp384r1`. Starting with version 2.11.0, pyjwt enforces the spec, see
119            # https://github.com/jpadilla/pyjwt/commit/5b8622773358e56d3d3c0a9acf404809ff34433a
120            # authentik will change its license generation to `algorithm="ES384"` in 2026.
121            # TODO: remove this when the last incompatible license runs out.
122            ECAlgorithm._validate_curve = lambda *_: True
123            body = from_dict(
124                LicenseKey,
125                decode(
126                    jwt,
127                    our_cert.public_key(),
128                    algorithms=["ES384", "ES512"],
129                    audience=get_license_aud(),
130                    options={"verify_exp": check_expiry, "verify_signature": check_expiry},
131                ),
132            )
133        except PyJWTError:
134            unverified = decode(jwt, options={"verify_signature": False})
135            if unverified["aud"] != get_license_aud():
136                raise ValidationError("Invalid Install ID in license") from None
137            raise ValidationError("Unable to verify license") from None
138        finally:
139            ECAlgorithm._validate_curve = _validate_curve_original
140        return body

Validate the license from a given JWT

@staticmethod
def get_total() -> LicenseKey:
142    @staticmethod
143    def get_total() -> LicenseKey:
144        """Get a summarized version of all (not expired) licenses"""
145        total = LicenseKey(get_license_aud(), 0, "Summarized license", 0, 0)
146        for lic in License.objects.all():
147            if lic.is_valid:
148                total.internal_users += lic.internal_users
149                total.external_users += lic.external_users
150                total.license_flags.extend(lic.status.license_flags)
151            exp_ts = int(mktime(lic.expiry.timetuple()))
152            if total.exp == 0:
153                total.exp = exp_ts
154            total.exp = max(total.exp, exp_ts)
155        return total

Get a summarized version of all (not expired) licenses

@staticmethod
def base_user_qs() -> django.db.models.query.QuerySet:
157    @staticmethod
158    def base_user_qs() -> QuerySet:
159        """Base query set for all users"""
160        return User.objects.all().exclude_anonymous().exclude(is_active=False)

Base query set for all users

@staticmethod
def get_internal_user_count():
162    @staticmethod
163    def get_internal_user_count():
164        """Get current default user count"""
165        return LicenseKey.base_user_qs().filter(type=UserTypes.INTERNAL).count()

Get current default user count

@staticmethod
def get_external_user_count():
167    @staticmethod
168    def get_external_user_count():
169        """Get current external user count"""
170        return LicenseKey.base_user_qs().filter(type=UserTypes.EXTERNAL).count()

Get current external user count

def status(self) -> authentik.enterprise.models.LicenseUsageStatus:
182    def status(self) -> LicenseUsageStatus:
183        """Check if the given license body covers all users, and is valid."""
184        last_valid = self._last_valid_date()
185        if self.exp == 0 and not License.objects.exists():
186            return LicenseUsageStatus.UNLICENSED
187        _now = now()
188        # Check limit-exceeded based status
189        internal_users = self.get_internal_user_count()
190        external_users = self.get_external_user_count()
191        if internal_users > self.internal_users or external_users > self.external_users:
192            if last_valid < _now - timedelta(weeks=THRESHOLD_READ_ONLY_WEEKS):
193                return LicenseUsageStatus.READ_ONLY
194            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_USER_WEEKS):
195                return LicenseUsageStatus.LIMIT_EXCEEDED_USER
196            if last_valid < _now - timedelta(weeks=THRESHOLD_WARNING_ADMIN_WEEKS):
197                return LicenseUsageStatus.LIMIT_EXCEEDED_ADMIN
198        # Check expiry based status
199        if datetime.fromtimestamp(self.exp, UTC) < _now:
200            if datetime.fromtimestamp(self.exp, UTC) < _now - timedelta(
201                weeks=THRESHOLD_READ_ONLY_WEEKS
202            ):
203                return LicenseUsageStatus.READ_ONLY
204            return LicenseUsageStatus.EXPIRED
205        # Expiry warning
206        if datetime.fromtimestamp(self.exp, UTC) <= _now + timedelta(
207            weeks=THRESHOLD_WARNING_EXPIRY_WEEKS
208        ):
209            return LicenseUsageStatus.EXPIRY_SOON
210        return LicenseUsageStatus.VALID

Check if the given license body covers all users, and is valid.

def record_usage(self):
212    def record_usage(self):
213        """Capture the current validity status and metrics and save them"""
214        threshold = now() - timedelta(hours=8)
215        usage = (
216            LicenseUsage.objects.order_by("-record_date").filter(record_date__gte=threshold).first()
217        )
218        if not usage:
219            usage = LicenseUsage.objects.create(
220                internal_user_count=self.get_internal_user_count(),
221                external_user_count=self.get_external_user_count(),
222                status=self.status(),
223            )
224        return usage

Capture the current validity status and metrics and save them

def summary(self) -> LicenseSummary:
226    def summary(self) -> LicenseSummary:
227        """Summary of license status"""
228        status = self.status()
229        latest_valid = datetime.fromtimestamp(self.exp).replace(tzinfo=UTC)
230        summary = LicenseSummary(
231            latest_valid=latest_valid,
232            internal_users=self.internal_users,
233            external_users=self.external_users,
234            status=status,
235            license_flags=self.license_flags,
236        )
237        cache.set(
238            CACHE_KEY_ENTERPRISE_LICENSE,
239            asdict(summary),
240            timeout=CACHE_EXPIRY_ENTERPRISE_LICENSE,
241        )
242        return summary

Summary of license status

@staticmethod
@in_memory_cache(key=lambda: None, timeout=30)
def cached_summary() -> LicenseSummary:
244    @staticmethod
245    # Checked on every request and audited model save, so don't go to the cache each time
246    @in_memory_cache(key=lambda: None, timeout=30)
247    def cached_summary() -> LicenseSummary:
248        """Helper method which looks up the last summary"""
249        summary = cache.get(CACHE_KEY_ENTERPRISE_LICENSE)
250        if not summary:
251            return LicenseKey.get_total().summary()
252        try:
253            return from_dict(LicenseSummary, summary)
254        except DaciteError:
255            cache.delete(CACHE_KEY_ENTERPRISE_LICENSE)
256            return LicenseKey.get_total().summary()

Helper method which looks up the last summary