authentik.outposts.api.service_connections

Outpost API Views

  1"""Outpost API Views"""
  2
  3from dataclasses import asdict
  4
  5from django.utils.translation import gettext_lazy as _
  6from drf_spectacular.utils import extend_schema
  7from rest_framework import mixins, serializers
  8from rest_framework.decorators import action
  9from rest_framework.fields import BooleanField, CharField, ReadOnlyField
 10from rest_framework.request import Request
 11from rest_framework.response import Response
 12from rest_framework.viewsets import GenericViewSet, ModelViewSet
 13
 14from authentik.core.api.object_types import TypesMixin
 15from authentik.core.api.used_by import UsedByMixin
 16from authentik.core.api.utils import (
 17    MetaNameSerializer,
 18    ModelSerializer,
 19    PassiveSerializer,
 20)
 21from authentik.outposts.models import (
 22    DockerServiceConnection,
 23    KubernetesServiceConnection,
 24    OutpostServiceConnection,
 25)
 26from authentik.rbac.filters import ObjectFilter
 27
 28
 29class ServiceConnectionSerializer(ModelSerializer, MetaNameSerializer):
 30    """ServiceConnection Serializer"""
 31
 32    component = ReadOnlyField()
 33
 34    def get_component(self, obj: OutpostServiceConnection) -> str:
 35        """Get object type so that we know how to edit the object"""
 36        if obj.__class__ == OutpostServiceConnection:
 37            return ""
 38        return obj.component
 39
 40    class Meta:
 41        model = OutpostServiceConnection
 42        fields = [
 43            "pk",
 44            "name",
 45            "local",
 46            "component",
 47            "verbose_name",
 48            "verbose_name_plural",
 49            "meta_model_name",
 50        ]
 51
 52
 53class ServiceConnectionStateSerializer(PassiveSerializer):
 54    """Serializer for Service connection state"""
 55
 56    healthy = BooleanField(read_only=True)
 57    version = CharField(read_only=True)
 58
 59
 60class ServiceConnectionViewSet(
 61    TypesMixin,
 62    mixins.RetrieveModelMixin,
 63    mixins.DestroyModelMixin,
 64    UsedByMixin,
 65    mixins.ListModelMixin,
 66    GenericViewSet,
 67):
 68    """ServiceConnection Viewset"""
 69
 70    queryset = OutpostServiceConnection.objects.select_subclasses()
 71    serializer_class = ServiceConnectionSerializer
 72    search_fields = ["name"]
 73    filterset_fields = ["name"]
 74
 75    @extend_schema(responses={200: ServiceConnectionStateSerializer(many=False)})
 76    @action(detail=True, pagination_class=None, filter_backends=[ObjectFilter])
 77    def state(self, request: Request, pk: str) -> Response:
 78        """Get the service connection's state"""
 79        connection = self.get_object()
 80        return Response(asdict(connection.state))
 81
 82
 83class DockerServiceConnectionSerializer(ServiceConnectionSerializer):
 84    """DockerServiceConnection Serializer"""
 85
 86    class Meta:
 87        model = DockerServiceConnection
 88        fields = ServiceConnectionSerializer.Meta.fields + [
 89            "url",
 90            "tls_verification",
 91            "tls_authentication",
 92        ]
 93
 94
 95class DockerServiceConnectionViewSet(UsedByMixin, ModelViewSet):
 96    """DockerServiceConnection Viewset"""
 97
 98    queryset = DockerServiceConnection.objects.all()
 99    serializer_class = DockerServiceConnectionSerializer
