authentik.crypto.api

Crypto API Views

  1"""Crypto API Views"""
  2
  3from cryptography.exceptions import InternalError, UnsupportedAlgorithm
  4from cryptography.hazmat.backends import default_backend
  5from cryptography.hazmat.primitives.serialization import load_pem_private_key
  6from cryptography.x509 import load_pem_x509_certificate
  7from django.http.response import HttpResponse
  8from django.urls import reverse
  9from django.utils.translation import gettext_lazy as _
 10from django_filters import FilterSet
 11from django_filters.filters import BooleanFilter, MultipleChoiceFilter
 12from drf_spectacular.types import OpenApiTypes
 13from drf_spectacular.utils import (
 14    OpenApiParameter,
 15    OpenApiResponse,
 16    extend_schema,
 17)
 18from rest_framework.decorators import action
 19from rest_framework.exceptions import ValidationError
 20from rest_framework.fields import (
 21    CharField,
 22    ChoiceField,
 23    IntegerField,
 24    SerializerMethodField,
 25)
 26from rest_framework.filters import OrderingFilter, SearchFilter
 27from rest_framework.permissions import IsAuthenticated
 28from rest_framework.request import Request
 29from rest_framework.response import Response
 30from rest_framework.validators import UniqueValidator
 31from rest_framework.viewsets import ModelViewSet
 32from structlog.stdlib import get_logger
 33
 34from authentik.api.validation import validate
 35from authentik.core.api.used_by import UsedByMixin
 36from authentik.core.api.utils import ModelSerializer, PassiveSerializer
 37from authentik.core.models import UserTypes
 38from authentik.crypto.apps import MANAGED_KEY
 39from authentik.crypto.builder import (
 40    CertificateBuilder,
 41    KeyAlgorithmUnavailableError,
 42    PrivateKeyAlg,
 43)
 44from authentik.crypto.models import CertificateKeyPair, KeyType
 45from authentik.events.models import Event, EventAction
 46from authentik.rbac.decorators import permission_required
 47from authentik.rbac.filters import SecretKeyFilter
 48
 49LOGGER = get_logger()
 50
 51
 52class CertificateKeyPairSerializer(ModelSerializer):
 53    """CertificateKeyPair Serializer"""
 54
 55    private_key_available = SerializerMethodField()
 56
 57    certificate_download_url = SerializerMethodField()
 58    private_key_download_url = SerializerMethodField()
 59
 60    def get_private_key_available(self, instance: CertificateKeyPair) -> bool:
 61        """Show if this keypair has a private key configured or not"""
 62        return instance.key_data != "" and instance.key_data is not None
 63
 64    def get_certificate_download_url(self, instance: CertificateKeyPair) -> str:
 65        """Get URL to download certificate"""
 66        return (
 67            reverse(
 68                "authentik_api:certificatekeypair-view-certificate",
 69                kwargs={"pk": instance.pk},
 70            )
 71            + "?download"
 72        )
 73
 74    def get_private_key_download_url(self, instance: CertificateKeyPair) -> str:
 75        """Get URL to download private key"""
 76        return (
 77            reverse(
 78                "authentik_api:certificatekeypair-view-private-key",
 79                kwargs={"pk": instance.pk},
 80            )
 81            + "?download"
 82        )
 83
 84    def validate_certificate_data(self, value: str) -> str:
 85        """Verify that input is a valid PEM x509 Certificate"""
 86        try:
 87            # Cast to string to fully load and parse certificate
 88            # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
 89            str(load_pem_x509_certificate(value.encode("utf-8"), default_backend()))
 90        except ValueError as exc:
 91            LOGGER.warning("Failed to load certificate", exc=exc)
 92            raise ValidationError("Unable to load certificate.") from None
 93        return value
 94
 95    def validate_key_data(self, value: str) -> str:
 96        """Verify that input is a valid PEM Key"""
 97        # Since this field is optional, data can be empty.
 98        if value != "":
 99            try:
