authentik.outposts.tasks
outpost tasks
1"""outpost tasks""" 2 3from hashlib import sha256 4from os import R_OK, access 5from pathlib import Path 6from socket import gethostname 7from typing import Any 8from urllib.parse import urlparse 9 10from channels.layers import get_channel_layer 11from django.core.cache import cache 12from django.utils.translation import gettext_lazy as _ 13from dramatiq.actor import actor 14from structlog.stdlib import get_logger 15from yaml import safe_load 16 17from authentik.lib.config import CONFIG 18from authentik.outposts.consumer import build_outpost_group 19from authentik.outposts.controllers.base import BaseController, ControllerException 20from authentik.outposts.models import ( 21 DockerServiceConnection, 22 KubernetesServiceConnection, 23 Outpost, 24 OutpostServiceConnection, 25 OutpostType, 26 ServiceConnectionInvalid, 27) 28from authentik.tasks.middleware import CurrentTask 29 30LOGGER = get_logger() 31CACHE_KEY_OUTPOST_DOWN = "goauthentik.io/outposts/teardown/%s" 32 33 34def hash_session_key(session_key: str) -> str: 35 """Hash the session key for sending session end signals""" 36 return sha256(session_key.encode("ascii")).hexdigest() 37 38 39def controller_for_outpost(outpost: Outpost) -> type[BaseController] | None: 40 """Get a controller for the outpost, when a service connection is defined""" 41 if not outpost.service_connection: 42 return None 43 service_connection = outpost.service_connection 44 # Controllers pull in the docker or kubernetes client, only import the one in use 45 if isinstance(service_connection, DockerServiceConnection): 46 from authentik.providers.ldap.controllers.docker import LDAPDockerController 47 from authentik.providers.proxy.controllers.docker import ProxyDockerController 48 from authentik.providers.rac.controllers.docker import RACDockerController 49 from authentik.providers.radius.controllers.docker import RadiusDockerController 50 51 return { 52 OutpostType.PROXY: ProxyDockerController, 53 OutpostType.LDAP: LDAPDockerController, 54 OutpostType.RADIUS: RadiusDockerController, 55 OutpostType.RAC: RACDockerController, 56 }.get(outpost.type) 57 if isinstance(service_connection, KubernetesServiceConnection): 58 from authentik.providers.ldap.controllers.kubernetes import LDAPKubernetesController 59 from authentik.providers.proxy.controllers.kubernetes import ProxyKubernetesController 60 from authentik.providers.rac.controllers.kubernetes import RACKubernetesController 61 from authentik.providers.radius.controllers.kubernetes import RadiusKubernetesController 62 63 return { 64 OutpostType.PROXY: ProxyKubernetesController, 65 OutpostType.LDAP: LDAPKubernetesController, 66 OutpostType.RADIUS: RadiusKubernetesController, 67 OutpostType.RAC: RACKubernetesController, 68 }.get(outpost.type) 69 return None 70 71 72@actor(description=_("Update cached state of service connection.")) 73def outpost_service_connection_monitor(connection_pk: Any): 74 """Update cached state of a service connection""" 75 connection: OutpostServiceConnection = ( 76 OutpostServiceConnection.objects.filter(pk=connection_pk).select_subclasses().first() 77 ) 78 if not connection: 79 return 80 cls = None 81 if isinstance(connection, DockerServiceConnection): 82 from authentik.outposts.controllers.docker import DockerClient 83 84 cls = DockerClient 85 if isinstance(connection, KubernetesServiceConnection): 86 from authentik.outposts.controllers.kubernetes import KubernetesClient 87 88 cls = KubernetesClient 89 if not cls: 90 LOGGER.warning("No class found for service connection", connection=connection) 91 return 92 try: 93 with cls(connection) as client: 94 state = client.fetch_state() 95 except ServiceConnectionInvalid as exc: 96 LOGGER.warning("Failed to get client status", exc=exc) 97 return 98 cache.set(connection.state_key, state, timeout=None) 99 100 101@actor(description=_("Create/update/monitor/delete the deployment of an Outpost.")) 102def outpost_controller(outpost_pk: str, action: str = "up", from_cache: bool = False): 103 """Create/update/monitor/delete the deployment of an Outpost""" 104 self = CurrentTask.get_task() 105 logs = [] 106 if from_cache: 107 outpost: Outpost = cache.get(CACHE_KEY_OUTPOST_DOWN % outpost_pk) 108 LOGGER.debug("Getting outpost from cache to delete") 109 else: 110 outpost: Outpost = Outpost.objects.filter(pk=outpost_pk).first() 111 LOGGER.debug("Getting outpost from DB") 112 if not outpost: 113 LOGGER.warning("No outpost") 114 return 115 try: 116 controller_type = controller_for_outpost(outpost) 117 if not controller_type: 118 return 119 with controller_type(outpost, outpost.service_connection) as controller: 120 LOGGER.debug("---------------Outpost Controller logs starting----------------") 121 logs = getattr(controller, f"{action}_with_logs")() 122 LOGGER.debug("-----------------Outpost Controller logs end-------------------") 123 except (ControllerException, ServiceConnectionInvalid) as exc: 124 self.error(exc) 125 else: 126 if from_cache: 127 cache.delete(CACHE_KEY_OUTPOST_DOWN % outpost_pk) 128 self.logs(logs) 129 130 131@actor(description=_("Ensure that all Outposts have valid Service Accounts and Tokens.")) 132def outpost_token_ensurer(): 133 """ 134 Periodically ensure that all Outposts have valid Service Accounts and Tokens 135 """ 136 self = CurrentTask.get_task() 137 all_outposts = Outpost.objects.all() 138 for outpost in all_outposts: 139 _ = outpost.token 140 outpost.build_user_permissions(outpost.user) 141 self.info(f"Successfully checked {len(all_outposts)} Outposts.") 142 143 144@actor(description=_("Send update to outpost")) 145def outpost_send_update(pk: Any): 146 """Update outpost instance""" 147 outpost = Outpost.objects.filter(pk=pk).first() 148 if not outpost: 149 return 150 # Ensure token again, because this function is called when anything related to an 151 # OutpostModel is saved, so we can be sure permissions are right 152 _ = outpost.token 153 outpost.build_user_permissions(outpost.user) 154 layer = get_channel_layer() 155 group = build_outpost_group(outpost.pk) 156 LOGGER.debug("sending update", channel=group, outpost=outpost) 157 layer.group_send_blocking(group, {"type": "event.update"}) 158 159 160@actor(description=_("Checks the local environment and create Service connections.")) 161def outpost_connection_discovery(): 162 """Checks the local environment and create Service connections.""" 163 self = CurrentTask.get_task() 164 if not CONFIG.get_bool("outposts.discover"): 165 self.info("Outpost integration discovery is disabled") 166 return 167 from docker.constants import DEFAULT_UNIX_SOCKET 168 from kubernetes.config.incluster_config import SERVICE_TOKEN_FILENAME 169 from kubernetes.config.kube_config import KUBE_CONFIG_DEFAULT_LOCATION 170 171 # Explicitly check against token filename, as that's 172 # only present when the integration is enabled 173 if Path(SERVICE_TOKEN_FILENAME).exists(): 174 self.info("Detected in-cluster Kubernetes Config") 175 if not KubernetesServiceConnection.objects.filter(local=True).exists(): 176 self.info("Created Service Connection for in-cluster") 177 KubernetesServiceConnection.objects.create( 178 name="Local Kubernetes Cluster", local=True, kubeconfig={} 179 ) 180 # For development, check for the existence of a kubeconfig file 181 kubeconfig_path = Path(KUBE_CONFIG_DEFAULT_LOCATION).expanduser() 182 if kubeconfig_path.exists(): 183 self.info("Detected kubeconfig") 184 kubeconfig_local_name = f"k8s-{gethostname()}" 185 if not KubernetesServiceConnection.objects.filter(name=kubeconfig_local_name).exists(): 186 self.info("Creating kubeconfig Service Connection") 187 with kubeconfig_path.open("r", encoding="utf8") as _kubeconfig: 188 KubernetesServiceConnection.objects.create( 189 name=kubeconfig_local_name, 190 kubeconfig=safe_load(_kubeconfig), 191 ) 192 unix_socket_path = urlparse(DEFAULT_UNIX_SOCKET).path 193 socket = Path(unix_socket_path) 194 if socket.exists() and access(socket, R_OK): 195 self.info("Detected local docker socket") 196 if len(DockerServiceConnection.objects.filter(local=True)) == 0: 197 self.info("Created Service Connection for docker") 198 DockerServiceConnection.objects.create( 199 name="Local Docker connection", 200 local=True, 201 url=unix_socket_path, 202 ) 203 204 205@actor(description=_("Terminate session on all outposts.")) 206def outpost_session_end(session_id: str): 207 layer = get_channel_layer() 208 hashed_session_id = hash_session_key(session_id) 209 for outpost in Outpost.objects.all(): 210 LOGGER.info("Sending session end signal to outpost", outpost=outpost) 211 group = build_outpost_group(outpost.pk) 212 layer.group_send_blocking( 213 group, 214 { 215 "type": "event.session.end", 216 "session_id": hashed_session_id, 217 }, 218 )
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
CACHE_KEY_OUTPOST_DOWN =
'goauthentik.io/outposts/teardown/%s'
def
hash_session_key(session_key: str) -> str:
35def hash_session_key(session_key: str) -> str: 36 """Hash the session key for sending session end signals""" 37 return sha256(session_key.encode("ascii")).hexdigest()
Hash the session key for sending session end signals
def
controller_for_outpost( outpost: authentik.outposts.models.Outpost) -> type[authentik.outposts.controllers.base.BaseController] | None:
40def controller_for_outpost(outpost: Outpost) -> type[BaseController] | None: 41 """Get a controller for the outpost, when a service connection is defined""" 42 if not outpost.service_connection: 43 return None 44 service_connection = outpost.service_connection 45 # Controllers pull in the docker or kubernetes client, only import the one in use 46 if isinstance(service_connection, DockerServiceConnection): 47 from authentik.providers.ldap.controllers.docker import LDAPDockerController 48 from authentik.providers.proxy.controllers.docker import ProxyDockerController 49 from authentik.providers.rac.controllers.docker import RACDockerController 50 from authentik.providers.radius.controllers.docker import RadiusDockerController 51 52 return { 53 OutpostType.PROXY: ProxyDockerController, 54 OutpostType.LDAP: LDAPDockerController, 55 OutpostType.RADIUS: RadiusDockerController, 56 OutpostType.RAC: RACDockerController, 57 }.get(outpost.type) 58 if isinstance(service_connection, KubernetesServiceConnection): 59 from authentik.providers.ldap.controllers.kubernetes import LDAPKubernetesController 60 from authentik.providers.proxy.controllers.kubernetes import ProxyKubernetesController 61 from authentik.providers.rac.controllers.kubernetes import RACKubernetesController 62 from authentik.providers.radius.controllers.kubernetes import RadiusKubernetesController 63 64 return { 65 OutpostType.PROXY: ProxyKubernetesController, 66 OutpostType.LDAP: LDAPKubernetesController, 67 OutpostType.RADIUS: RadiusKubernetesController, 68 OutpostType.RAC: RACKubernetesController, 69 }.get(outpost.type) 70 return None
Get a controller for the outpost, when a service connection is defined
outpost_service_connection_monitor =
Actor(<function outpost_service_connection_monitor>, queue_name='default', actor_name='outpost_service_connection_monitor')
Update cached state of a service connection
outpost_controller =
Actor(<function outpost_controller>, queue_name='default', actor_name='outpost_controller')
Create/update/monitor/delete the deployment of an Outpost
outpost_token_ensurer =
Actor(<function outpost_token_ensurer>, queue_name='default', actor_name='outpost_token_ensurer')
Periodically ensure that all Outposts have valid Service Accounts and Tokens
outpost_send_update =
Actor(<function outpost_send_update>, queue_name='default', actor_name='outpost_send_update')
Update outpost instance
outpost_connection_discovery =
Actor(<function outpost_connection_discovery>, queue_name='default', actor_name='outpost_connection_discovery')
Checks the local environment and create Service connections.