authentik.providers.rac.views
RAC Views
1"""RAC Views""" 2 3from typing import Any 4 5from django.http import Http404, HttpRequest, HttpResponse 6from django.shortcuts import get_object_or_404, redirect 7from django.urls import reverse 8from django.utils.timezone import now 9from django.utils.translation import gettext as _ 10 11from authentik.core.models import Application 12from authentik.core.views.interface import InterfaceView 13from authentik.endpoints.models import Device 14from authentik.events.models import Event, EventAction 15from authentik.flows.challenge import RedirectChallenge 16from authentik.flows.exceptions import FlowNonApplicableException 17from authentik.flows.models import in_memory_stage 18from authentik.flows.planner import PLAN_CONTEXT_APPLICATION, FlowPlanner 19from authentik.flows.stage import RedirectStage 20from authentik.lib.utils.time import timedelta_from_string 21from authentik.policies.engine import PolicyEngine 22from authentik.policies.views import PolicyAccessView 23from authentik.providers.rac.models import ConnectionToken, RACProvider, available_protocols 24from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT 25 26PLAN_CONNECTION_SETTINGS = "connection_settings" 27# The connection this flow authorized, so that re-requesting the challenge doesn't 28# authorize a second one 29PLAN_CONTEXT_CONNECTION_TOKEN = "connection_token" # nosec 30# The device that is being connected to. Distinct from `PLAN_CONTEXT_DEVICE`, which 31# holds the device a user is authenticating from. 32PLAN_CONTEXT_RAC_DEVICE = "rac_device" 33 34 35class RACStartView(PolicyAccessView): 36 """Start a RAC connection by checking access and creating a connection token""" 37 38 device: Device 39 protocol: str 40 41 def resolve_provider_application(self): 42 self.application = get_object_or_404(Application, slug=self.kwargs["app"]) 43 self.provider = RACProvider.objects.get(application=self.application) 44 # The device must be accessible through this application's provider; the 45 # policies bound to the device itself are validated in the RACFinalStage below 46 self.device = get_object_or_404(self.provider.devices(), pk=self.kwargs["device"]) 47 # ...and it must be reachable with the requested protocol 48 self.protocol = self.kwargs["protocol"] 49 if self.protocol not in available_protocols(self.device): 50 raise Http404 51 52 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 53 """Start flow planner for RAC provider""" 54 planner = FlowPlanner(self.provider.authorization_flow) 55 planner.allow_empty_flows = True 56 try: 57 plan = planner.plan( 58 self.request, 59 { 60 PLAN_CONTEXT_APPLICATION: self.application, 61 # so that policies and stages in the authorization flow can 62 # check the device that is being connected to 63 PLAN_CONTEXT_RAC_DEVICE: self.device, 64 }, 65 ) 66 except FlowNonApplicableException: 67 raise Http404 from None 68 plan.append_stage( 69 in_memory_stage( 70 RACFinalStage, 71 application=self.application, 72 device=self.device, 73 protocol=self.protocol, 74 provider=self.provider, 75 ) 76 ) 77 return plan.to_redirect(request, self.provider.authorization_flow) 78 79 80class RACInterface(InterfaceView): 81 """Start RAC connection""" 82 83 template_name = "if/rac.html" 84 token: ConnectionToken 85 86 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 87 # Early sanity check to ensure token still exists 88 token = ConnectionToken.objects.filter( 89 token=self.kwargs["token"], 90 session__session__session_key=request.session.session_key, 91 ).first() 92 if not token: 93 return redirect("authentik_core:if-user") 94 self.token = token 95 return super().dispatch(request, *args, **kwargs) 96 97 def get_context_data(self, **kwargs: Any) -> dict[str, Any]: 98 kwargs["token"] = self.token 99 return super().get_context_data(**kwargs) 100 101 102class RACFinalStage(RedirectStage): 103 """RAC Connection final stage, set the connection token in the stage""" 104 105 device: Device 106 protocol: str 107 provider: RACProvider 108 application: Application 109 110 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 111 self.device = self.executor.current_stage.device 112 self.protocol = self.executor.current_stage.protocol 113 self.provider = self.executor.current_stage.provider 114 self.application = self.executor.current_stage.application 115 # Check policies bound to the device directly, which includes both device 116 # compliance policies and the bindings of users and groups to the device 117 engine = PolicyEngine(self.device, self.request.user, self.request) 118 engine.use_cache = False 119 engine.build() 120 passing = engine.result 121 if not passing.passing: 122 return self.executor.stage_invalid(", ".join(passing.messages)) 123 # Check if we're already at the maximum connection limit 124 all_tokens = ConnectionToken.objects.filter( 125 device=self.device, 126 provider=self.provider, 127 ) 128 if self.provider.maximum_connections > -1: 129 if all_tokens.count() >= self.provider.maximum_connections: 130 msg = [_("Maximum connection limit reached.")] 131 # Check if any other tokens exist for the current user, and inform them 132 # they are already connected 133 if all_tokens.filter(session__user=self.request.user).exists(): 134 msg.append(_("(You are already connected in another tab/window)")) 135 return self.executor.stage_invalid(" ".join(msg)) 136 return super().dispatch(request, *args, **kwargs) 137 138 def get_challenge(self, *args, **kwargs) -> RedirectChallenge: 139 token = self.executor.plan.context.get(PLAN_CONTEXT_CONNECTION_TOKEN) 140 if not token: 141 token = self.authorize_connection() 142 self.executor.plan.context[PLAN_CONTEXT_CONNECTION_TOKEN] = token 143 self.executor.current_stage.destination = self.request.build_absolute_uri( 144 reverse("authentik_providers_rac:if-rac", kwargs={"token": str(token.token)}) 145 ) 146 return super().get_challenge(*args, **kwargs) 147 148 def authorize_connection(self) -> ConnectionToken: 149 """Authorize a single connection to the device""" 150 settings = self.executor.plan.context.get(PLAN_CONNECTION_SETTINGS) 151 if not settings: 152 settings = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).get( 153 PLAN_CONNECTION_SETTINGS 154 ) 155 token = ConnectionToken.objects.create( 156 provider=self.provider, 157 device=self.device, 158 protocol=self.protocol, 159 settings=settings or {}, 160 session=self.request.session["authenticatedsession"], 161 expires=now() + timedelta_from_string(self.provider.connection_expiry), 162 expiring=True, 163 ) 164 Event.new( 165 EventAction.AUTHORIZE_APPLICATION, 166 authorized_application=self.application, 167 flow=self.executor.plan.flow_pk, 168 device=self.device.name, 169 protocol=self.protocol, 170 ).from_http(self.request) 171 return token
PLAN_CONNECTION_SETTINGS =
'connection_settings'
PLAN_CONTEXT_CONNECTION_TOKEN =
'connection_token'
PLAN_CONTEXT_RAC_DEVICE =
'rac_device'
36class RACStartView(PolicyAccessView): 37 """Start a RAC connection by checking access and creating a connection token""" 38 39 device: Device 40 protocol: str 41 42 def resolve_provider_application(self): 43 self.application = get_object_or_404(Application, slug=self.kwargs["app"]) 44 self.provider = RACProvider.objects.get(application=self.application) 45 # The device must be accessible through this application's provider; the 46 # policies bound to the device itself are validated in the RACFinalStage below 47 self.device = get_object_or_404(self.provider.devices(), pk=self.kwargs["device"]) 48 # ...and it must be reachable with the requested protocol 49 self.protocol = self.kwargs["protocol"] 50 if self.protocol not in available_protocols(self.device): 51 raise Http404 52 53 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 54 """Start flow planner for RAC provider""" 55 planner = FlowPlanner(self.provider.authorization_flow) 56 planner.allow_empty_flows = True 57 try: 58 plan = planner.plan( 59 self.request, 60 { 61 PLAN_CONTEXT_APPLICATION: self.application, 62 # so that policies and stages in the authorization flow can 63 # check the device that is being connected to 64 PLAN_CONTEXT_RAC_DEVICE: self.device, 65 }, 66 ) 67 except FlowNonApplicableException: 68 raise Http404 from None 69 plan.append_stage( 70 in_memory_stage( 71 RACFinalStage, 72 application=self.application, 73 device=self.device, 74 protocol=self.protocol, 75 provider=self.provider, 76 ) 77 ) 78 return plan.to_redirect(request, self.provider.authorization_flow)
Start a RAC connection by checking access and creating a connection token
def
resolve_provider_application(self):
42 def resolve_provider_application(self): 43 self.application = get_object_or_404(Application, slug=self.kwargs["app"]) 44 self.provider = RACProvider.objects.get(application=self.application) 45 # The device must be accessible through this application's provider; the 46 # policies bound to the device itself are validated in the RACFinalStage below 47 self.device = get_object_or_404(self.provider.devices(), pk=self.kwargs["device"]) 48 # ...and it must be reachable with the requested protocol 49 self.protocol = self.kwargs["protocol"] 50 if self.protocol not in available_protocols(self.device): 51 raise Http404
Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal AccessDenied view to be shown. An Http404 exception is not caught, and will return directly
def
get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
53 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 54 """Start flow planner for RAC provider""" 55 planner = FlowPlanner(self.provider.authorization_flow) 56 planner.allow_empty_flows = True 57 try: 58 plan = planner.plan( 59 self.request, 60 { 61 PLAN_CONTEXT_APPLICATION: self.application, 62 # so that policies and stages in the authorization flow can 63 # check the device that is being connected to 64 PLAN_CONTEXT_RAC_DEVICE: self.device, 65 }, 66 ) 67 except FlowNonApplicableException: 68 raise Http404 from None 69 plan.append_stage( 70 in_memory_stage( 71 RACFinalStage, 72 application=self.application, 73 device=self.device, 74 protocol=self.protocol, 75 provider=self.provider, 76 ) 77 ) 78 return plan.to_redirect(request, self.provider.authorization_flow)
Start flow planner for RAC provider
81class RACInterface(InterfaceView): 82 """Start RAC connection""" 83 84 template_name = "if/rac.html" 85 token: ConnectionToken 86 87 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 88 # Early sanity check to ensure token still exists 89 token = ConnectionToken.objects.filter( 90 token=self.kwargs["token"], 91 session__session__session_key=request.session.session_key, 92 ).first() 93 if not token: 94 return redirect("authentik_core:if-user") 95 self.token = token 96 return super().dispatch(request, *args, **kwargs) 97 98 def get_context_data(self, **kwargs: Any) -> dict[str, Any]: 99 kwargs["token"] = self.token 100 return super().get_context_data(**kwargs)
Start RAC connection
def
dispatch( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
87 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 88 # Early sanity check to ensure token still exists 89 token = ConnectionToken.objects.filter( 90 token=self.kwargs["token"], 91 session__session__session_key=request.session.session_key, 92 ).first() 93 if not token: 94 return redirect("authentik_core:if-user") 95 self.token = token 96 return super().dispatch(request, *args, **kwargs)
103class RACFinalStage(RedirectStage): 104 """RAC Connection final stage, set the connection token in the stage""" 105 106 device: Device 107 protocol: str 108 provider: RACProvider 109 application: Application 110 111 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 112 self.device = self.executor.current_stage.device 113 self.protocol = self.executor.current_stage.protocol 114 self.provider = self.executor.current_stage.provider 115 self.application = self.executor.current_stage.application 116 # Check policies bound to the device directly, which includes both device 117 # compliance policies and the bindings of users and groups to the device 118 engine = PolicyEngine(self.device, self.request.user, self.request) 119 engine.use_cache = False 120 engine.build() 121 passing = engine.result 122 if not passing.passing: 123 return self.executor.stage_invalid(", ".join(passing.messages)) 124 # Check if we're already at the maximum connection limit 125 all_tokens = ConnectionToken.objects.filter( 126 device=self.device, 127 provider=self.provider, 128 ) 129 if self.provider.maximum_connections > -1: 130 if all_tokens.count() >= self.provider.maximum_connections: 131 msg = [_("Maximum connection limit reached.")] 132 # Check if any other tokens exist for the current user, and inform them 133 # they are already connected 134 if all_tokens.filter(session__user=self.request.user).exists(): 135 msg.append(_("(You are already connected in another tab/window)")) 136 return self.executor.stage_invalid(" ".join(msg)) 137 return super().dispatch(request, *args, **kwargs) 138 139 def get_challenge(self, *args, **kwargs) -> RedirectChallenge: 140 token = self.executor.plan.context.get(PLAN_CONTEXT_CONNECTION_TOKEN) 141 if not token: 142 token = self.authorize_connection() 143 self.executor.plan.context[PLAN_CONTEXT_CONNECTION_TOKEN] = token 144 self.executor.current_stage.destination = self.request.build_absolute_uri( 145 reverse("authentik_providers_rac:if-rac", kwargs={"token": str(token.token)}) 146 ) 147 return super().get_challenge(*args, **kwargs) 148 149 def authorize_connection(self) -> ConnectionToken: 150 """Authorize a single connection to the device""" 151 settings = self.executor.plan.context.get(PLAN_CONNECTION_SETTINGS) 152 if not settings: 153 settings = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).get( 154 PLAN_CONNECTION_SETTINGS 155 ) 156 token = ConnectionToken.objects.create( 157 provider=self.provider, 158 device=self.device, 159 protocol=self.protocol, 160 settings=settings or {}, 161 session=self.request.session["authenticatedsession"], 162 expires=now() + timedelta_from_string(self.provider.connection_expiry), 163 expiring=True, 164 ) 165 Event.new( 166 EventAction.AUTHORIZE_APPLICATION, 167 authorized_application=self.application, 168 flow=self.executor.plan.flow_pk, 169 device=self.device.name, 170 protocol=self.protocol, 171 ).from_http(self.request) 172 return token
RAC Connection final stage, set the connection token in the stage
application: authentik.core.models.Application
def
dispatch( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
111 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 112 self.device = self.executor.current_stage.device 113 self.protocol = self.executor.current_stage.protocol 114 self.provider = self.executor.current_stage.provider 115 self.application = self.executor.current_stage.application 116 # Check policies bound to the device directly, which includes both device 117 # compliance policies and the bindings of users and groups to the device 118 engine = PolicyEngine(self.device, self.request.user, self.request) 119 engine.use_cache = False 120 engine.build() 121 passing = engine.result 122 if not passing.passing: 123 return self.executor.stage_invalid(", ".join(passing.messages)) 124 # Check if we're already at the maximum connection limit 125 all_tokens = ConnectionToken.objects.filter( 126 device=self.device, 127 provider=self.provider, 128 ) 129 if self.provider.maximum_connections > -1: 130 if all_tokens.count() >= self.provider.maximum_connections: 131 msg = [_("Maximum connection limit reached.")] 132 # Check if any other tokens exist for the current user, and inform them 133 # they are already connected 134 if all_tokens.filter(session__user=self.request.user).exists(): 135 msg.append(_("(You are already connected in another tab/window)")) 136 return self.executor.stage_invalid(" ".join(msg)) 137 return super().dispatch(request, *args, **kwargs)
139 def get_challenge(self, *args, **kwargs) -> RedirectChallenge: 140 token = self.executor.plan.context.get(PLAN_CONTEXT_CONNECTION_TOKEN) 141 if not token: 142 token = self.authorize_connection() 143 self.executor.plan.context[PLAN_CONTEXT_CONNECTION_TOKEN] = token 144 self.executor.current_stage.destination = self.request.build_absolute_uri( 145 reverse("authentik_providers_rac:if-rac", kwargs={"token": str(token.token)}) 146 ) 147 return super().get_challenge(*args, **kwargs)
Return the challenge that the client should solve