100                # Cast to string to fully load and parse certificate
101                # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
102                str(
103                    load_pem_private_key(
104                        str.encode("\n".join([x.strip() for x in value.split("\n")])),
105                        password=None,
106                        backend=default_backend(),
107                    )
108                )
109            except (ValueError, TypeError) as exc:
110                LOGGER.warning("Failed to load private key", exc=exc)
111                raise ValidationError("Unable to load private key (possibly encrypted?).") from None
112            except (InternalError, UnsupportedAlgorithm) as exc:
113                # TODO: Remove when OpenSSL/FIPS is updated
114                # OpenSSL has no implementation for this key type in the current configuration,
115                # for example an ML-DSA key with a FIPS provider that predates ML-DSA
116                LOGGER.warning("Private key algorithm not available", exc=exc)
117                raise ValidationError(
118                    "The private key's algorithm is not available in the current OpenSSL "
119                    "configuration (for example ML-DSA in FIPS mode)."
120                ) from None
121        return value
122
123    class Meta:
124        model = CertificateKeyPair
125        fields = [
126            "pk",
127            "name",
128            "fingerprint_sha256",
129            "fingerprint_sha1",
130            "certificate_data",
131            "key_data",
132            "cert_expiry",
133            "cert_subject",
134            "private_key_available",
135            "key_type",
136            "certificate_download_url",
137            "private_key_download_url",
138            "managed",
139        ]
140        extra_kwargs = {
141            "managed": {"read_only": True},
142            "key_data": {"write_only": True},
143            "certificate_data": {"write_only": True},
144            "fingerprint_sha256": {"read_only": True},
145            "fingerprint_sha1": {"read_only": True},
146            "cert_expiry": {"read_only": True},
147            "cert_subject": {"read_only": True},
148            "key_type": {"read_only": True},
149        }
150
151
152class CertificateDataSerializer(PassiveSerializer):
153    """Get CertificateKeyPair's data"""
154
155    data = CharField(read_only=True)
156
157
158class CertificateGenerationSerializer(PassiveSerializer):
159    """Certificate generation parameters"""
160
161    common_name = CharField(
162        validators=[UniqueValidator(queryset=CertificateKeyPair.objects.all())],
163        source="name",
164    )
165    subject_alt_name = CharField(required=False, allow_blank=True, label=_("Subject-alt name"))
166    validity_days = IntegerField(initial=365)
167    alg = ChoiceField(default=PrivateKeyAlg.RSA, choices=PrivateKeyAlg.choices)
168
169
170class CertificateKeyPairFilter(FilterSet):
171    """Filter for certificates"""
172
173    has_key = BooleanFilter(
174        label="Only return certificate-key pairs with keys", method="filter_has_key"
175    )
176
177    key_type = MultipleChoiceFilter(
178        choices=KeyType.choices,
179        label="Filter by key algorithm type",
180        method="filter_key_type",
181    )
182
183    def filter_has_key(self, queryset, name, value):  # pragma: no cover
184        """Only return certificate-key pairs with keys"""
185        if not value:
186            return queryset
187        return queryset.exclude(key_data__exact="")
188
189    def filter_key_type(self, queryset, name, value):  # pragma: no cover
190        """Filter certificates by key type using the stored database field"""
191        if not value:
192            return queryset
193
194        # value is a list of KeyType enum values from MultipleChoiceFilter
195        return queryset.filter(key_type__in=value)
196
197    class Meta:
198        model = CertificateKeyPair
199        fields = ["name", "managed"]
200
201
202class CertificateKeyPairViewSet(UsedByMixin, ModelViewSet):
203    """CertificateKeyPair Viewset"""
204
205    queryset = CertificateKeyPair.objects.exclude(managed=MANAGED_KEY)
206    serializer_class = CertificateKeyPairSerializer
207    filterset_class = CertificateKeyPairFilter
208    ordering = ["name"]
209    search_fields = ["name"]
210    filter_backends = [SecretKeyFilter, OrderingFilter, SearchFilter]
211
212    @extend_schema(
213        parameters=[
214            # Override the type for `has_key` above
215            OpenApiParameter(
216                "has_key",
217                bool,
218                required=False,
219                description="Only return certificate-key pairs with keys",
220            ),
221            OpenApiParameter(
222                "key_type",
223                OpenApiTypes.STR,
224                required=False,
225                many=True,
226                enum=[choice[0] for choice in KeyType.choices],
227                description=(
228                    "Filter by key algorithm type (RSA, EC, DSA, etc). "
229                    "Can be specified multiple times (e.g. '?key_type=rsa&key_type=ec')"
230                ),
231            ),
232        ]
233    )
234    def list(self, request, *args, **kwargs):
235        return super().list(request, *args, **kwargs)
236
237    @permission_required(None, ["authentik_crypto.add_certificatekeypair"])
238    @extend_schema(
239        request=CertificateGenerationSerializer(),
240        responses={
241            200: CertificateKeyPairSerializer,
242            400: OpenApiResponse(description="Bad request"),
243        },
244    )
245    @action(detail=False, methods=["POST"])
246    @validate(CertificateGenerationSerializer)
247    def generate(self, request: Request, body: CertificateGenerationSerializer) -> Response:
248        """Generate a new, self-signed certificate-key pair"""
249        raw_san = body.validated_data.get("subject_alt_name", "")
250        sans = raw_san.split(",") if raw_san != "" else []
251        builder = CertificateBuilder(body.validated_data["name"])
252        builder.alg = body.validated_data["alg"]
253        try:
254            builder.build(
255                subject_alt_names=sans,
256                validity_days=int(body.validated_data["validity_days"]),
257            )
258        except KeyAlgorithmUnavailableError as exc:
259            # TODO: Remove when OpenSSL/FIPS is updated
260            # Raised when the selected algorithm cannot be generated in the current OpenSSL
261            # configuration, for example ML-DSA under the validated FIPS provider.
262            LOGGER.warning("Failed to generate certificate keypair", error=str(exc))
263            raise ValidationError(
264                {
265                    "alg": [
266                        _("The selected algorithm is not supported in the current configuration.")
267                    ]
268                }
269            ) from exc
270        instance = builder.save()
271        serializer = self.get_serializer(instance)
272        return Response(serializer.data)
273
274    @permission_required("view_certificatekeypair_certificate")
275    @extend_schema(
276        parameters=[
277            OpenApiParameter(
278                name="download",
279                location=OpenApiParameter.QUERY,
280                type=OpenApiTypes.BOOL,
281            )
282        ],
283        responses={200: CertificateDataSerializer(many=False)},
284    )
285    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
286    def view_certificate(self, request: Request, pk: str) -> Response:
287        """Return certificate-key pairs certificate and log access"""
288        certificate: CertificateKeyPair = self.get_object()
289        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
290            Event.new(  # noqa # nosec
291                EventAction.SECRET_VIEW,
292                secret=certificate,
293                type="certificate",
294            ).from_http(request)
295        if "download" in request.query_params:
296            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
297            response = HttpResponse(
298                certificate.certificate_data, content_type="application/x-pem-file"
299            )
300            response["Content-Disposition"] = (
301                f'attachment; filename="{certificate.name}_certificate.pem"'
302            )
303            return response
304        return Response(CertificateDataSerializer({"data": certificate.certificate_data}).data)
305
306    @permission_required("view_certificatekeypair_key")
307    @extend_schema(
308        parameters=[
309            OpenApiParameter(
310                name="download",
311                location=OpenApiParameter.QUERY,
312                type=OpenApiTypes.BOOL,
313            )
314        ],
315        responses={200: CertificateDataSerializer(many=False)},
316    )
317    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
318    def view_private_key(self, request: Request, pk: str) -> Response:
319        """Return certificate-key pairs private key and log access"""
320        certificate: CertificateKeyPair = self.get_object()
321        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
322            Event.new(  # noqa # nosec
323                EventAction.SECRET_VIEW,
324                secret=certificate,
325                type="private_key",
326            ).from_http(request)
327        if "download" in request.query_params:
328            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
329            response = HttpResponse(certificate.key_data, content_type="application/x-pem-file")
330            response["Content-Disposition"] = (
331                f'attachment; filename="{certificate.name}_private_key.pem"'
332            )
333            return response
334        return Response(CertificateDataSerializer({"data": certificate.key_data}).data)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class CertificateKeyPairSerializer(authentik.core.api.utils.ModelSerializer):
 53class CertificateKeyPairSerializer(ModelSerializer):
 54    """CertificateKeyPair Serializer"""
 55
 56    private_key_available = SerializerMethodField()
 57
 58    certificate_download_url = SerializerMethodField()
 59    private_key_download_url = SerializerMethodField()
 60
 61    def get_private_key_available(self, instance: CertificateKeyPair) -> bool:
 62        """Show if this keypair has a private key configured or not"""
 63        return instance.key_data != "" and instance.key_data is not None
 64
 65    def get_certificate_download_url(self, instance: CertificateKeyPair) -> str:
 66        """Get URL to download certificate"""
 67        return (
 68            reverse(
 69                "authentik_api:certificatekeypair-view-certificate",
 70                kwargs={"pk": instance.pk},
 71            )
 72            + "?download"
 73        )
 74
 75    def get_private_key_download_url(self, instance: CertificateKeyPair) -> str:
 76        """Get URL to download private key"""
 77        return (
 78            reverse(
 79                "authentik_api:certificatekeypair-view-private-key",
 80                kwargs={"pk": instance.pk},
 81            )
 82            + "?download"
 83        )
 84
 85    def validate_certificate_data(self, value: str) -> str:
 86        """Verify that input is a valid PEM x509 Certificate"""
 87        try:
 88            # Cast to string to fully load and parse certificate
 89            # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
 90            str(load_pem_x509_certificate(value.encode("utf-8"), default_backend()))
 91        except ValueError as exc:
 92            LOGGER.warning("Failed to load certificate", exc=exc)
 93            raise ValidationError("Unable to load certificate.") from None
 94        return value
 95
 96    def validate_key_data(self, value: str) -> str:
 97        """Verify that input is a valid PEM Key"""
 98        # Since this field is optional, data can be empty.
 99        if value != "":
