authentik.providers.rac.models

RAC Models

  1"""RAC Models"""
  2
  3from typing import Any
  4from uuid import uuid4
  5
  6from deepmerge import always_merger
  7from django.db import models
  8from django.db.models import QuerySet
  9from django.http import HttpRequest
 10from django.templatetags.static import static
 11from django.utils.translation import gettext_lazy as _
 12from rest_framework.serializers import Serializer
 13from structlog.stdlib import get_logger
 14
 15from authentik.core.expression.exceptions import PropertyMappingExpressionException
 16from authentik.core.models import PropertyMapping, Provider, User, default_token_key
 17from authentik.endpoints.connectors.agent.controller import AgentConnectorController
 18from authentik.endpoints.models import Device
 19from authentik.events.models import Event, EventAction
 20from authentik.lib.models import ExpiringModel, InternallyManagedMixin
 21from authentik.lib.utils.time import timedelta_string_validator
 22from authentik.outposts.models import OutpostModel
 23
 24LOGGER = get_logger()
 25
 26# Settings the outpost turns into an SSH certificate, instead of passing them on to
 27# guacd. Keep in sync with `internal/outpost/rac/ssh.go`.
 28SSH_TOKEN_SETTING = "goauthentik.io/rac/ssh-token"  # nosec
 29SSH_HOST_KEY_SETTING = "goauthentik.io/rac/ssh-host-key"
 30
 31
 32class Protocols(models.TextChoices):
 33    """Supported protocols"""
 34
 35    RDP = "rdp"
 36    VNC = "vnc"
 37    SSH = "ssh"
 38
 39
 40class AuthenticationMode(models.TextChoices):
 41    """Authentication modes"""
 42
 43    STATIC = "static"
 44    PROMPT = "prompt"
 45
 46
 47def connection_override(device: Device) -> RACConnectionOverride | None:
 48    """Connection override of a device, if it has one"""
 49    return getattr(device, "rac_override", None)
 50
 51
 52def available_protocols(device: Device) -> list[str]:
 53    """Protocols a device can be connected to with. Set explicitly by a connection
 54    override, otherwise based on what the device reports. Devices which report neither
 55    can be connected to with either protocol, as there is nothing that says they
 56    can't."""
 57    if override := connection_override(device):
 58        if override.protocol:
 59            return [override.protocol]
 60    vendor = (device.facts_data.get("vendor") or {}).get(
 61        AgentConnectorController.vendor_identifier()
 62    ) or {}
 63    protocols = []
 64    if vendor.get("rdp_cert_fingerprint"):
 65        protocols.append(Protocols.RDP)
 66    if vendor.get("ssh_host_keys"):
 67        protocols.append(Protocols.SSH)
 68    return protocols or [Protocols.RDP, Protocols.SSH]
 69
 70
 71def agent_ssh_host_key(device: Device) -> str | None:
 72    """A host key the authentik agent reported for a device, which is what the device
 73    identifies itself with when it validates a certificate"""
 74    vendor = (device.facts_data.get("vendor") or {}).get(
 75        AgentConnectorController.vendor_identifier()
 76    ) or {}
 77    for host_key in vendor.get("ssh_host_keys") or []:
 78        # The agent reports keys the way `ssh-keyscan` does, prefixed with the host
 79        return host_key.removeprefix("localhost ").strip()
 80    return None
 81
 82
 83def address_settings(device: Device) -> dict[str, str]:
 84    """Hostname and port to connect to a device on. Set explicitly for devices which
 85    are not enrolled, otherwise taken from the facts the device reported."""
 86    override = connection_override(device)
 87    address = override.host if override else device.address
 88    if not address:
 89        return {}
 90    # An IPv6 address is bracketed when it carries a port: [2001:db8::1]:3389
 91    if address.startswith("["):
 92        host, _, port = address.removeprefix("[").partition("]:")
 93        settings = {"hostname": host.removesuffix("]")}
 94        if port:
 95            settings["port"] = port
 96        return settings
 97    host, _, port = address.rpartition(":")
 98    # Any other colon belongs to an IPv6 address, not to a port
 99    if host and ":" not in host and port.isdigit():