100    filterset_fields = ["name", "local", "url", "tls_verification", "tls_authentication"]
101    ordering = ["name"]
102    search_fields = ["name"]
103
104
105class KubernetesServiceConnectionSerializer(ServiceConnectionSerializer):
106    """KubernetesServiceConnection Serializer"""
107
108    def validate_kubeconfig(self, kubeconfig):
109        """Validate kubeconfig by attempting to load it"""
110        if kubeconfig == {}:
111            if not self.initial_data["local"]:
112                raise serializers.ValidationError(
113                    _("You can only use an empty kubeconfig when connecting to a local cluster.")
114                )
115            # Empty kubeconfig is valid
116            return kubeconfig
117        from kubernetes.client.configuration import Configuration
118        from kubernetes.config.config_exception import ConfigException
119        from kubernetes.config.kube_config import load_kube_config_from_dict
120
121        from authentik.outposts.controllers.kubernetes import check_kubeconfig_user
122
123        config = Configuration()
124        try:
125            check_kubeconfig_user(kubeconfig)
126            load_kube_config_from_dict(kubeconfig, client_configuration=config)
127        except ConfigException:
128            raise serializers.ValidationError(_("Invalid kubeconfig")) from None
129        return kubeconfig
130
131    class Meta:
132        model = KubernetesServiceConnection
133        fields = ServiceConnectionSerializer.Meta.fields + ["kubeconfig", "verify_ssl"]
134        secret_fields = ["kubeconfig"]
135
136
137class KubernetesServiceConnectionViewSet(UsedByMixin, ModelViewSet):
138    """KubernetesServiceConnection Viewset"""
139
140    queryset = KubernetesServiceConnection.objects.all()
141    serializer_class = KubernetesServiceConnectionSerializer
142    filterset_fields = ["name", "local"]
143    ordering = ["name"]
144    search_fields = ["name"]
30class ServiceConnectionSerializer(ModelSerializer, MetaNameSerializer):
31    """ServiceConnection Serializer"""
32
33    component = ReadOnlyField()
34
35    def get_component(self, obj: OutpostServiceConnection) -> str:
36        """Get object type so that we know how to edit the object"""
37        if obj.__class__ == OutpostServiceConnection:
38            return ""
39        return obj.component
40
41    class Meta:
42        model = OutpostServiceConnection
43        fields = [
44            "pk",
45            "name",
46            "local",
47            "component",
48            "verbose_name",
49            "verbose_name_plural",
50            "meta_model_name",
51        ]

ServiceConnection Serializer

component
def get_component(self, obj: authentik.outposts.models.OutpostServiceConnection) -> str:
35    def get_component(self, obj: OutpostServiceConnection) -> str:
36        """Get object type so that we know how to edit the object"""
37        if obj.__class__ == OutpostServiceConnection:
38            return ""
39        return obj.component

Get object type so that we know how to edit the object

class ServiceConnectionSerializer.Meta:
41    class Meta:
42        model = OutpostServiceConnection
43        fields = [
44            "pk",
45            "name",
46            "local",
47            "component",
48            "verbose_name",
49            "verbose_name_plural",
50            "meta_model_name",
51        ]
fields = ['pk', 'name', 'local', 'component', 'verbose_name', 'verbose_name_plural', 'meta_model_name']
class ServiceConnectionStateSerializer(authentik.core.api.utils.PassiveSerializer):
54class ServiceConnectionStateSerializer(PassiveSerializer):
55    """Serializer for Service connection state"""
56
57    healthy = BooleanField(read_only=True)
58    version = CharField(read_only=True)

Serializer for Service connection state

healthy
version
class ServiceConnectionViewSet(authentik.core.api.object_types.TypesMixin, rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.DestroyModelMixin, authentik.core.api.used_by.UsedByMixin, rest_framework.mixins.ListModelMixin, rest_framework.viewsets.GenericViewSet):
61class ServiceConnectionViewSet(
62    TypesMixin,
63    mixins.RetrieveModelMixin,
64    mixins.DestroyModelMixin,
65    UsedByMixin,
66    mixins.ListModelMixin,
67    GenericViewSet,
68):
69    """ServiceConnection Viewset"""
70
71    queryset = OutpostServiceConnection.objects.select_subclasses()
72    serializer_class = ServiceConnectionSerializer
73    search_fields = ["name"]
74    filterset_fields = ["name"]
75
76    @extend_schema(responses={200: ServiceConnectionStateSerializer(many=False)})
77    @action(detail=True, pagination_class=None, filter_backends=[ObjectFilter])
78    def state(self, request: Request, pk: str) -> Response:
79        """Get the service connection's state"""
80        connection = self.get_object()
81        return Response(asdict(connection.state))

ServiceConnection Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'ServiceConnectionSerializer'>
search_fields = ['name']
filterset_fields = ['name']
@extend_schema(responses={200: ServiceConnectionStateSerializer(many=False)})
@action(detail=True, pagination_class=None, filter_backends=[ObjectFilter])
def state( self, request: rest_framework.request.Request, pk: str) -> rest_framework.response.Response:
76    @extend_schema(responses={200: ServiceConnectionStateSerializer(many=False)})
77    @action(detail=True, pagination_class=None, filter_backends=[ObjectFilter])
78    def state(self, request: Request, pk: str) -> Response:
79        """Get the service connection's state"""
80        connection = self.get_object()
81        return Response(asdict(connection.state))

Get the service connection's state

name = None
description = None
suffix = None
detail = None
basename = None
class DockerServiceConnectionSerializer(ServiceConnectionSerializer):
84class DockerServiceConnectionSerializer(ServiceConnectionSerializer):
85    """DockerServiceConnection Serializer"""
86
87    class Meta:
88        model = DockerServiceConnection
89        fields = ServiceConnectionSerializer.Meta.fields + [
90            "url",
91            "tls_verification",
92            "tls_authentication",
93        ]

DockerServiceConnection Serializer

