authentik.enterprise.requests.api.grant_requests
1from datetime import timedelta 2from http import HTTPMethod 3 4from django.db.models import Q 5from django.http import Http404 6from django.utils.timezone import now 7from django.utils.translation import gettext_lazy as _ 8from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field 9from rest_framework.decorators import action 10from rest_framework.exceptions import PermissionDenied, ValidationError 11from rest_framework.fields import BooleanField, CharField, ChoiceField, SerializerMethodField 12from rest_framework.mixins import ( 13 DestroyModelMixin, 14 ListModelMixin, 15 RetrieveModelMixin, 16) 17from rest_framework.permissions import IsAuthenticated 18from rest_framework.request import Request 19from rest_framework.response import Response 20from rest_framework.viewsets import GenericViewSet 21 22from authentik.api.validation import validate 23from authentik.brands.models import Brand 24from authentik.core.api.groups import PartialUserSerializer 25from authentik.core.api.utils import ( 26 JSONDictField, 27 LinkSerializer, 28 ModelSerializer, 29 PassiveSerializer, 30) 31from authentik.core.apps import AppAccessWithoutBindings 32from authentik.core.models import User 33from authentik.core.sources.flow_manager import MessageStage 34from authentik.enterprise.agents.models import Agent 35from authentik.enterprise.api import EnterpriseRequiredMixin, enterprise_action 36from authentik.enterprise.requests.api.apps import ( 37 RequestableTargetSerializer, 38 granting_rule_bindings, 39 user_can_request, 40) 41from authentik.enterprise.requests.grants import ( 42 GrantExpiry, 43 create_grant_request, 44 fulfill_url, 45) 46from authentik.enterprise.requests.models import ( 47 GrantRequest, 48 RequestRule, 49 RequestRuleBinding, 50 RequestStatus, 51) 52from authentik.enterprise.requests.stage import ( 53 PLAN_CONTEXT_GRANT_MAX_EXPIRY, 54 PLAN_CONTEXT_GRANT_PENDING_EXPIRY, 55 PLAN_CONTEXT_GRANT_REQUESTED_EXPIRY, 56 PLAN_CONTEXT_GRANT_REQUESTED_PBMS, 57 GrantRequestFinalStageView, 58) 59from authentik.flows.models import Flow, in_memory_stage 60from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner 61from authentik.lib.utils.time import timedelta_from_string, timedelta_string_validator 62from authentik.policies.api.bindings import PolicyBindingModelForeignKey 63from authentik.policies.engine import ListPolicyEngine 64from authentik.policies.models import PolicyBindingModel, RequestableChildModel, RequestableModel 65from authentik.rbac.decorators import permission_required 66 67 68def _owner_holds( 69 pbms: list[PolicyBindingModel], owner: User, request: Request 70) -> set[PolicyBindingModel]: 71 """The subset of `pbms` that `owner` already has access to.""" 72 children = [pbm for pbm in pbms if isinstance(pbm, RequestableChildModel)] 73 parents = [pbm for pbm in pbms if not isinstance(pbm, RequestableChildModel)] 74 held = set() 75 for targets, empty_result in ((parents, AppAccessWithoutBindings.get()), (children, False)): 76 if not targets: 77 continue 78 engine = ListPolicyEngine( 79 PolicyBindingModel.objects.filter(pbm_uuid__in=[pbm.pbm_uuid for pbm in targets]), 80 owner, 81 request, 82 ) 83 engine.empty_result = empty_result 84 held |= {obj.pbm_uuid for obj in engine.build().result} 85 return held 86 87 88def _binding_default(field_name: str) -> timedelta: 89 """A `RequestRuleBinding` expiry field default. RequestRules play no part in an agent's 90 request, so it has no binding to take a duration from -- borrowing their defaults keeps 91 agent grants in step with the rest of the requests system rather than inventing a knob.""" 92 return timedelta_from_string(RequestRuleBinding._meta.get_field(field_name).default) 93 94 95class GrantRequestSerializer(EnterpriseRequiredMixin, ModelSerializer): 96 97 created_by = PartialUserSerializer(read_only=True) 98 revoked_by = PartialUserSerializer(read_only=True, allow_null=True) 99 agent_owner = PartialUserSerializer(read_only=True, allow_null=True) 100 is_active = BooleanField(read_only=True) 101 102 target_objs = SerializerMethodField() 103 104 @extend_schema_field(RequestableTargetSerializer(many=True)) 105 def get_target_objs(self, inst: GrantRequest) -> list[RequestableTargetSerializer]: 106 return RequestableTargetSerializer(inst.targets.all().select_subclasses(), many=True).data 107 108 class Meta: 109 model = GrantRequest 110 fields = [ 111 "created", 112 "created_by", 113 "requester_data", 114 "fulfiller_data", 115 "revoked_by", 116 "agent_owner", 117 "is_active", 118 "expires", 119 "status", 120 "targets", 121 "target_objs", 122 "uuid", 123 ] 124 extra_kwargs = { 125 "status": {"read_only": True}, 126 } 127 128 129class GrantRequestViewSet(RetrieveModelMixin, DestroyModelMixin, ListModelMixin, GenericViewSet): 130 131 # All requests are visible to users even if they're expired 132 queryset = GrantRequest.objects.including_expired() 133 serializer_class = GrantRequestSerializer 134 filterset_fields = ["created_by", "agent_owner", "status"] 135 rbac_allow_create_without_perm = True 136 ordering = ["-created_by"] 137 138 class GrantRequestCreateSerializer(PassiveSerializer): 139 140 pbms = PolicyBindingModelForeignKey( 141 queryset=PolicyBindingModel.objects.select_subclasses(), 142 many=True, 143 allow_empty=False, 144 ) 145 expiry = CharField( 146 required=False, 147 allow_blank=True, 148 validators=[timedelta_string_validator], 149 help_text=( 150 "Optional override for how long the grant should last once approved. " 151 "Clamped to the granting rule binding(s)' expiry_granted_max." 152 ), 153 ) 154 155 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 156 request = self.context["request"] 157 # De-dupe by pk so a caller passing the same target twice can't mint duplicate 158 # GrantRequestTargets (and therefore duplicate granted PolicyBindings). 159 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 160 for pbm in deduped: 161 if not isinstance(pbm, RequestableModel | RequestableChildModel): 162 raise ValidationError(f"'{pbm}' is not requestable") 163 if not user_can_request(pbm, request.user, request): 164 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 165 return deduped 166 167 class AgentGrantRequestCreateSerializer(PassiveSerializer): 168 """Body for an agent requesting access for itself. Deliberately narrower than 169 `GrantRequestCreateSerializer`: an agent may not pick its own expiry, which is 170 derived from the granting rules and capped by the agent's own lifetime.""" 171 172 pbms = PolicyBindingModelForeignKey( 173 queryset=PolicyBindingModel.objects.select_subclasses(), 174 many=True, 175 allow_empty=False, 176 ) 177 178 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 179 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 180 for pbm in deduped: 181 if not isinstance(pbm, RequestableModel | RequestableChildModel): 182 raise ValidationError(f"'{pbm}' is not requestable") 183 return deduped 184 185 class GrantRequestFulfillSerializer(PassiveSerializer): 186 187 data = JSONDictField() 188 status = ChoiceField(choices=RequestStatus.choices) 189 190 class AgentGrantRequestCreatedSerializer(PassiveSerializer): 191 """Response to an agent's access request: the request it created, plus the URL to hand to 192 the human it acts for. An agent has no browser, so it cannot run the approval itself -- 193 `fulfill_url` is what its owner opens to approve or deny.""" 194 195 grant_request = GrantRequestSerializer(read_only=True) 196 fulfill_url = CharField(read_only=True) 197 198 def _assert_reviewer(self, request: Request, grant: GrantRequest): 199 # An agent's request is decided by its owner and nobody else -- it only ever delegates 200 # access the owner already holds, so rules attached to the target play no part. A rule 201 # reviewer must not be able to deny it (a denial finalizes immediately) or revoke it. 202 if grant.agent_owner_id: 203 if request.user.pk != grant.agent_owner_id: 204 raise ValidationError("User does not have permissions to act on this object") 205 return 206 rules = RequestRule.objects.filter(targets__in=grant.targets.all()).distinct() 207 engine = ListPolicyEngine(rules, request.user, request) 208 # A rule with no reviewer bindings at all has nobody configured to approve 209 # it -- unlike app access, absence of bindings must not mean "anyone passes". 210 engine.empty_result = False 211 passing_rules = engine.build().result 212 # The user only needs to be an eligible reviewer of *at least one* rule attached 213 # to the request's targets -- rules are satisfied independently (see 214 # GrantRequest.is_satisfied), and this must match what `pending_review` lists. 215 if rules.exists() and not passing_rules.exists(): 216 raise ValidationError("User does not have permissions to act on this object") 217 218 def destroy(self, request: Request, *args, **kwargs): 219 grant: GrantRequest = self.get_object() 220 if grant.status != RequestStatus.CREATED: 221 raise ValidationError("Only a pending request can be cancelled") 222 return super().destroy(request, *args, **kwargs) 223 224 @extend_schema(responses={200: GrantRequestSerializer(many=True)}) 225 @action(detail=False, methods=[HTTPMethod.GET]) 226 def pending_review(self, request: Request) -> Response: 227 """List pending grant requests the current user is eligible to review.""" 228 engine = ListPolicyEngine(RequestRule.objects.all(), request.user, request) 229 # A rule with no reviewer bindings at all has nobody configured to approve 230 # it -- unlike app access, absence of bindings must not mean "anyone passes". 231 engine.empty_result = False 232 reviewable_rules = engine.build().result 233 queryset = ( 234 GrantRequest.objects.filter( 235 # An agent's request is its owner's to decide alone, so it reaches them through 236 # ownership rather than reviewer eligibility -- and must not reach a rule 237 # reviewer, who could no longer act on it anyway. 238 Q(targets__request_rules__in=reviewable_rules, agent_owner__isnull=True) 239 | Q(agent_owner=request.user), 240 status=RequestStatus.CREATED, 241 ) 242 .distinct() 243 .order_by("-created") 244 ) 245 page = self.paginate_queryset(queryset) 246 if page is not None: 247 serializer = self.get_serializer(page, many=True) 248 return self.get_paginated_response(serializer.data) 249 serializer = self.get_serializer(queryset, many=True) 250 return Response(serializer.data) 251 252 @extend_schema(request=GrantRequestCreateSerializer, responses={200: LinkSerializer}) 253 @validate(GrantRequestCreateSerializer) 254 def create(self, request: Request, body: GrantRequestCreateSerializer) -> Response: 255 brand: Brand = request.brand 256 pbms = body.validated_data["pbms"] 257 rule_bindings = list( 258 granting_rule_bindings(pbms, request.user, request).select_related("rule") 259 ) 260 # If every rule that granted access to one of the requested pbms agrees on a 261 # single request flow, prefer it over the brand's default. 262 flow = brand.flow_request 263 shared_flows = {rb.rule.request_flow_id for rb in rule_bindings} 264 if len(shared_flows) == 1: 265 (shared_flow_pk,) = shared_flows 266 if shared_flow_pk is not None: 267 flow = Flow.objects.get(pk=shared_flow_pk) 268 if not flow: 269 raise Http404 270 planner = FlowPlanner(flow) 271 planner.allow_empty_flows = True 272 # The strictest (shortest) pending/max expiry among the bindings that actually 273 # granted this request wins, so access can never outlive the tightest rule that 274 # applies. The requester's override is passed through as-is (not clamped here) -- 275 # a stage in the flow may still change it, so GrantRequestFinalStageView enforces 276 # the maximum once the flow has actually run. 277 pending_binding = min( 278 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_pending) 279 ) 280 max_binding = min( 281 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_granted_max) 282 ) 283 plan = planner.plan( 284 request, 285 { 286 PLAN_CONTEXT_GRANT_REQUESTED_PBMS: pbms, 287 PLAN_CONTEXT_PENDING_USER: request.user, 288 PLAN_CONTEXT_GRANT_PENDING_EXPIRY: pending_binding.expiry_pending, 289 PLAN_CONTEXT_GRANT_MAX_EXPIRY: max_binding.expiry_granted_max, 290 PLAN_CONTEXT_GRANT_REQUESTED_EXPIRY: body.validated_data.get("expiry") or None, 291 }, 292 ) 293 plan.append_stage(in_memory_stage(GrantRequestFinalStageView)) 294 plan.append_stage( 295 in_memory_stage( 296 MessageStage, 297 message=_("Successfully requested access!"), 298 ) 299 ) 300 return Response({"link": plan.to_redirect(request, flow).url}) 301 302 @extend_schema( 303 request=AgentGrantRequestCreateSerializer, 304 responses={201: AgentGrantRequestCreatedSerializer}, 305 ) 306 @action([HTTPMethod.POST], detail=False, permission_classes=[IsAuthenticated]) 307 @validate(AgentGrantRequestCreateSerializer) 308 @enterprise_action 309 def agent(self, request: Request, body: AgentGrantRequestCreateSerializer) -> Response: 310 """Delegate access an agent's owner already holds to the agent, time-boxed. Unlike 311 `create` this persists the request directly instead of returning a flow link -- an agent 312 authenticates with an API token and has no browser to run a flow in, so no justification 313 is ever collected. That is why the agent may only ask for what its owner already has: 314 the owner's approval is then the whole decision, and no reviewer is asked to judge a 315 request with nothing in it. The returned `fulfill_url` is what the agent hands to its 316 owner so they can act on it.""" 317 agent = Agent.objects.filter(pk=request.user.pk).first() 318 if not agent: 319 raise PermissionDenied(_("Only agents can request access through this endpoint.")) 320 owner: User | None = agent.parent 321 if not owner: 322 raise PermissionDenied(_("This agent has no owner who could approve its request.")) 323 # Delegated access is time-boxed by the agent's own lifetime, so a standing agent has 324 # nothing to bound the grant with. 325 if not (agent.expiring and agent.expires): 326 raise PermissionDenied(_("Only agents with an expiry can request access.")) 327 328 pbms = body.validated_data["pbms"] 329 # An agent can never reach past its owner: it may only be delegated access the owner 330 # already holds. Anything more would need the requester's justification and the reviewer 331 # flow that collects it, and this endpoint has no flow to run. 332 owner_holds = _owner_holds(pbms, owner, request) 333 for pbm in pbms: 334 if pbm.pbm_uuid not in owner_holds: 335 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 336 337 # No RequestRule gates this request, so there is no binding to take a duration from. 338 # The grant is additionally capped so it can never outlive the agent holding it. 339 pending_expiry = _binding_default("expiry_pending") 340 granted_expiry = min( 341 _binding_default("expiry_granted_max"), max(agent.expires - now(), timedelta(0)) 342 ) 343 344 req = create_grant_request( 345 request, 346 created_by=agent, 347 pbms=pbms, 348 requester_data={}, 349 expiry=GrantExpiry(pending=pending_expiry, granted=granted_expiry), 350 agent_owner=owner, 351 ) 352 return Response( 353 self.AgentGrantRequestCreatedSerializer( 354 {"grant_request": req, "fulfill_url": fulfill_url(request, req)} 355 ).data, 356 status=201, 357 ) 358 359 @extend_schema( 360 request=GrantRequestFulfillSerializer, 361 responses={ 362 204: OpenApiResponse(description="Request fulfilled"), 363 }, 364 ) 365 @action([HTTPMethod.PATCH], detail=True, permission_classes=[IsAuthenticated]) 366 @validate(GrantRequestFulfillSerializer) 367 @permission_required("authentik_requests.fulfill_grantrequest") 368 def fulfill(self, request: Request, body: GrantRequestFulfillSerializer, *args, **kwargs): 369 grant: GrantRequest = self.get_object() 370 if request.user.pk == grant.created_by_id: 371 raise ValidationError("Cannot fulfill your own request") 372 self._assert_reviewer(request, grant) 373 grant.record_approval( 374 request, 375 request.user, 376 body.validated_data.get("status"), 377 data=body.validated_data.get("data"), 378 ) 379 return Response(status=204) 380 381 @extend_schema( 382 request=None, 383 responses={ 384 204: OpenApiResponse(description="Grant revoked"), 385 }, 386 ) 387 @action([HTTPMethod.DELETE], detail=True, permission_classes=[IsAuthenticated]) 388 @permission_required("authentik_requests.revoke_grantrequest") 389 def revoke(self, request: Request, *args, **kwargs): 390 """Immediately end an active grant. Available to the same reviewers who could 391 approve it in the first place.""" 392 grant: GrantRequest = self.get_object() 393 self._assert_reviewer(request, grant) 394 grant.revoke(request, request.user) 395 return Response(status=204)
96class GrantRequestSerializer(EnterpriseRequiredMixin, ModelSerializer): 97 98 created_by = PartialUserSerializer(read_only=True) 99 revoked_by = PartialUserSerializer(read_only=True, allow_null=True) 100 agent_owner = PartialUserSerializer(read_only=True, allow_null=True) 101 is_active = BooleanField(read_only=True) 102 103 target_objs = SerializerMethodField() 104 105 @extend_schema_field(RequestableTargetSerializer(many=True)) 106 def get_target_objs(self, inst: GrantRequest) -> list[RequestableTargetSerializer]: 107 return RequestableTargetSerializer(inst.targets.all().select_subclasses(), many=True).data 108 109 class Meta: 110 model = GrantRequest 111 fields = [ 112 "created", 113 "created_by", 114 "requester_data", 115 "fulfiller_data", 116 "revoked_by", 117 "agent_owner", 118 "is_active", 119 "expires", 120 "status", 121 "targets", 122 "target_objs", 123 "uuid", 124 ] 125 extra_kwargs = { 126 "status": {"read_only": True}, 127 }
Mixin to validate that a valid enterprise license exists before allowing to save the object
109 class Meta: 110 model = GrantRequest 111 fields = [ 112 "created", 113 "created_by", 114 "requester_data", 115 "fulfiller_data", 116 "revoked_by", 117 "agent_owner", 118 "is_active", 119 "expires", 120 "status", 121 "targets", 122 "target_objs", 123 "uuid", 124 ] 125 extra_kwargs = { 126 "status": {"read_only": True}, 127 }
130class GrantRequestViewSet(RetrieveModelMixin, DestroyModelMixin, ListModelMixin, GenericViewSet): 131 132 # All requests are visible to users even if they're expired 133 queryset = GrantRequest.objects.including_expired() 134 serializer_class = GrantRequestSerializer 135 filterset_fields = ["created_by", "agent_owner", "status"] 136 rbac_allow_create_without_perm = True 137 ordering = ["-created_by"] 138 139 class GrantRequestCreateSerializer(PassiveSerializer): 140 141 pbms = PolicyBindingModelForeignKey( 142 queryset=PolicyBindingModel.objects.select_subclasses(), 143 many=True, 144 allow_empty=False, 145 ) 146 expiry = CharField( 147 required=False, 148 allow_blank=True, 149 validators=[timedelta_string_validator], 150 help_text=( 151 "Optional override for how long the grant should last once approved. " 152 "Clamped to the granting rule binding(s)' expiry_granted_max." 153 ), 154 ) 155 156 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 157 request = self.context["request"] 158 # De-dupe by pk so a caller passing the same target twice can't mint duplicate 159 # GrantRequestTargets (and therefore duplicate granted PolicyBindings). 160 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 161 for pbm in deduped: 162 if not isinstance(pbm, RequestableModel | RequestableChildModel): 163 raise ValidationError(f"'{pbm}' is not requestable") 164 if not user_can_request(pbm, request.user, request): 165 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 166 return deduped 167 168 class AgentGrantRequestCreateSerializer(PassiveSerializer): 169 """Body for an agent requesting access for itself. Deliberately narrower than 170 `GrantRequestCreateSerializer`: an agent may not pick its own expiry, which is 171 derived from the granting rules and capped by the agent's own lifetime.""" 172 173 pbms = PolicyBindingModelForeignKey( 174 queryset=PolicyBindingModel.objects.select_subclasses(), 175 many=True, 176 allow_empty=False, 177 ) 178 179 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 180 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 181 for pbm in deduped: 182 if not isinstance(pbm, RequestableModel | RequestableChildModel): 183 raise ValidationError(f"'{pbm}' is not requestable") 184 return deduped 185 186 class GrantRequestFulfillSerializer(PassiveSerializer): 187 188 data = JSONDictField() 189 status = ChoiceField(choices=RequestStatus.choices) 190 191 class AgentGrantRequestCreatedSerializer(PassiveSerializer): 192 """Response to an agent's access request: the request it created, plus the URL to hand to 193 the human it acts for. An agent has no browser, so it cannot run the approval itself -- 194 `fulfill_url` is what its owner opens to approve or deny.""" 195 196 grant_request = GrantRequestSerializer(read_only=True) 197 fulfill_url = CharField(read_only=True) 198 199 def _assert_reviewer(self, request: Request, grant: GrantRequest): 200 # An agent's request is decided by its owner and nobody else -- it only ever delegates 201 # access the owner already holds, so rules attached to the target play no part. A rule 202 # reviewer must not be able to deny it (a denial finalizes immediately) or revoke it. 203 if grant.agent_owner_id: 204 if request.user.pk != grant.agent_owner_id: 205 raise ValidationError("User does not have permissions to act on this object") 206 return 207 rules = RequestRule.objects.filter(targets__in=grant.targets.all()).distinct() 208 engine = ListPolicyEngine(rules, request.user, request) 209 # A rule with no reviewer bindings at all has nobody configured to approve 210 # it -- unlike app access, absence of bindings must not mean "anyone passes". 211 engine.empty_result = False 212 passing_rules = engine.build().result 213 # The user only needs to be an eligible reviewer of *at least one* rule attached 214 # to the request's targets -- rules are satisfied independently (see 215 # GrantRequest.is_satisfied), and this must match what `pending_review` lists. 216 if rules.exists() and not passing_rules.exists(): 217 raise ValidationError("User does not have permissions to act on this object") 218 219 def destroy(self, request: Request, *args, **kwargs): 220 grant: GrantRequest = self.get_object() 221 if grant.status != RequestStatus.CREATED: 222 raise ValidationError("Only a pending request can be cancelled") 223 return super().destroy(request, *args, **kwargs) 224 225 @extend_schema(responses={200: GrantRequestSerializer(many=True)}) 226 @action(detail=False, methods=[HTTPMethod.GET]) 227 def pending_review(self, request: Request) -> Response: 228 """List pending grant requests the current user is eligible to review.""" 229 engine = ListPolicyEngine(RequestRule.objects.all(), request.user, request) 230 # A rule with no reviewer bindings at all has nobody configured to approve 231 # it -- unlike app access, absence of bindings must not mean "anyone passes". 232 engine.empty_result = False 233 reviewable_rules = engine.build().result 234 queryset = ( 235 GrantRequest.objects.filter( 236 # An agent's request is its owner's to decide alone, so it reaches them through 237 # ownership rather than reviewer eligibility -- and must not reach a rule 238 # reviewer, who could no longer act on it anyway. 239 Q(targets__request_rules__in=reviewable_rules, agent_owner__isnull=True) 240 | Q(agent_owner=request.user), 241 status=RequestStatus.CREATED, 242 ) 243 .distinct() 244 .order_by("-created") 245 ) 246 page = self.paginate_queryset(queryset) 247 if page is not None: 248 serializer = self.get_serializer(page, many=True) 249 return self.get_paginated_response(serializer.data) 250 serializer = self.get_serializer(queryset, many=True) 251 return Response(serializer.data) 252 253 @extend_schema(request=GrantRequestCreateSerializer, responses={200: LinkSerializer}) 254 @validate(GrantRequestCreateSerializer) 255 def create(self, request: Request, body: GrantRequestCreateSerializer) -> Response: 256 brand: Brand = request.brand 257 pbms = body.validated_data["pbms"] 258 rule_bindings = list( 259 granting_rule_bindings(pbms, request.user, request).select_related("rule") 260 ) 261 # If every rule that granted access to one of the requested pbms agrees on a 262 # single request flow, prefer it over the brand's default. 263 flow = brand.flow_request 264 shared_flows = {rb.rule.request_flow_id for rb in rule_bindings} 265 if len(shared_flows) == 1: 266 (shared_flow_pk,) = shared_flows 267 if shared_flow_pk is not None: 268 flow = Flow.objects.get(pk=shared_flow_pk) 269 if not flow: 270 raise Http404 271 planner = FlowPlanner(flow) 272 planner.allow_empty_flows = True 273 # The strictest (shortest) pending/max expiry among the bindings that actually 274 # granted this request wins, so access can never outlive the tightest rule that 275 # applies. The requester's override is passed through as-is (not clamped here) -- 276 # a stage in the flow may still change it, so GrantRequestFinalStageView enforces 277 # the maximum once the flow has actually run. 278 pending_binding = min( 279 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_pending) 280 ) 281 max_binding = min( 282 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_granted_max) 283 ) 284 plan = planner.plan( 285 request, 286 { 287 PLAN_CONTEXT_GRANT_REQUESTED_PBMS: pbms, 288 PLAN_CONTEXT_PENDING_USER: request.user, 289 PLAN_CONTEXT_GRANT_PENDING_EXPIRY: pending_binding.expiry_pending, 290 PLAN_CONTEXT_GRANT_MAX_EXPIRY: max_binding.expiry_granted_max, 291 PLAN_CONTEXT_GRANT_REQUESTED_EXPIRY: body.validated_data.get("expiry") or None, 292 }, 293 ) 294 plan.append_stage(in_memory_stage(GrantRequestFinalStageView)) 295 plan.append_stage( 296 in_memory_stage( 297 MessageStage, 298 message=_("Successfully requested access!"), 299 ) 300 ) 301 return Response({"link": plan.to_redirect(request, flow).url}) 302 303 @extend_schema( 304 request=AgentGrantRequestCreateSerializer, 305 responses={201: AgentGrantRequestCreatedSerializer}, 306 ) 307 @action([HTTPMethod.POST], detail=False, permission_classes=[IsAuthenticated]) 308 @validate(AgentGrantRequestCreateSerializer) 309 @enterprise_action 310 def agent(self, request: Request, body: AgentGrantRequestCreateSerializer) -> Response: 311 """Delegate access an agent's owner already holds to the agent, time-boxed. Unlike 312 `create` this persists the request directly instead of returning a flow link -- an agent 313 authenticates with an API token and has no browser to run a flow in, so no justification 314 is ever collected. That is why the agent may only ask for what its owner already has: 315 the owner's approval is then the whole decision, and no reviewer is asked to judge a 316 request with nothing in it. The returned `fulfill_url` is what the agent hands to its 317 owner so they can act on it.""" 318 agent = Agent.objects.filter(pk=request.user.pk).first() 319 if not agent: 320 raise PermissionDenied(_("Only agents can request access through this endpoint.")) 321 owner: User | None = agent.parent 322 if not owner: 323 raise PermissionDenied(_("This agent has no owner who could approve its request.")) 324 # Delegated access is time-boxed by the agent's own lifetime, so a standing agent has 325 # nothing to bound the grant with. 326 if not (agent.expiring and agent.expires): 327 raise PermissionDenied(_("Only agents with an expiry can request access.")) 328 329 pbms = body.validated_data["pbms"] 330 # An agent can never reach past its owner: it may only be delegated access the owner 331 # already holds. Anything more would need the requester's justification and the reviewer 332 # flow that collects it, and this endpoint has no flow to run. 333 owner_holds = _owner_holds(pbms, owner, request) 334 for pbm in pbms: 335 if pbm.pbm_uuid not in owner_holds: 336 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 337 338 # No RequestRule gates this request, so there is no binding to take a duration from. 339 # The grant is additionally capped so it can never outlive the agent holding it. 340 pending_expiry = _binding_default("expiry_pending") 341 granted_expiry = min( 342 _binding_default("expiry_granted_max"), max(agent.expires - now(), timedelta(0)) 343 ) 344 345 req = create_grant_request( 346 request, 347 created_by=agent, 348 pbms=pbms, 349 requester_data={}, 350 expiry=GrantExpiry(pending=pending_expiry, granted=granted_expiry), 351 agent_owner=owner, 352 ) 353 return Response( 354 self.AgentGrantRequestCreatedSerializer( 355 {"grant_request": req, "fulfill_url": fulfill_url(request, req)} 356 ).data, 357 status=201, 358 ) 359 360 @extend_schema( 361 request=GrantRequestFulfillSerializer, 362 responses={ 363 204: OpenApiResponse(description="Request fulfilled"), 364 }, 365 ) 366 @action([HTTPMethod.PATCH], detail=True, permission_classes=[IsAuthenticated]) 367 @validate(GrantRequestFulfillSerializer) 368 @permission_required("authentik_requests.fulfill_grantrequest") 369 def fulfill(self, request: Request, body: GrantRequestFulfillSerializer, *args, **kwargs): 370 grant: GrantRequest = self.get_object() 371 if request.user.pk == grant.created_by_id: 372 raise ValidationError("Cannot fulfill your own request") 373 self._assert_reviewer(request, grant) 374 grant.record_approval( 375 request, 376 request.user, 377 body.validated_data.get("status"), 378 data=body.validated_data.get("data"), 379 ) 380 return Response(status=204) 381 382 @extend_schema( 383 request=None, 384 responses={ 385 204: OpenApiResponse(description="Grant revoked"), 386 }, 387 ) 388 @action([HTTPMethod.DELETE], detail=True, permission_classes=[IsAuthenticated]) 389 @permission_required("authentik_requests.revoke_grantrequest") 390 def revoke(self, request: Request, *args, **kwargs): 391 """Immediately end an active grant. Available to the same reviewers who could 392 approve it in the first place.""" 393 grant: GrantRequest = self.get_object() 394 self._assert_reviewer(request, grant) 395 grant.revoke(request, request.user) 396 return Response(status=204)
Retrieve a model instance.
225 @extend_schema(responses={200: GrantRequestSerializer(many=True)}) 226 @action(detail=False, methods=[HTTPMethod.GET]) 227 def pending_review(self, request: Request) -> Response: 228 """List pending grant requests the current user is eligible to review.""" 229 engine = ListPolicyEngine(RequestRule.objects.all(), request.user, request) 230 # A rule with no reviewer bindings at all has nobody configured to approve 231 # it -- unlike app access, absence of bindings must not mean "anyone passes". 232 engine.empty_result = False 233 reviewable_rules = engine.build().result 234 queryset = ( 235 GrantRequest.objects.filter( 236 # An agent's request is its owner's to decide alone, so it reaches them through 237 # ownership rather than reviewer eligibility -- and must not reach a rule 238 # reviewer, who could no longer act on it anyway. 239 Q(targets__request_rules__in=reviewable_rules, agent_owner__isnull=True) 240 | Q(agent_owner=request.user), 241 status=RequestStatus.CREATED, 242 ) 243 .distinct() 244 .order_by("-created") 245 ) 246 page = self.paginate_queryset(queryset) 247 if page is not None: 248 serializer = self.get_serializer(page, many=True) 249 return self.get_paginated_response(serializer.data) 250 serializer = self.get_serializer(queryset, many=True) 251 return Response(serializer.data)
List pending grant requests the current user is eligible to review.
253 @extend_schema(request=GrantRequestCreateSerializer, responses={200: LinkSerializer}) 254 @validate(GrantRequestCreateSerializer) 255 def create(self, request: Request, body: GrantRequestCreateSerializer) -> Response: 256 brand: Brand = request.brand 257 pbms = body.validated_data["pbms"] 258 rule_bindings = list( 259 granting_rule_bindings(pbms, request.user, request).select_related("rule") 260 ) 261 # If every rule that granted access to one of the requested pbms agrees on a 262 # single request flow, prefer it over the brand's default. 263 flow = brand.flow_request 264 shared_flows = {rb.rule.request_flow_id for rb in rule_bindings} 265 if len(shared_flows) == 1: 266 (shared_flow_pk,) = shared_flows 267 if shared_flow_pk is not None: 268 flow = Flow.objects.get(pk=shared_flow_pk) 269 if not flow: 270 raise Http404 271 planner = FlowPlanner(flow) 272 planner.allow_empty_flows = True 273 # The strictest (shortest) pending/max expiry among the bindings that actually 274 # granted this request wins, so access can never outlive the tightest rule that 275 # applies. The requester's override is passed through as-is (not clamped here) -- 276 # a stage in the flow may still change it, so GrantRequestFinalStageView enforces 277 # the maximum once the flow has actually run. 278 pending_binding = min( 279 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_pending) 280 ) 281 max_binding = min( 282 rule_bindings, key=lambda rb: timedelta_from_string(rb.expiry_granted_max) 283 ) 284 plan = planner.plan( 285 request, 286 { 287 PLAN_CONTEXT_GRANT_REQUESTED_PBMS: pbms, 288 PLAN_CONTEXT_PENDING_USER: request.user, 289 PLAN_CONTEXT_GRANT_PENDING_EXPIRY: pending_binding.expiry_pending, 290 PLAN_CONTEXT_GRANT_MAX_EXPIRY: max_binding.expiry_granted_max, 291 PLAN_CONTEXT_GRANT_REQUESTED_EXPIRY: body.validated_data.get("expiry") or None, 292 }, 293 ) 294 plan.append_stage(in_memory_stage(GrantRequestFinalStageView)) 295 plan.append_stage( 296 in_memory_stage( 297 MessageStage, 298 message=_("Successfully requested access!"), 299 ) 300 ) 301 return Response({"link": plan.to_redirect(request, flow).url})
303 @extend_schema( 304 request=AgentGrantRequestCreateSerializer, 305 responses={201: AgentGrantRequestCreatedSerializer}, 306 ) 307 @action([HTTPMethod.POST], detail=False, permission_classes=[IsAuthenticated]) 308 @validate(AgentGrantRequestCreateSerializer) 309 @enterprise_action 310 def agent(self, request: Request, body: AgentGrantRequestCreateSerializer) -> Response: 311 """Delegate access an agent's owner already holds to the agent, time-boxed. Unlike 312 `create` this persists the request directly instead of returning a flow link -- an agent 313 authenticates with an API token and has no browser to run a flow in, so no justification 314 is ever collected. That is why the agent may only ask for what its owner already has: 315 the owner's approval is then the whole decision, and no reviewer is asked to judge a 316 request with nothing in it. The returned `fulfill_url` is what the agent hands to its 317 owner so they can act on it.""" 318 agent = Agent.objects.filter(pk=request.user.pk).first() 319 if not agent: 320 raise PermissionDenied(_("Only agents can request access through this endpoint.")) 321 owner: User | None = agent.parent 322 if not owner: 323 raise PermissionDenied(_("This agent has no owner who could approve its request.")) 324 # Delegated access is time-boxed by the agent's own lifetime, so a standing agent has 325 # nothing to bound the grant with. 326 if not (agent.expiring and agent.expires): 327 raise PermissionDenied(_("Only agents with an expiry can request access.")) 328 329 pbms = body.validated_data["pbms"] 330 # An agent can never reach past its owner: it may only be delegated access the owner 331 # already holds. Anything more would need the requester's justification and the reviewer 332 # flow that collects it, and this endpoint has no flow to run. 333 owner_holds = _owner_holds(pbms, owner, request) 334 for pbm in pbms: 335 if pbm.pbm_uuid not in owner_holds: 336 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 337 338 # No RequestRule gates this request, so there is no binding to take a duration from. 339 # The grant is additionally capped so it can never outlive the agent holding it. 340 pending_expiry = _binding_default("expiry_pending") 341 granted_expiry = min( 342 _binding_default("expiry_granted_max"), max(agent.expires - now(), timedelta(0)) 343 ) 344 345 req = create_grant_request( 346 request, 347 created_by=agent, 348 pbms=pbms, 349 requester_data={}, 350 expiry=GrantExpiry(pending=pending_expiry, granted=granted_expiry), 351 agent_owner=owner, 352 ) 353 return Response( 354 self.AgentGrantRequestCreatedSerializer( 355 {"grant_request": req, "fulfill_url": fulfill_url(request, req)} 356 ).data, 357 status=201, 358 )
Delegate access an agent's owner already holds to the agent, time-boxed. Unlike
create this persists the request directly instead of returning a flow link -- an agent
authenticates with an API token and has no browser to run a flow in, so no justification
is ever collected. That is why the agent may only ask for what its owner already has:
the owner's approval is then the whole decision, and no reviewer is asked to judge a
request with nothing in it. The returned fulfill_url is what the agent hands to its
owner so they can act on it.
360 @extend_schema( 361 request=GrantRequestFulfillSerializer, 362 responses={ 363 204: OpenApiResponse(description="Request fulfilled"), 364 }, 365 ) 366 @action([HTTPMethod.PATCH], detail=True, permission_classes=[IsAuthenticated]) 367 @validate(GrantRequestFulfillSerializer) 368 @permission_required("authentik_requests.fulfill_grantrequest") 369 def fulfill(self, request: Request, body: GrantRequestFulfillSerializer, *args, **kwargs): 370 grant: GrantRequest = self.get_object() 371 if request.user.pk == grant.created_by_id: 372 raise ValidationError("Cannot fulfill your own request") 373 self._assert_reviewer(request, grant) 374 grant.record_approval( 375 request, 376 request.user, 377 body.validated_data.get("status"), 378 data=body.validated_data.get("data"), 379 ) 380 return Response(status=204)
382 @extend_schema( 383 request=None, 384 responses={ 385 204: OpenApiResponse(description="Grant revoked"), 386 }, 387 ) 388 @action([HTTPMethod.DELETE], detail=True, permission_classes=[IsAuthenticated]) 389 @permission_required("authentik_requests.revoke_grantrequest") 390 def revoke(self, request: Request, *args, **kwargs): 391 """Immediately end an active grant. Available to the same reviewers who could 392 approve it in the first place.""" 393 grant: GrantRequest = self.get_object() 394 self._assert_reviewer(request, grant) 395 grant.revoke(request, request.user) 396 return Response(status=204)
Immediately end an active grant. Available to the same reviewers who could approve it in the first place.
139 class GrantRequestCreateSerializer(PassiveSerializer): 140 141 pbms = PolicyBindingModelForeignKey( 142 queryset=PolicyBindingModel.objects.select_subclasses(), 143 many=True, 144 allow_empty=False, 145 ) 146 expiry = CharField( 147 required=False, 148 allow_blank=True, 149 validators=[timedelta_string_validator], 150 help_text=( 151 "Optional override for how long the grant should last once approved. " 152 "Clamped to the granting rule binding(s)' expiry_granted_max." 153 ), 154 ) 155 156 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 157 request = self.context["request"] 158 # De-dupe by pk so a caller passing the same target twice can't mint duplicate 159 # GrantRequestTargets (and therefore duplicate granted PolicyBindings). 160 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 161 for pbm in deduped: 162 if not isinstance(pbm, RequestableModel | RequestableChildModel): 163 raise ValidationError(f"'{pbm}' is not requestable") 164 if not user_can_request(pbm, request.user, request): 165 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 166 return deduped
Base serializer class which doesn't implement create/update methods
156 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 157 request = self.context["request"] 158 # De-dupe by pk so a caller passing the same target twice can't mint duplicate 159 # GrantRequestTargets (and therefore duplicate granted PolicyBindings). 160 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 161 for pbm in deduped: 162 if not isinstance(pbm, RequestableModel | RequestableChildModel): 163 raise ValidationError(f"'{pbm}' is not requestable") 164 if not user_can_request(pbm, request.user, request): 165 raise ValidationError(f"Cannot request access to '{pbm.requestable_label}'") 166 return deduped
Inherited Members
168 class AgentGrantRequestCreateSerializer(PassiveSerializer): 169 """Body for an agent requesting access for itself. Deliberately narrower than 170 `GrantRequestCreateSerializer`: an agent may not pick its own expiry, which is 171 derived from the granting rules and capped by the agent's own lifetime.""" 172 173 pbms = PolicyBindingModelForeignKey( 174 queryset=PolicyBindingModel.objects.select_subclasses(), 175 many=True, 176 allow_empty=False, 177 ) 178 179 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 180 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 181 for pbm in deduped: 182 if not isinstance(pbm, RequestableModel | RequestableChildModel): 183 raise ValidationError(f"'{pbm}' is not requestable") 184 return deduped
Body for an agent requesting access for itself. Deliberately narrower than
GrantRequestCreateSerializer: an agent may not pick its own expiry, which is
derived from the granting rules and capped by the agent's own lifetime.
179 def validate_pbms(self, pbms: list[PolicyBindingModel]) -> list[PolicyBindingModel]: 180 deduped = list({pbm.pk: pbm for pbm in pbms}.values()) 181 for pbm in deduped: 182 if not isinstance(pbm, RequestableModel | RequestableChildModel): 183 raise ValidationError(f"'{pbm}' is not requestable") 184 return deduped
Inherited Members
186 class GrantRequestFulfillSerializer(PassiveSerializer): 187 188 data = JSONDictField() 189 status = ChoiceField(choices=RequestStatus.choices)
Base serializer class which doesn't implement create/update methods
Inherited Members
191 class AgentGrantRequestCreatedSerializer(PassiveSerializer): 192 """Response to an agent's access request: the request it created, plus the URL to hand to 193 the human it acts for. An agent has no browser, so it cannot run the approval itself -- 194 `fulfill_url` is what its owner opens to approve or deny.""" 195 196 grant_request = GrantRequestSerializer(read_only=True) 197 fulfill_url = CharField(read_only=True)
Response to an agent's access request: the request it created, plus the URL to hand to
the human it acts for. An agent has no browser, so it cannot run the approval itself --
fulfill_url is what its owner opens to approve or deny.