100            try:
101                # Cast to string to fully load and parse certificate
102                # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
103                str(
104                    load_pem_private_key(
105                        str.encode("\n".join([x.strip() for x in value.split("\n")])),
106                        password=None,
107                        backend=default_backend(),
108                    )
109                )
110            except (ValueError, TypeError) as exc:
111                LOGGER.warning("Failed to load private key", exc=exc)
112                raise ValidationError("Unable to load private key (possibly encrypted?).") from None
113            except (InternalError, UnsupportedAlgorithm) as exc:
114                # TODO: Remove when OpenSSL/FIPS is updated
115                # OpenSSL has no implementation for this key type in the current configuration,
116                # for example an ML-DSA key with a FIPS provider that predates ML-DSA
117                LOGGER.warning("Private key algorithm not available", exc=exc)
118                raise ValidationError(
119                    "The private key's algorithm is not available in the current OpenSSL "
120                    "configuration (for example ML-DSA in FIPS mode)."
121                ) from None
122        return value
123
124    class Meta:
125        model = CertificateKeyPair
126        fields = [
127            "pk",
128            "name",
129            "fingerprint_sha256",
130            "fingerprint_sha1",
131            "certificate_data",
132            "key_data",
133            "cert_expiry",
134            "cert_subject",
135            "private_key_available",
136            "key_type",
137            "certificate_download_url",
138            "private_key_download_url",
139            "managed",
140        ]
141        extra_kwargs = {
142            "managed": {"read_only": True},
143            "key_data": {"write_only": True},
144            "certificate_data": {"write_only": True},
145            "fingerprint_sha256": {"read_only": True},
146            "fingerprint_sha1": {"read_only": True},
147            "cert_expiry": {"read_only": True},
148            "cert_subject": {"read_only": True},
149            "key_type": {"read_only": True},
150        }

