authentik.outposts.models
Outpost models
1"""Outpost models""" 2 3from collections.abc import Iterable 4from dataclasses import asdict, dataclass, field 5from datetime import datetime 6from pathlib import Path 7from typing import Any 8from uuid import uuid4 9 10from dacite.core import from_dict 11from django.contrib.auth.models import Permission 12from django.core.cache import cache 13from django.db import IntegrityError, models, transaction 14from django.db.models.base import Model 15from django.utils.translation import gettext_lazy as _ 16from guardian.models import RoleModelPermission, RoleObjectPermission 17from model_utils.managers import InheritanceManager 18from packaging.version import parse 19from rest_framework.serializers import Serializer 20from structlog.stdlib import get_logger 21 22from authentik import authentik_build_hash, authentik_version 23from authentik.blueprints.models import ManagedModel 24from authentik.brands.models import Brand 25from authentik.core.models import ( 26 USER_PATH_SYSTEM_PREFIX, 27 Provider, 28 Token, 29 TokenIntents, 30 User, 31 UserTypes, 32) 33from authentik.crypto.models import CertificateKeyPair 34from authentik.events.models import Event, EventAction 35from authentik.lib.config import CONFIG 36from authentik.lib.models import InheritanceForeignKey, SerializerModel, SimpleThroughModel 37from authentik.lib.tracing.exceptions import TracingIgnoredException 38from authentik.lib.utils.time import fqdn_rand 39from authentik.stages.password.models import PasswordDevice 40from authentik.tasks.schedules.common import ScheduleSpec 41from authentik.tasks.schedules.models import ScheduledModel 42 43OUR_VERSION = parse(authentik_version()) 44OUTPOST_HELLO_INTERVAL = 10 45LOGGER = get_logger() 46 47USER_PATH_OUTPOSTS = USER_PATH_SYSTEM_PREFIX + "/outposts" 48USER_PREFIX_OUTPOSTS = "ak-outpost-" 49# Matches kubernetes.config.incluster_config, without importing the kubernetes client 50K8S_SERVICE_ACCOUNT_NAMESPACE = Path("/var/run/secrets/kubernetes.io/serviceaccount/namespace") 51 52 53def get_namespace() -> str: 54 """Get the namespace if we're running in a pod, otherwise default to default""" 55 if K8S_SERVICE_ACCOUNT_NAMESPACE.exists(): 56 return K8S_SERVICE_ACCOUNT_NAMESPACE.read_text(encoding="utf8") 57 return "default" 58 59 60class ServiceConnectionInvalid(TracingIgnoredException): 61 """Exception raised when a Service Connection has invalid parameters""" 62 63 64@dataclass 65class OutpostConfig: 66 """Configuration an outpost uses to configure it self""" 67 68 # update website/docs/add-secure-apps/outposts/_config.mdx 69 70 authentik_host: str = "" 71 authentik_host_insecure: bool = False 72 authentik_host_browser: str = "" 73 74 log_level: str = CONFIG.get("log_level") 75 object_naming_template: str = field(default="ak-outpost-%(name)s") 76 refresh_interval: str = "minutes=5" 77 78 container_image: str | None = field(default=None) 79 80 docker_network: str | None = field(default=None) 81 docker_map_ports: bool = field(default=True) 82 docker_labels: dict[str, str] | None = field(default=None) 83 84 kubernetes_replicas: int = field(default=1) 85 kubernetes_namespace: str = field(default_factory=get_namespace) 86 kubernetes_ingress_annotations: dict[str, str] = field(default_factory=dict) 87 kubernetes_ingress_secret_name: str = field(default="authentik-outpost-tls") 88 kubernetes_ingress_class_name: str | None = field(default=None) 89 kubernetes_ingress_path_type: str | None = field(default=None) 90 kubernetes_httproute_annotations: dict[str, str] = field(default_factory=dict) 91 kubernetes_httproute_parent_refs: list[dict[str, str]] = field(default_factory=list) 92 kubernetes_listenerset_parent_ref: dict[str, str] = field(default_factory=dict) 93 kubernetes_service_type: str = field(default="ClusterIP") 94 kubernetes_disabled_components: list[str] = field(default_factory=list) 95 kubernetes_image_pull_secrets: list[str] = field(default_factory=list) 96 kubernetes_json_patches: dict[str, list[dict[str, Any]]] | None = field(default=None) 97 kubernetes_disable_x509_strict: bool = field(default=False) 98 99 100class OutpostModel(Model): 101 """Base model for providers that need more objects than just themselves""" 102 103 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 104 """Return a list of all required objects""" 105 return [self] 106 107 class Meta: 108 abstract = True 109 110 111class OutpostType(models.TextChoices): 112 """Outpost types""" 113 114 PROXY = "proxy" 115 LDAP = "ldap" 116 RADIUS = "radius" 117 RAC = "rac" 118 119 120def default_outpost_config(host: str | None = None): 121 """Get default outpost config""" 122 return asdict(OutpostConfig(authentik_host=host or "")) 123 124 125@dataclass 126class OutpostServiceConnectionState: 127 """State of an Outpost Service Connection""" 128 129 version: str 130 healthy: bool 131 132 133class OutpostServiceConnection(ScheduledModel, models.Model): 134 """Connection details for an Outpost Controller, like Docker or Kubernetes""" 135 136 uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True) 137 name = models.TextField(unique=True) 138 139 local = models.BooleanField( 140 default=False, 141 help_text=_( 142 "If enabled, use the local connection. Required Docker socket/Kubernetes Integration" 143 ), 144 ) 145 146 objects = InheritanceManager() 147 148 class Meta: 149 verbose_name = _("Outpost Service-Connection") 150 verbose_name_plural = _("Outpost Service-Connections") 151 152 def __str__(self) -> str: 153 return f"Outpost service connection {self.name}" 154 155 @property 156 def state_key(self) -> str: 157 """Key used to save connection state in cache""" 158 return f"goauthentik.io/outposts/service_connection_state/{self.pk.hex}" 159 160 @property 161 def state(self) -> OutpostServiceConnectionState: 162 """Get state of service connection""" 163 from authentik.outposts.tasks import outpost_service_connection_monitor 164 165 state = cache.get(self.state_key, None) 166 if not state: 167 outpost_service_connection_monitor.send_with_options(args=(self.pk,), rel_obj=self) 168 return OutpostServiceConnectionState("", False) 169 return state 170 171 @property 172 def component(self) -> str: 173 """Return component used to edit this object""" 174 # This is called when creating an outpost with a service connection 175 # since the response doesn't use the correct inheritance 176 return "" 177 178 @property 179 def schedule_specs(self) -> list[ScheduleSpec]: 180 from authentik.outposts.tasks import outpost_service_connection_monitor 181 182 return [ 183 ScheduleSpec( 184 actor=outpost_service_connection_monitor, 185 uid=self.name, 186 args=(self.pk,), 187 crontab="3-59/15 * * * *", 188 send_on_save=True, 189 ), 190 ] 191 192 193class DockerServiceConnection(SerializerModel, OutpostServiceConnection): 194 """Service Connection to a Docker endpoint""" 195 196 url = models.TextField( 197 help_text=_( 198 "Can be in the format of 'unix://<path>' when connecting to a local docker daemon, " 199 "or 'https://<hostname>:2376' when connecting to a remote system." 200 ) 201 ) 202 tls_verification = models.ForeignKey( 203 CertificateKeyPair, 204 null=True, 205 blank=True, 206 default=None, 207 related_name="+", 208 on_delete=models.SET_DEFAULT, 209 help_text=_( 210 "CA which the endpoint's Certificate is verified against. " 211 "Can be left empty for no validation." 212 ), 213 ) 214 tls_authentication = models.ForeignKey( 215 CertificateKeyPair, 216 null=True, 217 blank=True, 218 default=None, 219 related_name="+", 220 on_delete=models.SET_DEFAULT, 221 help_text=_( 222 "Certificate/Key used for authentication. Can be left empty for no authentication." 223 ), 224 ) 225 226 class Meta: 227 verbose_name = _("Docker Service-Connection") 228 verbose_name_plural = _("Docker Service-Connections") 229 230 def __str__(self) -> str: 231 return f"Docker Service-Connection {self.name}" 232 233 @property 234 def serializer(self) -> Serializer: 235 from authentik.outposts.api.service_connections import DockerServiceConnectionSerializer 236 237 return DockerServiceConnectionSerializer 238 239 @property 240 def component(self) -> str: 241 return "ak-service-connection-docker-form" 242 243 244class KubernetesServiceConnection(SerializerModel, OutpostServiceConnection): 245 """Service Connection to a Kubernetes cluster""" 246 247 kubeconfig = models.JSONField( 248 help_text=_( 249 "Paste your kubeconfig here. authentik will automatically use " 250 "the currently selected context." 251 ), 252 blank=True, 253 ) 254 verify_ssl = models.BooleanField( 255 default=True, help_text=_("Verify SSL Certificates of the Kubernetes API endpoint") 256 ) 257 258 class Meta: 259 verbose_name = _("Kubernetes Service-Connection") 260 verbose_name_plural = _("Kubernetes Service-Connections") 261 262 def __str__(self) -> str: 263 return f"Kubernetes Service-Connection {self.name}" 264 265 @property 266 def serializer(self) -> Serializer: 267 from authentik.outposts.api.service_connections import KubernetesServiceConnectionSerializer 268 269 return KubernetesServiceConnectionSerializer 270 271 @property 272 def component(self) -> str: 273 return "ak-service-connection-kubernetes-form" 274 275 276class Outpost(ScheduledModel, SerializerModel, ManagedModel): 277 """Outpost instance which manages a service user and token""" 278 279 uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True) 280 name = models.TextField(unique=True) 281 282 type = models.TextField(choices=OutpostType.choices, default=OutpostType.PROXY) 283 service_connection = InheritanceForeignKey( 284 OutpostServiceConnection, 285 default=None, 286 null=True, 287 blank=True, 288 help_text=_( 289 "Select Service-Connection authentik should use to manage this outpost. " 290 "Leave empty if authentik should not handle the deployment." 291 ), 292 on_delete=models.SET_DEFAULT, 293 ) 294 295 _config = models.JSONField(default=default_outpost_config) 296 297 providers = models.ManyToManyField(Provider, through="OutpostProvider") 298 299 @property 300 def serializer(self) -> Serializer: 301 from authentik.outposts.api.outposts import OutpostSerializer 302 303 return OutpostSerializer 304 305 @property 306 def config(self) -> OutpostConfig: 307 """Load config as OutpostConfig object""" 308 return from_dict(OutpostConfig, self._config) 309 310 @config.setter 311 def config(self, value): 312 """Dump config into json""" 313 self._config = asdict(value) 314 315 @property 316 def state_cache_prefix(self) -> str: 317 """Key by which the outposts status is saved""" 318 return f"goauthentik.io/outposts/state/{self.uuid.hex}" 319 320 @property 321 def state(self) -> list[OutpostState]: 322 """Get outpost's health status""" 323 return OutpostState.for_outpost(self) 324 325 @property 326 def user_identifier(self): 327 """Username for service user""" 328 return f"{USER_PREFIX_OUTPOSTS}{self.uuid.hex}" 329 330 @property 331 def schedule_specs(self) -> list[ScheduleSpec]: 332 from authentik.outposts.tasks import outpost_controller 333 334 return [ 335 ScheduleSpec( 336 actor=outpost_controller, 337 uid=self.name, 338 args=(self.pk,), 339 kwargs={"action": "up", "from_cache": False}, 340 crontab=f"{fqdn_rand('outpost_controller')} */4 * * *", 341 send_on_save=True, 342 ), 343 ] 344 345 def build_user_permissions(self, user: User, rebuild: bool = False): 346 """Create per-object and global permissions for outpost service-account. 347 With `rebuild`, delete all of them first and recreate them, for troubleshooting.""" 348 # Only write the difference, so saving a provider whose required objects didn't change 349 # doesn't rewrite every permission row of the outpost. Concurrent transactions (such as 350 # parallel blueprint applies) would otherwise lock the same rows and deadlock. 351 permissions: dict[str, Permission] = {} 352 model_perms: dict[int, Permission] = {} 353 obj_perms: dict[tuple[int, str], Permission] = {} 354 code_name = model_or_perm = None 355 try: 356 for model_or_perm in self.get_required_objects(): 357 obj = None 358 if isinstance(model_or_perm, models.Model): 359 obj = model_or_perm 360 code_name = f"{obj._meta.app_label}.view_{obj._meta.model_name}" 361 elif isinstance(model_or_perm, tuple): 362 code_name, obj = model_or_perm 363 else: 364 code_name = model_or_perm 365 if code_name not in permissions: 366 app_label, codename = code_name.split(".", 1) 367 permissions[code_name] = Permission.objects.get( 368 content_type__app_label=app_label, codename=codename 369 ) 370 permission = permissions[code_name] 371 if obj is None: 372 model_perms[permission.pk] = permission 373 else: 374 obj_perms[(permission.pk, str(obj.pk))] = permission 375 except (Permission.DoesNotExist, AttributeError) as exc: 376 LOGGER.warning( 377 "permission doesn't exist", 378 code_name=code_name, 379 user=user, 380 model=model_or_perm, 381 ) 382 Event.new( 383 action=EventAction.SYSTEM_EXCEPTION, 384 message=( 385 "While setting the permissions for the service-account, a " 386 "permission was not found: Check " 387 "https://docs.goauthentik.io/troubleshooting/missing_permission" 388 ), 389 ).with_exception(exc).set_user(user).save() 390 return 391 with transaction.atomic(): 392 # Only after all required permissions resolved, so a missing permission doesn't 393 # leave the outpost without any 394 if rebuild: 395 user.remove_all_perms_from_managed_role() 396 role = user.get_managed_role(create=True) 397 existing_model_permissions: set[int] = set( 398 RoleModelPermission.objects.filter(role=role).values_list( 399 "permission_id", flat=True 400 ) 401 ) 402 # (permission ID, object PK) -> RoleObjectPermission PK 403 existing_obj_permissions: dict[tuple[int, str], int] = { 404 (perm_id, object_pk): pk 405 for pk, perm_id, object_pk in RoleObjectPermission.objects.filter( 406 role=role 407 ).values_list("pk", "permission_id", "object_pk") 408 } 409 if stale := existing_model_permissions - model_perms.keys(): 410 RoleModelPermission.objects.filter(role=role, permission_id__in=stale).delete() 411 if stale_pks := [ 412 pk for key, pk in existing_obj_permissions.items() if key not in obj_perms 413 ]: 414 RoleObjectPermission.objects.filter(pk__in=stale_pks).delete() 415 # Sorted, so concurrent rebuilds insert shared rows in the same order 416 RoleModelPermission.objects.bulk_create( 417 [ 418 RoleModelPermission( 419 role=role, 420 permission=model_perms[perm_id], 421 content_type_id=model_perms[perm_id].content_type_id, 422 ) 423 for perm_id in sorted(model_perms.keys() - existing_model_permissions) 424 ], 425 ignore_conflicts=True, 426 ) 427 RoleObjectPermission.objects.bulk_create( 428 [ 429 RoleObjectPermission( 430 role=role, 431 permission=obj_perms[key], 432 content_type_id=obj_perms[key].content_type_id, 433 object_pk=key[1], 434 ) 435 for key in sorted(obj_perms.keys() - existing_obj_permissions.keys()) 436 ], 437 ignore_conflicts=True, 438 ) 439 LOGGER.debug( 440 "Updated service account's permissions", 441 obj_perms=user.get_all_obj_perms_on_managed_role(), 442 perms=user.get_all_model_perms_on_managed_role(), 443 ) 444 445 @property 446 def user(self) -> User: 447 """Get/create user with access to all required objects""" 448 user = User.objects.filter(username=self.user_identifier).first() 449 user_created = False 450 if not user: 451 user: User = User.objects.create(username=self.user_identifier) 452 user_created = True 453 attrs = { 454 "type": UserTypes.INTERNAL_SERVICE_ACCOUNT, 455 "name": f"Outpost {self.name} Service-Account", 456 "path": USER_PATH_OUTPOSTS, 457 } 458 dirty = False 459 for key, value in attrs.items(): 460 if getattr(user, key) != value: 461 dirty = True 462 setattr(user, key, value) 463 if dirty: 464 user.save() 465 if user.has_usable_password(): 466 PasswordDevice.set_unusable_password(user) 467 if user_created: 468 self.build_user_permissions(user) 469 return user 470 471 @property 472 def token_identifier(self) -> str: 473 """Get Token identifier""" 474 return f"ak-outpost-{self.pk}-api" 475 476 @property 477 def token(self) -> Token: 478 """Get/create token for auto-generated user""" 479 managed = f"goauthentik.io/outpost/{self.token_identifier}" 480 tokens = Token.objects.filter( 481 identifier=self.token_identifier, 482 intent=TokenIntents.INTENT_API, 483 managed=managed, 484 ) 485 if tokens.exists(): 486 return tokens.first() 487 try: 488 return Token.objects.create( 489 user=self.user, 490 identifier=self.token_identifier, 491 intent=TokenIntents.INTENT_API, 492 description=f"Autogenerated by authentik for Outpost {self.name}", 493 expiring=False, 494 managed=managed, 495 ) 496 except IntegrityError: 497 # Integrity error happens mostly when managed is reused 498 Token.objects.filter(managed=managed).delete() 499 Token.objects.filter(identifier=self.token_identifier).delete() 500 return self.token 501 502 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 503 """Get an iterator of all objects the user needs read access to""" 504 objects: list[models.Model | str] = [ 505 self, 506 "authentik_events.add_event", 507 ] 508 for provider in Provider.objects.filter(outpost=self).select_related().select_subclasses(): 509 if isinstance(provider, OutpostModel): 510 objects.extend(provider.get_required_objects()) 511 else: 512 objects.append(provider) 513 if self.managed: 514 for brand in Brand.objects.filter(web_certificate__isnull=False): 515 objects.append(brand) 516 objects.append(("authentik_crypto.view_certificatekeypair", brand.web_certificate)) 517 objects.append( 518 ("authentik_crypto.view_certificatekeypair_certificate", brand.web_certificate) 519 ) 520 objects.append( 521 ("authentik_crypto.view_certificatekeypair_key", brand.web_certificate) 522 ) 523 return objects 524 525 def __str__(self) -> str: 526 return f"Outpost {self.name}" 527 528 class Meta: 529 verbose_name = _("Outpost") 530 verbose_name_plural = _("Outposts") 531 532 533class OutpostProvider(SimpleThroughModel): 534 outpost = models.ForeignKey(Outpost, on_delete=models.CASCADE) 535 provider = models.ForeignKey(Provider, on_delete=models.CASCADE) 536 537 class Meta: 538 db_table = "authentik_outposts_outpost_providers" 539 unique_together = (("outpost", "provider"),) 540 verbose_name = _("Outpost Provider") 541 verbose_name_plural = _("Outpost Providers") 542 543 def __str__(self): 544 return f"OutpostProvider for Outpost {self.outpost_id} and Provider {self.provider_id}." 545 546 547@dataclass 548class OutpostState: 549 """Outpost instance state, last_seen and version""" 550 551 uid: str 552 last_seen: datetime | None = field(default=None) 553 version: str | None = field(default=None) 554 build_hash: str = field(default="") 555 golang_version: str = field(default="") 556 openssl_enabled: bool = field(default=False) 557 openssl_version: str = field(default="") 558 fips_enabled: bool = field(default=False) 559 hostname: str = field(default="") 560 args: dict = field(default_factory=dict) 561 562 _outpost: Outpost | None = field(default=None) 563 564 @property 565 def version_outdated(self) -> bool: 566 """Check if outpost version matches our version""" 567 if not self.version: 568 return False 569 if self.build_hash != authentik_build_hash(): 570 return False 571 return parse(self.version) != OUR_VERSION 572 573 @staticmethod 574 def for_outpost(outpost: Outpost) -> list[OutpostState]: 575 """Get all states for an outpost""" 576 keys = cache.keys(f"{outpost.state_cache_prefix}/*") 577 if not keys: 578 return [] 579 states = [] 580 for key in keys: 581 instance_uid = key.replace(f"{outpost.state_cache_prefix}/", "") 582 states.append(OutpostState.for_instance_uid(outpost, instance_uid)) 583 return states 584 585 @staticmethod 586 def for_instance_uid(outpost: Outpost, uid: str) -> OutpostState: 587 """Get state for a single instance""" 588 key = f"{outpost.state_cache_prefix}/{uid}" 589 default_data = {"uid": uid} 590 data = cache.get(key, default_data) 591 if isinstance(data, str): 592 cache.delete(key) 593 data = default_data 594 state = from_dict(OutpostState, data) 595 596 state._outpost = outpost 597 return state 598 599 def save(self, timeout=OUTPOST_HELLO_INTERVAL): 600 """Save current state to cache""" 601 full_key = f"{self._outpost.state_cache_prefix}/{self.uid}" 602 return cache.set(full_key, asdict(self), timeout=timeout) 603 604 def delete(self): 605 """Manually delete from cache, used on channel disconnect""" 606 full_key = f"{self._outpost.state_cache_prefix}/{self.uid}" 607 cache.delete(full_key)
54def get_namespace() -> str: 55 """Get the namespace if we're running in a pod, otherwise default to default""" 56 if K8S_SERVICE_ACCOUNT_NAMESPACE.exists(): 57 return K8S_SERVICE_ACCOUNT_NAMESPACE.read_text(encoding="utf8") 58 return "default"
Get the namespace if we're running in a pod, otherwise default to default
61class ServiceConnectionInvalid(TracingIgnoredException): 62 """Exception raised when a Service Connection has invalid parameters"""
Exception raised when a Service Connection has invalid parameters
65@dataclass 66class OutpostConfig: 67 """Configuration an outpost uses to configure it self""" 68 69 # update website/docs/add-secure-apps/outposts/_config.mdx 70 71 authentik_host: str = "" 72 authentik_host_insecure: bool = False 73 authentik_host_browser: str = "" 74 75 log_level: str = CONFIG.get("log_level") 76 object_naming_template: str = field(default="ak-outpost-%(name)s") 77 refresh_interval: str = "minutes=5" 78 79 container_image: str | None = field(default=None) 80 81 docker_network: str | None = field(default=None) 82 docker_map_ports: bool = field(default=True) 83 docker_labels: dict[str, str] | None = field(default=None) 84 85 kubernetes_replicas: int = field(default=1) 86 kubernetes_namespace: str = field(default_factory=get_namespace) 87 kubernetes_ingress_annotations: dict[str, str] = field(default_factory=dict) 88 kubernetes_ingress_secret_name: str = field(default="authentik-outpost-tls") 89 kubernetes_ingress_class_name: str | None = field(default=None) 90 kubernetes_ingress_path_type: str | None = field(default=None) 91 kubernetes_httproute_annotations: dict[str, str] = field(default_factory=dict) 92 kubernetes_httproute_parent_refs: list[dict[str, str]] = field(default_factory=list) 93 kubernetes_listenerset_parent_ref: dict[str, str] = field(default_factory=dict) 94 kubernetes_service_type: str = field(default="ClusterIP") 95 kubernetes_disabled_components: list[str] = field(default_factory=list) 96 kubernetes_image_pull_secrets: list[str] = field(default_factory=list) 97 kubernetes_json_patches: dict[str, list[dict[str, Any]]] | None = field(default=None) 98 kubernetes_disable_x509_strict: bool = field(default=False)
Configuration an outpost uses to configure it self
101class OutpostModel(Model): 102 """Base model for providers that need more objects than just themselves""" 103 104 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 105 """Return a list of all required objects""" 106 return [self] 107 108 class Meta: 109 abstract = True
Base model for providers that need more objects than just themselves
104 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 105 """Return a list of all required objects""" 106 return [self]
Return a list of all required objects
112class OutpostType(models.TextChoices): 113 """Outpost types""" 114 115 PROXY = "proxy" 116 LDAP = "ldap" 117 RADIUS = "radius" 118 RAC = "rac"
Outpost types
121def default_outpost_config(host: str | None = None): 122 """Get default outpost config""" 123 return asdict(OutpostConfig(authentik_host=host or ""))
Get default outpost config
126@dataclass 127class OutpostServiceConnectionState: 128 """State of an Outpost Service Connection""" 129 130 version: str 131 healthy: bool
State of an Outpost Service Connection
134class OutpostServiceConnection(ScheduledModel, models.Model): 135 """Connection details for an Outpost Controller, like Docker or Kubernetes""" 136 137 uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True) 138 name = models.TextField(unique=True) 139 140 local = models.BooleanField( 141 default=False, 142 help_text=_( 143 "If enabled, use the local connection. Required Docker socket/Kubernetes Integration" 144 ), 145 ) 146 147 objects = InheritanceManager() 148 149 class Meta: 150 verbose_name = _("Outpost Service-Connection") 151 verbose_name_plural = _("Outpost Service-Connections") 152 153 def __str__(self) -> str: 154 return f"Outpost service connection {self.name}" 155 156 @property 157 def state_key(self) -> str: 158 """Key used to save connection state in cache""" 159 return f"goauthentik.io/outposts/service_connection_state/{self.pk.hex}" 160 161 @property 162 def state(self) -> OutpostServiceConnectionState: 163 """Get state of service connection""" 164 from authentik.outposts.tasks import outpost_service_connection_monitor 165 166 state = cache.get(self.state_key, None) 167 if not state: 168 outpost_service_connection_monitor.send_with_options(args=(self.pk,), rel_obj=self) 169 return OutpostServiceConnectionState("", False) 170 return state 171 172 @property 173 def component(self) -> str: 174 """Return component used to edit this object""" 175 # This is called when creating an outpost with a service connection 176 # since the response doesn't use the correct inheritance 177 return "" 178 179 @property 180 def schedule_specs(self) -> list[ScheduleSpec]: 181 from authentik.outposts.tasks import outpost_service_connection_monitor 182 183 return [ 184 ScheduleSpec( 185 actor=outpost_service_connection_monitor, 186 uid=self.name, 187 args=(self.pk,), 188 crontab="3-59/15 * * * *", 189 send_on_save=True, 190 ), 191 ]
Connection details for an Outpost Controller, like Docker or Kubernetes
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
156 @property 157 def state_key(self) -> str: 158 """Key used to save connection state in cache""" 159 return f"goauthentik.io/outposts/service_connection_state/{self.pk.hex}"
Key used to save connection state in cache
161 @property 162 def state(self) -> OutpostServiceConnectionState: 163 """Get state of service connection""" 164 from authentik.outposts.tasks import outpost_service_connection_monitor 165 166 state = cache.get(self.state_key, None) 167 if not state: 168 outpost_service_connection_monitor.send_with_options(args=(self.pk,), rel_obj=self) 169 return OutpostServiceConnectionState("", False) 170 return state
Get state of service connection
172 @property 173 def component(self) -> str: 174 """Return component used to edit this object""" 175 # This is called when creating an outpost with a service connection 176 # since the response doesn't use the correct inheritance 177 return ""
Return component used to edit this object
179 @property 180 def schedule_specs(self) -> list[ScheduleSpec]: 181 from authentik.outposts.tasks import outpost_service_connection_monitor 182 183 return [ 184 ScheduleSpec( 185 actor=outpost_service_connection_monitor, 186 uid=self.name, 187 args=(self.pk,), 188 crontab="3-59/15 * * * *", 189 send_on_save=True, 190 ), 191 ]
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related object on the reverse side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Place.restaurant is a ReverseOneToOneDescriptor instance.
Accessor to the related object on the reverse side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Place.restaurant is a ReverseOneToOneDescriptor instance.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
194class DockerServiceConnection(SerializerModel, OutpostServiceConnection): 195 """Service Connection to a Docker endpoint""" 196 197 url = models.TextField( 198 help_text=_( 199 "Can be in the format of 'unix://<path>' when connecting to a local docker daemon, " 200 "or 'https://<hostname>:2376' when connecting to a remote system." 201 ) 202 ) 203 tls_verification = models.ForeignKey( 204 CertificateKeyPair, 205 null=True, 206 blank=True, 207 default=None, 208 related_name="+", 209 on_delete=models.SET_DEFAULT, 210 help_text=_( 211 "CA which the endpoint's Certificate is verified against. " 212 "Can be left empty for no validation." 213 ), 214 ) 215 tls_authentication = models.ForeignKey( 216 CertificateKeyPair, 217 null=True, 218 blank=True, 219 default=None, 220 related_name="+", 221 on_delete=models.SET_DEFAULT, 222 help_text=_( 223 "Certificate/Key used for authentication. Can be left empty for no authentication." 224 ), 225 ) 226 227 class Meta: 228 verbose_name = _("Docker Service-Connection") 229 verbose_name_plural = _("Docker Service-Connections") 230 231 def __str__(self) -> str: 232 return f"Docker Service-Connection {self.name}" 233 234 @property 235 def serializer(self) -> Serializer: 236 from authentik.outposts.api.service_connections import DockerServiceConnectionSerializer 237 238 return DockerServiceConnectionSerializer 239 240 @property 241 def component(self) -> str: 242 return "ak-service-connection-docker-form"
Service Connection to a Docker endpoint
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
234 @property 235 def serializer(self) -> Serializer: 236 from authentik.outposts.api.service_connections import DockerServiceConnectionSerializer 237 238 return DockerServiceConnectionSerializer
Get serializer for this model
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
The requested object does not exist
The query returned multiple objects when only one was expected.
245class KubernetesServiceConnection(SerializerModel, OutpostServiceConnection): 246 """Service Connection to a Kubernetes cluster""" 247 248 kubeconfig = models.JSONField( 249 help_text=_( 250 "Paste your kubeconfig here. authentik will automatically use " 251 "the currently selected context." 252 ), 253 blank=True, 254 ) 255 verify_ssl = models.BooleanField( 256 default=True, help_text=_("Verify SSL Certificates of the Kubernetes API endpoint") 257 ) 258 259 class Meta: 260 verbose_name = _("Kubernetes Service-Connection") 261 verbose_name_plural = _("Kubernetes Service-Connections") 262 263 def __str__(self) -> str: 264 return f"Kubernetes Service-Connection {self.name}" 265 266 @property 267 def serializer(self) -> Serializer: 268 from authentik.outposts.api.service_connections import KubernetesServiceConnectionSerializer 269 270 return KubernetesServiceConnectionSerializer 271 272 @property 273 def component(self) -> str: 274 return "ak-service-connection-kubernetes-form"
Service Connection to a Kubernetes cluster
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
266 @property 267 def serializer(self) -> Serializer: 268 from authentik.outposts.api.service_connections import KubernetesServiceConnectionSerializer 269 270 return KubernetesServiceConnectionSerializer
Get serializer for this model
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
The requested object does not exist
The query returned multiple objects when only one was expected.
277class Outpost(ScheduledModel, SerializerModel, ManagedModel): 278 """Outpost instance which manages a service user and token""" 279 280 uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True) 281 name = models.TextField(unique=True) 282 283 type = models.TextField(choices=OutpostType.choices, default=OutpostType.PROXY) 284 service_connection = InheritanceForeignKey( 285 OutpostServiceConnection, 286 default=None, 287 null=True, 288 blank=True, 289 help_text=_( 290 "Select Service-Connection authentik should use to manage this outpost. " 291 "Leave empty if authentik should not handle the deployment." 292 ), 293 on_delete=models.SET_DEFAULT, 294 ) 295 296 _config = models.JSONField(default=default_outpost_config) 297 298 providers = models.ManyToManyField(Provider, through="OutpostProvider") 299 300 @property 301 def serializer(self) -> Serializer: 302 from authentik.outposts.api.outposts import OutpostSerializer 303 304 return OutpostSerializer 305 306 @property 307 def config(self) -> OutpostConfig: 308 """Load config as OutpostConfig object""" 309 return from_dict(OutpostConfig, self._config) 310 311 @config.setter 312 def config(self, value): 313 """Dump config into json""" 314 self._config = asdict(value) 315 316 @property 317 def state_cache_prefix(self) -> str: 318 """Key by which the outposts status is saved""" 319 return f"goauthentik.io/outposts/state/{self.uuid.hex}" 320 321 @property 322 def state(self) -> list[OutpostState]: 323 """Get outpost's health status""" 324 return OutpostState.for_outpost(self) 325 326 @property 327 def user_identifier(self): 328 """Username for service user""" 329 return f"{USER_PREFIX_OUTPOSTS}{self.uuid.hex}" 330 331 @property 332 def schedule_specs(self) -> list[ScheduleSpec]: 333 from authentik.outposts.tasks import outpost_controller 334 335 return [ 336 ScheduleSpec( 337 actor=outpost_controller, 338 uid=self.name, 339 args=(self.pk,), 340 kwargs={"action": "up", "from_cache": False}, 341 crontab=f"{fqdn_rand('outpost_controller')} */4 * * *", 342 send_on_save=True, 343 ), 344 ] 345 346 def build_user_permissions(self, user: User, rebuild: bool = False): 347 """Create per-object and global permissions for outpost service-account. 348 With `rebuild`, delete all of them first and recreate them, for troubleshooting.""" 349 # Only write the difference, so saving a provider whose required objects didn't change 350 # doesn't rewrite every permission row of the outpost. Concurrent transactions (such as 351 # parallel blueprint applies) would otherwise lock the same rows and deadlock. 352 permissions: dict[str, Permission] = {} 353 model_perms: dict[int, Permission] = {} 354 obj_perms: dict[tuple[int, str], Permission] = {} 355 code_name = model_or_perm = None 356 try: 357 for model_or_perm in self.get_required_objects(): 358 obj = None 359 if isinstance(model_or_perm, models.Model): 360 obj = model_or_perm 361 code_name = f"{obj._meta.app_label}.view_{obj._meta.model_name}" 362 elif isinstance(model_or_perm, tuple): 363 code_name, obj = model_or_perm 364 else: 365 code_name = model_or_perm 366 if code_name not in permissions: 367 app_label, codename = code_name.split(".", 1) 368 permissions[code_name] = Permission.objects.get( 369 content_type__app_label=app_label, codename=codename 370 ) 371 permission = permissions[code_name] 372 if obj is None: 373 model_perms[permission.pk] = permission 374 else: 375 obj_perms[(permission.pk, str(obj.pk))] = permission 376 except (Permission.DoesNotExist, AttributeError) as exc: 377 LOGGER.warning( 378 "permission doesn't exist", 379 code_name=code_name, 380 user=user, 381 model=model_or_perm, 382 ) 383 Event.new( 384 action=EventAction.SYSTEM_EXCEPTION, 385 message=( 386 "While setting the permissions for the service-account, a " 387 "permission was not found: Check " 388 "https://docs.goauthentik.io/troubleshooting/missing_permission" 389 ), 390 ).with_exception(exc).set_user(user).save() 391 return 392 with transaction.atomic(): 393 # Only after all required permissions resolved, so a missing permission doesn't 394 # leave the outpost without any 395 if rebuild: 396 user.remove_all_perms_from_managed_role() 397 role = user.get_managed_role(create=True) 398 existing_model_permissions: set[int] = set( 399 RoleModelPermission.objects.filter(role=role).values_list( 400 "permission_id", flat=True 401 ) 402 ) 403 # (permission ID, object PK) -> RoleObjectPermission PK 404 existing_obj_permissions: dict[tuple[int, str], int] = { 405 (perm_id, object_pk): pk 406 for pk, perm_id, object_pk in RoleObjectPermission.objects.filter( 407 role=role 408 ).values_list("pk", "permission_id", "object_pk") 409 } 410 if stale := existing_model_permissions - model_perms.keys(): 411 RoleModelPermission.objects.filter(role=role, permission_id__in=stale).delete() 412 if stale_pks := [ 413 pk for key, pk in existing_obj_permissions.items() if key not in obj_perms 414 ]: 415 RoleObjectPermission.objects.filter(pk__in=stale_pks).delete() 416 # Sorted, so concurrent rebuilds insert shared rows in the same order 417 RoleModelPermission.objects.bulk_create( 418 [ 419 RoleModelPermission( 420 role=role, 421 permission=model_perms[perm_id], 422 content_type_id=model_perms[perm_id].content_type_id, 423 ) 424 for perm_id in sorted(model_perms.keys() - existing_model_permissions) 425 ], 426 ignore_conflicts=True, 427 ) 428 RoleObjectPermission.objects.bulk_create( 429 [ 430 RoleObjectPermission( 431 role=role, 432 permission=obj_perms[key], 433 content_type_id=obj_perms[key].content_type_id, 434 object_pk=key[1], 435 ) 436 for key in sorted(obj_perms.keys() - existing_obj_permissions.keys()) 437 ], 438 ignore_conflicts=True, 439 ) 440 LOGGER.debug( 441 "Updated service account's permissions", 442 obj_perms=user.get_all_obj_perms_on_managed_role(), 443 perms=user.get_all_model_perms_on_managed_role(), 444 ) 445 446 @property 447 def user(self) -> User: 448 """Get/create user with access to all required objects""" 449 user = User.objects.filter(username=self.user_identifier).first() 450 user_created = False 451 if not user: 452 user: User = User.objects.create(username=self.user_identifier) 453 user_created = True 454 attrs = { 455 "type": UserTypes.INTERNAL_SERVICE_ACCOUNT, 456 "name": f"Outpost {self.name} Service-Account", 457 "path": USER_PATH_OUTPOSTS, 458 } 459 dirty = False 460 for key, value in attrs.items(): 461 if getattr(user, key) != value: 462 dirty = True 463 setattr(user, key, value) 464 if dirty: 465 user.save() 466 if user.has_usable_password(): 467 PasswordDevice.set_unusable_password(user) 468 if user_created: 469 self.build_user_permissions(user) 470 return user 471 472 @property 473 def token_identifier(self) -> str: 474 """Get Token identifier""" 475 return f"ak-outpost-{self.pk}-api" 476 477 @property 478 def token(self) -> Token: 479 """Get/create token for auto-generated user""" 480 managed = f"goauthentik.io/outpost/{self.token_identifier}" 481 tokens = Token.objects.filter( 482 identifier=self.token_identifier, 483 intent=TokenIntents.INTENT_API, 484 managed=managed, 485 ) 486 if tokens.exists(): 487 return tokens.first() 488 try: 489 return Token.objects.create( 490 user=self.user, 491 identifier=self.token_identifier, 492 intent=TokenIntents.INTENT_API, 493 description=f"Autogenerated by authentik for Outpost {self.name}", 494 expiring=False, 495 managed=managed, 496 ) 497 except IntegrityError: 498 # Integrity error happens mostly when managed is reused 499 Token.objects.filter(managed=managed).delete() 500 Token.objects.filter(identifier=self.token_identifier).delete() 501 return self.token 502 503 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 504 """Get an iterator of all objects the user needs read access to""" 505 objects: list[models.Model | str] = [ 506 self, 507 "authentik_events.add_event", 508 ] 509 for provider in Provider.objects.filter(outpost=self).select_related().select_subclasses(): 510 if isinstance(provider, OutpostModel): 511 objects.extend(provider.get_required_objects()) 512 else: 513 objects.append(provider) 514 if self.managed: 515 for brand in Brand.objects.filter(web_certificate__isnull=False): 516 objects.append(brand) 517 objects.append(("authentik_crypto.view_certificatekeypair", brand.web_certificate)) 518 objects.append( 519 ("authentik_crypto.view_certificatekeypair_certificate", brand.web_certificate) 520 ) 521 objects.append( 522 ("authentik_crypto.view_certificatekeypair_key", brand.web_certificate) 523 ) 524 return objects 525 526 def __str__(self) -> str: 527 return f"Outpost {self.name}" 528 529 class Meta: 530 verbose_name = _("Outpost") 531 verbose_name_plural = _("Outposts")
Outpost instance which manages a service user and token
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager.
Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
Pizza.toppings and Topping.pizzas are ManyToManyDescriptor
instances.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
300 @property 301 def serializer(self) -> Serializer: 302 from authentik.outposts.api.outposts import OutpostSerializer 303 304 return OutpostSerializer
Get serializer for this model
306 @property 307 def config(self) -> OutpostConfig: 308 """Load config as OutpostConfig object""" 309 return from_dict(OutpostConfig, self._config)
Load config as OutpostConfig object
316 @property 317 def state_cache_prefix(self) -> str: 318 """Key by which the outposts status is saved""" 319 return f"goauthentik.io/outposts/state/{self.uuid.hex}"
Key by which the outposts status is saved
321 @property 322 def state(self) -> list[OutpostState]: 323 """Get outpost's health status""" 324 return OutpostState.for_outpost(self)
Get outpost's health status
326 @property 327 def user_identifier(self): 328 """Username for service user""" 329 return f"{USER_PREFIX_OUTPOSTS}{self.uuid.hex}"
Username for service user
331 @property 332 def schedule_specs(self) -> list[ScheduleSpec]: 333 from authentik.outposts.tasks import outpost_controller 334 335 return [ 336 ScheduleSpec( 337 actor=outpost_controller, 338 uid=self.name, 339 args=(self.pk,), 340 kwargs={"action": "up", "from_cache": False}, 341 crontab=f"{fqdn_rand('outpost_controller')} */4 * * *", 342 send_on_save=True, 343 ), 344 ]
346 def build_user_permissions(self, user: User, rebuild: bool = False): 347 """Create per-object and global permissions for outpost service-account. 348 With `rebuild`, delete all of them first and recreate them, for troubleshooting.""" 349 # Only write the difference, so saving a provider whose required objects didn't change 350 # doesn't rewrite every permission row of the outpost. Concurrent transactions (such as 351 # parallel blueprint applies) would otherwise lock the same rows and deadlock. 352 permissions: dict[str, Permission] = {} 353 model_perms: dict[int, Permission] = {} 354 obj_perms: dict[tuple[int, str], Permission] = {} 355 code_name = model_or_perm = None 356 try: 357 for model_or_perm in self.get_required_objects(): 358 obj = None 359 if isinstance(model_or_perm, models.Model): 360 obj = model_or_perm 361 code_name = f"{obj._meta.app_label}.view_{obj._meta.model_name}" 362 elif isinstance(model_or_perm, tuple): 363 code_name, obj = model_or_perm 364 else: 365 code_name = model_or_perm 366 if code_name not in permissions: 367 app_label, codename = code_name.split(".", 1) 368 permissions[code_name] = Permission.objects.get( 369 content_type__app_label=app_label, codename=codename 370 ) 371 permission = permissions[code_name] 372 if obj is None: 373 model_perms[permission.pk] = permission 374 else: 375 obj_perms[(permission.pk, str(obj.pk))] = permission 376 except (Permission.DoesNotExist, AttributeError) as exc: 377 LOGGER.warning( 378 "permission doesn't exist", 379 code_name=code_name, 380 user=user, 381 model=model_or_perm, 382 ) 383 Event.new( 384 action=EventAction.SYSTEM_EXCEPTION, 385 message=( 386 "While setting the permissions for the service-account, a " 387 "permission was not found: Check " 388 "https://docs.goauthentik.io/troubleshooting/missing_permission" 389 ), 390 ).with_exception(exc).set_user(user).save() 391 return 392 with transaction.atomic(): 393 # Only after all required permissions resolved, so a missing permission doesn't 394 # leave the outpost without any 395 if rebuild: 396 user.remove_all_perms_from_managed_role() 397 role = user.get_managed_role(create=True) 398 existing_model_permissions: set[int] = set( 399 RoleModelPermission.objects.filter(role=role).values_list( 400 "permission_id", flat=True 401 ) 402 ) 403 # (permission ID, object PK) -> RoleObjectPermission PK 404 existing_obj_permissions: dict[tuple[int, str], int] = { 405 (perm_id, object_pk): pk 406 for pk, perm_id, object_pk in RoleObjectPermission.objects.filter( 407 role=role 408 ).values_list("pk", "permission_id", "object_pk") 409 } 410 if stale := existing_model_permissions - model_perms.keys(): 411 RoleModelPermission.objects.filter(role=role, permission_id__in=stale).delete() 412 if stale_pks := [ 413 pk for key, pk in existing_obj_permissions.items() if key not in obj_perms 414 ]: 415 RoleObjectPermission.objects.filter(pk__in=stale_pks).delete() 416 # Sorted, so concurrent rebuilds insert shared rows in the same order 417 RoleModelPermission.objects.bulk_create( 418 [ 419 RoleModelPermission( 420 role=role, 421 permission=model_perms[perm_id], 422 content_type_id=model_perms[perm_id].content_type_id, 423 ) 424 for perm_id in sorted(model_perms.keys() - existing_model_permissions) 425 ], 426 ignore_conflicts=True, 427 ) 428 RoleObjectPermission.objects.bulk_create( 429 [ 430 RoleObjectPermission( 431 role=role, 432 permission=obj_perms[key], 433 content_type_id=obj_perms[key].content_type_id, 434 object_pk=key[1], 435 ) 436 for key in sorted(obj_perms.keys() - existing_obj_permissions.keys()) 437 ], 438 ignore_conflicts=True, 439 ) 440 LOGGER.debug( 441 "Updated service account's permissions", 442 obj_perms=user.get_all_obj_perms_on_managed_role(), 443 perms=user.get_all_model_perms_on_managed_role(), 444 )
Create per-object and global permissions for outpost service-account.
With rebuild, delete all of them first and recreate them, for troubleshooting.
446 @property 447 def user(self) -> User: 448 """Get/create user with access to all required objects""" 449 user = User.objects.filter(username=self.user_identifier).first() 450 user_created = False 451 if not user: 452 user: User = User.objects.create(username=self.user_identifier) 453 user_created = True 454 attrs = { 455 "type": UserTypes.INTERNAL_SERVICE_ACCOUNT, 456 "name": f"Outpost {self.name} Service-Account", 457 "path": USER_PATH_OUTPOSTS, 458 } 459 dirty = False 460 for key, value in attrs.items(): 461 if getattr(user, key) != value: 462 dirty = True 463 setattr(user, key, value) 464 if dirty: 465 user.save() 466 if user.has_usable_password(): 467 PasswordDevice.set_unusable_password(user) 468 if user_created: 469 self.build_user_permissions(user) 470 return user
Get/create user with access to all required objects
472 @property 473 def token_identifier(self) -> str: 474 """Get Token identifier""" 475 return f"ak-outpost-{self.pk}-api"
Get Token identifier
477 @property 478 def token(self) -> Token: 479 """Get/create token for auto-generated user""" 480 managed = f"goauthentik.io/outpost/{self.token_identifier}" 481 tokens = Token.objects.filter( 482 identifier=self.token_identifier, 483 intent=TokenIntents.INTENT_API, 484 managed=managed, 485 ) 486 if tokens.exists(): 487 return tokens.first() 488 try: 489 return Token.objects.create( 490 user=self.user, 491 identifier=self.token_identifier, 492 intent=TokenIntents.INTENT_API, 493 description=f"Autogenerated by authentik for Outpost {self.name}", 494 expiring=False, 495 managed=managed, 496 ) 497 except IntegrityError: 498 # Integrity error happens mostly when managed is reused 499 Token.objects.filter(managed=managed).delete() 500 Token.objects.filter(identifier=self.token_identifier).delete() 501 return self.token
Get/create token for auto-generated user
503 def get_required_objects(self) -> Iterable[models.Model | str | tuple[str, models.Model]]: 504 """Get an iterator of all objects the user needs read access to""" 505 objects: list[models.Model | str] = [ 506 self, 507 "authentik_events.add_event", 508 ] 509 for provider in Provider.objects.filter(outpost=self).select_related().select_subclasses(): 510 if isinstance(provider, OutpostModel): 511 objects.extend(provider.get_required_objects()) 512 else: 513 objects.append(provider) 514 if self.managed: 515 for brand in Brand.objects.filter(web_certificate__isnull=False): 516 objects.append(brand) 517 objects.append(("authentik_crypto.view_certificatekeypair", brand.web_certificate)) 518 objects.append( 519 ("authentik_crypto.view_certificatekeypair_certificate", brand.web_certificate) 520 ) 521 objects.append( 522 ("authentik_crypto.view_certificatekeypair_key", brand.web_certificate) 523 ) 524 return objects
Get an iterator of all objects the user needs read access to
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
534class OutpostProvider(SimpleThroughModel): 535 outpost = models.ForeignKey(Outpost, on_delete=models.CASCADE) 536 provider = models.ForeignKey(Provider, on_delete=models.CASCADE) 537 538 class Meta: 539 db_table = "authentik_outposts_outpost_providers" 540 unique_together = (("outpost", "provider"),) 541 verbose_name = _("Outpost Provider") 542 verbose_name_plural = _("Outpost Providers") 543 544 def __str__(self): 545 return f"OutpostProvider for Outpost {self.outpost_id} and Provider {self.provider_id}."
OutpostProvider(id, outpost, 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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
548@dataclass 549class OutpostState: 550 """Outpost instance state, last_seen and version""" 551 552 uid: str 553 last_seen: datetime | None = field(default=None) 554 version: str | None = field(default=None) 555 build_hash: str = field(default="") 556 golang_version: str = field(default="") 557 openssl_enabled: bool = field(default=False) 558 openssl_version: str = field(default="") 559 fips_enabled: bool = field(default=False) 560 hostname: str = field(default="") 561 args: dict = field(default_factory=dict) 562 563 _outpost: Outpost | None = field(default=None) 564 565 @property 566 def version_outdated(self) -> bool: 567 """Check if outpost version matches our version""" 568 if not self.version: 569 return False 570 if self.build_hash != authentik_build_hash(): 571 return False 572 return parse(self.version) != OUR_VERSION 573 574 @staticmethod 575 def for_outpost(outpost: Outpost) -> list[OutpostState]: 576 """Get all states for an outpost""" 577 keys = cache.keys(f"{outpost.state_cache_prefix}/*") 578 if not keys: 579 return [] 580 states = [] 581 for key in keys: 582 instance_uid = key.replace(f"{outpost.state_cache_prefix}/", "") 583 states.append(OutpostState.for_instance_uid(outpost, instance_uid)) 584 return states 585 586 @staticmethod 587 def for_instance_uid(outpost: Outpost, uid: str) -> OutpostState: 588 """Get state for a single instance""" 589 key = f"{outpost.state_cache_prefix}/{uid}" 590 default_data = {"uid": uid} 591 data = cache.get(key, default_data) 592 if isinstance(data, str): 593 cache.delete(key) 594 data = default_data 595 state = from_dict(OutpostState, data) 596 597 state._outpost = outpost 598 return state 599 600 def save(self, timeout=OUTPOST_HELLO_INTERVAL): 601 """Save current state to cache""" 602 full_key = f"{self._outpost.state_cache_prefix}/{self.uid}" 603 return cache.set(full_key, asdict(self), timeout=timeout) 604 605 def delete(self): 606 """Manually delete from cache, used on channel disconnect""" 607 full_key = f"{self._outpost.state_cache_prefix}/{self.uid}" 608 cache.delete(full_key)
Outpost instance state, last_seen and version
565 @property 566 def version_outdated(self) -> bool: 567 """Check if outpost version matches our version""" 568 if not self.version: 569 return False 570 if self.build_hash != authentik_build_hash(): 571 return False 572 return parse(self.version) != OUR_VERSION
Check if outpost version matches our version
574 @staticmethod 575 def for_outpost(outpost: Outpost) -> list[OutpostState]: 576 """Get all states for an outpost""" 577 keys = cache.keys(f"{outpost.state_cache_prefix}/*") 578 if not keys: 579 return [] 580 states = [] 581 for key in keys: 582 instance_uid = key.replace(f"{outpost.state_cache_prefix}/", "") 583 states.append(OutpostState.for_instance_uid(outpost, instance_uid)) 584 return states
Get all states for an outpost
586 @staticmethod 587 def for_instance_uid(outpost: Outpost, uid: str) -> OutpostState: 588 """Get state for a single instance""" 589 key = f"{outpost.state_cache_prefix}/{uid}" 590 default_data = {"uid": uid} 591 data = cache.get(key, default_data) 592 if isinstance(data, str): 593 cache.delete(key) 594 data = default_data 595 state = from_dict(OutpostState, data) 596 597 state._outpost = outpost 598 return state
Get state for a single instance