100        return {"hostname": host, "port": port}
101    return {"hostname": address}
102
103
104class RACProvider(OutpostModel, Provider):
105    """Remotely access devices via RDP/SSH/VNC."""
106
107    settings = models.JSONField(default=dict)
108    access_group = models.ForeignKey(
109        "authentik_endpoints.DeviceAccessGroup",
110        null=True,
111        blank=True,
112        default=None,
113        on_delete=models.SET_DEFAULT,
114        help_text=_(
115            "Only devices in this access group can be accessed through this provider. "
116            "When left empty, every device the user has access to can be accessed."
117        ),
118    )
119    maximum_connections = models.IntegerField(
120        default=1,
121        help_text=_(
122            "Maximum concurrent connections to a single device. Can be set to -1 to "
123            "disable the limit."
124        ),
125    )
126    auth_mode = models.TextField(
127        choices=AuthenticationMode.choices, default=AuthenticationMode.PROMPT
128    )
129    connection_expiry = models.TextField(
130        default="hours=8",
131        validators=[timedelta_string_validator],
132        help_text=_(
133            "Determines how long a session lasts. Default of 0 means "
134            "that the sessions lasts until the browser is closed. "
135            "(Format: hours=-1;minutes=-2;seconds=-3)"
136        ),
137    )
138    delete_token_on_disconnect = models.BooleanField(
139        default=False,
140        help_text=_("When set to true, connection tokens will be deleted upon disconnect."),
141    )
142
143    def devices(self) -> QuerySet[Device]:
144        """All devices this provider can connect to, before policies are checked"""
145        devices = Device.objects.all()
146        if self.access_group_id:
147            devices = devices.filter(access_group=self.access_group_id)
148        return devices
149
150    @property
151    def launch_url(self) -> str | None:
152        """URL to this provider and initiate authorization for the user.
153        Can return None for providers that are not URL-based"""
154        return "goauthentik.io://providers/rac/launch"
155
156    @property
157    def icon_url(self) -> str | None:
158        return static("authentik/sources/rac/light.svg")
159
160    @property
161    def component(self) -> str:
162        return "ak-provider-rac-form"
163
164    @property
165    def serializer(self) -> type[Serializer]:
166        from authentik.providers.rac.api.providers import RACProviderSerializer
167
168        return RACProviderSerializer
169
170    class Meta:
171        verbose_name = _("RAC Provider")
172        verbose_name_plural = _("RAC Providers")
173
174
175class RACPropertyMapping(PropertyMapping):
176    """Configure settings for remote access to devices."""
177
178    expression_allowed_types = [dict]
179
180    static_settings = models.JSONField(default=dict)
181
182    def evaluate(self, user: User | None, request: HttpRequest | None, **kwargs) -> Any:
183        """Evaluate `self.expression` using `**kwargs` as Context."""
184        settings = {}
185        for key, value in self.static_settings.items():
186            if value and value != "":
187                settings[key] = value
188        if self.expression != "":
189            always_merger.merge(settings, super().evaluate(user, request, **kwargs))
190        return settings
191
192    @property
193    def component(self) -> str:
194        return "ak-property-mapping-provider-rac-form"
195
196    @property
197    def serializer(self) -> type[Serializer]:
198        from authentik.providers.rac.api.property_mappings import (
199            RACPropertyMappingSerializer,
200        )
201
202        return RACPropertyMappingSerializer
203
204    class Meta:
205        verbose_name = _("RAC Provider Property Mapping")
206        verbose_name_plural = _("RAC Provider Property Mappings")
207
208
209class RACConnectionOverride(InternallyManagedMixin, models.Model):
210    """How to reach a single device, for devices which don't report an address and
211    protocol themselves."""
212
213    device = models.OneToOneField(
214        "authentik_endpoints.Device",
215        on_delete=models.CASCADE,
216        related_name="rac_override",
217    )
218    host = models.TextField(help_text=_("Hostname/IP to connect to. Optionally specify the port."))
219    protocol = models.TextField(choices=Protocols.choices)
220
221    class Meta:
222        verbose_name = _("RAC Connection override")
223        verbose_name_plural = _("RAC Connection overrides")
224
225    def __str__(self):
226        return f"RAC Connection override for device {self.device_id}"
227
228
229class ConnectionToken(InternallyManagedMixin, ExpiringModel):
230    """Token for a single connection to a device"""
231
232    connection_token_uuid = models.UUIDField(default=uuid4, primary_key=True)
233    provider = models.ForeignKey(RACProvider, on_delete=models.CASCADE)
234    device = models.ForeignKey("authentik_endpoints.Device", on_delete=models.CASCADE)
235    protocol = models.TextField(choices=Protocols.choices)
236    token = models.TextField(default=default_token_key)
237    settings = models.JSONField(default=dict)
238    session = models.ForeignKey("authentik_core.AuthenticatedSession", on_delete=models.CASCADE)
239
240    def get_settings(self) -> dict:
241        """Get settings"""
242        settings = {}
243        if self.protocol == Protocols.RDP:
244            settings["resize-method"] = "display-update"
245        settings["client-name"] = f"authentik - {self.session.user}"
246        always_merger.merge(settings, self.provider.settings)
247        always_merger.merge(settings, address_settings(self.device))
248        always_merger.merge(settings, self.agent_ssh_settings())
249
250        def mapping_evaluator(mappings: QuerySet):
251            for mapping in mappings:
252                mapping: RACPropertyMapping
253                try:
254                    mapping_settings = mapping.evaluate(
255                        self.session.user, None, device=self.device, provider=self.provider
256                    )
257                    always_merger.merge(settings, mapping_settings)
258                except PropertyMappingExpressionException as exc:
259                    Event.new(
260                        EventAction.CONFIGURATION_ERROR,
261                        message=f"Failed to evaluate property-mapping: '{mapping.name}'",
262                        provider=self.provider,
263                        mapping=mapping,
264                    ).set_user(self.session.user).save()
265                    LOGGER.warning("Failed to evaluate property mapping", exc=exc)
266
267        mapping_evaluator(
268            RACPropertyMapping.objects.filter(provider__in=[self.provider]).order_by("name")
269        )
270        always_merger.merge(settings, self.settings)
271
272        settings["drive-path"] = f"/tmp/connection/{self.token}"  # nosec
273        settings["create-drive-path"] = "true"
274        # Ensure all values of the settings dict are strings
275        for key, value in settings.items():
276            if isinstance(value, str):
277                continue
278            # Special case for bools
279            if isinstance(value, bool):
280                settings[key] = str(value).lower()
281                continue
282            settings[key] = str(value)
283        return settings
284
285    def agent_ssh_settings(self) -> dict[str, str]:
286        """Log into a device managed by the authentik agent as the user this connection
287        was authorized for. The outpost turns the token into an SSH certificate, which
288        the agent on the device validates with authentik before accepting the login."""
289        from authentik.endpoints.connectors.agent.auth import agent_auth_issue_token
290        from authentik.endpoints.connectors.agent.models import AgentConnector
291
292        if self.protocol != Protocols.SSH:
293            return {}
294        host_key = agent_ssh_host_key(self.device)
295        if not host_key:
296            return {}
297        connector = AgentConnector.objects.filter(device__in=[self.device]).first()
298        if not connector:
299            return {}
300        token, _ = agent_auth_issue_token(self.device, connector, self.session.user)
301        if not token:
302            LOGGER.warning("Failed to issue agent token for device", device=self.device)
303            return {}
304        return {
305            "username": self.session.user.username,
306            SSH_TOKEN_SETTING: token,
307            SSH_HOST_KEY_SETTING: host_key,
308        }
309
310    def __str__(self):
311        return f"RAC Connection token {self.session_id} to {self.provider_id}/{self.device_id}"
312
313    class Meta:
314        verbose_name = _("RAC Connection token")
315        verbose_name_plural = _("RAC Connection tokens")
316        indexes = ExpiringModel.Meta.indexes
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
SSH_TOKEN_SETTING = 'goauthentik.io/rac/ssh-token'
SSH_HOST_KEY_SETTING = 'goauthentik.io/rac/ssh-host-key'
class Protocols(django.db.models.enums.TextChoices):
33class Protocols(models.TextChoices):
34    """Supported protocols"""
35
36    RDP = "rdp"
37    VNC = "vnc"
38    SSH = "ssh"