CertificateKeyPair Serializer

private_key_available
certificate_download_url
private_key_download_url
def get_private_key_available(self, instance: authentik.crypto.models.CertificateKeyPair) -> bool:
61    def get_private_key_available(self, instance: CertificateKeyPair) -> bool:
62        """Show if this keypair has a private key configured or not"""
63        return instance.key_data != "" and instance.key_data is not None

Show if this keypair has a private key configured or not

def get_certificate_download_url(self, instance: authentik.crypto.models.CertificateKeyPair) -> str:
65    def get_certificate_download_url(self, instance: CertificateKeyPair) -> str:
66        """Get URL to download certificate"""
67        return (
68            reverse(
69                "authentik_api:certificatekeypair-view-certificate",
70                kwargs={"pk": instance.pk},
71            )
72            + "?download"
73        )

Get URL to download certificate

def get_private_key_download_url(self, instance: authentik.crypto.models.CertificateKeyPair) -> str:
75    def get_private_key_download_url(self, instance: CertificateKeyPair) -> str:
76        """Get URL to download private key"""
77        return (
78            reverse(
79                "authentik_api:certificatekeypair-view-private-key",
80                kwargs={"pk": instance.pk},
81            )
82            + "?download"
83        )

Get URL to download private key

def validate_certificate_data(self, value: str) -> str:
85    def validate_certificate_data(self, value: str) -> str:
86        """Verify that input is a valid PEM x509 Certificate"""
87        try:
88            # Cast to string to fully load and parse certificate
89            # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
90            str(load_pem_x509_certificate(value.encode("utf-8"), default_backend()))
91        except ValueError as exc:
92            LOGGER.warning("Failed to load certificate", exc=exc)
93            raise ValidationError("Unable to load certificate.") from None
94        return value

Verify that input is a valid PEM x509 Certificate