class DockerServiceConnectionSerializer.Meta:
87    class Meta:
88        model = DockerServiceConnection
89        fields = ServiceConnectionSerializer.Meta.fields + [
90            "url",
91            "tls_verification",
92            "tls_authentication",
93        ]
fields = ['pk', 'name', 'local', 'component', 'verbose_name', 'verbose_name_plural', 'meta_model_name', 'url', 'tls_verification', 'tls_authentication']
class DockerServiceConnectionViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
 96class DockerServiceConnectionViewSet(UsedByMixin, ModelViewSet):
 97    """DockerServiceConnection Viewset"""
 98
 99    queryset = DockerServiceConnection.objects.all()
100    serializer_class = DockerServiceConnectionSerializer
101    filterset_fields = ["name", "local", "url", "tls_verification", "tls_authentication"]
102    ordering = ["name"]
103    search_fields = ["name"]

DockerServiceConnection Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'DockerServiceConnectionSerializer'>
filterset_fields = ['name', 'local', 'url', 'tls_verification', 'tls_authentication']
ordering = ['name']
search_fields = ['name']
name = None
description = None
suffix = None
detail = None
basename = None
class KubernetesServiceConnectionSerializer(ServiceConnectionSerializer):
106class KubernetesServiceConnectionSerializer(ServiceConnectionSerializer):
107    """KubernetesServiceConnection Serializer"""
108
109    def validate_kubeconfig(self, kubeconfig):
110        """Validate kubeconfig by attempting to load it"""
111        if kubeconfig == {}:
112            if not self.initial_data["local"]:
113                raise serializers.ValidationError(
114                    _("You can only use an empty kubeconfig when connecting to a local cluster.")
115                )
116            # Empty kubeconfig is valid
117            return kubeconfig
118        from kubernetes.client.configuration import Configuration
119        from kubernetes.config.config_exception import ConfigException
120        from kubernetes.config.kube_config import load_kube_config_from_dict
121
122        from authentik.outposts.controllers.kubernetes import check_kubeconfig_user
123
124        config = Configuration()
125        try:
126            check_kubeconfig_user(kubeconfig)
127            load_kube_config_from_dict(kubeconfig, client_configuration=config)
128        except ConfigException:
129            raise serializers.ValidationError(_("Invalid kubeconfig")) from None
130        return kubeconfig
131
132    class Meta:
133        model = KubernetesServiceConnection
134        fields = ServiceConnectionSerializer.Meta.fields + ["kubeconfig", "verify_ssl"]
135        secret_fields = ["kubeconfig"]

KubernetesServiceConnection Serializer

def validate_kubeconfig(self, kubeconfig):
109    def validate_kubeconfig(self, kubeconfig):
110        """Validate kubeconfig by attempting to load it"""
111        if kubeconfig == {}:
112            if not self.initial_data["local"]:
113                raise serializers.ValidationError(
114                    _("You can only use an empty kubeconfig when connecting to a local cluster.")
115                )
116            # Empty kubeconfig is valid
117            return kubeconfig
118        from kubernetes.client.configuration import Configuration
119        from kubernetes.config.config_exception import ConfigException
120        from kubernetes.config.kube_config import load_kube_config_from_dict
121
122        from authentik.outposts.controllers.kubernetes import check_kubeconfig_user
123
124        config = Configuration()
125        try:
126            check_kubeconfig_user(kubeconfig)
127            load_kube_config_from_dict(kubeconfig, client_configuration=config)
128        except ConfigException:
129            raise serializers.ValidationError(_("Invalid kubeconfig")) from None
130        return kubeconfig

Validate kubeconfig by attempting to load it

class KubernetesServiceConnectionSerializer.Meta:
132    class Meta:
133        model = KubernetesServiceConnection
134        fields = ServiceConnectionSerializer.Meta.fields + ["kubeconfig", "verify_ssl"]
135        secret_fields = ["kubeconfig"]
fields = ['pk', 'name', 'local', 'component', 'verbose_name', 'verbose_name_plural', 'meta_model_name', 'kubeconfig', 'verify_ssl']
secret_fields = ['kubeconfig']
class KubernetesServiceConnectionViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
138class KubernetesServiceConnectionViewSet(UsedByMixin, ModelViewSet):
139    """KubernetesServiceConnection Viewset"""
140
141    queryset = KubernetesServiceConnection.objects.all()
142    serializer_class = KubernetesServiceConnectionSerializer
143    filterset_fields = ["name", "local"]
144    ordering = ["name"]
145    search_fields = ["name"]

KubernetesServiceConnection Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'KubernetesServiceConnectionSerializer'>
filterset_fields = ['name', 'local']
ordering = ['name']
search_fields = ['name']
name = None
description = None
suffix = None
detail = None
basename = None