Supported protocols

class AuthenticationMode(django.db.models.enums.TextChoices):
41class AuthenticationMode(models.TextChoices):
42    """Authentication modes"""
43
44    STATIC = "static"
45    PROMPT = "prompt"

Authentication modes

def connection_override( device: authentik.endpoints.models.Device) -> RACConnectionOverride | None:
48def connection_override(device: Device) -> RACConnectionOverride | None:
49    """Connection override of a device, if it has one"""
50    return getattr(device, "rac_override", None)

Connection override of a device, if it has one

def available_protocols(device: authentik.endpoints.models.Device) -> list[str]:
53def available_protocols(device: Device) -> list[str]:
54    """Protocols a device can be connected to with. Set explicitly by a connection
55    override, otherwise based on what the device reports. Devices which report neither
56    can be connected to with either protocol, as there is nothing that says they
57    can't."""
58    if override := connection_override(device):
59        if override.protocol:
60            return [override.protocol]
61    vendor = (device.facts_data.get("vendor") or {}).get(
62        AgentConnectorController.vendor_identifier()
63    ) or {}
64    protocols = []
65    if vendor.get("rdp_cert_fingerprint"):
66        protocols.append(Protocols.RDP)
67    if vendor.get("ssh_host_keys"):
68        protocols.append(Protocols.SSH)
69    return protocols or [Protocols.RDP, Protocols.SSH]