def validate_key_data(self, value: str) -> str:
 96    def validate_key_data(self, value: str) -> str:
 97        """Verify that input is a valid PEM Key"""
 98        # Since this field is optional, data can be empty.
 99        if value != "":
100            try:
101                # Cast to string to fully load and parse certificate
102                # Prevents issues like https://github.com/goauthentik/authentik/issues/2082
103                str(
104                    load_pem_private_key(
105                        str.encode("\n".join([x.strip() for x in value.split("\n")])),
106                        password=None,
107                        backend=default_backend(),
108                    )
109                )
110            except (ValueError, TypeError) as exc:
111                LOGGER.warning("Failed to load private key", exc=exc)
112                raise ValidationError("Unable to load private key (possibly encrypted?).") from None
113            except (InternalError, UnsupportedAlgorithm) as exc:
114                # TODO: Remove when OpenSSL/FIPS is updated
115                # OpenSSL has no implementation for this key type in the current configuration,
116                # for example an ML-DSA key with a FIPS provider that predates ML-DSA
117                LOGGER.warning("Private key algorithm not available", exc=exc)
118                raise ValidationError(
119                    "The private key's algorithm is not available in the current OpenSSL "
120                    "configuration (for example ML-DSA in FIPS mode)."
121                ) from None
122        return value

Verify that input is a valid PEM Key

class CertificateKeyPairSerializer.Meta:
124    class Meta:
125        model = CertificateKeyPair
126        fields = [
127            "pk",
128            "name",
129            "fingerprint_sha256",
130            "fingerprint_sha1",
131            "certificate_data",
132            "key_data",
133            "cert_expiry",
134            "cert_subject",
135            "private_key_available",
136            "key_type",
137            "certificate_download_url",
138            "private_key_download_url",
139            "managed",
140        ]
141        extra_kwargs = {
142            "managed": {"read_only": True},
143            "key_data": {"write_only": True},
144            "certificate_data": {"write_only": True},
145            "fingerprint_sha256": {"read_only": True},
146            "fingerprint_sha1": {"read_only": True},
147            "cert_expiry": {"read_only": True},
148            "cert_subject": {"read_only": True},
149            "key_type": {"read_only": True},
150        }
fields = ['pk', 'name', 'fingerprint_sha256', 'fingerprint_sha1', 'certificate_data', 'key_data', 'cert_expiry', 'cert_subject', 'private_key_available', 'key_type', 'certificate_download_url', 'private_key_download_url', 'managed']
extra_kwargs = {'managed': {'read_only': True}, 'key_data': {'write_only': True}, 'certificate_data': {'write_only': True}, 'fingerprint_sha256': {'read_only': True}, 'fingerprint_sha1': {'read_only': True}, 'cert_expiry': {'read_only': True}, 'cert_subject': {'read_only': True}, 'key_type': {'read_only': True}}
class CertificateDataSerializer(authentik.core.api.utils.PassiveSerializer):
153class CertificateDataSerializer(PassiveSerializer):
154    """Get CertificateKeyPair's data"""
155
156    data = CharField(read_only=True)

Get CertificateKeyPair's data

data
584    @property
585    def data(self):
586        ret = super().data
587        return ReturnDict(ret, serializer=self)
class CertificateGenerationSerializer(authentik.core.api.utils.PassiveSerializer):
159class CertificateGenerationSerializer(PassiveSerializer):
160    """Certificate generation parameters"""
161
162    common_name = CharField(
163        validators=[UniqueValidator(queryset=CertificateKeyPair.objects.all())],
164        source="name",
165    )
166    subject_alt_name = CharField(required=False, allow_blank=True, label=_("Subject-alt name"))
167    validity_days = IntegerField(initial=365)
168    alg = ChoiceField(default=PrivateKeyAlg.RSA, choices=PrivateKeyAlg.choices)

Certificate generation parameters

common_name
subject_alt_name
validity_days
alg
class CertificateKeyPairFilter(django_filters.filterset.FilterSet):
171class CertificateKeyPairFilter(FilterSet):
172    """Filter for certificates"""
173
174    has_key = BooleanFilter(
175        label="Only return certificate-key pairs with keys", method="filter_has_key"
176    )
177
178    key_type = MultipleChoiceFilter(
179        choices=KeyType.choices,
180        label="Filter by key algorithm type",
181        method="filter_key_type",
182    )
183
184    def filter_has_key(self, queryset, name, value):  # pragma: no cover
185        """Only return certificate-key pairs with keys"""
186        if not value:
187            return queryset
188        return queryset.exclude(key_data__exact="")
189
190    def filter_key_type(self, queryset, name, value):  # pragma: no cover
191        """Filter certificates by key type using the stored database field"""
192        if not value:
193            return queryset
194
195        # value is a list of KeyType enum values from MultipleChoiceFilter
196        return queryset.filter(key_type__in=value)
197
198    class Meta:
199        model = CertificateKeyPair
200        fields = ["name", "managed"]

