authentik.crypto.signals

authentik crypto signals

 1"""authentik crypto signals"""
 2
 3from binascii import hexlify
 4from datetime import datetime
 5from ssl import CertificateError
 6
 7from cryptography.hazmat.primitives import hashes
 8from cryptography.x509 import Certificate
 9from django.db.models.signals import pre_save
10from django.dispatch import receiver
11from structlog.stdlib import get_logger
12
13from authentik.crypto.apps import GAUGE_CERTIFICATE_EXPIRY
14from authentik.crypto.models import (
15    CertificateKeyPair,
16    detect_key_type,
17    fingerprint_sha256,
18    generate_key_id,
19    generate_key_id_legacy,
20)
21from authentik.root.monitoring import monitoring_set
22
23LOGGER = get_logger()
24
25
26def extract_certificate_metadata(certificate: Certificate) -> dict[str, str | datetime]:
27    """Extract all metadata fields from a certificate."""
28    metadata = {}
29
30    try:
31        metadata["key_type"] = detect_key_type(certificate)
32        metadata["cert_expiry"] = certificate.not_valid_after_utc
33        metadata["cert_subject"] = certificate.subject.rfc4514_string()
34        metadata["fingerprint_sha256"] = fingerprint_sha256(certificate)
35        metadata["fingerprint_sha1"] = hexlify(
36            certificate.fingerprint(hashes.SHA1()), ":"  # nosec
37        ).decode("utf-8")
38    except (ValueError, TypeError, AttributeError) as exc:
39        raise CertificateError(f"Invalid certificate metadata: {exc}") from exc
40
41    return metadata
42
43
44@receiver(pre_save, sender="authentik_crypto.CertificateKeyPair")
45def certificate_key_pair_pre_save(
46    sender: type[CertificateKeyPair], instance: CertificateKeyPair, **_
47):
48    """Automatically populate certificate metadata fields before saving"""
49
50    # Only extract metadata if certificate_data is present
51    if not instance.certificate_data:
52        return
53
54    try:
55        metadata = extract_certificate_metadata(instance.certificate)
56    except (CertificateError, ValueError, TypeError, AttributeError) as exc:
57        LOGGER.warning("Failed to extract certificate metadata", exc=exc)
58        return
59
60    instance.key_type = metadata["key_type"]
61    instance.cert_expiry = metadata["cert_expiry"]
62    instance.cert_subject = metadata["cert_subject"]
63    instance.fingerprint_sha256 = metadata["fingerprint_sha256"]
64    instance.fingerprint_sha1 = metadata["fingerprint_sha1"]
65
66    # Generate kid if not set, or regenerate if key_data has changed
67    # Preserve existing kid (MD5 or SHA512) if it matches the current key_data
68    if instance.key_data:
69        new_kid = generate_key_id(instance.key_data)
70        legacy_kid = generate_key_id_legacy(instance.key_data)
71        if instance.kid not in (new_kid, legacy_kid):
72            instance.kid = new_kid
73
74
75@receiver(monitoring_set)
76def monitoring_set_certificates(sender, **kwargs):
77    """Set certificate expiry gauge"""
78    # A labelset stays in this process' mmap file under multiprocess collection until it is
79    # overwritten, so pairs that were deleted or renamed are set to NaN rather than left
80    # reporting their old expiry; 0 would read as a certificate that expired in 1970.
81    for metric in GAUGE_CERTIFICATE_EXPIRY.collect():
82        for sample in metric.samples:
83            GAUGE_CERTIFICATE_EXPIRY.labels(**sample.labels).set(float("nan"))
84    for kp in CertificateKeyPair.objects.filter(cert_expiry__isnull=False).only(
85        "kp_uuid", "name", "cert_expiry"
86    ):
87        GAUGE_CERTIFICATE_EXPIRY.labels(name=kp.name, kp_uuid=str(kp.kp_uuid)).set(
88            kp.cert_expiry.timestamp()
89        )
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def extract_certificate_metadata( certificate: cryptography.hazmat.bindings._rust.x509.Certificate) -> dict[str, str | datetime.datetime]:
27def extract_certificate_metadata(certificate: Certificate) -> dict[str, str | datetime]:
28    """Extract all metadata fields from a certificate."""
29    metadata = {}
30
31    try:
32        metadata["key_type"] = detect_key_type(certificate)
33        metadata["cert_expiry"] = certificate.not_valid_after_utc
34        metadata["cert_subject"] = certificate.subject.rfc4514_string()
35        metadata["fingerprint_sha256"] = fingerprint_sha256(certificate)
36        metadata["fingerprint_sha1"] = hexlify(
37            certificate.fingerprint(hashes.SHA1()), ":"  # nosec
38        ).decode("utf-8")
39    except (ValueError, TypeError, AttributeError) as exc:
40        raise CertificateError(f"Invalid certificate metadata: {exc}") from exc
41
42    return metadata

Extract all metadata fields from a certificate.

@receiver(pre_save, sender='authentik_crypto.CertificateKeyPair')
def certificate_key_pair_pre_save( sender: type[authentik.crypto.models.CertificateKeyPair], instance: authentik.crypto.models.CertificateKeyPair, **_):
45@receiver(pre_save, sender="authentik_crypto.CertificateKeyPair")
46def certificate_key_pair_pre_save(
47    sender: type[CertificateKeyPair], instance: CertificateKeyPair, **_
48):
49    """Automatically populate certificate metadata fields before saving"""
50
51    # Only extract metadata if certificate_data is present
52    if not instance.certificate_data:
53        return
54
55    try:
56        metadata = extract_certificate_metadata(instance.certificate)
57    except (CertificateError, ValueError, TypeError, AttributeError) as exc:
58        LOGGER.warning("Failed to extract certificate metadata", exc=exc)
59        return
60
61    instance.key_type = metadata["key_type"]
62    instance.cert_expiry = metadata["cert_expiry"]
63    instance.cert_subject = metadata["cert_subject"]
64    instance.fingerprint_sha256 = metadata["fingerprint_sha256"]
65    instance.fingerprint_sha1 = metadata["fingerprint_sha1"]
66
67    # Generate kid if not set, or regenerate if key_data has changed
68    # Preserve existing kid (MD5 or SHA512) if it matches the current key_data
69    if instance.key_data:
70        new_kid = generate_key_id(instance.key_data)
71        legacy_kid = generate_key_id_legacy(instance.key_data)
72        if instance.kid not in (new_kid, legacy_kid):
73            instance.kid = new_kid

Automatically populate certificate metadata fields before saving

@receiver(monitoring_set)
def monitoring_set_certificates(sender, **kwargs):
76@receiver(monitoring_set)
77def monitoring_set_certificates(sender, **kwargs):
78    """Set certificate expiry gauge"""
79    # A labelset stays in this process' mmap file under multiprocess collection until it is
80    # overwritten, so pairs that were deleted or renamed are set to NaN rather than left
81    # reporting their old expiry; 0 would read as a certificate that expired in 1970.
82    for metric in GAUGE_CERTIFICATE_EXPIRY.collect():
83        for sample in metric.samples:
84            GAUGE_CERTIFICATE_EXPIRY.labels(**sample.labels).set(float("nan"))
85    for kp in CertificateKeyPair.objects.filter(cert_expiry__isnull=False).only(
86        "kp_uuid", "name", "cert_expiry"
87    ):
88        GAUGE_CERTIFICATE_EXPIRY.labels(name=kp.name, kp_uuid=str(kp.kp_uuid)).set(
89            kp.cert_expiry.timestamp()
90        )

Set certificate expiry gauge