Protocols a device can be connected to with. Set explicitly by a connection override, otherwise based on what the device reports. Devices which report neither can be connected to with either protocol, as there is nothing that says they can't.

def agent_ssh_host_key(device: authentik.endpoints.models.Device) -> str | None:
72def agent_ssh_host_key(device: Device) -> str | None:
73    """A host key the authentik agent reported for a device, which is what the device
74    identifies itself with when it validates a certificate"""
75    vendor = (device.facts_data.get("vendor") or {}).get(
76        AgentConnectorController.vendor_identifier()
77    ) or {}
78    for host_key in vendor.get("ssh_host_keys") or []:
79        # The agent reports keys the way `ssh-keyscan` does, prefixed with the host
80        return host_key.removeprefix("localhost ").strip()
81    return None

A host key the authentik agent reported for a device, which is what the device identifies itself with when it validates a certificate

def address_settings(device: authentik.endpoints.models.Device) -> dict[str, str]:
 84def address_settings(device: Device) -> dict[str, str]:
 85    """Hostname and port to connect to a device on. Set explicitly for devices which
 86    are not enrolled, otherwise taken from the facts the device reported."""
 87    override = connection_override(device)
 88    address = override.host if override else device.address
 89    if not address:
 90        return {}
 91    # An IPv6 address is bracketed when it carries a port: [2001:db8::1]:3389
 92    if address.startswith("["):
 93        host, _, port = address.removeprefix("[").partition("]:")
 94        settings = {"hostname": host.removesuffix("]")}
 95        if port:
 96            settings["port"] = port
 97        return settings
 98    host, _, port = address.rpartition(":")
 99    # Any other colon belongs to an IPv6 address, not to a port
100    if host and ":" not in host and port.isdigit():
101        return {"hostname": host, "port": port}
102    return {"hostname": address}

Hostname and port to connect to a device on. Set explicitly for devices which are not enrolled, otherwise taken from the facts the device reported.

105class RACProvider(OutpostModel, Provider):
106    """Remotely access devices via RDP/SSH/VNC."""
107
108    settings = models.JSONField(default=dict)
109    access_group = models.ForeignKey(
110        "authentik_endpoints.DeviceAccessGroup",
111        null=True,
112        blank=True,
113        default=None,
114        on_delete=models.SET_DEFAULT,
115        help_text=_(
116            "Only devices in this access group can be accessed through this provider. "
117            "When left empty, every device the user has access to can be accessed."
118        ),
119    )
120    maximum_connections = models.IntegerField(
121        default=1,
122        help_text=_(
123            "Maximum concurrent connections to a single device. Can be set to -1 to "
124            "disable the limit."
125        ),
126    )
127    auth_mode = models.TextField(
128        choices=AuthenticationMode.choices, default=AuthenticationMode.PROMPT
129    )
130    connection_expiry = models.TextField(
131        default="hours=8",
132        validators=[timedelta_string_validator],
133        help_text=_(
134            "Determines how long a session lasts. Default of 0 means "
135            "that the sessions lasts until the browser is closed. "
136            "(Format: hours=-1;minutes=-2;seconds=-3)"
137        ),
138    )
139    delete_token_on_disconnect = models.BooleanField(
140        default=False,
141        help_text=_("When set to true, connection tokens will be deleted upon disconnect."),
142    )
143
144    def devices(self) -> QuerySet[Device]:
145        """All devices this provider can connect to, before policies are checked"""
146        devices = Device.objects.all()
147        if self.access_group_id:
148            devices = devices.filter(access_group=self.access_group_id)
149        return devices
150
151    @property
152    def launch_url(self) -> str | None:
153        """URL to this provider and initiate authorization for the user.
154        Can return None for providers that are not URL-based"""
155        return "goauthentik.io://providers/rac/launch"
156
157    @property
158    def icon_url(self) -> str | None:
159        return static("authentik/sources/rac/light.svg")
160
161    @property
162    def component(self) -> str:
163        return "ak-provider-rac-form"
164
165    @property
166    def serializer(self) -> type[Serializer]:
167        from authentik.providers.rac.api.providers import RACProviderSerializer
168
169        return RACProviderSerializer
170
171    class Meta:
172        verbose_name = _("RAC Provider")
173        verbose_name_plural = _("RAC Providers")