Filter for certificates

has_key
key_type
def filter_has_key(self, queryset, name, value):
184    def filter_has_key(self, queryset, name, value):  # pragma: no cover
185        """Only return certificate-key pairs with keys"""
186        if not value:
187            return queryset
188        return queryset.exclude(key_data__exact="")

Only return certificate-key pairs with keys

def filter_key_type(self, queryset, name, value):
190    def filter_key_type(self, queryset, name, value):  # pragma: no cover
191        """Filter certificates by key type using the stored database field"""
192        if not value:
193            return queryset
194
195        # value is a list of KeyType enum values from MultipleChoiceFilter
196        return queryset.filter(key_type__in=value)

Filter certificates by key type using the stored database field

declared_filters = OrderedDict({'has_key': <django_filters.filters.BooleanFilter object>, 'key_type': <django_filters.filters.MultipleChoiceFilter object>})
base_filters = OrderedDict({'name': <django_filters.filters.CharFilter object>, 'managed': <django_filters.filters.CharFilter object>, 'has_key': <django_filters.filters.BooleanFilter object>, 'key_type': <django_filters.filters.MultipleChoiceFilter object>})
class CertificateKeyPairFilter.Meta:
198    class Meta:
199        model = CertificateKeyPair
200        fields = ["name", "managed"]
fields = ['name', 'managed']
class CertificateKeyPairViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
203class CertificateKeyPairViewSet(UsedByMixin, ModelViewSet):
204    """CertificateKeyPair Viewset"""
205
206    queryset = CertificateKeyPair.objects.exclude(managed=MANAGED_KEY)
207    serializer_class = CertificateKeyPairSerializer
208    filterset_class = CertificateKeyPairFilter
209    ordering = ["name"]
210    search_fields = ["name"]
211    filter_backends = [SecretKeyFilter, OrderingFilter, SearchFilter]
212
213    @extend_schema(
214        parameters=[
215            # Override the type for `has_key` above
216            OpenApiParameter(
217                "has_key",
218                bool,
219                required=False,
220                description="Only return certificate-key pairs with keys",
221            ),
222            OpenApiParameter(
223                "key_type",
224                OpenApiTypes.STR,
225                required=False,
226                many=True,
227                enum=[choice[0] for choice in KeyType.choices],
228                description=(
229                    "Filter by key algorithm type (RSA, EC, DSA, etc). "
230                    "Can be specified multiple times (e.g. '?key_type=rsa&key_type=ec')"
231                ),
232            ),
233        ]
234    )
235    def list(self, request, *args, **kwargs):
236        return super().list(request, *args, **kwargs)
237
238    @permission_required(None, ["authentik_crypto.add_certificatekeypair"])
239    @extend_schema(
240        request=CertificateGenerationSerializer(),
241        responses={
242            200: CertificateKeyPairSerializer,
243            400: OpenApiResponse(description="Bad request"),
244        },
245    )
246    @action(detail=False, methods=["POST"])
247    @validate(CertificateGenerationSerializer)
248    def generate(self, request: Request, body: CertificateGenerationSerializer) -> Response:
249        """Generate a new, self-signed certificate-key pair"""
250        raw_san = body.validated_data.get("subject_alt_name", "")
251        sans = raw_san.split(",") if raw_san != "" else []
252        builder = CertificateBuilder(body.validated_data["name"])
253        builder.alg = body.validated_data["alg"]
254        try:
255            builder.build(
256                subject_alt_names=sans,
257                validity_days=int(body.validated_data["validity_days"]),
258            )
259        except KeyAlgorithmUnavailableError as exc:
260            # TODO: Remove when OpenSSL/FIPS is updated
261            # Raised when the selected algorithm cannot be generated in the current OpenSSL
262            # configuration, for example ML-DSA under the validated FIPS provider.
263            LOGGER.warning("Failed to generate certificate keypair", error=str(exc))
264            raise ValidationError(
265                {
266                    "alg": [
267                        _("The selected algorithm is not supported in the current configuration.")
268                    ]
269                }
270            ) from exc
271        instance = builder.save()
272        serializer = self.get_serializer(instance)
273        return Response(serializer.data)
274
275    @permission_required("view_certificatekeypair_certificate")
276    @extend_schema(
277        parameters=[
278            OpenApiParameter(
279                name="download",
280                location=OpenApiParameter.QUERY,
281                type=OpenApiTypes.BOOL,
282            )
283        ],
284        responses={200: CertificateDataSerializer(many=False)},
285    )
286    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
287    def view_certificate(self, request: Request, pk: str) -> Response:
288        """Return certificate-key pairs certificate and log access"""
289        certificate: CertificateKeyPair = self.get_object()
290        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
291            Event.new(  # noqa # nosec
292                EventAction.SECRET_VIEW,
293                secret=certificate,
294                type="certificate",
295            ).from_http(request)
296        if "download" in request.query_params:
297            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
298            response = HttpResponse(
299                certificate.certificate_data, content_type="application/x-pem-file"
300            )
301            response["Content-Disposition"] = (
302                f'attachment; filename="{certificate.name}_certificate.pem"'
303            )
304            return response
305        return Response(CertificateDataSerializer({"data": certificate.certificate_data}).data)
306
307    @permission_required("view_certificatekeypair_key")
308    @extend_schema(
309        parameters=[
310            OpenApiParameter(
311                name="download",
312                location=OpenApiParameter.QUERY,
313                type=OpenApiTypes.BOOL,
314            )
315        ],
316        responses={200: CertificateDataSerializer(many=False)},
317    )
318    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
319    def view_private_key(self, request: Request, pk: str) -> Response:
320        """Return certificate-key pairs private key and log access"""
321        certificate: CertificateKeyPair = self.get_object()
322        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
323            Event.new(  # noqa # nosec
324                EventAction.SECRET_VIEW,
325                secret=certificate,
326                type="private_key",
327            ).from_http(request)
328        if "download" in request.query_params:
329            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
330            response = HttpResponse(certificate.key_data, content_type="application/x-pem-file")
331            response["Content-Disposition"] = (
332                f'attachment; filename="{certificate.name}_private_key.pem"'
333            )
334            return response
335        return Response(CertificateDataSerializer({"data": certificate.key_data}).data)

