This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/authentik/crypto/apps.py
Jens L ad9f500ad1
crypto: fix race conditions when creating self-signed certificates on startup (#7344)
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
2023-10-27 16:29:10 +02:00

72 lines
2.4 KiB
Python

"""authentik crypto app config"""
from datetime import datetime
from typing import Optional
from authentik.blueprints.apps import ManagedAppConfig
from authentik.lib.generators import generate_id
MANAGED_KEY = "goauthentik.io/crypto/jwt-managed"
class AuthentikCryptoConfig(ManagedAppConfig):
"""authentik crypto app config"""
name = "authentik.crypto"
label = "authentik_crypto"
verbose_name = "authentik Crypto"
default = True
def reconcile_load_crypto_tasks(self):
"""Load crypto tasks"""
self.import_module("authentik.crypto.tasks")
def _create_update_cert(self):
from authentik.crypto.builder import CertificateBuilder
from authentik.crypto.models import CertificateKeyPair
common_name = "authentik Internal JWT Certificate"
builder = CertificateBuilder(common_name)
builder.build(
subject_alt_names=["goauthentik.io"],
validity_days=360,
)
CertificateKeyPair.objects.update_or_create(
managed=MANAGED_KEY,
defaults={
"name": common_name,
"certificate_data": builder.certificate,
"key_data": builder.private_key,
},
)
def reconcile_managed_jwt_cert(self):
"""Ensure managed JWT certificate"""
from authentik.crypto.models import CertificateKeyPair
cert: Optional[CertificateKeyPair] = CertificateKeyPair.objects.filter(
managed=MANAGED_KEY
).first()
now = datetime.now()
if not cert or (
now < cert.certificate.not_valid_before or now > cert.certificate.not_valid_after
):
self._create_update_cert()
def reconcile_self_signed(self):
"""Create self-signed keypair"""
from authentik.crypto.builder import CertificateBuilder
from authentik.crypto.models import CertificateKeyPair
name = "authentik Self-signed Certificate"
if CertificateKeyPair.objects.filter(name=name).exists():
return
builder = CertificateBuilder(name)
builder.build(subject_alt_names=[f"{generate_id()}.self-signed.goauthentik.io"])
CertificateKeyPair.objects.get_or_create(
name=name,
defaults={
"certificate_data": builder.certificate,
"key_data": builder.private_key,
},
)