Remotely access devices via RDP/SSH/VNC.

def settings(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

access_group

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def maximum_connections(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def auth_mode(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def connection_expiry(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def delete_token_on_disconnect(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def devices(self) -> django.db.models.query.QuerySet:
144    def devices(self) -> QuerySet[Device]:
145        """All devices this provider can connect to, before policies are checked"""
146        devices = Device.objects.all()
147        if self.access_group_id:
148            devices = devices.filter(access_group=self.access_group_id)
149        return devices

All devices this provider can connect to, before policies are checked

launch_url: str | None
151    @property
152    def launch_url(self) -> str | None:
153        """URL to this provider and initiate authorization for the user.
154        Can return None for providers that are not URL-based"""
155        return "goauthentik.io://providers/rac/launch"

URL to this provider and initiate authorization for the user. Can return None for providers that are not URL-based

icon_url: str | None
157    @property
158    def icon_url(self) -> str | None:
159        return static("authentik/sources/rac/light.svg")
component: str
161    @property
162    def component(self) -> str:
163        return "ak-provider-rac-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
165    @property
166    def serializer(self) -> type[Serializer]:
167        from authentik.providers.rac.api.providers import RACProviderSerializer
168
169        return RACProviderSerializer

Get serializer for this model

access_group_id
def get_auth_mode_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

provider_ptr_id
provider_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

connectiontoken_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class RACProvider.DoesNotExist(authentik.core.models.Provider.DoesNotExist):

The requested object does not exist

class RACProvider.MultipleObjectsReturned(authentik.core.models.Provider.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class RACPropertyMapping(authentik.core.models.PropertyMapping):
176class RACPropertyMapping(PropertyMapping):
177    """Configure settings for remote access to devices."""
178
179    expression_allowed_types = [dict]
180
181    static_settings = models.JSONField(default=dict)
182
183    def evaluate(self, user: User | None, request: HttpRequest | None, **kwargs) -> Any:
184        """Evaluate `self.expression` using `**kwargs` as Context."""
185        settings = {}
186        for key, value in self.static_settings.items():
187            if value and value != "":
188                settings[key] = value
189        if self.expression != "":
190            always_merger.merge(settings, super().evaluate(user, request, **kwargs))
191        return settings
192
193    @property
194    def component(self) -> str:
195        return "ak-property-mapping-provider-rac-form"
196
197    @property
198    def serializer(self) -> type[Serializer]:
199        from authentik.providers.rac.api.property_mappings import (
200            RACPropertyMappingSerializer,
201        )
202
203        return RACPropertyMappingSerializer
204
205    class Meta:
206        verbose_name = _("RAC Provider Property Mapping")
207        verbose_name_plural = _("RAC Provider Property Mappings")

Configure settings for remote access to devices.

expression_allowed_types = [<class 'dict'>]
def static_settings(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def evaluate( self, user: authentik.core.models.User | None, request: django.http.request.HttpRequest | None, **kwargs) -> Any:
183    def evaluate(self, user: User | None, request: HttpRequest | None, **kwargs) -> Any:
184        """Evaluate `self.expression` using `**kwargs` as Context."""
185        settings = {}
186        for key, value in self.static_settings.items():
187            if value and value != "":
188                settings[key] = value
189        if self.expression != "":
190            always_merger.merge(settings, super().evaluate(user, request, **kwargs))
191        return settings

Evaluate self.expression using **kwargs as Context.

component: str
193    @property
194    def component(self) -> str:
195        return "ak-property-mapping-provider-rac-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
197    @property
198    def serializer(self) -> type[Serializer]:
199        from authentik.providers.rac.api.property_mappings import (
200            RACPropertyMappingSerializer,
201        )
202
203        return RACPropertyMappingSerializer

Get serializer for this model

propertymapping_ptr_id
propertymapping_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class RACPropertyMapping.DoesNotExist(authentik.core.models.PropertyMapping.DoesNotExist):

The requested object does not exist

class RACPropertyMapping.MultipleObjectsReturned(authentik.core.models.PropertyMapping.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class RACConnectionOverride(authentik.lib.models.InternallyManagedMixin, django.db.models.base.Model):
210class RACConnectionOverride(InternallyManagedMixin, models.Model):
211    """How to reach a single device, for devices which don't report an address and
212    protocol themselves."""
213
214    device = models.OneToOneField(
215        "authentik_endpoints.Device",
216        on_delete=models.CASCADE,
217        related_name="rac_override",
218    )
219    host = models.TextField(help_text=_("Hostname/IP to connect to. Optionally specify the port."))
220    protocol = models.TextField(choices=Protocols.choices)
221
222    class Meta:
223        verbose_name = _("RAC Connection override")
224        verbose_name_plural = _("RAC Connection overrides")
225
226    def __str__(self):
227        return f"RAC Connection override for device {self.device_id}"

How to reach a single device, for devices which don't report an address and protocol themselves.

device

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

def host(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def protocol(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

device_id
def get_protocol_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class RACConnectionOverride.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class RACConnectionOverride.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

230class ConnectionToken(InternallyManagedMixin, ExpiringModel):
231    """Token for a single connection to a device"""
232
233    connection_token_uuid = models.UUIDField(default=uuid4, primary_key=True)
234    provider = models.ForeignKey(RACProvider, on_delete=models.CASCADE)
235    device = models.ForeignKey("authentik_endpoints.Device", on_delete=models.CASCADE)
236    protocol = models.TextField(choices=Protocols.choices)
237    token = models.TextField(default=default_token_key)
238    settings = models.JSONField(default=dict)
239    session = models.ForeignKey("authentik_core.AuthenticatedSession", on_delete=models.CASCADE)
240
241    def get_settings(self) -> dict:
242        """Get settings"""
243        settings = {}
244        if self.protocol == Protocols.RDP:
245            settings["resize-method"] = "display-update"
246        settings["client-name"] = f"authentik - {self.session.user}"
247        always_merger.merge(settings, self.provider.settings)
248        always_merger.merge(settings, address_settings(self.device))
249        always_merger.merge(settings, self.agent_ssh_settings())
250
251        def mapping_evaluator(mappings: QuerySet):
252            for mapping in mappings:
253                mapping: RACPropertyMapping
254                try:
255                    mapping_settings = mapping.evaluate(
256                        self.session.user, None, device=self.device, provider=self.provider
257                    )
258                    always_merger.merge(settings, mapping_settings)
259                except PropertyMappingExpressionException as exc:
260                    Event.new(
261                        EventAction.CONFIGURATION_ERROR,
262                        message=f"Failed to evaluate property-mapping: '{mapping.name}'",
263                        provider=self.provider,
264                        mapping=mapping,
265                    ).set_user(self.session.user).save()
266                    LOGGER.warning("Failed to evaluate property mapping", exc=exc)
267
268        mapping_evaluator(
269            RACPropertyMapping.objects.filter(provider__in=[self.provider]).order_by("name")
270        )
271        always_merger.merge(settings, self.settings)
272
273        settings["drive-path"] = f"/tmp/connection/{self.token}"  # nosec
274        settings["create-drive-path"] = "true"
275        # Ensure all values of the settings dict are strings
276        for key, value in settings.items():
277            if isinstance(value, str):
278                continue
279            # Special case for bools
280            if isinstance(value, bool):
281                settings[key] = str(value).lower()
282                continue
283            settings[key] = str(value)
284        return settings
285
286    def agent_ssh_settings(self) -> dict[str, str]:
287        """Log into a device managed by the authentik agent as the user this connection
288        was authorized for. The outpost turns the token into an SSH certificate, which
289        the agent on the device validates with authentik before accepting the login."""
290        from authentik.endpoints.connectors.agent.auth import agent_auth_issue_token
291        from authentik.endpoints.connectors.agent.models import AgentConnector
292
293        if self.protocol != Protocols.SSH:
294            return {}
295        host_key = agent_ssh_host_key(self.device)
296        if not host_key:
297            return {}
298        connector = AgentConnector.objects.filter(device__in=[self.device]).first()
299        if not connector:
300            return {}
301        token, _ = agent_auth_issue_token(self.device, connector, self.session.user)
302        if not token:
303            LOGGER.warning("Failed to issue agent token for device", device=self.device)
304            return {}
305        return {
306            "username": self.session.user.username,
307            SSH_TOKEN_SETTING: token,
308            SSH_HOST_KEY_SETTING: host_key,
309        }
310
311    def __str__(self):
312        return f"RAC Connection token {self.session_id} to {self.provider_id}/{self.device_id}"
313
314    class Meta:
315        verbose_name = _("RAC Connection token")
316        verbose_name_plural = _("RAC Connection tokens")
317        indexes = ExpiringModel.Meta.indexes

Token for a single connection to a device

def connection_token_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

device

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def protocol(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def token(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def settings(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def get_settings(self) -> dict:
241    def get_settings(self) -> dict:
242        """Get settings"""
243        settings = {}
244        if self.protocol == Protocols.RDP:
245            settings["resize-method"] = "display-update"
246        settings["client-name"] = f"authentik - {self.session.user}"
247        always_merger.merge(settings, self.provider.settings)
248        always_merger.merge(settings, address_settings(self.device))
249        always_merger.merge(settings, self.agent_ssh_settings())
250
251        def mapping_evaluator(mappings: QuerySet):
252            for mapping in mappings:
253                mapping: RACPropertyMapping
254                try:
255                    mapping_settings = mapping.evaluate(
256                        self.session.user, None, device=self.device, provider=self.provider
257                    )
258                    always_merger.merge(settings, mapping_settings)
259                except PropertyMappingExpressionException as exc:
260                    Event.new(
261                        EventAction.CONFIGURATION_ERROR,
262                        message=f"Failed to evaluate property-mapping: '{mapping.name}'",
263                        provider=self.provider,
264                        mapping=mapping,
265                    ).set_user(self.session.user).save()
266                    LOGGER.warning("Failed to evaluate property mapping", exc=exc)
267
268        mapping_evaluator(
269            RACPropertyMapping.objects.filter(provider__in=[self.provider]).order_by("name")
270        )
271        always_merger.merge(settings, self.settings)
272
273        settings["drive-path"] = f"/tmp/connection/{self.token}"  # nosec
274        settings["create-drive-path"] = "true"
275        # Ensure all values of the settings dict are strings
276        for key, value in settings.items():
277            if isinstance(value, str):
278                continue
279            # Special case for bools
280            if isinstance(value, bool):
281                settings[key] = str(value).lower()
282                continue
283            settings[key] = str(value)
284        return settings

Get settings

def agent_ssh_settings(self) -> dict[str, str]:
286    def agent_ssh_settings(self) -> dict[str, str]:
287        """Log into a device managed by the authentik agent as the user this connection
288        was authorized for. The outpost turns the token into an SSH certificate, which
289        the agent on the device validates with authentik before accepting the login."""
290        from authentik.endpoints.connectors.agent.auth import agent_auth_issue_token
291        from authentik.endpoints.connectors.agent.models import AgentConnector
292
293        if self.protocol != Protocols.SSH:
294            return {}
295        host_key = agent_ssh_host_key(self.device)
296        if not host_key:
297            return {}
298        connector = AgentConnector.objects.filter(device__in=[self.device]).first()
299        if not connector:
300            return {}
301        token, _ = agent_auth_issue_token(self.device, connector, self.session.user)
302        if not token:
303            LOGGER.warning("Failed to issue agent token for device", device=self.device)
304            return {}
305        return {
306            "username": self.session.user.username,
307            SSH_TOKEN_SETTING: token,
308            SSH_HOST_KEY_SETTING: host_key,
309        }

Log into a device managed by the authentik agent as the user this connection was authorized for. The outpost turns the token into an SSH certificate, which the agent on the device validates with authentik before accepting the login.

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

provider_id
device_id
def get_protocol_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

session_id
class ConnectionToken.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class ConnectionToken.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.