CertificateKeyPair Viewset

queryset = <QuerySet []>
serializer_class = <class 'CertificateKeyPairSerializer'>
filterset_class = <class 'CertificateKeyPairFilter'>
ordering = ['name']
search_fields = ['name']
filter_backends = [<class 'authentik.rbac.filters.SecretKeyFilter'>, <class 'rest_framework.filters.OrderingFilter'>, <class 'rest_framework.filters.SearchFilter'>]
@extend_schema(parameters=[OpenApiParameter('has_key', bool, required=False, description='Only return certificate-key pairs with keys'), OpenApiParameter('key_type', OpenApiTypes.STR, required=False, many=True, enum=[choice[0] for choice in KeyType.choices], description="Filter by key algorithm type (RSA, EC, DSA, etc). Can be specified multiple times (e.g. '?key_type=rsa&key_type=ec')")])
def list(self, request, *args, **kwargs):
213    @extend_schema(
214        parameters=[
215            # Override the type for `has_key` above
216            OpenApiParameter(
217                "has_key",
218                bool,
219                required=False,
220                description="Only return certificate-key pairs with keys",
221            ),
222            OpenApiParameter(
223                "key_type",
224                OpenApiTypes.STR,
225                required=False,
226                many=True,
227                enum=[choice[0] for choice in KeyType.choices],
228                description=(
229                    "Filter by key algorithm type (RSA, EC, DSA, etc). "
230                    "Can be specified multiple times (e.g. '?key_type=rsa&key_type=ec')"
231                ),
232            ),
233        ]
234    )
235    def list(self, request, *args, **kwargs):
236        return super().list(request, *args, **kwargs)
@permission_required(None, ['authentik_crypto.add_certificatekeypair'])
@extend_schema(request=CertificateGenerationSerializer(), responses={200: CertificateKeyPairSerializer, 400: OpenApiResponse(description='Bad request')})
@action(detail=False, methods=['POST'])
@validate(CertificateGenerationSerializer)
def generate( self, request: rest_framework.request.Request, body: CertificateGenerationSerializer) -> rest_framework.response.Response:
238    @permission_required(None, ["authentik_crypto.add_certificatekeypair"])
239    @extend_schema(
240        request=CertificateGenerationSerializer(),
241        responses={
242            200: CertificateKeyPairSerializer,
243            400: OpenApiResponse(description="Bad request"),
244        },
245    )
246    @action(detail=False, methods=["POST"])
247    @validate(CertificateGenerationSerializer)
248    def generate(self, request: Request, body: CertificateGenerationSerializer) -> Response:
249        """Generate a new, self-signed certificate-key pair"""
250        raw_san = body.validated_data.get("subject_alt_name", "")
251        sans = raw_san.split(",") if raw_san != "" else []
252        builder = CertificateBuilder(body.validated_data["name"])
253        builder.alg = body.validated_data["alg"]
254        try:
255            builder.build(
256                subject_alt_names=sans,
257                validity_days=int(body.validated_data["validity_days"]),
258            )
259        except KeyAlgorithmUnavailableError as exc:
260            # TODO: Remove when OpenSSL/FIPS is updated
261            # Raised when the selected algorithm cannot be generated in the current OpenSSL
262            # configuration, for example ML-DSA under the validated FIPS provider.
263            LOGGER.warning("Failed to generate certificate keypair", error=str(exc))
264            raise ValidationError(
265                {
266                    "alg": [
267                        _("The selected algorithm is not supported in the current configuration.")
268                    ]
269                }
270            ) from exc
271        instance = builder.save()
272        serializer = self.get_serializer(instance)
273        return Response(serializer.data)

Generate a new, self-signed certificate-key pair

@permission_required('view_certificatekeypair_certificate')
@extend_schema(parameters=[OpenApiParameter(name='download', location=OpenApiParameter.QUERY, type=OpenApiTypes.BOOL)], responses={200: CertificateDataSerializer(many=False)})
@action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
def view_certificate( self, request: rest_framework.request.Request, pk: str) -> rest_framework.response.Response:
275    @permission_required("view_certificatekeypair_certificate")
276    @extend_schema(
277        parameters=[
278            OpenApiParameter(
279                name="download",
280                location=OpenApiParameter.QUERY,
281                type=OpenApiTypes.BOOL,
282            )
283        ],
284        responses={200: CertificateDataSerializer(many=False)},
285    )
286    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
287    def view_certificate(self, request: Request, pk: str) -> Response:
288        """Return certificate-key pairs certificate and log access"""
289        certificate: CertificateKeyPair = self.get_object()
290        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
291            Event.new(  # noqa # nosec
292                EventAction.SECRET_VIEW,
293                secret=certificate,
294                type="certificate",
295            ).from_http(request)
296        if "download" in request.query_params:
297            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
298            response = HttpResponse(
299                certificate.certificate_data, content_type="application/x-pem-file"
300            )
301            response["Content-Disposition"] = (
302                f'attachment; filename="{certificate.name}_certificate.pem"'
303            )
304            return response
305        return Response(CertificateDataSerializer({"data": certificate.certificate_data}).data)

Return certificate-key pairs certificate and log access

@permission_required('view_certificatekeypair_key')
@extend_schema(parameters=[OpenApiParameter(name='download', location=OpenApiParameter.QUERY, type=OpenApiTypes.BOOL)], responses={200: CertificateDataSerializer(many=False)})
@action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
def view_private_key( self, request: rest_framework.request.Request, pk: str) -> rest_framework.response.Response:
307    @permission_required("view_certificatekeypair_key")
308    @extend_schema(
309        parameters=[
310            OpenApiParameter(
311                name="download",
312                location=OpenApiParameter.QUERY,
313                type=OpenApiTypes.BOOL,
314            )
315        ],
316        responses={200: CertificateDataSerializer(many=False)},
317    )
318    @action(detail=True, pagination_class=None, permission_classes=[IsAuthenticated])
319    def view_private_key(self, request: Request, pk: str) -> Response:
320        """Return certificate-key pairs private key and log access"""
321        certificate: CertificateKeyPair = self.get_object()
322        if request.user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
323            Event.new(  # noqa # nosec
324                EventAction.SECRET_VIEW,
325                secret=certificate,
326                type="private_key",
327            ).from_http(request)
328        if "download" in request.query_params:
329            # Mime type from https://pki-tutorial.readthedocs.io/en/latest/mime.html
330            response = HttpResponse(certificate.key_data, content_type="application/x-pem-file")
331            response["Content-Disposition"] = (
332                f'attachment; filename="{certificate.name}_private_key.pem"'
333            )
334            return response
335        return Response(CertificateDataSerializer({"data": certificate.key_data}).data)

Return certificate-key pairs private key and log access

name = None
description = None
suffix = None
detail = None
basename = None